1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
15 * $PostgreSQL: pgsql/src/bin/pg_dump/pg_dump.c,v 1.414 2005/07/10 14:26:29 momjian Exp $
17 *-------------------------------------------------------------------------
21 * Although this is not a backend module, we must include postgres.h anyway
22 * so that we can include a bunch of backend include files. pg_dump has
23 * never pretended to be very independent of the backend anyhow ...
40 #include "getopt_long.h"
42 #ifndef HAVE_INT_OPTRESET
46 #include "access/attnum.h"
47 #include "access/htup.h"
48 #include "catalog/pg_class.h"
49 #include "catalog/pg_proc.h"
50 #include "catalog/pg_trigger.h"
51 #include "catalog/pg_type.h"
53 #include "commands/sequence.h"
56 #include "libpq/libpq-fs.h"
59 #include "pg_backup.h"
60 #include "pg_backup_archiver.h"
61 #include "dumputils.h"
70 const char *descr; /* comment for an object */
71 Oid classoid; /* object class (catalog OID) */
72 Oid objoid; /* object OID */
73 int objsubid; /* subobject (table column #) */
78 bool g_verbose; /* User wants verbose narration of our
80 Archive *g_fout; /* the script file */
81 PGconn *g_conn; /* the database connection */
83 /* various user-settable parameters */
84 bool dumpInserts; /* dump data using proper insert strings */
85 bool attrNames; /* put attr names into insert strings */
90 /* obsolete as of 7.3: */
91 static Oid g_last_builtin_oid; /* value of the last builtin oid */
93 static char *selectTableName = NULL; /* name of a single table to dump */
94 static char *selectSchemaName = NULL; /* name of a single schema to dump */
96 char g_opaque_type[10]; /* name for the opaque type */
98 /* placeholders for the delimiters for comments */
99 char g_comment_start[10];
100 char g_comment_end[10];
102 static const CatalogId nilCatalogId = {0, 0};
104 /* these are to avoid passing around info for findNamespace() */
105 static NamespaceInfo *g_namespaces;
106 static int g_numNamespaces;
108 /* flag to turn on/off dollar quoting */
109 static int disable_dollar_quoting = 0;
112 static void help(const char *progname);
113 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
114 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
115 static void dumpComment(Archive *fout, const char *target,
116 const char *namespace, const char *owner,
117 CatalogId catalogId, int subid, DumpId dumpId);
118 static int findComments(Archive *fout, Oid classoid, Oid objoid,
119 CommentItem **items);
120 static int collectComments(Archive *fout, CommentItem **items);
121 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
122 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
123 static void dumpType(Archive *fout, TypeInfo *tinfo);
124 static void dumpBaseType(Archive *fout, TypeInfo *tinfo);
125 static void dumpDomain(Archive *fout, TypeInfo *tinfo);
126 static void dumpCompositeType(Archive *fout, TypeInfo *tinfo);
127 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
128 static void dumpFunc(Archive *fout, FuncInfo *finfo);
129 static void dumpCast(Archive *fout, CastInfo *cast);
130 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
131 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
132 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
133 static void dumpRule(Archive *fout, RuleInfo *rinfo);
134 static void dumpAgg(Archive *fout, AggInfo *agginfo);
135 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
136 static void dumpTable(Archive *fout, TableInfo *tbinfo);
137 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
138 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
139 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
140 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
141 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
142 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
144 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
145 const char *type, const char *name,
146 const char *tag, const char *nspname, const char *owner,
149 static void getDependencies(void);
150 static void getDomainConstraints(TypeInfo *tinfo);
151 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
152 static char *format_function_arguments(FuncInfo *finfo, int nallargs,
156 static char *format_function_signature(FuncInfo *finfo, bool honor_quotes);
157 static const char *convertRegProcReference(const char *proc);
158 static const char *convertOperatorReference(const char *opr);
159 static Oid findLastBuiltinOid_V71(const char *);
160 static Oid findLastBuiltinOid_V70(void);
161 static void setMaxOid(Archive *fout);
162 static void selectSourceSchema(const char *schemaName);
163 static char *getFormattedTypeName(Oid oid, OidOptions opts);
164 static char *myFormatType(const char *typname, int32 typmod);
165 static const char *fmtQualifiedId(const char *schema, const char *id);
166 static bool hasBlobs(Archive *AH);
167 static int dumpBlobs(Archive *AH, void *arg);
168 static int dumpBlobComments(Archive *AH, void *arg);
169 static void dumpDatabase(Archive *AH);
170 static void dumpEncoding(Archive *AH);
171 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
172 static const char *fmtCopyColumnList(const TableInfo *ti);
173 static void do_sql_command(PGconn *conn, const char *query);
174 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
175 ExecStatusType expected);
179 main(int argc, char **argv)
182 const char *filename = NULL;
183 const char *format = "p";
184 const char *dbname = NULL;
185 const char *pghost = NULL;
186 const char *pgport = NULL;
187 const char *username = NULL;
191 DumpableObject **dobjs;
194 bool force_password = false;
195 int compressLevel = -1;
196 bool ignore_version = false;
199 int outputCreate = 0;
200 bool outputBlobs = true;
201 int outputNoOwner = 0;
202 static int use_setsessauth = 0;
203 static int disable_triggers = 0;
204 char *outputSuperuser = NULL;
206 RestoreOptions *ropt;
208 static struct option long_options[] = {
209 {"data-only", no_argument, NULL, 'a'},
210 {"blobs", no_argument, NULL, 'b'},
211 {"clean", no_argument, NULL, 'c'},
212 {"create", no_argument, NULL, 'C'},
213 {"file", required_argument, NULL, 'f'},
214 {"format", required_argument, NULL, 'F'},
215 {"inserts", no_argument, NULL, 'd'},
216 {"attribute-inserts", no_argument, NULL, 'D'},
217 {"column-inserts", no_argument, NULL, 'D'},
218 {"host", required_argument, NULL, 'h'},
219 {"ignore-version", no_argument, NULL, 'i'},
220 {"no-reconnect", no_argument, NULL, 'R'},
221 {"oids", no_argument, NULL, 'o'},
222 {"no-owner", no_argument, NULL, 'O'},
223 {"port", required_argument, NULL, 'p'},
224 {"schema", required_argument, NULL, 'n'},
225 {"schema-only", no_argument, NULL, 's'},
226 {"superuser", required_argument, NULL, 'S'},
227 {"table", required_argument, NULL, 't'},
228 {"password", no_argument, NULL, 'W'},
229 {"username", required_argument, NULL, 'U'},
230 {"verbose", no_argument, NULL, 'v'},
231 {"no-privileges", no_argument, NULL, 'x'},
232 {"no-acl", no_argument, NULL, 'x'},
233 {"compress", required_argument, NULL, 'Z'},
234 {"help", no_argument, NULL, '?'},
235 {"version", no_argument, NULL, 'V'},
238 * the following options don't have an equivalent short option
239 * letter, but are available as '-X long-name'
241 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
242 {"disable-triggers", no_argument, &disable_triggers, 1},
243 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
249 set_pglocale_pgservice(argv[0], "pg_dump");
253 strcpy(g_comment_start, "-- ");
254 g_comment_end[0] = '\0';
255 strcpy(g_opaque_type, "opaque");
257 dataOnly = schemaOnly = dumpInserts = attrNames = false;
259 progname = get_progname(argv[0]);
261 /* Set default options based on progname */
262 if (strcmp(progname, "pg_backup") == 0)
267 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
272 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
274 puts("pg_dump (PostgreSQL) " PG_VERSION);
279 while ((c = getopt_long(argc, argv, "abcCdDf:F:h:in:oOp:RsS:t:uU:vWxX:Z:",
280 long_options, &optindex)) != -1)
284 case 'a': /* Dump data only */
288 case 'b': /* Dump blobs */
289 /* this is now default, so just ignore the switch */
292 case 'c': /* clean (i.e., drop) schema prior to
297 case 'C': /* Create DB */
301 case 'd': /* dump data as proper insert strings */
305 case 'D': /* dump data as proper insert strings with
319 case 'h': /* server host */
323 case 'i': /* ignore database version mismatch */
324 ignore_version = true;
327 case 'n': /* Dump data for this schema only */
328 selectSchemaName = strdup(optarg);
331 case 'o': /* Dump oids */
335 case 'O': /* Don't reconnect to match owner */
339 case 'p': /* server port */
344 /* no-op, still accepted for backwards compatibility */
347 case 's': /* dump schema only */
352 case 'S': /* Username for superuser in plain text
354 outputSuperuser = strdup(optarg);
357 case 't': /* Dump data for this table only */
358 selectTableName = strdup(optarg);
362 force_password = true;
363 username = simple_prompt("User name: ", 100, true);
370 case 'v': /* verbose */
375 force_password = true;
378 case 'x': /* skip ACL dump */
383 * Option letters were getting scarce, so I invented this
384 * new scheme: '-X feature' turns on some feature. Compare
385 * to the -f option in GCC. You should also add an
386 * equivalent GNU-style option --feature. Features that
387 * require arguments should use '-X feature=foo'.
390 if (strcmp(optarg, "disable-dollar-quoting") == 0)
391 disable_dollar_quoting = 1;
392 else if (strcmp(optarg, "disable-triggers") == 0)
393 disable_triggers = 1;
394 else if (strcmp(optarg, "use-set-session-authorization") == 0)
399 _("%s: invalid -X option -- %s\n"),
401 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
406 case 'Z': /* Compression Level */
407 compressLevel = atoi(optarg);
409 /* This covers the long options equivalent to -X xxx. */
415 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
420 if (optind < (argc - 1))
422 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
423 progname, argv[optind + 1]);
424 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
429 /* Get database name from command line */
431 dbname = argv[optind];
433 if (dataOnly && schemaOnly)
435 write_msg(NULL, "options \"schema only\" (-s) and \"data only\" (-a) cannot be used together\n");
439 if (dataOnly && outputClean)
441 write_msg(NULL, "options \"clean\" (-c) and \"data only\" (-a) cannot be used together\n");
445 if (selectTableName != NULL || selectSchemaName != NULL)
448 if (dumpInserts == true && oids == true)
450 write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together\n");
451 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
455 /* open the output file */
460 g_fout = CreateArchive(filename, archCustom, compressLevel);
465 g_fout = CreateArchive(filename, archFiles, compressLevel);
471 g_fout = CreateArchive(filename, archNull, 0);
476 g_fout = CreateArchive(filename, archTar, compressLevel);
480 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
486 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
490 /* Let the archiver know how noisy to be */
491 g_fout->verbose = g_verbose;
493 g_fout->minRemoteVersion = 70000; /* we can handle back to 7.0 */
494 g_fout->maxRemoteVersion = parse_version(PG_VERSION);
495 if (g_fout->maxRemoteVersion < 0)
497 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
502 * Open the database using the Archiver, so it knows about it. Errors
505 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
506 username, force_password, ignore_version);
509 * Start serializable transaction to dump consistent data.
511 do_sql_command(g_conn, "BEGIN");
513 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
515 /* Set the datestyle to ISO to ensure the dump's portability */
516 do_sql_command(g_conn, "SET DATESTYLE = ISO");
519 * If supported, set extra_float_digits so that we can dump float data
520 * exactly (given correctly implemented float I/O code, anyway)
522 if (g_fout->remoteVersion >= 70400)
523 do_sql_command(g_conn, "SET extra_float_digits TO 2");
525 /* Find the last built-in OID, if needed */
526 if (g_fout->remoteVersion < 70300)
528 if (g_fout->remoteVersion >= 70100)
529 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
531 g_last_builtin_oid = findLastBuiltinOid_V70();
533 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
537 * Now scan the database and create DumpableObject structs for all the
538 * objects we intend to dump.
540 tblinfo = getSchemaData(&numTables, schemaOnly, dataOnly);
543 getTableData(tblinfo, numTables, oids);
545 if (outputBlobs && hasBlobs(g_fout))
547 /* Add placeholders to allow correct sorting of blobs */
548 DumpableObject *blobobj;
550 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
551 blobobj->objType = DO_BLOBS;
552 blobobj->catId = nilCatalogId;
553 AssignDumpId(blobobj);
554 blobobj->name = strdup("BLOBS");
556 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
557 blobobj->objType = DO_BLOB_COMMENTS;
558 blobobj->catId = nilCatalogId;
559 AssignDumpId(blobobj);
560 blobobj->name = strdup("BLOB COMMENTS");
564 * Collect dependency data to assist in ordering the objects.
569 * Sort the objects into a safe dump order (no forward references).
571 * In 7.3 or later, we can rely on dependency information to help us
572 * determine a safe order, so the initial sort is mostly for cosmetic
573 * purposes: we sort by name to ensure that logically identical
574 * schemas will dump identically. Before 7.3 we don't have
575 * dependencies and we use OID ordering as an (unreliable) guide to
578 getDumpableObjects(&dobjs, &numObjs);
580 if (g_fout->remoteVersion >= 70300)
581 sortDumpableObjectsByTypeName(dobjs, numObjs);
583 sortDumpableObjectsByTypeOid(dobjs, numObjs);
585 sortDumpableObjects(dobjs, numObjs);
588 * Create archive TOC entries for all the objects to be dumped, in a
592 /* First the special encoding entry. */
593 dumpEncoding(g_fout);
595 /* The database item is always second. */
597 dumpDatabase(g_fout);
599 /* Max OID is next. */
603 /* Now the rearrangeable objects. */
604 for (i = 0; i < numObjs; i++)
605 dumpDumpableObject(g_fout, dobjs[i]);
608 * And finally we can do the actual output.
612 ropt = NewRestoreOptions();
613 ropt->filename = (char *) filename;
614 ropt->dropSchema = outputClean;
615 ropt->aclsSkip = aclsSkip;
616 ropt->superuser = outputSuperuser;
617 ropt->create = outputCreate;
618 ropt->noOwner = outputNoOwner;
619 ropt->disable_triggers = disable_triggers;
620 ropt->use_setsessauth = use_setsessauth;
621 ropt->dataOnly = dataOnly;
623 if (compressLevel == -1)
624 ropt->compression = 0;
626 ropt->compression = compressLevel;
628 ropt->suppressDumpWarnings = true; /* We've already shown
631 RestoreArchive(g_fout, ropt);
634 CloseArchive(g_fout);
643 help(const char *progname)
645 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
646 printf(_("Usage:\n"));
647 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
649 printf(_("\nGeneral options:\n"));
650 printf(_(" -f, --file=FILENAME output file name\n"));
651 printf(_(" -F, --format=c|t|p output file format (custom, tar, plain text)\n"));
652 printf(_(" -i, --ignore-version proceed even when server version mismatches\n"
653 " pg_dump version\n"));
654 printf(_(" -v, --verbose verbose mode\n"));
655 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
656 printf(_(" --help show this help, then exit\n"));
657 printf(_(" --version output version information, then exit\n"));
659 printf(_("\nOptions controlling the output content:\n"));
660 printf(_(" -a, --data-only dump only the data, not the schema\n"));
661 printf(_(" -c, --clean clean (drop) schema prior to create\n"));
662 printf(_(" -C, --create include commands to create database in dump\n"));
663 printf(_(" -d, --inserts dump data as INSERT, rather than COPY, commands\n"));
664 printf(_(" -D, --column-inserts dump data as INSERT commands with column names\n"));
665 printf(_(" -n, --schema=SCHEMA dump the named schema only\n"));
666 printf(_(" -o, --oids include OIDs in dump\n"));
667 printf(_(" -O, --no-owner skip restoration of object ownership\n"
668 " in plain text format\n"));
669 printf(_(" -s, --schema-only dump only the schema, no data\n"));
670 printf(_(" -S, --superuser=NAME specify the superuser user name to use in\n"
671 " plain text format\n"));
672 printf(_(" -t, --table=TABLE dump the named table only\n"));
673 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
674 printf(_(" -X disable-dollar-quoting, --disable-dollar-quoting\n"
675 " disable dollar quoting, use SQL standard quoting\n"));
676 printf(_(" -X disable-triggers, --disable-triggers\n"
677 " disable triggers during data-only restore\n"));
678 printf(_(" -X use-set-session-authorization, --use-set-session-authorization\n"
679 " use SESSION AUTHORIZATION commands instead of\n"
680 " OWNER TO commands\n"));
682 printf(_("\nConnection options:\n"));
683 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
684 printf(_(" -p, --port=PORT database server port number\n"));
685 printf(_(" -U, --username=NAME connect as specified database user\n"));
686 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
688 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
689 "variable value is used.\n\n"));
690 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
698 write_msg(NULL, "*** aborted because of error\n");
703 * selectDumpableNamespace: policy-setting subroutine
704 * Mark a namespace as to be dumped or not
707 selectDumpableNamespace(NamespaceInfo *nsinfo)
710 * If a specific table is being dumped, do not dump any complete
711 * namespaces. If a specific namespace is being dumped, dump just
712 * that namespace. Otherwise, dump all non-system namespaces.
714 if (selectTableName != NULL)
715 nsinfo->dump = false;
716 else if (selectSchemaName != NULL)
718 if (strcmp(nsinfo->dobj.name, selectSchemaName) == 0)
721 nsinfo->dump = false;
723 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
724 strcmp(nsinfo->dobj.name, "information_schema") == 0)
725 nsinfo->dump = false;
731 * selectDumpableTable: policy-setting subroutine
732 * Mark a table as to be dumped or not
735 selectDumpableTable(TableInfo *tbinfo)
738 * Always dump if dumping parent namespace; else, if a particular
739 * tablename has been specified, dump matching table name; else, do
742 tbinfo->dump = false;
743 if (tbinfo->dobj.namespace->dump)
745 else if (selectTableName != NULL &&
746 strcmp(tbinfo->dobj.name, selectTableName) == 0)
748 /* If both -s and -t specified, must match both to dump */
749 if (selectSchemaName == NULL)
751 else if (strcmp(tbinfo->dobj.namespace->dobj.name, selectSchemaName) == 0)
757 * Dump a table's contents for loading using the COPY command
758 * - this routine is called by the Archiver when it wants the table
762 #define COPYBUFSIZ 8192
765 dumpTableData_copy(Archive *fout, void *dcontext)
767 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
768 TableInfo *tbinfo = tdinfo->tdtable;
769 const char *classname = tbinfo->dobj.name;
770 const bool hasoids = tbinfo->hasoids;
771 const bool oids = tdinfo->oids;
772 PQExpBuffer q = createPQExpBuffer();
776 char copybuf[COPYBUFSIZ];
777 const char *column_list;
780 write_msg(NULL, "dumping contents of table %s\n", classname);
783 * Make sure we are in proper schema. We will qualify the table name
784 * below anyway (in case its name conflicts with a pg_catalog table);
785 * but this ensures reproducible results in case the table contains
786 * regproc, regclass, etc columns.
788 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
791 * If possible, specify the column list explicitly so that we have no
792 * possibility of retrieving data in the wrong column order. (The
793 * default column ordering of COPY will not be what we want in certain
794 * corner cases involving ADD COLUMN and inheritance.)
796 if (g_fout->remoteVersion >= 70300)
797 column_list = fmtCopyColumnList(tbinfo);
799 column_list = ""; /* can't select columns in COPY */
803 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
804 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
810 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
811 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
815 res = PQexec(g_conn, q->data);
816 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
822 ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
824 if (copybuf[0] == '\\' &&
828 copydone = true; /* don't print this... */
832 archputs(copybuf, fout);
839 archputs("\n", fout);
849 * There was considerable discussion in late July, 2000 regarding
850 * slowing down pg_dump when backing up large tables. Users with
851 * both slow & fast (muti-processor) machines experienced
852 * performance degradation when doing a backup.
854 * Initial attempts based on sleeping for a number of ms for each ms
855 * of work were deemed too complex, then a simple 'sleep in each
856 * loop' implementation was suggested. The latter failed because
857 * the loop was too tight. Finally, the following was implemented:
859 * If throttle is non-zero, then See how long since the last sleep.
860 * Work out how long to sleep (based on ratio). If sleep is more
861 * than 100ms, then sleep reset timer EndIf EndIf
863 * where the throttle value was the number of ms to sleep per ms of
864 * work. The calculation was done in each loop.
866 * Most of the hard work is done in the backend, and this solution
867 * still did not work particularly well: on slow machines, the
868 * ratio was 50:1, and on medium paced machines, 1:1, and on fast
869 * multi-processor machines, it had little or no effect, for
870 * reasons that were unclear.
872 * Further discussion ensued, and the proposal was dropped.
874 * For those people who want this feature, it can be implemented
875 * using gettimeofday in each loop, calculating the time since
876 * last sleep, multiplying that by the sleep ratio, then if the
877 * result is more than a preset 'minimum sleep time' (say 100ms),
878 * call the 'select' function to sleep for a subsecond period ie.
880 * select(0, NULL, NULL, NULL, &tvi);
882 * This will return after the interval specified in the structure
883 * tvi. Finally, call gettimeofday again to save the 'last sleep
887 archprintf(fout, "\\.\n\n\n");
889 ret = PQendcopy(g_conn);
892 write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
893 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
894 write_msg(NULL, "The command was: %s\n", q->data);
899 destroyPQExpBuffer(q);
904 dumpTableData_insert(Archive *fout, void *dcontext)
906 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
907 TableInfo *tbinfo = tdinfo->tdtable;
908 const char *classname = tbinfo->dobj.name;
909 PQExpBuffer q = createPQExpBuffer();
916 * Make sure we are in proper schema. We will qualify the table name
917 * below anyway (in case its name conflicts with a pg_catalog table);
918 * but this ensures reproducible results in case the table contains
919 * regproc, regclass, etc columns.
921 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
923 if (fout->remoteVersion >= 70100)
925 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
926 "SELECT * FROM ONLY %s",
927 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
932 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
934 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
938 res = PQexec(g_conn, q->data);
939 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
945 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
946 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
948 nfields = PQnfields(res);
949 for (tuple = 0; tuple < PQntuples(res); tuple++)
951 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
954 /* corner case for zero-column table */
955 archprintf(fout, "DEFAULT VALUES;\n");
958 if (attrNames == true)
961 appendPQExpBuffer(q, "(");
962 for (field = 0; field < nfields; field++)
965 appendPQExpBuffer(q, ", ");
966 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
968 appendPQExpBuffer(q, ") ");
969 archputs(q->data, fout);
971 archprintf(fout, "VALUES (");
972 for (field = 0; field < nfields; field++)
975 archprintf(fout, ", ");
976 if (PQgetisnull(res, tuple, field))
978 archprintf(fout, "NULL");
982 /* XXX This code is partially duplicated in ruleutils.c */
983 switch (PQftype(res, field))
994 * These types are printed without quotes
995 * unless they contain values that aren't
996 * accepted by the scanner unquoted (e.g.,
997 * 'NaN'). Note that strtod() and friends
998 * might accept NaN, so we can't use that to
1001 * In reality we only need to defend against
1002 * infinity and NaN, so we need not get too
1003 * crazy about pattern matching here.
1005 const char *s = PQgetvalue(res, tuple, field);
1007 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1008 archprintf(fout, "%s", s);
1010 archprintf(fout, "'%s'", s);
1016 archprintf(fout, "B'%s'",
1017 PQgetvalue(res, tuple, field));
1021 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1022 archprintf(fout, "true");
1024 archprintf(fout, "false");
1028 /* All other types are printed as string literals. */
1029 resetPQExpBuffer(q);
1030 appendStringLiteral(q, PQgetvalue(res, tuple, field), false);
1031 archputs(q->data, fout);
1035 archprintf(fout, ");\n");
1037 } while (PQntuples(res) > 0);
1041 archprintf(fout, "\n\n");
1043 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1045 destroyPQExpBuffer(q);
1052 * dump the contents of a single table
1054 * Actually, this just makes an ArchiveEntry for the table contents.
1057 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1059 TableInfo *tbinfo = tdinfo->tdtable;
1060 PQExpBuffer copyBuf = createPQExpBuffer();
1061 DataDumperPtr dumpFn;
1066 /* Dump/restore using COPY */
1067 dumpFn = dumpTableData_copy;
1068 /* must use 2 steps here 'cause fmtId is nonreentrant */
1069 appendPQExpBuffer(copyBuf, "COPY %s ",
1070 fmtId(tbinfo->dobj.name));
1071 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1072 fmtCopyColumnList(tbinfo),
1073 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1074 copyStmt = copyBuf->data;
1078 /* Restore using INSERT */
1079 dumpFn = dumpTableData_insert;
1083 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1085 tbinfo->dobj.namespace->dobj.name,
1087 tbinfo->usename, false,
1088 "TABLE DATA", "", "", copyStmt,
1089 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1092 destroyPQExpBuffer(copyBuf);
1097 * set up dumpable objects representing the contents of tables
1100 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1104 for (i = 0; i < numTables; i++)
1106 /* Skip VIEWs (no data to dump) */
1107 if (tblinfo[i].relkind == RELKIND_VIEW)
1109 /* Skip SEQUENCEs (handled elsewhere) */
1110 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1113 if (tblinfo[i].dump)
1115 TableDataInfo *tdinfo;
1117 tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1119 tdinfo->dobj.objType = DO_TABLE_DATA;
1122 * Note: use tableoid 0 so that this object won't be mistaken
1123 * for something that pg_depend entries apply to.
1125 tdinfo->dobj.catId.tableoid = 0;
1126 tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1127 AssignDumpId(&tdinfo->dobj);
1128 tdinfo->dobj.name = tblinfo[i].dobj.name;
1129 tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1130 tdinfo->tdtable = &(tblinfo[i]);
1131 tdinfo->oids = oids;
1132 addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1140 * dump the database definition
1143 dumpDatabase(Archive *AH)
1145 PQExpBuffer dbQry = createPQExpBuffer();
1146 PQExpBuffer delQry = createPQExpBuffer();
1147 PQExpBuffer creaQry = createPQExpBuffer();
1157 const char *datname,
1162 datname = PQdb(g_conn);
1165 write_msg(NULL, "saving database definition\n");
1167 /* Make sure we are in proper schema */
1168 selectSourceSchema("pg_catalog");
1170 /* Get the database owner and parameters from pg_database */
1171 if (g_fout->remoteVersion >= 80000)
1173 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1174 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1175 "pg_encoding_to_char(encoding) as encoding, "
1176 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) as tablespace "
1178 "WHERE datname = ");
1179 appendStringLiteral(dbQry, datname, true);
1181 else if (g_fout->remoteVersion >= 70100)
1183 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1184 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1185 "pg_encoding_to_char(encoding) as encoding, "
1186 "NULL as tablespace "
1188 "WHERE datname = ");
1189 appendStringLiteral(dbQry, datname, true);
1193 appendPQExpBuffer(dbQry, "SELECT "
1194 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1196 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1197 "pg_encoding_to_char(encoding) as encoding, "
1198 "NULL as tablespace "
1200 "WHERE datname = ");
1201 appendStringLiteral(dbQry, datname, true);
1204 res = PQexec(g_conn, dbQry->data);
1205 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1207 ntups = PQntuples(res);
1211 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1218 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1223 i_tableoid = PQfnumber(res, "tableoid");
1224 i_oid = PQfnumber(res, "oid");
1225 i_dba = PQfnumber(res, "dba");
1226 i_encoding = PQfnumber(res, "encoding");
1227 i_tablespace = PQfnumber(res, "tablespace");
1229 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1230 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1231 dba = PQgetvalue(res, 0, i_dba);
1232 encoding = PQgetvalue(res, 0, i_encoding);
1233 tablespace = PQgetvalue(res, 0, i_tablespace);
1235 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1237 if (strlen(encoding) > 0)
1239 appendPQExpBuffer(creaQry, " ENCODING = ");
1240 appendStringLiteral(creaQry, encoding, true);
1242 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1243 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1245 appendPQExpBuffer(creaQry, ";\n");
1247 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1250 dbDumpId = createDumpId();
1253 dbCatId, /* catalog ID */
1254 dbDumpId, /* dump ID */
1256 NULL, /* Namespace */
1257 NULL, /* Tablespace */
1259 false, /* with oids */
1260 "DATABASE", /* Desc */
1261 creaQry->data, /* Create */
1262 delQry->data, /* Del */
1267 NULL); /* Dumper Arg */
1269 /* Dump DB comment if any */
1270 resetPQExpBuffer(dbQry);
1271 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1272 dumpComment(AH, dbQry->data, NULL, "",
1273 dbCatId, 0, dbDumpId);
1277 destroyPQExpBuffer(dbQry);
1278 destroyPQExpBuffer(delQry);
1279 destroyPQExpBuffer(creaQry);
1284 * dumpEncoding: put the correct encoding into the archive
1287 dumpEncoding(Archive *AH)
1292 /* Can't read the encoding from pre-7.3 servers (SHOW isn't a query) */
1293 if (AH->remoteVersion < 70300)
1297 write_msg(NULL, "saving encoding\n");
1299 qry = createPQExpBuffer();
1301 appendPQExpBuffer(qry, "SHOW client_encoding");
1303 res = PQexec(g_conn, qry->data);
1305 check_sql_result(res, g_conn, qry->data, PGRES_TUPLES_OK);
1307 resetPQExpBuffer(qry);
1309 appendPQExpBuffer(qry, "SET client_encoding = ");
1310 appendStringLiteral(qry, PQgetvalue(res, 0, 0), true);
1311 appendPQExpBuffer(qry, ";\n");
1313 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1314 "ENCODING", NULL, NULL, "",
1315 false, "ENCODING", qry->data, "", NULL,
1321 destroyPQExpBuffer(qry);
1327 * Test whether database contains any large objects
1330 hasBlobs(Archive *AH)
1333 const char *blobQry;
1336 /* Make sure we are in proper schema */
1337 selectSourceSchema("pg_catalog");
1339 /* Check for BLOB OIDs */
1340 if (AH->remoteVersion >= 70100)
1341 blobQry = "SELECT loid FROM pg_largeobject LIMIT 1";
1343 blobQry = "SELECT oid FROM pg_class WHERE relkind = 'l' LIMIT 1";
1345 res = PQexec(g_conn, blobQry);
1346 check_sql_result(res, g_conn, blobQry, PGRES_TUPLES_OK);
1348 result = PQntuples(res) > 0;
1360 dumpBlobs(Archive *AH, void *arg)
1362 const char *blobQry;
1363 const char *blobFetchQry;
1365 char buf[LOBBUFSIZE];
1370 write_msg(NULL, "saving large objects\n");
1372 /* Make sure we are in proper schema */
1373 selectSourceSchema("pg_catalog");
1375 /* Cursor to get all BLOB OIDs */
1376 if (AH->remoteVersion >= 70100)
1377 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
1379 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
1381 res = PQexec(g_conn, blobQry);
1382 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
1384 /* Command to fetch from cursor */
1385 blobFetchQry = "FETCH 1000 IN bloboid";
1392 res = PQexec(g_conn, blobFetchQry);
1393 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
1395 /* Process the tuples, if any */
1396 for (i = 0; i < PQntuples(res); i++)
1401 blobOid = atooid(PQgetvalue(res, i, 0));
1403 loFd = lo_open(g_conn, blobOid, INV_READ);
1406 write_msg(NULL, "dumpBlobs(): could not open large object: %s",
1407 PQerrorMessage(g_conn));
1411 StartBlob(AH, blobOid);
1413 /* Now read it in chunks, sending data to archive */
1416 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
1419 write_msg(NULL, "dumpBlobs(): error reading large object: %s",
1420 PQerrorMessage(g_conn));
1424 WriteData(AH, buf, cnt);
1427 lo_close(g_conn, loFd);
1429 EndBlob(AH, blobOid);
1431 } while (PQntuples(res) > 0);
1440 * dump all blob comments
1442 * Since we don't provide any way to be selective about dumping blobs,
1443 * there's no need to be selective about their comments either. We put
1444 * all the comments into one big TOC entry.
1447 dumpBlobComments(Archive *AH, void *arg)
1449 const char *blobQry;
1450 const char *blobFetchQry;
1451 PQExpBuffer commentcmd = createPQExpBuffer();
1456 write_msg(NULL, "saving large object comments\n");
1458 /* Make sure we are in proper schema */
1459 selectSourceSchema("pg_catalog");
1461 /* Cursor to get all BLOB comments */
1462 if (AH->remoteVersion >= 70200)
1463 blobQry = "DECLARE blobcmt CURSOR FOR SELECT DISTINCT loid, obj_description(loid, 'pg_largeobject') FROM pg_largeobject";
1464 else if (AH->remoteVersion >= 70100)
1465 blobQry = "DECLARE blobcmt CURSOR FOR SELECT DISTINCT loid, obj_description(loid) FROM pg_largeobject";
1467 blobQry = "DECLARE blobcmt CURSOR FOR SELECT oid, (SELECT description FROM pg_description pd WHERE pd.objoid=pc.oid) FROM pg_class pc WHERE relkind = 'l'";
1469 res = PQexec(g_conn, blobQry);
1470 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
1472 /* Command to fetch from cursor */
1473 blobFetchQry = "FETCH 100 IN blobcmt";
1480 res = PQexec(g_conn, blobFetchQry);
1481 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
1483 /* Process the tuples, if any */
1484 for (i = 0; i < PQntuples(res); i++)
1489 /* ignore blobs without comments */
1490 if (PQgetisnull(res, i, 1))
1493 blobOid = atooid(PQgetvalue(res, i, 0));
1494 comment = PQgetvalue(res, i, 1);
1496 printfPQExpBuffer(commentcmd, "COMMENT ON LARGE OBJECT %u IS ",
1498 appendStringLiteral(commentcmd, comment, false);
1499 appendPQExpBuffer(commentcmd, ";\n");
1501 archputs(commentcmd->data, AH);
1503 } while (PQntuples(res) > 0);
1509 destroyPQExpBuffer(commentcmd);
1516 * read all namespaces in the system catalogs and return them in the
1517 * NamespaceInfo* structure
1519 * numNamespaces is set to the number of namespaces read in
1522 getNamespaces(int *numNamespaces)
1528 NamespaceInfo *nsinfo;
1536 * Before 7.3, there are no real namespaces; create two dummy entries,
1537 * one for user stuff and one for system stuff.
1539 if (g_fout->remoteVersion < 70300)
1541 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
1543 nsinfo[0].dobj.objType = DO_NAMESPACE;
1544 nsinfo[0].dobj.catId.tableoid = 0;
1545 nsinfo[0].dobj.catId.oid = 0;
1546 AssignDumpId(&nsinfo[0].dobj);
1547 nsinfo[0].dobj.name = strdup("public");
1548 nsinfo[0].usename = strdup("");
1549 nsinfo[0].nspacl = strdup("");
1551 selectDumpableNamespace(&nsinfo[0]);
1553 nsinfo[1].dobj.objType = DO_NAMESPACE;
1554 nsinfo[1].dobj.catId.tableoid = 0;
1555 nsinfo[1].dobj.catId.oid = 1;
1556 AssignDumpId(&nsinfo[1].dobj);
1557 nsinfo[1].dobj.name = strdup("pg_catalog");
1558 nsinfo[1].usename = strdup("");
1559 nsinfo[1].nspacl = strdup("");
1561 selectDumpableNamespace(&nsinfo[1]);
1563 g_namespaces = nsinfo;
1564 g_numNamespaces = *numNamespaces = 2;
1569 query = createPQExpBuffer();
1571 /* Make sure we are in proper schema */
1572 selectSourceSchema("pg_catalog");
1575 * we fetch all namespaces including system ones, so that every object
1576 * we read in can be linked to a containing namespace.
1578 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1579 "(select usename from pg_user where nspowner = usesysid) as usename, "
1580 "nspacl FROM pg_namespace");
1582 res = PQexec(g_conn, query->data);
1583 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1585 ntups = PQntuples(res);
1587 nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1589 i_tableoid = PQfnumber(res, "tableoid");
1590 i_oid = PQfnumber(res, "oid");
1591 i_nspname = PQfnumber(res, "nspname");
1592 i_usename = PQfnumber(res, "usename");
1593 i_nspacl = PQfnumber(res, "nspacl");
1595 for (i = 0; i < ntups; i++)
1597 nsinfo[i].dobj.objType = DO_NAMESPACE;
1598 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1599 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1600 AssignDumpId(&nsinfo[i].dobj);
1601 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
1602 nsinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1603 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1605 /* Decide whether to dump this namespace */
1606 selectDumpableNamespace(&nsinfo[i]);
1608 if (strlen(nsinfo[i].usename) == 0)
1609 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
1610 nsinfo[i].dobj.name);
1614 * If the user attempted to dump a specific namespace, check to ensure
1615 * that the specified namespace actually exists.
1617 if (selectSchemaName)
1619 for (i = 0; i < ntups; i++)
1620 if (strcmp(nsinfo[i].dobj.name, selectSchemaName) == 0)
1623 /* Didn't find a match */
1626 write_msg(NULL, "specified schema \"%s\" does not exist\n",
1633 destroyPQExpBuffer(query);
1635 g_namespaces = nsinfo;
1636 g_numNamespaces = *numNamespaces = ntups;
1643 * given a namespace OID and an object OID, look up the info read by
1646 * NB: for pre-7.3 source database, we use object OID to guess whether it's
1647 * a system object or not. In 7.3 and later there is no guessing.
1649 static NamespaceInfo *
1650 findNamespace(Oid nsoid, Oid objoid)
1654 if (g_fout->remoteVersion >= 70300)
1656 for (i = 0; i < g_numNamespaces; i++)
1658 NamespaceInfo *nsinfo = &g_namespaces[i];
1660 if (nsoid == nsinfo->dobj.catId.oid)
1663 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
1668 /* This code depends on the layout set up by getNamespaces. */
1669 if (objoid > g_last_builtin_oid)
1670 i = 0; /* user object */
1672 i = 1; /* system object */
1673 return &g_namespaces[i];
1676 return NULL; /* keep compiler quiet */
1681 * read all types in the system catalogs and return them in the
1682 * TypeInfo* structure
1684 * numTypes is set to the number of types read in
1686 * NB: this must run after getFuncs() because we assume we can do
1690 getTypes(int *numTypes)
1695 PQExpBuffer query = createPQExpBuffer();
1711 * we include even the built-in types because those may be used as
1712 * array elements by user-defined types
1714 * we filter out the built-in types when we dump out the types
1716 * same approach for undefined (shell) types
1719 /* Make sure we are in proper schema */
1720 selectSourceSchema("pg_catalog");
1722 if (g_fout->remoteVersion >= 70300)
1724 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1726 "(select usename from pg_user where typowner = usesysid) as usename, "
1727 "typinput::oid as typinput, "
1728 "typoutput::oid as typoutput, typelem, typrelid, "
1729 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1730 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1731 "typtype, typisdefined "
1734 else if (g_fout->remoteVersion >= 70100)
1736 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1737 "0::oid as typnamespace, "
1738 "(select usename from pg_user where typowner = usesysid) as usename, "
1739 "typinput::oid as typinput, "
1740 "typoutput::oid as typoutput, typelem, typrelid, "
1741 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1742 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1743 "typtype, typisdefined "
1748 appendPQExpBuffer(query, "SELECT "
1749 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
1751 "0::oid as typnamespace, "
1752 "(select usename from pg_user where typowner = usesysid) as usename, "
1753 "typinput::oid as typinput, "
1754 "typoutput::oid as typoutput, typelem, typrelid, "
1755 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1756 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1757 "typtype, typisdefined "
1761 res = PQexec(g_conn, query->data);
1762 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1764 ntups = PQntuples(res);
1766 tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1768 i_tableoid = PQfnumber(res, "tableoid");
1769 i_oid = PQfnumber(res, "oid");
1770 i_typname = PQfnumber(res, "typname");
1771 i_typnamespace = PQfnumber(res, "typnamespace");
1772 i_usename = PQfnumber(res, "usename");
1773 i_typinput = PQfnumber(res, "typinput");
1774 i_typoutput = PQfnumber(res, "typoutput");
1775 i_typelem = PQfnumber(res, "typelem");
1776 i_typrelid = PQfnumber(res, "typrelid");
1777 i_typrelkind = PQfnumber(res, "typrelkind");
1778 i_typtype = PQfnumber(res, "typtype");
1779 i_typisdefined = PQfnumber(res, "typisdefined");
1781 for (i = 0; i < ntups; i++)
1786 tinfo[i].dobj.objType = DO_TYPE;
1787 tinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1788 tinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1789 AssignDumpId(&tinfo[i].dobj);
1790 tinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
1791 tinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
1792 tinfo[i].dobj.catId.oid);
1793 tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1794 tinfo[i].typinput = atooid(PQgetvalue(res, i, i_typinput));
1795 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
1796 tinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
1797 tinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
1798 tinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
1799 tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
1802 * If it's a table's rowtype, use special type code to facilitate
1803 * sorting into the desired order. (We don't want to consider it
1804 * an ordinary type because that would bring the table up into the
1805 * datatype part of the dump order.)
1807 if (OidIsValid(tinfo[i].typrelid) && tinfo[i].typrelkind != 'c')
1808 tinfo[i].dobj.objType = DO_TABLE_TYPE;
1811 * check for user-defined array types, omit system generated ones
1813 if (OidIsValid(tinfo[i].typelem) &&
1814 tinfo[i].dobj.name[0] != '_')
1815 tinfo[i].isArray = true;
1817 tinfo[i].isArray = false;
1819 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
1820 tinfo[i].isDefined = true;
1822 tinfo[i].isDefined = false;
1825 * If it's a domain, fetch info about its constraints, if any
1827 tinfo[i].nDomChecks = 0;
1828 tinfo[i].domChecks = NULL;
1829 if (tinfo[i].typtype == 'd')
1830 getDomainConstraints(&(tinfo[i]));
1833 * Make sure there are dependencies from the type to its input and
1834 * output functions. (We don't worry about typsend, typreceive,
1835 * or typanalyze since those are only valid in 7.4 and later,
1836 * wherein the standard dependency mechanism will pick them up.)
1838 funcInfo = findFuncByOid(tinfo[i].typinput);
1840 addObjectDependency(&tinfo[i].dobj,
1841 funcInfo->dobj.dumpId);
1842 funcInfo = findFuncByOid(typoutput);
1844 addObjectDependency(&tinfo[i].dobj,
1845 funcInfo->dobj.dumpId);
1847 if (strlen(tinfo[i].usename) == 0 && tinfo[i].isDefined)
1848 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
1849 tinfo[i].dobj.name);
1856 destroyPQExpBuffer(query);
1863 * read all operators in the system catalogs and return them in the
1864 * OprInfo* structure
1866 * numOprs is set to the number of operators read in
1869 getOperators(int *numOprs)
1874 PQExpBuffer query = createPQExpBuffer();
1884 * find all operators, including builtin operators; we filter out
1885 * system-defined operators at dump-out time.
1888 /* Make sure we are in proper schema */
1889 selectSourceSchema("pg_catalog");
1891 if (g_fout->remoteVersion >= 70300)
1893 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1895 "(select usename from pg_user where oprowner = usesysid) as usename, "
1896 "oprcode::oid as oprcode "
1897 "FROM pg_operator");
1899 else if (g_fout->remoteVersion >= 70100)
1901 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1902 "0::oid as oprnamespace, "
1903 "(select usename from pg_user where oprowner = usesysid) as usename, "
1904 "oprcode::oid as oprcode "
1905 "FROM pg_operator");
1909 appendPQExpBuffer(query, "SELECT "
1910 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
1912 "0::oid as oprnamespace, "
1913 "(select usename from pg_user where oprowner = usesysid) as usename, "
1914 "oprcode::oid as oprcode "
1915 "FROM pg_operator");
1918 res = PQexec(g_conn, query->data);
1919 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1921 ntups = PQntuples(res);
1924 oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
1926 i_tableoid = PQfnumber(res, "tableoid");
1927 i_oid = PQfnumber(res, "oid");
1928 i_oprname = PQfnumber(res, "oprname");
1929 i_oprnamespace = PQfnumber(res, "oprnamespace");
1930 i_usename = PQfnumber(res, "usename");
1931 i_oprcode = PQfnumber(res, "oprcode");
1933 for (i = 0; i < ntups; i++)
1935 oprinfo[i].dobj.objType = DO_OPERATOR;
1936 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1937 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1938 AssignDumpId(&oprinfo[i].dobj);
1939 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
1940 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
1941 oprinfo[i].dobj.catId.oid);
1942 oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1943 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
1945 if (strlen(oprinfo[i].usename) == 0)
1946 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
1947 oprinfo[i].dobj.name);
1952 destroyPQExpBuffer(query);
1959 * read all conversions in the system catalogs and return them in the
1960 * ConvInfo* structure
1962 * numConversions is set to the number of conversions read in
1965 getConversions(int *numConversions)
1970 PQExpBuffer query = createPQExpBuffer();
1978 /* Conversions didn't exist pre-7.3 */
1979 if (g_fout->remoteVersion < 70300)
1981 *numConversions = 0;
1986 * find all conversions, including builtin conversions; we filter out
1987 * system-defined conversions at dump-out time.
1990 /* Make sure we are in proper schema */
1991 selectSourceSchema("pg_catalog");
1993 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
1995 "(select usename from pg_user where conowner = usesysid) as usename "
1996 "FROM pg_conversion");
1998 res = PQexec(g_conn, query->data);
1999 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2001 ntups = PQntuples(res);
2002 *numConversions = ntups;
2004 convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
2006 i_tableoid = PQfnumber(res, "tableoid");
2007 i_oid = PQfnumber(res, "oid");
2008 i_conname = PQfnumber(res, "conname");
2009 i_connamespace = PQfnumber(res, "connamespace");
2010 i_usename = PQfnumber(res, "usename");
2012 for (i = 0; i < ntups; i++)
2014 convinfo[i].dobj.objType = DO_CONVERSION;
2015 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2016 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2017 AssignDumpId(&convinfo[i].dobj);
2018 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
2019 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
2020 convinfo[i].dobj.catId.oid);
2021 convinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2026 destroyPQExpBuffer(query);
2033 * read all opclasses in the system catalogs and return them in the
2034 * OpclassInfo* structure
2036 * numOpclasses is set to the number of opclasses read in
2039 getOpclasses(int *numOpclasses)
2044 PQExpBuffer query = createPQExpBuffer();
2045 OpclassInfo *opcinfo;
2053 * find all opclasses, including builtin opclasses; we filter out
2054 * system-defined opclasses at dump-out time.
2057 /* Make sure we are in proper schema */
2058 selectSourceSchema("pg_catalog");
2060 if (g_fout->remoteVersion >= 70300)
2062 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2064 "(select usename from pg_user where opcowner = usesysid) as usename "
2067 else if (g_fout->remoteVersion >= 70100)
2069 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2070 "0::oid as opcnamespace, "
2071 "''::name as usename "
2076 appendPQExpBuffer(query, "SELECT "
2077 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2079 "0::oid as opcnamespace, "
2080 "''::name as usename "
2084 res = PQexec(g_conn, query->data);
2085 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2087 ntups = PQntuples(res);
2088 *numOpclasses = ntups;
2090 opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2092 i_tableoid = PQfnumber(res, "tableoid");
2093 i_oid = PQfnumber(res, "oid");
2094 i_opcname = PQfnumber(res, "opcname");
2095 i_opcnamespace = PQfnumber(res, "opcnamespace");
2096 i_usename = PQfnumber(res, "usename");
2098 for (i = 0; i < ntups; i++)
2100 opcinfo[i].dobj.objType = DO_OPCLASS;
2101 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2102 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2103 AssignDumpId(&opcinfo[i].dobj);
2104 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
2105 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
2106 opcinfo[i].dobj.catId.oid);
2107 opcinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2109 if (g_fout->remoteVersion >= 70300)
2111 if (strlen(opcinfo[i].usename) == 0)
2112 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
2113 opcinfo[i].dobj.name);
2119 destroyPQExpBuffer(query);
2126 * read all the user-defined aggregates in the system catalogs and
2127 * return them in the AggInfo* structure
2129 * numAggs is set to the number of aggregates read in
2132 getAggregates(int *numAggs)
2137 PQExpBuffer query = createPQExpBuffer();
2147 /* Make sure we are in proper schema */
2148 selectSourceSchema("pg_catalog");
2150 /* find all user-defined aggregates */
2152 if (g_fout->remoteVersion >= 70300)
2154 appendPQExpBuffer(query, "SELECT tableoid, oid, proname as aggname, "
2155 "pronamespace as aggnamespace, "
2156 "proargtypes[0] as aggbasetype, "
2157 "(select usename from pg_user where proowner = usesysid) as usename, "
2161 "AND pronamespace != "
2162 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2164 else if (g_fout->remoteVersion >= 70100)
2166 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
2167 "0::oid as aggnamespace, "
2169 "(select usename from pg_user where aggowner = usesysid) as usename, "
2171 "FROM pg_aggregate "
2172 "where oid > '%u'::oid",
2173 g_last_builtin_oid);
2177 appendPQExpBuffer(query, "SELECT "
2178 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
2180 "0::oid as aggnamespace, "
2182 "(select usename from pg_user where aggowner = usesysid) as usename, "
2184 "FROM pg_aggregate "
2185 "where oid > '%u'::oid",
2186 g_last_builtin_oid);
2189 res = PQexec(g_conn, query->data);
2190 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2192 ntups = PQntuples(res);
2195 agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
2197 i_tableoid = PQfnumber(res, "tableoid");
2198 i_oid = PQfnumber(res, "oid");
2199 i_aggname = PQfnumber(res, "aggname");
2200 i_aggnamespace = PQfnumber(res, "aggnamespace");
2201 i_aggbasetype = PQfnumber(res, "aggbasetype");
2202 i_usename = PQfnumber(res, "usename");
2203 i_aggacl = PQfnumber(res, "aggacl");
2205 for (i = 0; i < ntups; i++)
2207 agginfo[i].aggfn.dobj.objType = DO_AGG;
2208 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2209 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2210 AssignDumpId(&agginfo[i].aggfn.dobj);
2211 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
2212 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
2213 agginfo[i].aggfn.dobj.catId.oid);
2214 agginfo[i].aggfn.usename = strdup(PQgetvalue(res, i, i_usename));
2215 if (strlen(agginfo[i].aggfn.usename) == 0)
2216 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
2217 agginfo[i].aggfn.dobj.name);
2218 agginfo[i].aggfn.lang = InvalidOid; /* not currently
2220 agginfo[i].aggfn.nargs = 1;
2221 agginfo[i].aggfn.argtypes = (Oid *) malloc(sizeof(Oid));
2222 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_aggbasetype));
2223 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
2224 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
2225 agginfo[i].anybasetype = false; /* computed when it's dumped */
2226 agginfo[i].fmtbasetype = NULL; /* computed when it's dumped */
2231 destroyPQExpBuffer(query);
2238 * read all the user-defined functions in the system catalogs and
2239 * return them in the FuncInfo* structure
2241 * numFuncs is set to the number of functions read in
2244 getFuncs(int *numFuncs)
2249 PQExpBuffer query = createPQExpBuffer();
2261 int i_is_pl_handler;
2263 /* Make sure we are in proper schema */
2264 selectSourceSchema("pg_catalog");
2266 /* find all user-defined funcs */
2268 if (g_fout->remoteVersion >= 70300)
2271 * We now collect info on pg_catalog resident functions, but
2272 * only if they are language call handlers or validators, and
2273 * only for non-default languages (i.e. not internal/C/SQL).
2275 appendPQExpBuffer(query,
2276 "SELECT tableoid, oid, proname, prolang, "
2277 "pronargs, proargtypes, prorettype, proacl, "
2279 "(select usename from pg_user "
2280 " where proowner = usesysid) as usename, "
2282 " (select lanplcallfoid from pg_language "
2283 " where lanplcallfoid != 0) THEN true "
2285 " (select lanvalidator from pg_language "
2286 " where lanplcallfoid != 0) THEN true "
2287 " ELSE false END AS is_pl_handler "
2289 "WHERE NOT proisagg "
2290 "AND (pronamespace != "
2291 " (select oid from pg_namespace "
2292 " where nspname = 'pg_catalog')"
2294 " (select lanplcallfoid from pg_language "
2295 " where lanplcallfoid != 0) "
2297 " (select lanvalidator from pg_language "
2298 " where lanplcallfoid != 0))"
2301 else if (g_fout->remoteVersion >= 70100)
2303 appendPQExpBuffer(query,
2304 "SELECT tableoid, oid, proname, prolang, "
2305 "pronargs, proargtypes, prorettype, "
2306 "'{=X}' as proacl, "
2307 "0::oid as pronamespace, "
2308 "(select usename from pg_user "
2309 " where proowner = usesysid) as usename, "
2310 "false AS is_pl_handler "
2312 "where pg_proc.oid > '%u'::oid",
2313 g_last_builtin_oid);
2317 appendPQExpBuffer(query,
2319 "(SELECT oid FROM pg_class "
2320 " WHERE relname = 'pg_proc') AS tableoid, "
2321 "oid, proname, prolang, "
2322 "pronargs, proargtypes, prorettype, "
2323 "'{=X}' as proacl, "
2324 "0::oid as pronamespace, "
2325 "(select usename from pg_user "
2326 " where proowner = usesysid) as usename, "
2327 "false AS is_pl_handler "
2329 "where pg_proc.oid > '%u'::oid",
2330 g_last_builtin_oid);
2333 res = PQexec(g_conn, query->data);
2334 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2336 ntups = PQntuples(res);
2340 finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
2342 i_tableoid = PQfnumber(res, "tableoid");
2343 i_oid = PQfnumber(res, "oid");
2344 i_proname = PQfnumber(res, "proname");
2345 i_pronamespace = PQfnumber(res, "pronamespace");
2346 i_usename = PQfnumber(res, "usename");
2347 i_prolang = PQfnumber(res, "prolang");
2348 i_pronargs = PQfnumber(res, "pronargs");
2349 i_proargtypes = PQfnumber(res, "proargtypes");
2350 i_prorettype = PQfnumber(res, "prorettype");
2351 i_proacl = PQfnumber(res, "proacl");
2352 i_is_pl_handler = PQfnumber(res,"is_pl_handler");
2354 for (i = 0; i < ntups; i++)
2356 finfo[i].dobj.objType = DO_FUNC;
2357 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2358 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2359 AssignDumpId(&finfo[i].dobj);
2360 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
2361 finfo[i].dobj.namespace =
2362 findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
2363 finfo[i].dobj.catId.oid);
2364 finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2365 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2366 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
2367 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
2368 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
2369 finfo[i].isProlangFunc =
2370 strcmp(PQgetvalue(res, i, i_is_pl_handler), "t") == 0;
2371 if (finfo[i].nargs == 0)
2372 finfo[i].argtypes = NULL;
2375 finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
2376 parseOidArray(PQgetvalue(res, i, i_proargtypes),
2377 finfo[i].argtypes, finfo[i].nargs);
2380 if (strlen(finfo[i].usename) == 0)
2382 "WARNING: owner of function \"%s\" appears to be invalid\n",
2383 finfo[i].dobj.name);
2388 destroyPQExpBuffer(query);
2395 * read all the user-defined tables (no indexes, no catalogs)
2396 * in the system catalogs return them in the TableInfo* structure
2398 * numTables is set to the number of tables read in
2401 getTables(int *numTables)
2406 PQExpBuffer query = createPQExpBuffer();
2407 PQExpBuffer delqry = createPQExpBuffer();
2408 PQExpBuffer lockquery = createPQExpBuffer();
2424 int i_reltablespace;
2426 /* Make sure we are in proper schema */
2427 selectSourceSchema("pg_catalog");
2430 * Find all the tables (including views and sequences).
2432 * We include system catalogs, so that we can work if a user table is
2433 * defined to inherit from a system catalog (pretty weird, but...)
2435 * We ignore tables that are not type 'r' (ordinary relation), 'S'
2436 * (sequence), 'v' (view), or 'c' (composite type).
2438 * Composite-type table entries won't be dumped as such, but we have
2439 * to make a DumpableObject for them so that we can track dependencies
2440 * of the composite type (pg_depend entries for columns of the composite
2441 * type link to the pg_class entry not the pg_type entry).
2443 * Note: in this phase we should collect only a minimal amount of
2444 * information about each table, basically just enough to decide if it
2445 * is interesting. We must fetch all tables in this phase because
2446 * otherwise we cannot correctly identify inherited columns, serial
2450 if (g_fout->remoteVersion >= 80000)
2453 * Left join to pick up dependency info linking sequences to their
2454 * serial column, if any
2456 appendPQExpBuffer(query,
2457 "SELECT c.tableoid, c.oid, relname, "
2458 "relacl, relkind, relnamespace, "
2459 "(select usename from pg_user where relowner = usesysid) as usename, "
2460 "relchecks, reltriggers, "
2461 "relhasindex, relhasrules, relhasoids, "
2462 "d.refobjid as owning_tab, "
2463 "d.refobjsubid as owning_col, "
2464 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace "
2466 "left join pg_depend d on "
2467 "(c.relkind = '%c' and "
2468 "d.classid = c.tableoid and d.objid = c.oid and "
2469 "d.objsubid = 0 and "
2470 "d.refclassid = c.tableoid and d.deptype = 'i') "
2471 "where relkind in ('%c', '%c', '%c', '%c') "
2474 RELKIND_RELATION, RELKIND_SEQUENCE,
2475 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
2477 else if (g_fout->remoteVersion >= 70300)
2480 * Left join to pick up dependency info linking sequences to their
2481 * serial column, if any
2483 appendPQExpBuffer(query,
2484 "SELECT c.tableoid, c.oid, relname, "
2485 "relacl, relkind, relnamespace, "
2486 "(select usename from pg_user where relowner = usesysid) as usename, "
2487 "relchecks, reltriggers, "
2488 "relhasindex, relhasrules, relhasoids, "
2489 "d.refobjid as owning_tab, "
2490 "d.refobjsubid as owning_col, "
2491 "NULL as reltablespace "
2493 "left join pg_depend d on "
2494 "(c.relkind = '%c' and "
2495 "d.classid = c.tableoid and d.objid = c.oid and "
2496 "d.objsubid = 0 and "
2497 "d.refclassid = c.tableoid and d.deptype = 'i') "
2498 "where relkind in ('%c', '%c', '%c', '%c') "
2501 RELKIND_RELATION, RELKIND_SEQUENCE,
2502 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
2504 else if (g_fout->remoteVersion >= 70200)
2506 appendPQExpBuffer(query,
2507 "SELECT tableoid, oid, relname, relacl, relkind, "
2508 "0::oid as relnamespace, "
2509 "(select usename from pg_user where relowner = usesysid) as usename, "
2510 "relchecks, reltriggers, "
2511 "relhasindex, relhasrules, relhasoids, "
2512 "NULL::oid as owning_tab, "
2513 "NULL::int4 as owning_col, "
2514 "NULL as reltablespace "
2516 "where relkind in ('%c', '%c', '%c') "
2518 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2520 else if (g_fout->remoteVersion >= 70100)
2522 /* all tables have oids in 7.1 */
2523 appendPQExpBuffer(query,
2524 "SELECT tableoid, oid, relname, relacl, relkind, "
2525 "0::oid as relnamespace, "
2526 "(select usename from pg_user where relowner = usesysid) as usename, "
2527 "relchecks, reltriggers, "
2528 "relhasindex, relhasrules, "
2529 "'t'::bool as relhasoids, "
2530 "NULL::oid as owning_tab, "
2531 "NULL::int4 as owning_col, "
2532 "NULL as reltablespace "
2534 "where relkind in ('%c', '%c', '%c') "
2536 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2541 * Before 7.1, view relkind was not set to 'v', so we must check
2542 * if we have a view by looking for a rule in pg_rewrite.
2544 appendPQExpBuffer(query,
2546 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2547 "oid, relname, relacl, "
2548 "CASE WHEN relhasrules and relkind = 'r' "
2549 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
2550 " r.ev_class = c.oid AND r.ev_type = '1') "
2551 "THEN '%c'::\"char\" "
2552 "ELSE relkind END AS relkind,"
2553 "0::oid as relnamespace, "
2554 "(select usename from pg_user where relowner = usesysid) as usename, "
2555 "relchecks, reltriggers, "
2556 "relhasindex, relhasrules, "
2557 "'t'::bool as relhasoids, "
2558 "NULL::oid as owning_tab, "
2559 "NULL::int4 as owning_col, "
2560 "NULL as reltablespace "
2562 "where relkind in ('%c', '%c') "
2565 RELKIND_RELATION, RELKIND_SEQUENCE);
2568 res = PQexec(g_conn, query->data);
2569 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2571 ntups = PQntuples(res);
2576 * Extract data from result and lock dumpable tables. We do the
2577 * locking before anything else, to minimize the window wherein a
2578 * table could disappear under us.
2580 * Note that we have to save info about all tables here, even when
2581 * dumping only one, because we don't yet know which tables might be
2582 * inheritance ancestors of the target table.
2584 tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
2586 i_reltableoid = PQfnumber(res, "tableoid");
2587 i_reloid = PQfnumber(res, "oid");
2588 i_relname = PQfnumber(res, "relname");
2589 i_relnamespace = PQfnumber(res, "relnamespace");
2590 i_relacl = PQfnumber(res, "relacl");
2591 i_relkind = PQfnumber(res, "relkind");
2592 i_usename = PQfnumber(res, "usename");
2593 i_relchecks = PQfnumber(res, "relchecks");
2594 i_reltriggers = PQfnumber(res, "reltriggers");
2595 i_relhasindex = PQfnumber(res, "relhasindex");
2596 i_relhasrules = PQfnumber(res, "relhasrules");
2597 i_relhasoids = PQfnumber(res, "relhasoids");
2598 i_owning_tab = PQfnumber(res, "owning_tab");
2599 i_owning_col = PQfnumber(res, "owning_col");
2600 i_reltablespace = PQfnumber(res, "reltablespace");
2602 for (i = 0; i < ntups; i++)
2604 tblinfo[i].dobj.objType = DO_TABLE;
2605 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
2606 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
2607 AssignDumpId(&tblinfo[i].dobj);
2608 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
2609 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
2610 tblinfo[i].dobj.catId.oid);
2611 tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2612 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
2613 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
2614 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
2615 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
2616 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
2617 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
2618 tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2619 if (PQgetisnull(res, i, i_owning_tab))
2621 tblinfo[i].owning_tab = InvalidOid;
2622 tblinfo[i].owning_col = 0;
2626 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
2627 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
2629 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
2631 /* other fields were zeroed above */
2634 * Decide whether we want to dump this table. Sequences owned by
2635 * serial columns are never dumpable on their own; we will
2636 * transpose their owning table's dump flag to them below.
2638 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
2639 tblinfo[i].dump = false;
2640 else if (OidIsValid(tblinfo[i].owning_tab))
2641 tblinfo[i].dump = false;
2643 selectDumpableTable(&tblinfo[i]);
2644 tblinfo[i].interesting = tblinfo[i].dump;
2647 * Read-lock target tables to make sure they aren't DROPPED or
2648 * altered in schema before we get around to dumping them.
2650 * Note that we don't explicitly lock parents of the target tables;
2651 * we assume our lock on the child is enough to prevent schema
2652 * alterations to parent tables.
2654 * NOTE: it'd be kinda nice to lock views and sequences too, not only
2655 * plain tables, but the backend doesn't presently allow that.
2657 if (tblinfo[i].dump && tblinfo[i].relkind == RELKIND_RELATION)
2659 resetPQExpBuffer(lockquery);
2660 appendPQExpBuffer(lockquery,
2661 "LOCK TABLE %s IN ACCESS SHARE MODE",
2662 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
2663 tblinfo[i].dobj.name));
2664 do_sql_command(g_conn, lockquery->data);
2667 /* Emit notice if join for owner failed */
2668 if (strlen(tblinfo[i].usename) == 0)
2669 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
2670 tblinfo[i].dobj.name);
2674 * If the user is attempting to dump a specific table, check to ensure
2675 * that the specified table actually exists. (This is a bit
2676 * simplistic since we don't fully check the combination of -n and -t
2679 if (selectTableName)
2681 for (i = 0; i < ntups; i++)
2682 if (strcmp(tblinfo[i].dobj.name, selectTableName) == 0)
2685 /* Didn't find a match */
2688 write_msg(NULL, "specified table \"%s\" does not exist\n",
2695 destroyPQExpBuffer(query);
2696 destroyPQExpBuffer(delqry);
2697 destroyPQExpBuffer(lockquery);
2704 * read all the inheritance information
2705 * from the system catalogs return them in the InhInfo* structure
2707 * numInherits is set to the number of pairs read in
2710 getInherits(int *numInherits)
2715 PQExpBuffer query = createPQExpBuffer();
2721 /* Make sure we are in proper schema */
2722 selectSourceSchema("pg_catalog");
2724 /* find all the inheritance information */
2726 appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2728 res = PQexec(g_conn, query->data);
2729 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2731 ntups = PQntuples(res);
2733 *numInherits = ntups;
2735 inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
2737 i_inhrelid = PQfnumber(res, "inhrelid");
2738 i_inhparent = PQfnumber(res, "inhparent");
2740 for (i = 0; i < ntups; i++)
2742 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
2743 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
2748 destroyPQExpBuffer(query);
2755 * get information about every index on a dumpable table
2757 * Note: index data is not returned directly to the caller, but it
2758 * does get entered into the DumpableObject tables.
2761 getIndexes(TableInfo tblinfo[], int numTables)
2765 PQExpBuffer query = createPQExpBuffer();
2768 ConstraintInfo *constrinfo;
2783 for (i = 0; i < numTables; i++)
2785 TableInfo *tbinfo = &tblinfo[i];
2787 /* Only plain tables have indexes */
2788 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
2795 write_msg(NULL, "reading indexes for table \"%s\"\n",
2798 /* Make sure we are in proper schema so indexdef is right */
2799 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2802 * The point of the messy-looking outer join is to find a
2803 * constraint that is related by an internal dependency link to
2804 * the index. If we find one, create a CONSTRAINT entry linked to
2805 * the INDEX entry. We assume an index won't have more than one
2806 * internal dependency.
2808 resetPQExpBuffer(query);
2809 if (g_fout->remoteVersion >= 80000)
2811 appendPQExpBuffer(query,
2812 "SELECT t.tableoid, t.oid, "
2813 "t.relname as indexname, "
2814 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2815 "t.relnatts as indnkeys, "
2816 "i.indkey, i.indisclustered, "
2817 "c.contype, c.conname, "
2818 "c.tableoid as contableoid, "
2820 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) as tablespace "
2821 "FROM pg_catalog.pg_index i "
2822 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2823 "LEFT JOIN pg_catalog.pg_depend d "
2824 "ON (d.classid = t.tableoid "
2825 "AND d.objid = t.oid "
2826 "AND d.deptype = 'i') "
2827 "LEFT JOIN pg_catalog.pg_constraint c "
2828 "ON (d.refclassid = c.tableoid "
2829 "AND d.refobjid = c.oid) "
2830 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2831 "ORDER BY indexname",
2832 tbinfo->dobj.catId.oid);
2834 else if (g_fout->remoteVersion >= 70300)
2836 appendPQExpBuffer(query,
2837 "SELECT t.tableoid, t.oid, "
2838 "t.relname as indexname, "
2839 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2840 "t.relnatts as indnkeys, "
2841 "i.indkey, i.indisclustered, "
2842 "c.contype, c.conname, "
2843 "c.tableoid as contableoid, "
2845 "NULL as tablespace "
2846 "FROM pg_catalog.pg_index i "
2847 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2848 "LEFT JOIN pg_catalog.pg_depend d "
2849 "ON (d.classid = t.tableoid "
2850 "AND d.objid = t.oid "
2851 "AND d.deptype = 'i') "
2852 "LEFT JOIN pg_catalog.pg_constraint c "
2853 "ON (d.refclassid = c.tableoid "
2854 "AND d.refobjid = c.oid) "
2855 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2856 "ORDER BY indexname",
2857 tbinfo->dobj.catId.oid);
2859 else if (g_fout->remoteVersion >= 70100)
2861 appendPQExpBuffer(query,
2862 "SELECT t.tableoid, t.oid, "
2863 "t.relname as indexname, "
2864 "pg_get_indexdef(i.indexrelid) as indexdef, "
2865 "t.relnatts as indnkeys, "
2866 "i.indkey, false as indisclustered, "
2867 "CASE WHEN i.indisprimary THEN 'p'::char "
2868 "ELSE '0'::char END as contype, "
2869 "t.relname as conname, "
2870 "0::oid as contableoid, "
2872 "NULL as tablespace "
2873 "FROM pg_index i, pg_class t "
2874 "WHERE t.oid = i.indexrelid "
2875 "AND i.indrelid = '%u'::oid "
2876 "ORDER BY indexname",
2877 tbinfo->dobj.catId.oid);
2881 appendPQExpBuffer(query,
2883 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2885 "t.relname as indexname, "
2886 "pg_get_indexdef(i.indexrelid) as indexdef, "
2887 "t.relnatts as indnkeys, "
2888 "i.indkey, false as indisclustered, "
2889 "CASE WHEN i.indisprimary THEN 'p'::char "
2890 "ELSE '0'::char END as contype, "
2891 "t.relname as conname, "
2892 "0::oid as contableoid, "
2894 "NULL as tablespace "
2895 "FROM pg_index i, pg_class t "
2896 "WHERE t.oid = i.indexrelid "
2897 "AND i.indrelid = '%u'::oid "
2898 "ORDER BY indexname",
2899 tbinfo->dobj.catId.oid);
2902 res = PQexec(g_conn, query->data);
2903 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2905 ntups = PQntuples(res);
2907 i_tableoid = PQfnumber(res, "tableoid");
2908 i_oid = PQfnumber(res, "oid");
2909 i_indexname = PQfnumber(res, "indexname");
2910 i_indexdef = PQfnumber(res, "indexdef");
2911 i_indnkeys = PQfnumber(res, "indnkeys");
2912 i_indkey = PQfnumber(res, "indkey");
2913 i_indisclustered = PQfnumber(res, "indisclustered");
2914 i_contype = PQfnumber(res, "contype");
2915 i_conname = PQfnumber(res, "conname");
2916 i_contableoid = PQfnumber(res, "contableoid");
2917 i_conoid = PQfnumber(res, "conoid");
2918 i_tablespace = PQfnumber(res, "tablespace");
2920 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
2921 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2923 for (j = 0; j < ntups; j++)
2927 indxinfo[j].dobj.objType = DO_INDEX;
2928 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
2929 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
2930 AssignDumpId(&indxinfo[j].dobj);
2931 indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
2932 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2933 indxinfo[j].indextable = tbinfo;
2934 indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
2935 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
2936 indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
2939 * In pre-7.4 releases, indkeys may contain more entries than
2940 * indnkeys says (since indnkeys will be 1 for a functional
2941 * index). We don't actually care about this case since we
2942 * don't examine indkeys except for indexes associated with
2943 * PRIMARY and UNIQUE constraints, which are never functional
2944 * indexes. But we have to allocate enough space to keep
2945 * parseOidArray from complaining.
2947 indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
2948 parseOidArray(PQgetvalue(res, j, i_indkey),
2949 indxinfo[j].indkeys, INDEX_MAX_KEYS);
2950 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
2951 contype = *(PQgetvalue(res, j, i_contype));
2953 if (contype == 'p' || contype == 'u')
2956 * If we found a constraint matching the index, create an
2959 * In a pre-7.3 database, we take this path iff the index was
2960 * marked indisprimary.
2962 constrinfo[j].dobj.objType = DO_CONSTRAINT;
2963 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2964 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2965 AssignDumpId(&constrinfo[j].dobj);
2966 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2967 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2968 constrinfo[j].contable = tbinfo;
2969 constrinfo[j].condomain = NULL;
2970 constrinfo[j].contype = contype;
2971 constrinfo[j].condef = NULL;
2972 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
2973 constrinfo[j].coninherited = false;
2974 constrinfo[j].separate = true;
2976 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
2978 /* If pre-7.3 DB, better make sure table comes first */
2979 addObjectDependency(&constrinfo[j].dobj,
2980 tbinfo->dobj.dumpId);
2984 /* Plain secondary index */
2985 indxinfo[j].indexconstraint = 0;
2992 destroyPQExpBuffer(query);
2998 * Get info about constraints on dumpable tables.
3000 * Currently handles foreign keys only.
3001 * Unique and primary key constraints are handled with indexes,
3002 * while check constraints are processed in getTableAttrs().
3005 getConstraints(TableInfo tblinfo[], int numTables)
3009 ConstraintInfo *constrinfo;
3018 /* pg_constraint was created in 7.3, so nothing to do if older */
3019 if (g_fout->remoteVersion < 70300)
3022 query = createPQExpBuffer();
3024 for (i = 0; i < numTables; i++)
3026 TableInfo *tbinfo = &tblinfo[i];
3028 if (tbinfo->ntrig == 0 || !tbinfo->dump)
3032 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
3036 * select table schema to ensure constraint expr is qualified if
3039 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3041 resetPQExpBuffer(query);
3042 appendPQExpBuffer(query,
3043 "SELECT tableoid, oid, conname, "
3044 "pg_catalog.pg_get_constraintdef(oid) as condef "
3045 "FROM pg_catalog.pg_constraint "
3046 "WHERE conrelid = '%u'::pg_catalog.oid "
3047 "AND contype = 'f'",
3048 tbinfo->dobj.catId.oid);
3049 res = PQexec(g_conn, query->data);
3050 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3052 ntups = PQntuples(res);
3054 i_contableoid = PQfnumber(res, "tableoid");
3055 i_conoid = PQfnumber(res, "oid");
3056 i_conname = PQfnumber(res, "conname");
3057 i_condef = PQfnumber(res, "condef");
3059 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3061 for (j = 0; j < ntups; j++)
3063 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
3064 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
3065 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
3066 AssignDumpId(&constrinfo[j].dobj);
3067 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
3068 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3069 constrinfo[j].contable = tbinfo;
3070 constrinfo[j].condomain = NULL;
3071 constrinfo[j].contype = 'f';
3072 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
3073 constrinfo[j].conindex = 0;
3074 constrinfo[j].coninherited = false;
3075 constrinfo[j].separate = true;
3081 destroyPQExpBuffer(query);
3085 * getDomainConstraints
3087 * Get info about constraints on a domain.
3090 getDomainConstraints(TypeInfo *tinfo)
3093 ConstraintInfo *constrinfo;
3102 /* pg_constraint was created in 7.3, so nothing to do if older */
3103 if (g_fout->remoteVersion < 70300)
3107 * select appropriate schema to ensure names in constraint are
3108 * properly qualified
3110 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
3112 query = createPQExpBuffer();
3114 if (g_fout->remoteVersion >= 70400)
3115 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3116 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3117 "FROM pg_catalog.pg_constraint "
3118 "WHERE contypid = '%u'::pg_catalog.oid "
3120 tinfo->dobj.catId.oid);
3122 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3123 "'CHECK (' || consrc || ')' AS consrc "
3124 "FROM pg_catalog.pg_constraint "
3125 "WHERE contypid = '%u'::pg_catalog.oid "
3127 tinfo->dobj.catId.oid);
3129 res = PQexec(g_conn, query->data);
3130 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3132 ntups = PQntuples(res);
3134 i_tableoid = PQfnumber(res, "tableoid");
3135 i_oid = PQfnumber(res, "oid");
3136 i_conname = PQfnumber(res, "conname");
3137 i_consrc = PQfnumber(res, "consrc");
3139 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3141 tinfo->nDomChecks = ntups;
3142 tinfo->domChecks = constrinfo;
3144 for (i = 0; i < ntups; i++)
3146 constrinfo[i].dobj.objType = DO_CONSTRAINT;
3147 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3148 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3149 AssignDumpId(&constrinfo[i].dobj);
3150 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
3151 constrinfo[i].dobj.namespace = tinfo->dobj.namespace;
3152 constrinfo[i].contable = NULL;
3153 constrinfo[i].condomain = tinfo;
3154 constrinfo[i].contype = 'c';
3155 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
3156 constrinfo[i].conindex = 0;
3157 constrinfo[i].coninherited = false;
3158 constrinfo[i].separate = false;
3161 * Make the domain depend on the constraint, ensuring it won't be
3162 * output till any constraint dependencies are OK.
3164 addObjectDependency(&tinfo->dobj,
3165 constrinfo[i].dobj.dumpId);
3170 destroyPQExpBuffer(query);
3175 * get basic information about every rule in the system
3177 * numRules is set to the number of rules read in
3180 getRules(int *numRules)
3185 PQExpBuffer query = createPQExpBuffer();
3194 /* Make sure we are in proper schema */
3195 selectSourceSchema("pg_catalog");
3197 if (g_fout->remoteVersion >= 70100)
3199 appendPQExpBuffer(query, "SELECT "
3200 "tableoid, oid, rulename, "
3201 "ev_class as ruletable, ev_type, is_instead "
3207 appendPQExpBuffer(query, "SELECT "
3208 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
3210 "ev_class as ruletable, ev_type, is_instead "
3215 res = PQexec(g_conn, query->data);
3216 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3218 ntups = PQntuples(res);
3222 ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
3224 i_tableoid = PQfnumber(res, "tableoid");
3225 i_oid = PQfnumber(res, "oid");
3226 i_rulename = PQfnumber(res, "rulename");
3227 i_ruletable = PQfnumber(res, "ruletable");
3228 i_ev_type = PQfnumber(res, "ev_type");
3229 i_is_instead = PQfnumber(res, "is_instead");
3231 for (i = 0; i < ntups; i++)
3235 ruleinfo[i].dobj.objType = DO_RULE;
3236 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3237 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3238 AssignDumpId(&ruleinfo[i].dobj);
3239 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
3240 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
3241 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
3242 if (ruleinfo[i].ruletable == NULL)
3244 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
3246 ruleinfo[i].dobj.catId.oid);
3249 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
3250 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
3251 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
3252 if (ruleinfo[i].ruletable)
3255 * If the table is a view, force its ON SELECT rule to be
3256 * sorted before the view itself --- this ensures that any
3257 * dependencies for the rule affect the table's positioning.
3258 * Other rules are forced to appear after their table.
3260 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
3261 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
3263 addObjectDependency(&ruleinfo[i].ruletable->dobj,
3264 ruleinfo[i].dobj.dumpId);
3265 /* We'll merge the rule into CREATE VIEW, if possible */
3266 ruleinfo[i].separate = false;
3270 addObjectDependency(&ruleinfo[i].dobj,
3271 ruleinfo[i].ruletable->dobj.dumpId);
3272 ruleinfo[i].separate = true;
3276 ruleinfo[i].separate = true;
3281 destroyPQExpBuffer(query);
3288 * get information about every trigger on a dumpable table
3290 * Note: trigger data is not returned directly to the caller, but it
3291 * does get entered into the DumpableObject tables.
3294 getTriggers(TableInfo tblinfo[], int numTables)
3298 PQExpBuffer query = createPQExpBuffer();
3300 TriggerInfo *tginfo;
3316 for (i = 0; i < numTables; i++)
3318 TableInfo *tbinfo = &tblinfo[i];
3320 if (tbinfo->ntrig == 0 || !tbinfo->dump)
3324 write_msg(NULL, "reading triggers for table \"%s\"\n",
3328 * select table schema to ensure regproc name is qualified if
3331 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3333 resetPQExpBuffer(query);
3334 if (g_fout->remoteVersion >= 70300)
3337 * We ignore triggers that are tied to a foreign-key
3340 appendPQExpBuffer(query,
3342 "tgfoid::pg_catalog.regproc as tgfname, "
3343 "tgtype, tgnargs, tgargs, "
3344 "tgisconstraint, tgconstrname, tgdeferrable, "
3345 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3346 "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
3347 "from pg_catalog.pg_trigger t "
3348 "where tgrelid = '%u'::pg_catalog.oid "
3349 "and (not tgisconstraint "
3351 " (SELECT 1 FROM pg_catalog.pg_depend d "
3352 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
3353 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
3354 tbinfo->dobj.catId.oid);
3356 else if (g_fout->remoteVersion >= 70100)
3358 appendPQExpBuffer(query,
3359 "SELECT tgname, tgfoid::regproc as tgfname, "
3360 "tgtype, tgnargs, tgargs, "
3361 "tgisconstraint, tgconstrname, tgdeferrable, "
3362 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3363 "(select relname from pg_class where oid = tgconstrrelid) "
3364 " as tgconstrrelname "
3366 "where tgrelid = '%u'::oid",
3367 tbinfo->dobj.catId.oid);
3371 appendPQExpBuffer(query,
3372 "SELECT tgname, tgfoid::regproc as tgfname, "
3373 "tgtype, tgnargs, tgargs, "
3374 "tgisconstraint, tgconstrname, tgdeferrable, "
3375 "tgconstrrelid, tginitdeferred, "
3376 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
3379 "(select relname from pg_class where oid = tgconstrrelid) "
3380 " as tgconstrrelname "
3382 "where tgrelid = '%u'::oid",
3383 tbinfo->dobj.catId.oid);
3385 res = PQexec(g_conn, query->data);
3386 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3388 ntups = PQntuples(res);
3391 * We may have less triggers than recorded due to having ignored
3392 * foreign-key triggers
3394 if (ntups > tbinfo->ntrig)
3396 write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
3397 tbinfo->ntrig, tbinfo->dobj.name, ntups);
3400 i_tableoid = PQfnumber(res, "tableoid");
3401 i_oid = PQfnumber(res, "oid");
3402 i_tgname = PQfnumber(res, "tgname");
3403 i_tgfname = PQfnumber(res, "tgfname");
3404 i_tgtype = PQfnumber(res, "tgtype");
3405 i_tgnargs = PQfnumber(res, "tgnargs");
3406 i_tgargs = PQfnumber(res, "tgargs");
3407 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
3408 i_tgconstrname = PQfnumber(res, "tgconstrname");
3409 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
3410 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
3411 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
3412 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
3414 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
3416 for (j = 0; j < ntups; j++)
3418 tginfo[j].dobj.objType = DO_TRIGGER;
3419 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3420 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3421 AssignDumpId(&tginfo[j].dobj);
3422 tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
3423 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
3424 tginfo[j].tgtable = tbinfo;
3425 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
3426 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
3427 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
3428 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
3429 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
3430 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
3431 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
3433 if (tginfo[j].tgisconstraint)
3435 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
3436 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
3437 if (OidIsValid(tginfo[j].tgconstrrelid))
3439 if (PQgetisnull(res, j, i_tgconstrrelname))
3441 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
3442 tginfo[j].dobj.name, tbinfo->dobj.name,
3443 tginfo[j].tgconstrrelid);
3446 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
3449 tginfo[j].tgconstrrelname = NULL;
3453 tginfo[j].tgconstrname = NULL;
3454 tginfo[j].tgconstrrelid = InvalidOid;
3455 tginfo[j].tgconstrrelname = NULL;
3462 destroyPQExpBuffer(query);
3467 * get basic information about every procedural language in the system
3469 * numProcLangs is set to the number of langs read in
3471 * NB: this must run after getFuncs() because we assume we can do
3475 getProcLangs(int *numProcLangs)
3480 PQExpBuffer query = createPQExpBuffer();
3481 ProcLangInfo *planginfo;
3486 int i_lanplcallfoid;
3487 int i_lanvalidator = -1;
3490 /* Make sure we are in proper schema */
3491 selectSourceSchema("pg_catalog");
3493 if (g_fout->remoteVersion >= 70100)
3495 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
3501 appendPQExpBuffer(query, "SELECT "
3502 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
3503 "oid, * FROM pg_language "
3508 res = PQexec(g_conn, query->data);
3509 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3511 ntups = PQntuples(res);
3513 *numProcLangs = ntups;
3515 planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
3517 i_tableoid = PQfnumber(res, "tableoid");
3518 i_oid = PQfnumber(res, "oid");
3519 i_lanname = PQfnumber(res, "lanname");
3520 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
3521 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
3522 if (g_fout->remoteVersion >= 70300)
3524 i_lanvalidator = PQfnumber(res, "lanvalidator");
3525 i_lanacl = PQfnumber(res, "lanacl");
3528 for (i = 0; i < ntups; i++)
3530 planginfo[i].dobj.objType = DO_PROCLANG;
3531 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3532 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3533 AssignDumpId(&planginfo[i].dobj);
3535 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
3536 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
3537 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
3538 if (g_fout->remoteVersion >= 70300)
3540 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
3541 planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
3547 planginfo[i].lanvalidator = InvalidOid;
3548 planginfo[i].lanacl = strdup("{=U}");
3551 * We need to make a dependency to ensure the function will be
3552 * dumped first. (In 7.3 and later the regular dependency
3553 * mechanism will handle this for us.)
3555 funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
3557 addObjectDependency(&planginfo[i].dobj,
3558 funcInfo->dobj.dumpId);
3564 destroyPQExpBuffer(query);
3571 * get basic information about every cast in the system
3573 * numCasts is set to the number of casts read in
3576 getCasts(int *numCasts)
3581 PQExpBuffer query = createPQExpBuffer();
3590 /* Make sure we are in proper schema */
3591 selectSourceSchema("pg_catalog");
3593 if (g_fout->remoteVersion >= 70300)
3595 appendPQExpBuffer(query, "SELECT tableoid, oid, "
3596 "castsource, casttarget, castfunc, castcontext "
3597 "FROM pg_cast ORDER BY 3,4");
3601 appendPQExpBuffer(query, "SELECT 0 as tableoid, p.oid, "
3602 "t1.oid as castsource, t2.oid as casttarget, "
3603 "p.oid as castfunc, 'e' as castcontext "
3604 "FROM pg_type t1, pg_type t2, pg_proc p "
3605 "WHERE p.pronargs = 1 AND "
3606 "p.proargtypes[0] = t1.oid AND "
3607 "p.prorettype = t2.oid AND p.proname = t2.typname "
3611 res = PQexec(g_conn, query->data);
3612 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3614 ntups = PQntuples(res);
3618 castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
3620 i_tableoid = PQfnumber(res, "tableoid");
3621 i_oid = PQfnumber(res, "oid");
3622 i_castsource = PQfnumber(res, "castsource");
3623 i_casttarget = PQfnumber(res, "casttarget");
3624 i_castfunc = PQfnumber(res, "castfunc");
3625 i_castcontext = PQfnumber(res, "castcontext");
3627 for (i = 0; i < ntups; i++)
3629 PQExpBufferData namebuf;
3630 TypeInfo *sTypeInfo;
3631 TypeInfo *tTypeInfo;
3633 castinfo[i].dobj.objType = DO_CAST;
3634 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3635 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3636 AssignDumpId(&castinfo[i].dobj);
3637 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
3638 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
3639 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
3640 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
3643 * Try to name cast as concatenation of typnames. This is only
3644 * used for purposes of sorting. If we fail to find either type,
3645 * the name will be an empty string.
3647 initPQExpBuffer(&namebuf);
3648 sTypeInfo = findTypeByOid(castinfo[i].castsource);
3649 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
3650 if (sTypeInfo && tTypeInfo)
3651 appendPQExpBuffer(&namebuf, "%s %s",
3652 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
3653 castinfo[i].dobj.name = namebuf.data;
3655 if (OidIsValid(castinfo[i].castfunc))
3658 * We need to make a dependency to ensure the function will be
3659 * dumped first. (In 7.3 and later the regular dependency
3660 * mechanism will handle this for us.)
3664 funcInfo = findFuncByOid(castinfo[i].castfunc);
3666 addObjectDependency(&castinfo[i].dobj,
3667 funcInfo->dobj.dumpId);
3673 destroyPQExpBuffer(query);
3680 * for each interesting table, read info about its attributes
3681 * (names, types, default values, CHECK constraints, etc)
3683 * This is implemented in a very inefficient way right now, looping
3684 * through the tblinfo and doing a join per table to find the attrs and their
3685 * types. However, because we want type names and so forth to be named
3686 * relative to the schema of each table, we couldn't do it in just one
3687 * query. (Maybe one query per schema?)
3692 getTableAttrs(TableInfo *tblinfo, int numTables)
3697 PQExpBuffer q = createPQExpBuffer();
3702 int i_attstattarget;
3713 for (i = 0; i < numTables; i++)
3715 TableInfo *tbinfo = &tblinfo[i];
3717 /* Don't bother to collect info for sequences */
3718 if (tbinfo->relkind == RELKIND_SEQUENCE)
3721 /* Don't bother with uninteresting tables, either */
3722 if (!tbinfo->interesting)
3726 * Make sure we are in proper schema for this table; this allows
3727 * correct retrieval of formatted type names and default exprs
3729 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3731 /* find all the user attributes and their types */
3734 * we must read the attribute names in attribute number order!
3735 * because we will use the attnum to index into the attnames array
3736 * later. We actually ask to order by "attrelid, attnum" because
3737 * (at least up to 7.3) the planner is not smart enough to realize
3738 * it needn't re-sort the output of an indexscan on
3739 * pg_attribute_relid_attnum_index.
3742 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
3745 resetPQExpBuffer(q);
3747 if (g_fout->remoteVersion >= 70300)
3749 /* need left join here to not fail on dropped columns ... */
3750 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, "
3751 "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, "
3752 "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname "
3753 "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t "
3754 "on a.atttypid = t.oid "
3755 "where a.attrelid = '%u'::pg_catalog.oid "
3756 "and a.attnum > 0::pg_catalog.int2 "
3757 "order by a.attrelid, a.attnum",
3758 tbinfo->dobj.catId.oid);
3760 else if (g_fout->remoteVersion >= 70100)
3763 * attstattarget doesn't exist in 7.1. It does exist in 7.2,
3764 * but we don't dump it because we can't tell whether it's
3765 * been explicitly set or was just a default.
3767 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, "
3768 "a.attnotnull, a.atthasdef, false as attisdropped, false as attislocal, "
3769 "format_type(t.oid,a.atttypmod) as atttypname "
3770 "from pg_attribute a left join pg_type t "
3771 "on a.atttypid = t.oid "
3772 "where a.attrelid = '%u'::oid "
3773 "and a.attnum > 0::int2 "
3774 "order by a.attrelid, a.attnum",
3775 tbinfo->dobj.catId.oid);
3779 /* format_type not available before 7.1 */
3780 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, "
3781 "attnotnull, atthasdef, false as attisdropped, false as attislocal, "
3782 "(select typname from pg_type where oid = atttypid) as atttypname "
3783 "from pg_attribute a "
3784 "where attrelid = '%u'::oid "
3785 "and attnum > 0::int2 "
3786 "order by attrelid, attnum",
3787 tbinfo->dobj.catId.oid);
3790 res = PQexec(g_conn, q->data);
3791 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3793 ntups = PQntuples(res);
3795 i_attnum = PQfnumber(res, "attnum");
3796 i_attname = PQfnumber(res, "attname");
3797 i_atttypname = PQfnumber(res, "atttypname");
3798 i_atttypmod = PQfnumber(res, "atttypmod");
3799 i_attstattarget = PQfnumber(res, "attstattarget");
3800 i_attstorage = PQfnumber(res, "attstorage");
3801 i_typstorage = PQfnumber(res, "typstorage");
3802 i_attnotnull = PQfnumber(res, "attnotnull");
3803 i_atthasdef = PQfnumber(res, "atthasdef");
3804 i_attisdropped = PQfnumber(res, "attisdropped");
3805 i_attislocal = PQfnumber(res, "attislocal");
3807 tbinfo->numatts = ntups;
3808 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
3809 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
3810 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
3811 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
3812 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
3813 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
3814 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
3815 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
3816 tbinfo->attisserial = (bool *) malloc(ntups * sizeof(bool));
3817 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
3818 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
3819 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
3820 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
3821 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
3822 hasdefaults = false;
3824 for (j = 0; j < ntups; j++)
3826 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
3828 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
3832 tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
3833 tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
3834 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
3835 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
3836 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
3837 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
3838 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
3839 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
3840 tbinfo->attisserial[j] = false; /* fix below */
3841 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
3842 tbinfo->attrdefs[j] = NULL; /* fix below */
3843 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
3845 /* these flags will be set in flagInhAttrs() */
3846 tbinfo->inhAttrs[j] = false;
3847 tbinfo->inhAttrDef[j] = false;
3848 tbinfo->inhNotNull[j] = false;
3854 * Get info about column defaults
3858 AttrDefInfo *attrdefs;
3862 write_msg(NULL, "finding default expressions of table \"%s\"\n",
3865 resetPQExpBuffer(q);
3866 if (g_fout->remoteVersion >= 70300)
3868 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
3869 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
3870 "FROM pg_catalog.pg_attrdef "
3871 "WHERE adrelid = '%u'::pg_catalog.oid",
3872 tbinfo->dobj.catId.oid);
3874 else if (g_fout->remoteVersion >= 70200)
3876 /* 7.2 did not have OIDs in pg_attrdef */
3877 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, adnum, "
3878 "pg_get_expr(adbin, adrelid) AS adsrc "
3880 "WHERE adrelid = '%u'::oid",
3881 tbinfo->dobj.catId.oid);
3883 else if (g_fout->remoteVersion >= 70100)
3885 /* no pg_get_expr, so must rely on adsrc */
3886 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
3888 "WHERE adrelid = '%u'::oid",
3889 tbinfo->dobj.catId.oid);
3893 /* no pg_get_expr, no tableoid either */
3894 appendPQExpBuffer(q, "SELECT "
3895 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
3896 "oid, adnum, adsrc "
3898 "WHERE adrelid = '%u'::oid",
3899 tbinfo->dobj.catId.oid);
3901 res = PQexec(g_conn, q->data);
3902 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3904 numDefaults = PQntuples(res);
3905 attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
3907 for (j = 0; j < numDefaults; j++)
3911 attrdefs[j].dobj.objType = DO_ATTRDEF;
3912 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3913 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3914 AssignDumpId(&attrdefs[j].dobj);
3915 attrdefs[j].adtable = tbinfo;
3916 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
3917 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
3919 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
3920 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
3923 * Defaults on a VIEW must always be dumped as separate
3924 * ALTER TABLE commands. Defaults on regular tables are
3925 * dumped as part of the CREATE TABLE if possible. To
3926 * check if it's safe, we mark the default as needing to
3927 * appear before the CREATE.
3929 if (tbinfo->relkind == RELKIND_VIEW)
3931 attrdefs[j].separate = true;
3932 /* needed in case pre-7.3 DB: */
3933 addObjectDependency(&attrdefs[j].dobj,
3934 tbinfo->dobj.dumpId);
3938 attrdefs[j].separate = false;
3939 addObjectDependency(&tbinfo->dobj,
3940 attrdefs[j].dobj.dumpId);
3943 if (adnum <= 0 || adnum > ntups)
3945 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
3946 adnum, tbinfo->dobj.name);
3949 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
3955 * Get info about table CHECK constraints
3957 if (tbinfo->ncheck > 0)
3959 ConstraintInfo *constrs;
3963 write_msg(NULL, "finding check constraints for table \"%s\"\n",
3966 resetPQExpBuffer(q);
3967 if (g_fout->remoteVersion >= 70400)
3969 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3970 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3971 "FROM pg_catalog.pg_constraint "
3972 "WHERE conrelid = '%u'::pg_catalog.oid "
3973 " AND contype = 'c' "
3975 tbinfo->dobj.catId.oid);
3977 else if (g_fout->remoteVersion >= 70300)
3979 /* no pg_get_constraintdef, must use consrc */
3980 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3981 "'CHECK (' || consrc || ')' AS consrc "
3982 "FROM pg_catalog.pg_constraint "
3983 "WHERE conrelid = '%u'::pg_catalog.oid "
3984 " AND contype = 'c' "
3986 tbinfo->dobj.catId.oid);
3988 else if (g_fout->remoteVersion >= 70200)
3990 /* 7.2 did not have OIDs in pg_relcheck */
3991 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, "
3992 "rcname AS conname, "
3993 "'CHECK (' || rcsrc || ')' AS consrc "
3995 "WHERE rcrelid = '%u'::oid "
3997 tbinfo->dobj.catId.oid);
3999 else if (g_fout->remoteVersion >= 70100)
4001 appendPQExpBuffer(q, "SELECT tableoid, oid, "
4002 "rcname AS conname, "
4003 "'CHECK (' || rcsrc || ')' AS consrc "
4005 "WHERE rcrelid = '%u'::oid "
4007 tbinfo->dobj.catId.oid);
4011 /* no tableoid in 7.0 */
4012 appendPQExpBuffer(q, "SELECT "
4013 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
4014 "oid, rcname AS conname, "
4015 "'CHECK (' || rcsrc || ')' AS consrc "
4017 "WHERE rcrelid = '%u'::oid "
4019 tbinfo->dobj.catId.oid);
4021 res = PQexec(g_conn, q->data);
4022 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
4024 numConstrs = PQntuples(res);
4025 if (numConstrs != tbinfo->ncheck)
4027 write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
4028 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
4029 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
4033 constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
4034 tbinfo->checkexprs = constrs;
4036 for (j = 0; j < numConstrs; j++)
4038 constrs[j].dobj.objType = DO_CONSTRAINT;
4039 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
4040 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
4041 AssignDumpId(&constrs[j].dobj);
4042 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
4043 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
4044 constrs[j].contable = tbinfo;
4045 constrs[j].condomain = NULL;
4046 constrs[j].contype = 'c';
4047 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
4048 constrs[j].conindex = 0;
4049 constrs[j].coninherited = false;
4050 constrs[j].separate = false;
4052 * Mark the constraint as needing to appear before the
4053 * table --- this is so that any other dependencies of
4054 * the constraint will be emitted before we try to create
4057 addObjectDependency(&tbinfo->dobj,
4058 constrs[j].dobj.dumpId);
4061 * If the constraint is inherited, this will be detected
4062 * later. We also detect later if the constraint must be
4063 * split out from the table definition.
4070 * Check to see if any columns are serial columns. Our first
4071 * quick filter is that it must be integer or bigint with a
4072 * default. If so, we scan to see if we found a sequence linked
4073 * to this column. If we did, mark the column and sequence
4076 for (j = 0; j < ntups; j++)
4079 * Note assumption that format_type will show these types as
4080 * exactly "integer" and "bigint" regardless of schema path.
4081 * This is correct in 7.3 but needs to be watched.
4083 if (strcmp(tbinfo->atttypnames[j], "integer") != 0 &&
4084 strcmp(tbinfo->atttypnames[j], "bigint") != 0)
4086 if (tbinfo->attrdefs[j] == NULL)
4088 for (k = 0; k < numTables; k++)
4090 TableInfo *seqinfo = &tblinfo[k];
4092 if (OidIsValid(seqinfo->owning_tab) &&
4093 seqinfo->owning_tab == tbinfo->dobj.catId.oid &&
4094 seqinfo->owning_col == j + 1)
4097 * Found a match. Copy the table's interesting and
4098 * dumpable flags to the sequence.
4100 tbinfo->attisserial[j] = true;
4101 seqinfo->interesting = tbinfo->interesting;
4102 seqinfo->dump = tbinfo->dump;
4109 destroyPQExpBuffer(q);
4116 * This routine is used to dump any comments associated with the
4117 * object handed to this routine. The routine takes a constant character
4118 * string for the target part of the comment-creation command, plus
4119 * the namespace and owner of the object (for labeling the ArchiveEntry),
4120 * plus catalog ID and subid which are the lookup key for pg_description,
4121 * plus the dump ID for the object (for setting a dependency).
4122 * If a matching pg_description entry is found, it is dumped.
4124 * Note: although this routine takes a dumpId for dependency purposes,
4125 * that purpose is just to mark the dependency in the emitted dump file
4126 * for possible future use by pg_restore. We do NOT use it for determining
4127 * ordering of the comment in the dump file, because this routine is called
4128 * after dependency sorting occurs. This routine should be called just after
4129 * calling ArchiveEntry() for the specified object.
4132 dumpComment(Archive *fout, const char *target,
4133 const char *namespace, const char *owner,
4134 CatalogId catalogId, int subid, DumpId dumpId)
4136 CommentItem *comments;
4139 /* Comments are SCHEMA not data */
4143 /* Search for comments associated with catalogId, using table */
4144 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
4147 /* Is there one matching the subid? */
4148 while (ncomments > 0)
4150 if (comments->objsubid == subid)
4156 /* If a comment exists, build COMMENT ON statement */
4159 PQExpBuffer query = createPQExpBuffer();
4161 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
4162 appendStringLiteral(query, comments->descr, false);
4163 appendPQExpBuffer(query, ";\n");
4165 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4166 target, namespace, NULL, owner, false,
4167 "COMMENT", query->data, "", NULL,
4171 destroyPQExpBuffer(query);
4176 * dumpTableComment --
4178 * As above, but dump comments for both the specified table (or view)
4182 dumpTableComment(Archive *fout, TableInfo *tbinfo,
4183 const char *reltypename)
4185 CommentItem *comments;
4190 /* Comments are SCHEMA not data */
4194 /* Search for comments associated with relation, using table */
4195 ncomments = findComments(fout,
4196 tbinfo->dobj.catId.tableoid,
4197 tbinfo->dobj.catId.oid,
4200 /* If comments exist, build COMMENT ON statements */
4204 query = createPQExpBuffer();
4205 target = createPQExpBuffer();
4207 while (ncomments > 0)
4209 const char *descr = comments->descr;
4210 int objsubid = comments->objsubid;
4214 resetPQExpBuffer(target);
4215 appendPQExpBuffer(target, "%s %s", reltypename,
4216 fmtId(tbinfo->dobj.name));
4218 resetPQExpBuffer(query);
4219 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4220 appendStringLiteral(query, descr, false);
4221 appendPQExpBuffer(query, ";\n");
4223 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4225 tbinfo->dobj.namespace->dobj.name,
4228 false, "COMMENT", query->data, "", NULL,
4229 &(tbinfo->dobj.dumpId), 1,
4232 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
4234 resetPQExpBuffer(target);
4235 appendPQExpBuffer(target, "COLUMN %s.",
4236 fmtId(tbinfo->dobj.name));
4237 appendPQExpBuffer(target, "%s",
4238 fmtId(tbinfo->attnames[objsubid - 1]));
4240 resetPQExpBuffer(query);
4241 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4242 appendStringLiteral(query, descr, false);
4243 appendPQExpBuffer(query, ";\n");
4245 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4247 tbinfo->dobj.namespace->dobj.name,
4250 false, "COMMENT", query->data, "", NULL,
4251 &(tbinfo->dobj.dumpId), 1,
4259 destroyPQExpBuffer(query);
4260 destroyPQExpBuffer(target);
4266 * Find the comment(s), if any, associated with the given object. All the
4267 * objsubid values associated with the given classoid/objoid are found with
4271 findComments(Archive *fout, Oid classoid, Oid objoid,
4272 CommentItem **items)
4274 /* static storage for table of comments */
4275 static CommentItem *comments = NULL;
4276 static int ncomments = -1;
4278 CommentItem *middle = NULL;
4283 /* Get comments if we didn't already */
4285 ncomments = collectComments(fout, &comments);
4288 * Pre-7.2, pg_description does not contain classoid, so
4289 * collectComments just stores a zero. If there's a collision on
4290 * object OID, well, you get duplicate comments.
4292 if (fout->remoteVersion < 70200)
4296 * Do binary search to find some item matching the object.
4299 high = &comments[ncomments - 1];
4302 middle = low + (high - low) / 2;
4304 if (classoid < middle->classoid)
4306 else if (classoid > middle->classoid)
4308 else if (objoid < middle->objoid)
4310 else if (objoid > middle->objoid)
4313 break; /* found a match */
4316 if (low > high) /* no matches */
4323 * Now determine how many items match the object. The search loop
4324 * invariant still holds: only items between low and high inclusive
4328 while (middle > low)
4330 if (classoid != middle[-1].classoid ||
4331 objoid != middle[-1].objoid)
4340 while (middle <= high)
4342 if (classoid != middle->classoid ||
4343 objoid != middle->objoid)
4353 * collectComments --
4355 * Construct a table of all comments available for database objects.
4356 * We used to do per-object queries for the comments, but it's much faster
4357 * to pull them all over at once, and on most databases the memory cost
4360 * The table is sorted by classoid/objid/objsubid for speed in lookup.
4363 collectComments(Archive *fout, CommentItem **items)
4373 CommentItem *comments;
4376 * Note we do NOT change source schema here; preserve the caller's
4380 query = createPQExpBuffer();
4382 if (fout->remoteVersion >= 70300)
4384 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4385 "FROM pg_catalog.pg_description "
4386 "ORDER BY classoid, objoid, objsubid");
4388 else if (fout->remoteVersion >= 70200)
4390 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4391 "FROM pg_description "
4392 "ORDER BY classoid, objoid, objsubid");
4396 /* Note: this will fail to find attribute comments in pre-7.2... */
4397 appendPQExpBuffer(query, "SELECT description, 0 as classoid, objoid, 0 as objsubid "
4398 "FROM pg_description "
4402 res = PQexec(g_conn, query->data);
4403 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4405 /* Construct lookup table containing OIDs in numeric form */
4407 i_description = PQfnumber(res, "description");
4408 i_classoid = PQfnumber(res, "classoid");
4409 i_objoid = PQfnumber(res, "objoid");
4410 i_objsubid = PQfnumber(res, "objsubid");
4412 ntups = PQntuples(res);
4414 comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
4416 for (i = 0; i < ntups; i++)
4418 comments[i].descr = PQgetvalue(res, i, i_description);
4419 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
4420 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
4421 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
4424 /* Do NOT free the PGresult since we are keeping pointers into it */
4425 destroyPQExpBuffer(query);
4432 * dumpDumpableObject
4434 * This routine and its subsidiaries are responsible for creating
4435 * ArchiveEntries (TOC objects) for each object to be dumped.
4438 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
4440 switch (dobj->objType)
4443 dumpNamespace(fout, (NamespaceInfo *) dobj);
4446 dumpType(fout, (TypeInfo *) dobj);
4449 dumpFunc(fout, (FuncInfo *) dobj);
4452 dumpAgg(fout, (AggInfo *) dobj);
4455 dumpOpr(fout, (OprInfo *) dobj);
4458 dumpOpclass(fout, (OpclassInfo *) dobj);
4461 dumpConversion(fout, (ConvInfo *) dobj);
4464 dumpTable(fout, (TableInfo *) dobj);
4467 dumpAttrDef(fout, (AttrDefInfo *) dobj);
4470 dumpIndex(fout, (IndxInfo *) dobj);
4473 dumpRule(fout, (RuleInfo *) dobj);
4476 dumpTrigger(fout, (TriggerInfo *) dobj);
4479 dumpConstraint(fout, (ConstraintInfo *) dobj);
4481 case DO_FK_CONSTRAINT:
4482 dumpConstraint(fout, (ConstraintInfo *) dobj);
4485 dumpProcLang(fout, (ProcLangInfo *) dobj);
4488 dumpCast(fout, (CastInfo *) dobj);
4491 dumpTableData(fout, (TableDataInfo *) dobj);
4494 /* table rowtypes are never dumped separately */
4497 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4498 dobj->name, NULL, NULL, "",
4499 false, "BLOBS", "", "", NULL,
4503 case DO_BLOB_COMMENTS:
4504 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4505 dobj->name, NULL, NULL, "",
4506 false, "BLOB COMMENTS", "", "", NULL,
4508 dumpBlobComments, NULL);
4515 * writes out to fout the queries to recreate a user-defined namespace
4518 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
4524 /* skip if not to be dumped */
4525 if (!nspinfo->dump || dataOnly)
4528 /* don't dump dummy namespace from pre-7.3 source */
4529 if (strlen(nspinfo->dobj.name) == 0)
4532 q = createPQExpBuffer();
4533 delq = createPQExpBuffer();
4535 qnspname = strdup(fmtId(nspinfo->dobj.name));
4537 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
4539 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
4541 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
4545 false, "SCHEMA", q->data, delq->data, NULL,
4546 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
4549 /* Dump Schema Comments */
4550 resetPQExpBuffer(q);
4551 appendPQExpBuffer(q, "SCHEMA %s", qnspname);
4552 dumpComment(fout, q->data,
4553 NULL, nspinfo->usename,
4554 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
4556 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
4557 qnspname, nspinfo->dobj.name, NULL,
4558 nspinfo->usename, nspinfo->nspacl);
4562 destroyPQExpBuffer(q);
4563 destroyPQExpBuffer(delq);
4568 * writes out to fout the queries to recreate a user-defined type
4571 dumpType(Archive *fout, TypeInfo *tinfo)
4573 /* Dump only types in dumpable namespaces */
4574 if (!tinfo->dobj.namespace->dump || dataOnly)
4577 /* skip complex types, except for standalone composite types */
4578 /* (note: this test should now be unnecessary) */
4579 if (OidIsValid(tinfo->typrelid) && tinfo->typrelkind != 'c')
4582 /* skip undefined placeholder types */
4583 if (!tinfo->isDefined)
4586 /* skip all array types that start w/ underscore */
4587 if ((tinfo->dobj.name[0] == '_') &&
4588 OidIsValid(tinfo->typelem))
4591 /* Dump out in proper style */
4592 if (tinfo->typtype == 'b')
4593 dumpBaseType(fout, tinfo);
4594 else if (tinfo->typtype == 'd')
4595 dumpDomain(fout, tinfo);
4596 else if (tinfo->typtype == 'c')
4597 dumpCompositeType(fout, tinfo);
4602 * writes out to fout the queries to recreate a user-defined base type
4605 dumpBaseType(Archive *fout, TypeInfo *tinfo)
4607 PQExpBuffer q = createPQExpBuffer();
4608 PQExpBuffer delq = createPQExpBuffer();
4609 PQExpBuffer query = createPQExpBuffer();
4629 /* Set proper schema search path so regproc references list correctly */
4630 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4632 /* Fetch type-specific details */
4633 if (fout->remoteVersion >= 80000)
4635 appendPQExpBuffer(query, "SELECT typlen, "
4636 "typinput, typoutput, typreceive, typsend, "
4638 "typinput::pg_catalog.oid as typinputoid, "
4639 "typoutput::pg_catalog.oid as typoutputoid, "
4640 "typreceive::pg_catalog.oid as typreceiveoid, "
4641 "typsend::pg_catalog.oid as typsendoid, "
4642 "typanalyze::pg_catalog.oid as typanalyzeoid, "
4643 "typdelim, typdefault, typbyval, typalign, "
4645 "FROM pg_catalog.pg_type "
4646 "WHERE oid = '%u'::pg_catalog.oid",
4647 tinfo->dobj.catId.oid);
4649 else if (fout->remoteVersion >= 70400)
4651 appendPQExpBuffer(query, "SELECT typlen, "
4652 "typinput, typoutput, typreceive, typsend, "
4653 "'-' as typanalyze, "
4654 "typinput::pg_catalog.oid as typinputoid, "
4655 "typoutput::pg_catalog.oid as typoutputoid, "
4656 "typreceive::pg_catalog.oid as typreceiveoid, "
4657 "typsend::pg_catalog.oid as typsendoid, "
4658 "0 as typanalyzeoid, "
4659 "typdelim, typdefault, typbyval, typalign, "
4661 "FROM pg_catalog.pg_type "
4662 "WHERE oid = '%u'::pg_catalog.oid",
4663 tinfo->dobj.catId.oid);
4665 else if (fout->remoteVersion >= 70300)
4667 appendPQExpBuffer(query, "SELECT typlen, "
4668 "typinput, typoutput, "
4669 "'-' as typreceive, '-' as typsend, "
4670 "'-' as typanalyze, "
4671 "typinput::pg_catalog.oid as typinputoid, "
4672 "typoutput::pg_catalog.oid as typoutputoid, "
4673 "0 as typreceiveoid, 0 as typsendoid, "
4674 "0 as typanalyzeoid, "
4675 "typdelim, typdefault, typbyval, typalign, "
4677 "FROM pg_catalog.pg_type "
4678 "WHERE oid = '%u'::pg_catalog.oid",
4679 tinfo->dobj.catId.oid);
4681 else if (fout->remoteVersion >= 70100)
4684 * Note: although pre-7.3 catalogs contain typreceive and typsend,
4685 * ignore them because they are not right.
4687 appendPQExpBuffer(query, "SELECT typlen, "
4688 "typinput, typoutput, "
4689 "'-' as typreceive, '-' as typsend, "
4690 "'-' as typanalyze, "
4691 "typinput::oid as typinputoid, "
4692 "typoutput::oid as typoutputoid, "
4693 "0 as typreceiveoid, 0 as typsendoid, "
4694 "0 as typanalyzeoid, "
4695 "typdelim, typdefault, typbyval, typalign, "
4698 "WHERE oid = '%u'::oid",
4699 tinfo->dobj.catId.oid);
4703 appendPQExpBuffer(query, "SELECT typlen, "
4704 "typinput, typoutput, "
4705 "'-' as typreceive, '-' as typsend, "
4706 "'-' as typanalyze, "
4707 "typinput::oid as typinputoid, "
4708 "typoutput::oid as typoutputoid, "
4709 "0 as typreceiveoid, 0 as typsendoid, "
4710 "0 as typanalyzeoid, "
4711 "typdelim, typdefault, typbyval, typalign, "
4712 "'p'::char as typstorage "
4714 "WHERE oid = '%u'::oid",
4715 tinfo->dobj.catId.oid);
4718 res = PQexec(g_conn, query->data);
4719 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4721 /* Expecting a single result only */
4722 ntups = PQntuples(res);
4725 write_msg(NULL, "Got %d rows instead of one from: %s",
4726 ntups, query->data);
4730 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
4731 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
4732 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
4733 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
4734 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
4735 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
4736 typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
4737 typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
4738 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
4739 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
4740 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
4741 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
4742 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4745 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4746 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
4747 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
4748 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
4751 * DROP must be fully qualified in case same name appears in
4754 appendPQExpBuffer(delq, "DROP TYPE %s.",
4755 fmtId(tinfo->dobj.namespace->dobj.name));
4756 appendPQExpBuffer(delq, "%s CASCADE;\n",
4757 fmtId(tinfo->dobj.name));
4759 appendPQExpBuffer(q,
4760 "CREATE TYPE %s (\n"
4761 " INTERNALLENGTH = %s",
4762 fmtId(tinfo->dobj.name),
4763 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
4765 if (fout->remoteVersion >= 70300)
4767 /* regproc result is correctly quoted as of 7.3 */
4768 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
4769 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
4770 if (OidIsValid(typreceiveoid))
4771 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
4772 if (OidIsValid(typsendoid))
4773 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
4774 if (OidIsValid(typanalyzeoid))
4775 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
4779 /* regproc delivers an unquoted name before 7.3 */
4780 /* cannot combine these because fmtId uses static result area */
4781 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
4782 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
4783 /* no chance that receive/send/analyze need be printed */
4786 if (typdefault != NULL)
4788 appendPQExpBuffer(q, ",\n DEFAULT = ");
4789 appendStringLiteral(q, typdefault, true);
4796 /* reselect schema in case changed by function dump */
4797 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4798 elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
4799 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
4803 if (typdelim && strcmp(typdelim, ",") != 0)
4805 appendPQExpBuffer(q, ",\n DELIMITER = ");
4806 appendStringLiteral(q, typdelim, true);
4809 if (strcmp(typalign, "c") == 0)
4810 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
4811 else if (strcmp(typalign, "s") == 0)
4812 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
4813 else if (strcmp(typalign, "i") == 0)
4814 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
4815 else if (strcmp(typalign, "d") == 0)
4816 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
4818 if (strcmp(typstorage, "p") == 0)
4819 appendPQExpBuffer(q, ",\n STORAGE = plain");
4820 else if (strcmp(typstorage, "e") == 0)
4821 appendPQExpBuffer(q, ",\n STORAGE = external");
4822 else if (strcmp(typstorage, "x") == 0)
4823 appendPQExpBuffer(q, ",\n STORAGE = extended");
4824 else if (strcmp(typstorage, "m") == 0)
4825 appendPQExpBuffer(q, ",\n STORAGE = main");
4827 if (strcmp(typbyval, "t") == 0)
4828 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
4830 appendPQExpBuffer(q, "\n);\n");
4832 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4834 tinfo->dobj.namespace->dobj.name,
4836 tinfo->usename, false,
4837 "TYPE", q->data, delq->data, NULL,
4838 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4841 /* Dump Type Comments */
4842 resetPQExpBuffer(q);
4844 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4845 dumpComment(fout, q->data,
4846 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4847 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4850 destroyPQExpBuffer(q);
4851 destroyPQExpBuffer(delq);
4852 destroyPQExpBuffer(query);
4857 * writes out to fout the queries to recreate a user-defined domain
4860 dumpDomain(Archive *fout, TypeInfo *tinfo)
4862 PQExpBuffer q = createPQExpBuffer();
4863 PQExpBuffer delq = createPQExpBuffer();
4864 PQExpBuffer query = createPQExpBuffer();
4872 /* Set proper schema search path so type references list correctly */
4873 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4875 /* Fetch domain specific details */
4876 /* We assume here that remoteVersion must be at least 70300 */
4877 appendPQExpBuffer(query, "SELECT typnotnull, "
4878 "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
4880 "FROM pg_catalog.pg_type "
4881 "WHERE oid = '%u'::pg_catalog.oid",
4882 tinfo->dobj.catId.oid);
4884 res = PQexec(g_conn, query->data);
4885 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4887 /* Expecting a single result only */
4888 ntups = PQntuples(res);
4891 write_msg(NULL, "Got %d rows instead of one from: %s",
4892 ntups, query->data);
4896 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
4897 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
4898 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4901 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4903 appendPQExpBuffer(q,
4904 "CREATE DOMAIN %s AS %s",
4905 fmtId(tinfo->dobj.name),
4908 if (typnotnull[0] == 't')
4909 appendPQExpBuffer(q, " NOT NULL");
4912 appendPQExpBuffer(q, " DEFAULT %s", typdefault);
4917 * Add any CHECK constraints for the domain
4919 for (i = 0; i < tinfo->nDomChecks; i++)
4921 ConstraintInfo *domcheck = &(tinfo->domChecks[i]);
4923 if (!domcheck->separate)
4924 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
4925 fmtId(domcheck->dobj.name), domcheck->condef);
4928 appendPQExpBuffer(q, ";\n");
4931 * DROP must be fully qualified in case same name appears in
4934 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
4935 fmtId(tinfo->dobj.namespace->dobj.name));
4936 appendPQExpBuffer(delq, "%s;\n",
4937 fmtId(tinfo->dobj.name));
4939 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4941 tinfo->dobj.namespace->dobj.name,
4943 tinfo->usename, false,
4944 "DOMAIN", q->data, delq->data, NULL,
4945 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4948 /* Dump Domain Comments */
4949 resetPQExpBuffer(q);
4951 appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->dobj.name));
4952 dumpComment(fout, q->data,
4953 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4954 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4956 destroyPQExpBuffer(q);
4957 destroyPQExpBuffer(delq);
4958 destroyPQExpBuffer(query);
4963 * writes out to fout the queries to recreate a user-defined stand-alone
4967 dumpCompositeType(Archive *fout, TypeInfo *tinfo)
4969 PQExpBuffer q = createPQExpBuffer();
4970 PQExpBuffer delq = createPQExpBuffer();
4971 PQExpBuffer query = createPQExpBuffer();
4978 /* Set proper schema search path so type references list correctly */
4979 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4981 /* Fetch type specific details */
4982 /* We assume here that remoteVersion must be at least 70300 */
4984 appendPQExpBuffer(query, "SELECT a.attname, "
4985 "pg_catalog.format_type(a.atttypid, a.atttypmod) as atttypdefn "
4986 "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
4987 "WHERE t.oid = '%u'::pg_catalog.oid "
4988 "AND a.attrelid = t.typrelid "
4989 "AND NOT a.attisdropped "
4990 "ORDER BY a.attnum ",
4991 tinfo->dobj.catId.oid);
4993 res = PQexec(g_conn, query->data);
4994 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4996 /* Expecting at least a single result */
4997 ntups = PQntuples(res);
5000 write_msg(NULL, "query yielded no rows: %s\n", query->data);
5004 i_attname = PQfnumber(res, "attname");
5005 i_atttypdefn = PQfnumber(res, "atttypdefn");
5007 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
5008 fmtId(tinfo->dobj.name));
5010 for (i = 0; i < ntups; i++)
5015 attname = PQgetvalue(res, i, i_attname);
5016 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
5018 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
5020 appendPQExpBuffer(q, ",");
5022 appendPQExpBuffer(q, "\n);\n");
5025 * DROP must be fully qualified in case same name appears in
5028 appendPQExpBuffer(delq, "DROP TYPE %s.",
5029 fmtId(tinfo->dobj.namespace->dobj.name));
5030 appendPQExpBuffer(delq, "%s;\n",
5031 fmtId(tinfo->dobj.name));
5033 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
5035 tinfo->dobj.namespace->dobj.name,
5037 tinfo->usename, false,
5038 "TYPE", q->data, delq->data, NULL,
5039 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
5043 /* Dump Type Comments */
5044 resetPQExpBuffer(q);
5046 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
5047 dumpComment(fout, q->data,
5048 tinfo->dobj.namespace->dobj.name, tinfo->usename,
5049 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
5052 destroyPQExpBuffer(q);
5053 destroyPQExpBuffer(delq);
5054 destroyPQExpBuffer(query);
5059 * writes out to fout the queries to recreate a user-defined
5060 * procedural language
5063 dumpProcLang(Archive *fout, ProcLangInfo *plang)
5069 FuncInfo *validatorInfo = NULL;
5075 * We dump PLs iff their underlying call handler functions have been
5076 * marked as language functions (or have a non-system OID in
5077 * pre-7.3 databases). We treat the PL itself as being in
5078 * the underlying function's namespace, though it isn't really. This
5079 * avoids searchpath problems for the HANDLER clause.
5083 funcInfo = findFuncByOid(plang->lanplcallfoid);
5084 if (funcInfo == NULL)
5087 if (!funcInfo->isProlangFunc && !funcInfo->dobj.namespace->dump)
5090 if (OidIsValid(plang->lanvalidator))
5092 validatorInfo = findFuncByOid(plang->lanvalidator);
5093 if (validatorInfo == NULL)
5097 defqry = createPQExpBuffer();
5098 delqry = createPQExpBuffer();
5100 qlanname = strdup(fmtId(plang->dobj.name));
5102 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
5105 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
5106 plang->lanpltrusted ? "TRUSTED " : "",
5108 appendPQExpBuffer(defqry, " HANDLER %s",
5109 fmtId(funcInfo->dobj.name));
5110 if (OidIsValid(plang->lanvalidator))
5112 appendPQExpBuffer(defqry, " VALIDATOR ");
5113 /* Cope with possibility that validator is in different schema */
5114 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
5115 appendPQExpBuffer(defqry, "%s.",
5116 fmtId(validatorInfo->dobj.namespace->dobj.name));
5117 appendPQExpBuffer(defqry, "%s",
5118 fmtId(validatorInfo->dobj.name));
5120 appendPQExpBuffer(defqry, ";\n");
5122 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
5124 funcInfo->dobj.namespace->dobj.name, NULL, "",
5125 false, "PROCEDURAL LANGUAGE",
5126 defqry->data, delqry->data, NULL,
5127 plang->dobj.dependencies, plang->dobj.nDeps,
5130 /* Dump Proc Lang Comments */
5131 resetPQExpBuffer(defqry);
5133 appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
5134 dumpComment(fout, defqry->data,
5136 plang->dobj.catId, 0, plang->dobj.dumpId);
5138 if (plang->lanpltrusted)
5139 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
5140 qlanname, plang->dobj.name,
5141 funcInfo->dobj.namespace->dobj.name,
5142 NULL, plang->lanacl);
5146 destroyPQExpBuffer(defqry);
5147 destroyPQExpBuffer(delqry);
5151 * format_function_arguments: generate function name and argument list
5153 * The argument type names are qualified if needed. The function name
5154 * is never qualified.
5156 * Any or all of allargtypes, argmodes, argnames may be NULL.
5159 format_function_arguments(FuncInfo *finfo, int nallargs,
5167 initPQExpBuffer(&fn);
5168 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5169 for (j = 0; j < nallargs; j++)
5173 const char *argmode;
5174 const char *argname;
5176 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
5177 typname = getFormattedTypeName(typid, zeroAsOpaque);
5181 switch (argmodes[j][0])
5193 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
5201 argname = argnames ? argnames[j] : (char *) NULL;
5202 if (argname && argname[0] == '\0')
5205 appendPQExpBuffer(&fn, "%s%s%s%s%s",
5206 (j > 0) ? ", " : "",
5208 argname ? fmtId(argname) : "",
5213 appendPQExpBuffer(&fn, ")");
5218 * format_function_signature: generate function name and argument list
5220 * This is like format_function_arguments except that only a minimal
5221 * list of input argument types is generated; this is sufficient to
5222 * reference the function, but not to define it.
5224 * If honor_quotes is false then the function name is never quoted.
5225 * This is appropriate for use in TOC tags, but not in SQL commands.
5228 format_function_signature(FuncInfo *finfo, bool honor_quotes)
5233 initPQExpBuffer(&fn);
5235 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5237 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
5238 for (j = 0; j < finfo->nargs; j++)
5242 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
5244 appendPQExpBuffer(&fn, "%s%s",
5245 (j > 0) ? ", " : "",
5249 appendPQExpBuffer(&fn, ")");
5256 * dump out one function
5259 dumpFunc(Archive *fout, FuncInfo *finfo)
5272 char *proallargtypes;
5281 char **allargtypes = NULL;
5282 char **argmodes = NULL;
5283 char **argnames = NULL;
5285 /* Dump only funcs in dumpable namespaces, or needed language handlers */
5286 if ((!finfo->isProlangFunc && !finfo->dobj.namespace->dump) || dataOnly)
5290 query = createPQExpBuffer();
5291 q = createPQExpBuffer();
5292 delqry = createPQExpBuffer();
5293 asPart = createPQExpBuffer();
5295 /* Set proper schema search path so type references list correctly */
5296 selectSourceSchema(finfo->dobj.namespace->dobj.name);
5298 /* Fetch function-specific details */
5299 if (g_fout->remoteVersion >= 80100)
5301 appendPQExpBuffer(query,
5302 "SELECT proretset, prosrc, probin, "
5303 "proallargtypes, proargmodes, proargnames, "
5304 "provolatile, proisstrict, prosecdef, "
5305 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5306 "FROM pg_catalog.pg_proc "
5307 "WHERE oid = '%u'::pg_catalog.oid",
5308 finfo->dobj.catId.oid);
5310 else if (g_fout->remoteVersion >= 80000)
5312 appendPQExpBuffer(query,
5313 "SELECT proretset, prosrc, probin, "
5314 "null as proallargtypes, "
5315 "null as proargmodes, "
5317 "provolatile, proisstrict, prosecdef, "
5318 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5319 "FROM pg_catalog.pg_proc "
5320 "WHERE oid = '%u'::pg_catalog.oid",
5321 finfo->dobj.catId.oid);
5323 else if (g_fout->remoteVersion >= 70300)
5325 appendPQExpBuffer(query,
5326 "SELECT proretset, prosrc, probin, "
5327 "null as proallargtypes, "
5328 "null as proargmodes, "
5329 "null as proargnames, "
5330 "provolatile, proisstrict, prosecdef, "
5331 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5332 "FROM pg_catalog.pg_proc "
5333 "WHERE oid = '%u'::pg_catalog.oid",
5334 finfo->dobj.catId.oid);
5336 else if (g_fout->remoteVersion >= 70100)
5338 appendPQExpBuffer(query,
5339 "SELECT proretset, prosrc, probin, "
5340 "null as proallargtypes, "
5341 "null as proargmodes, "
5342 "null as proargnames, "
5343 "case when proiscachable then 'i' else 'v' end as provolatile, "
5345 "'f'::boolean as prosecdef, "
5346 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5348 "WHERE oid = '%u'::oid",
5349 finfo->dobj.catId.oid);
5353 appendPQExpBuffer(query,
5354 "SELECT proretset, prosrc, probin, "
5355 "null as proallargtypes, "
5356 "null as proargmodes, "
5357 "null as proargnames, "
5358 "case when proiscachable then 'i' else 'v' end as provolatile, "
5359 "'f'::boolean as proisstrict, "
5360 "'f'::boolean as prosecdef, "
5361 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5363 "WHERE oid = '%u'::oid",
5364 finfo->dobj.catId.oid);
5367 res = PQexec(g_conn, query->data);
5368 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5370 /* Expecting a single result only */
5371 ntups = PQntuples(res);
5374 write_msg(NULL, "Got %d rows instead of one from: %s",
5375 ntups, query->data);
5379 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
5380 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
5381 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
5382 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
5383 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
5384 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
5385 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
5386 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
5387 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
5388 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
5391 * See backend/commands/define.c for details of how the 'AS' clause is
5394 if (strcmp(probin, "-") != 0)
5396 appendPQExpBuffer(asPart, "AS ");
5397 appendStringLiteral(asPart, probin, true);
5398 if (strcmp(prosrc, "-") != 0)
5400 appendPQExpBuffer(asPart, ", ");
5403 * where we have bin, use dollar quoting if allowed and src
5404 * contains quote or backslash; else use regular quoting.
5406 if (disable_dollar_quoting)
5407 appendStringLiteral(asPart, prosrc, false);
5409 appendStringLiteralDQOpt(asPart, prosrc, false, NULL);
5414 if (strcmp(prosrc, "-") != 0)
5416 appendPQExpBuffer(asPart, "AS ");
5417 /* with no bin, dollar quote src unconditionally if allowed */
5418 if (disable_dollar_quoting)
5419 appendStringLiteral(asPart, prosrc, false);
5421 appendStringLiteralDQ(asPart, prosrc, NULL);
5425 nallargs = finfo->nargs; /* unless we learn different from allargs */
5427 if (proallargtypes && *proallargtypes)
5431 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
5432 nitems < finfo->nargs)
5434 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
5443 if (proargmodes && *proargmodes)
5447 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
5450 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
5457 if (proargnames && *proargnames)
5461 if (!parsePGArray(proargnames, &argnames, &nitems) ||
5464 write_msg(NULL, "WARNING: could not parse proargnames array\n");
5471 funcsig = format_function_arguments(finfo, nallargs, allargtypes,
5472 argmodes, argnames);
5473 funcsig_tag = format_function_signature(finfo, false);
5476 * DROP must be fully qualified in case same name appears in
5479 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
5480 fmtId(finfo->dobj.namespace->dobj.name),
5483 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
5485 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
5486 appendPQExpBuffer(q, "RETURNS %s%s\n %s\n LANGUAGE %s",
5487 (proretset[0] == 't') ? "SETOF " : "",
5494 if (provolatile[0] != PROVOLATILE_VOLATILE)
5496 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
5497 appendPQExpBuffer(q, " IMMUTABLE");
5498 else if (provolatile[0] == PROVOLATILE_STABLE)
5499 appendPQExpBuffer(q, " STABLE");
5500 else if (provolatile[0] != PROVOLATILE_VOLATILE)
5502 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
5508 if (proisstrict[0] == 't')
5509 appendPQExpBuffer(q, " STRICT");
5511 if (prosecdef[0] == 't')
5512 appendPQExpBuffer(q, " SECURITY DEFINER");
5514 appendPQExpBuffer(q, ";\n");
5516 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
5518 finfo->dobj.namespace->dobj.name,
5520 finfo->usename, false,
5521 "FUNCTION", q->data, delqry->data, NULL,
5522 finfo->dobj.dependencies, finfo->dobj.nDeps,
5525 /* Dump Function Comments */
5526 resetPQExpBuffer(q);
5527 appendPQExpBuffer(q, "FUNCTION %s", funcsig);
5528 dumpComment(fout, q->data,
5529 finfo->dobj.namespace->dobj.name, finfo->usename,
5530 finfo->dobj.catId, 0, finfo->dobj.dumpId);
5532 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
5533 funcsig, funcsig_tag,
5534 finfo->dobj.namespace->dobj.name,
5535 finfo->usename, finfo->proacl);
5539 destroyPQExpBuffer(query);
5540 destroyPQExpBuffer(q);
5541 destroyPQExpBuffer(delqry);
5542 destroyPQExpBuffer(asPart);
5555 * Dump a user-defined cast
5558 dumpCast(Archive *fout, CastInfo *cast)
5562 PQExpBuffer castsig;
5563 FuncInfo *funcInfo = NULL;
5564 TypeInfo *sourceInfo;
5565 TypeInfo *targetInfo;
5570 if (OidIsValid(cast->castfunc))
5572 funcInfo = findFuncByOid(cast->castfunc);
5573 if (funcInfo == NULL)
5578 * As per discussion we dump casts if one or more of the underlying
5579 * objects (the conversion function and the two data types) are not
5580 * builtin AND if all of the non-builtin objects namespaces are
5581 * included in the dump. Builtin meaning, the namespace name does not
5584 sourceInfo = findTypeByOid(cast->castsource);
5585 targetInfo = findTypeByOid(cast->casttarget);
5587 if (sourceInfo == NULL || targetInfo == NULL)
5591 * Skip this cast if all objects are from pg_
5593 if ((funcInfo == NULL ||
5594 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
5595 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
5596 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
5600 * Skip cast if function isn't from pg_ and that namespace is not
5604 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5605 !funcInfo->dobj.namespace->dump)
5609 * Same for the Source type
5611 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5612 !sourceInfo->dobj.namespace->dump)
5616 * and the target type.
5618 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5619 !targetInfo->dobj.namespace->dump)
5622 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
5623 selectSourceSchema("pg_catalog");
5625 defqry = createPQExpBuffer();
5626 delqry = createPQExpBuffer();
5627 castsig = createPQExpBuffer();
5629 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
5630 getFormattedTypeName(cast->castsource, zeroAsNone),
5631 getFormattedTypeName(cast->casttarget, zeroAsNone));
5633 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
5634 getFormattedTypeName(cast->castsource, zeroAsNone),
5635 getFormattedTypeName(cast->casttarget, zeroAsNone));
5637 if (!OidIsValid(cast->castfunc))
5638 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
5642 * Always qualify the function name, in case it is not in
5643 * pg_catalog schema (format_function_signature won't qualify it).
5645 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
5646 fmtId(funcInfo->dobj.namespace->dobj.name));
5647 appendPQExpBuffer(defqry, "%s",
5648 format_function_signature(funcInfo, true));
5651 if (cast->castcontext == 'a')
5652 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
5653 else if (cast->castcontext == 'i')
5654 appendPQExpBuffer(defqry, " AS IMPLICIT");
5655 appendPQExpBuffer(defqry, ";\n");
5657 appendPQExpBuffer(castsig, "CAST (%s AS %s)",
5658 getFormattedTypeName(cast->castsource, zeroAsNone),
5659 getFormattedTypeName(cast->casttarget, zeroAsNone));
5661 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
5663 "pg_catalog", NULL, "",
5664 false, "CAST", defqry->data, delqry->data, NULL,
5665 cast->dobj.dependencies, cast->dobj.nDeps,
5668 /* Dump Cast Comments */
5669 resetPQExpBuffer(defqry);
5670 appendPQExpBuffer(defqry, "CAST (%s AS %s)",
5671 getFormattedTypeName(cast->castsource, zeroAsNone),
5672 getFormattedTypeName(cast->casttarget, zeroAsNone));
5673 dumpComment(fout, defqry->data,
5675 cast->dobj.catId, 0, cast->dobj.dumpId);
5677 destroyPQExpBuffer(defqry);
5678 destroyPQExpBuffer(delqry);
5679 destroyPQExpBuffer(castsig);
5684 * write out a single operator definition
5687 dumpOpr(Archive *fout, OprInfo *oprinfo)
5693 PQExpBuffer details;
5724 /* Dump only operators in dumpable namespaces */
5725 if (!oprinfo->dobj.namespace->dump || dataOnly)
5729 * some operators are invalid because they were the result of user
5730 * defining operators before commutators exist
5732 if (!OidIsValid(oprinfo->oprcode))
5735 query = createPQExpBuffer();
5736 q = createPQExpBuffer();
5737 delq = createPQExpBuffer();
5738 oprid = createPQExpBuffer();
5739 details = createPQExpBuffer();
5741 /* Make sure we are in proper schema so regoperator works correctly */
5742 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
5744 if (g_fout->remoteVersion >= 70300)
5746 appendPQExpBuffer(query, "SELECT oprkind, "
5747 "oprcode::pg_catalog.regprocedure, "
5748 "oprleft::pg_catalog.regtype, "
5749 "oprright::pg_catalog.regtype, "
5750 "oprcom::pg_catalog.regoperator, "
5751 "oprnegate::pg_catalog.regoperator, "
5752 "oprrest::pg_catalog.regprocedure, "
5753 "oprjoin::pg_catalog.regprocedure, "
5755 "oprlsortop::pg_catalog.regoperator, "
5756 "oprrsortop::pg_catalog.regoperator, "
5757 "oprltcmpop::pg_catalog.regoperator, "
5758 "oprgtcmpop::pg_catalog.regoperator "
5759 "from pg_catalog.pg_operator "
5760 "where oid = '%u'::pg_catalog.oid",
5761 oprinfo->dobj.catId.oid);
5763 else if (g_fout->remoteVersion >= 70100)
5765 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5766 "CASE WHEN oprleft = 0 THEN '-' "
5767 "ELSE format_type(oprleft, NULL) END as oprleft, "
5768 "CASE WHEN oprright = 0 THEN '-' "
5769 "ELSE format_type(oprright, NULL) END as oprright, "
5770 "oprcom, oprnegate, oprrest, oprjoin, "
5771 "oprcanhash, oprlsortop, oprrsortop, "
5772 "0 as oprltcmpop, 0 as oprgtcmpop "
5774 "where oid = '%u'::oid",
5775 oprinfo->dobj.catId.oid);
5779 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5780 "CASE WHEN oprleft = 0 THEN '-'::name "
5781 "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
5782 "CASE WHEN oprright = 0 THEN '-'::name "
5783 "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
5784 "oprcom, oprnegate, oprrest, oprjoin, "
5785 "oprcanhash, oprlsortop, oprrsortop, "
5786 "0 as oprltcmpop, 0 as oprgtcmpop "
5788 "where oid = '%u'::oid",
5789 oprinfo->dobj.catId.oid);
5792 res = PQexec(g_conn, query->data);
5793 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5795 /* Expecting a single result only */
5796 ntups = PQntuples(res);
5799 write_msg(NULL, "Got %d rows instead of one from: %s",
5800 ntups, query->data);
5804 i_oprkind = PQfnumber(res, "oprkind");
5805 i_oprcode = PQfnumber(res, "oprcode");
5806 i_oprleft = PQfnumber(res, "oprleft");
5807 i_oprright = PQfnumber(res, "oprright");
5808 i_oprcom = PQfnumber(res, "oprcom");
5809 i_oprnegate = PQfnumber(res, "oprnegate");
5810 i_oprrest = PQfnumber(res, "oprrest");
5811 i_oprjoin = PQfnumber(res, "oprjoin");
5812 i_oprcanhash = PQfnumber(res, "oprcanhash");
5813 i_oprlsortop = PQfnumber(res, "oprlsortop");
5814 i_oprrsortop = PQfnumber(res, "oprrsortop");
5815 i_oprltcmpop = PQfnumber(res, "oprltcmpop");
5816 i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");
5818 oprkind = PQgetvalue(res, 0, i_oprkind);
5819 oprcode = PQgetvalue(res, 0, i_oprcode);
5820 oprleft = PQgetvalue(res, 0, i_oprleft);
5821 oprright = PQgetvalue(res, 0, i_oprright);
5822 oprcom = PQgetvalue(res, 0, i_oprcom);
5823 oprnegate = PQgetvalue(res, 0, i_oprnegate);
5824 oprrest = PQgetvalue(res, 0, i_oprrest);
5825 oprjoin = PQgetvalue(res, 0, i_oprjoin);
5826 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
5827 oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
5828 oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
5829 oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
5830 oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);
5832 appendPQExpBuffer(details, " PROCEDURE = %s",
5833 convertRegProcReference(oprcode));
5835 appendPQExpBuffer(oprid, "%s (",
5836 oprinfo->dobj.name);
5839 * right unary means there's a left arg and left unary means there's a
5842 if (strcmp(oprkind, "r") == 0 ||
5843 strcmp(oprkind, "b") == 0)
5845 if (g_fout->remoteVersion >= 70100)
5848 name = fmtId(oprleft);
5849 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
5850 appendPQExpBuffer(oprid, "%s", name);
5853 appendPQExpBuffer(oprid, "NONE");
5855 if (strcmp(oprkind, "l") == 0 ||
5856 strcmp(oprkind, "b") == 0)
5858 if (g_fout->remoteVersion >= 70100)
5861 name = fmtId(oprright);
5862 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
5863 appendPQExpBuffer(oprid, ", %s)", name);
5866 appendPQExpBuffer(oprid, ", NONE)");
5868 name = convertOperatorReference(oprcom);
5870 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
5872 name = convertOperatorReference(oprnegate);
5874 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
5876 if (strcmp(oprcanhash, "t") == 0)
5877 appendPQExpBuffer(details, ",\n HASHES");
5879 name = convertRegProcReference(oprrest);
5881 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
5883 name = convertRegProcReference(oprjoin);
5885 appendPQExpBuffer(details, ",\n JOIN = %s", name);
5887 name = convertOperatorReference(oprlsortop);
5889 appendPQExpBuffer(details, ",\n SORT1 = %s", name);
5891 name = convertOperatorReference(oprrsortop);
5893 appendPQExpBuffer(details, ",\n SORT2 = %s", name);
5895 name = convertOperatorReference(oprltcmpop);
5897 appendPQExpBuffer(details, ",\n LTCMP = %s", name);
5899 name = convertOperatorReference(oprgtcmpop);
5901 appendPQExpBuffer(details, ",\n GTCMP = %s", name);
5904 * DROP must be fully qualified in case same name appears in
5907 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
5908 fmtId(oprinfo->dobj.namespace->dobj.name),
5911 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
5912 oprinfo->dobj.name, details->data);
5914 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
5916 oprinfo->dobj.namespace->dobj.name,
5919 false, "OPERATOR", q->data, delq->data, NULL,
5920 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
5923 /* Dump Operator Comments */
5924 resetPQExpBuffer(q);
5925 appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
5926 dumpComment(fout, q->data,
5927 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5928 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
5932 destroyPQExpBuffer(query);
5933 destroyPQExpBuffer(q);
5934 destroyPQExpBuffer(delq);
5935 destroyPQExpBuffer(oprid);
5936 destroyPQExpBuffer(details);
5940 * Convert a function reference obtained from pg_operator
5942 * Returns what to print, or NULL if function references is InvalidOid
5944 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
5945 * argument-types part. In prior versions, the input is a REGPROC display.
5948 convertRegProcReference(const char *proc)
5950 /* In all cases "-" means a null reference */
5951 if (strcmp(proc, "-") == 0)
5954 if (g_fout->remoteVersion >= 70300)
5960 name = strdup(proc);
5961 /* find non-double-quoted left paren */
5963 for (paren = name; *paren; paren++)
5965 if (*paren == '(' && !inquote)
5976 /* REGPROC before 7.3 does not quote its result */
5981 * Convert an operator cross-reference obtained from pg_operator
5983 * Returns what to print, or NULL to print nothing
5985 * In 7.3 the input is a REGOPERATOR display; we have to strip the
5986 * argument-types part. In prior versions, the input is just a
5987 * numeric OID, which we search our operator list for.
5990 convertOperatorReference(const char *opr)
5994 /* In all cases "0" means a null reference */
5995 if (strcmp(opr, "0") == 0)
5998 if (g_fout->remoteVersion >= 70300)
6005 /* find non-double-quoted left paren */
6007 for (paren = name; *paren; paren++)
6009 if (*paren == '(' && !inquote)
6020 oprInfo = findOprByOid(atooid(opr));
6021 if (oprInfo == NULL)
6023 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
6027 return oprInfo->dobj.name;
6032 * write out a single operator class definition
6035 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
6063 /* Dump only opclasses in dumpable namespaces */
6064 if (!opcinfo->dobj.namespace->dump || dataOnly)
6068 * XXX currently we do not implement dumping of operator classes from
6069 * pre-7.3 databases. This could be done but it seems not worth the
6072 if (g_fout->remoteVersion < 70300)
6075 query = createPQExpBuffer();
6076 q = createPQExpBuffer();
6077 delq = createPQExpBuffer();
6079 /* Make sure we are in proper schema so regoperator works correctly */
6080 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
6082 /* Get additional fields from the pg_opclass row */
6083 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
6084 "opckeytype::pg_catalog.regtype, "
6086 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
6087 "FROM pg_catalog.pg_opclass "
6088 "WHERE oid = '%u'::pg_catalog.oid",
6089 opcinfo->dobj.catId.oid);
6091 res = PQexec(g_conn, query->data);
6092 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6094 /* Expecting a single result only */
6095 ntups = PQntuples(res);
6098 write_msg(NULL, "Got %d rows instead of one from: %s",
6099 ntups, query->data);
6103 i_opcintype = PQfnumber(res, "opcintype");
6104 i_opckeytype = PQfnumber(res, "opckeytype");
6105 i_opcdefault = PQfnumber(res, "opcdefault");
6106 i_amname = PQfnumber(res, "amname");
6108 opcintype = PQgetvalue(res, 0, i_opcintype);
6109 opckeytype = PQgetvalue(res, 0, i_opckeytype);
6110 opcdefault = PQgetvalue(res, 0, i_opcdefault);
6111 /* amname will still be needed after we PQclear res */
6112 amname = strdup(PQgetvalue(res, 0, i_amname));
6115 * DROP must be fully qualified in case same name appears in
6118 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
6119 fmtId(opcinfo->dobj.namespace->dobj.name));
6120 appendPQExpBuffer(delq, ".%s",
6121 fmtId(opcinfo->dobj.name));
6122 appendPQExpBuffer(delq, " USING %s;\n",
6125 /* Build the fixed portion of the CREATE command */
6126 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
6127 fmtId(opcinfo->dobj.name));
6128 if (strcmp(opcdefault, "t") == 0)
6129 appendPQExpBuffer(q, "DEFAULT ");
6130 appendPQExpBuffer(q, "FOR TYPE %s USING %s AS\n ",
6136 if (strcmp(opckeytype, "-") != 0)
6138 appendPQExpBuffer(q, "STORAGE %s",
6146 * Now fetch and print the OPERATOR entries (pg_amop rows).
6148 resetPQExpBuffer(query);
6150 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
6151 "amopopr::pg_catalog.regoperator "
6152 "FROM pg_catalog.pg_amop "
6153 "WHERE amopclaid = '%u'::pg_catalog.oid "
6154 "ORDER BY amopstrategy",
6155 opcinfo->dobj.catId.oid);
6157 res = PQexec(g_conn, query->data);
6158 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6160 ntups = PQntuples(res);
6162 i_amopstrategy = PQfnumber(res, "amopstrategy");
6163 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
6164 i_amopopr = PQfnumber(res, "amopopr");
6166 for (i = 0; i < ntups; i++)
6168 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
6169 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
6170 amopopr = PQgetvalue(res, i, i_amopopr);
6173 appendPQExpBuffer(q, " ,\n ");
6175 appendPQExpBuffer(q, "OPERATOR %s %s",
6176 amopstrategy, amopopr);
6177 if (strcmp(amopreqcheck, "t") == 0)
6178 appendPQExpBuffer(q, " RECHECK");
6186 * Now fetch and print the FUNCTION entries (pg_amproc rows).
6188 resetPQExpBuffer(query);
6190 appendPQExpBuffer(query, "SELECT amprocnum, "
6191 "amproc::pg_catalog.regprocedure "
6192 "FROM pg_catalog.pg_amproc "
6193 "WHERE amopclaid = '%u'::pg_catalog.oid "
6194 "ORDER BY amprocnum",
6195 opcinfo->dobj.catId.oid);
6197 res = PQexec(g_conn, query->data);
6198 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6200 ntups = PQntuples(res);
6202 i_amprocnum = PQfnumber(res, "amprocnum");
6203 i_amproc = PQfnumber(res, "amproc");
6205 for (i = 0; i < ntups; i++)
6207 amprocnum = PQgetvalue(res, i, i_amprocnum);
6208 amproc = PQgetvalue(res, i, i_amproc);
6211 appendPQExpBuffer(q, " ,\n ");
6213 appendPQExpBuffer(q, "FUNCTION %s %s",
6221 appendPQExpBuffer(q, ";\n");
6223 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
6225 opcinfo->dobj.namespace->dobj.name,
6228 false, "OPERATOR CLASS", q->data, delq->data, NULL,
6229 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
6232 /* Dump Operator Class Comments */
6233 resetPQExpBuffer(q);
6234 appendPQExpBuffer(q, "OPERATOR CLASS %s",
6235 fmtId(opcinfo->dobj.name));
6236 appendPQExpBuffer(q, " USING %s",
6238 dumpComment(fout, q->data,
6239 NULL, opcinfo->usename,
6240 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
6243 destroyPQExpBuffer(query);
6244 destroyPQExpBuffer(q);
6245 destroyPQExpBuffer(delq);
6250 * write out a single conversion definition
6253 dumpConversion(Archive *fout, ConvInfo *convinfo)
6258 PQExpBuffer details;
6262 int i_conforencoding;
6263 int i_contoencoding;
6266 const char *conname;
6267 const char *conforencoding;
6268 const char *contoencoding;
6269 const char *conproc;
6272 /* Dump only conversions in dumpable namespaces */
6273 if (!convinfo->dobj.namespace->dump || dataOnly)
6276 query = createPQExpBuffer();
6277 q = createPQExpBuffer();
6278 delq = createPQExpBuffer();
6279 details = createPQExpBuffer();
6281 /* Make sure we are in proper schema */
6282 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
6284 /* Get conversion-specific details */
6285 appendPQExpBuffer(query, "SELECT conname, "
6286 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
6287 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
6288 "conproc, condefault "
6289 "FROM pg_catalog.pg_conversion c "
6290 "WHERE c.oid = '%u'::pg_catalog.oid",
6291 convinfo->dobj.catId.oid);
6293 res = PQexec(g_conn, query->data);
6294 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6296 /* Expecting a single result only */
6297 ntups = PQntuples(res);
6300 write_msg(NULL, "Got %d rows instead of one from: %s",
6301 ntups, query->data);
6305 i_conname = PQfnumber(res, "conname");
6306 i_conforencoding = PQfnumber(res, "conforencoding");
6307 i_contoencoding = PQfnumber(res, "contoencoding");
6308 i_conproc = PQfnumber(res, "conproc");
6309 i_condefault = PQfnumber(res, "condefault");
6311 conname = PQgetvalue(res, 0, i_conname);
6312 conforencoding = PQgetvalue(res, 0, i_conforencoding);
6313 contoencoding = PQgetvalue(res, 0, i_contoencoding);
6314 conproc = PQgetvalue(res, 0, i_conproc);
6315 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
6318 * DROP must be fully qualified in case same name appears in
6321 appendPQExpBuffer(delq, "DROP CONVERSION %s",
6322 fmtId(convinfo->dobj.namespace->dobj.name));
6323 appendPQExpBuffer(delq, ".%s;\n",
6324 fmtId(convinfo->dobj.name));
6326 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
6327 (condefault) ? "DEFAULT " : "",
6328 fmtId(convinfo->dobj.name));
6329 appendStringLiteral(q, conforencoding, true);
6330 appendPQExpBuffer(q, " TO ");
6331 appendStringLiteral(q, contoencoding, true);
6332 /* regproc is automatically quoted in 7.3 and above */
6333 appendPQExpBuffer(q, " FROM %s;\n", conproc);
6335 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
6336 convinfo->dobj.name,
6337 convinfo->dobj.namespace->dobj.name,
6340 false, "CONVERSION", q->data, delq->data, NULL,
6341 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
6344 /* Dump Conversion Comments */
6345 resetPQExpBuffer(q);
6346 appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
6347 dumpComment(fout, q->data,
6348 convinfo->dobj.namespace->dobj.name, convinfo->usename,
6349 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
6353 destroyPQExpBuffer(query);
6354 destroyPQExpBuffer(q);
6355 destroyPQExpBuffer(delq);
6356 destroyPQExpBuffer(details);
6360 * format_aggregate_signature: generate aggregate name and argument list
6362 * The argument type names are qualified if needed. The aggregate name
6363 * is never qualified.
6366 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
6368 PQExpBufferData buf;
6370 initPQExpBuffer(&buf);
6372 appendPQExpBuffer(&buf, "%s",
6373 fmtId(agginfo->aggfn.dobj.name));
6375 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
6377 /* If using regtype or format_type, fmtbasetype is already quoted */
6378 if (fout->remoteVersion >= 70100)
6380 if (agginfo->anybasetype)
6381 appendPQExpBuffer(&buf, "(*)");
6383 appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
6387 if (agginfo->anybasetype)
6388 appendPQExpBuffer(&buf, "(*)");
6390 appendPQExpBuffer(&buf, "(%s)",
6391 fmtId(agginfo->fmtbasetype));
6399 * write out a single aggregate definition
6402 dumpAgg(Archive *fout, AggInfo *agginfo)
6407 PQExpBuffer details;
6420 const char *aggtransfn;
6421 const char *aggfinalfn;
6422 const char *aggsortop;
6423 const char *aggtranstype;
6424 const char *agginitval;
6427 /* Dump only aggs in dumpable namespaces */
6428 if (!agginfo->aggfn.dobj.namespace->dump || dataOnly)
6431 query = createPQExpBuffer();
6432 q = createPQExpBuffer();
6433 delq = createPQExpBuffer();
6434 details = createPQExpBuffer();
6436 /* Make sure we are in proper schema */
6437 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
6439 /* Get aggregate-specific details */
6440 if (g_fout->remoteVersion >= 80100)
6442 appendPQExpBuffer(query, "SELECT aggtransfn, "
6443 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6444 "aggsortop::pg_catalog.regoperator, "
6446 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6447 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6448 "'t'::boolean as convertok "
6449 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6450 "where a.aggfnoid = p.oid "
6451 "and p.oid = '%u'::pg_catalog.oid",
6452 agginfo->aggfn.dobj.catId.oid);
6454 else if (g_fout->remoteVersion >= 70300)
6456 appendPQExpBuffer(query, "SELECT aggtransfn, "
6457 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6460 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6461 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6462 "'t'::boolean as convertok "
6463 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6464 "where a.aggfnoid = p.oid "
6465 "and p.oid = '%u'::pg_catalog.oid",
6466 agginfo->aggfn.dobj.catId.oid);
6468 else if (g_fout->remoteVersion >= 70100)
6470 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
6471 "format_type(aggtranstype, NULL) as aggtranstype, "
6474 "aggbasetype = 0 as anybasetype, "
6475 "CASE WHEN aggbasetype = 0 THEN '-' "
6476 "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
6477 "'t'::boolean as convertok "
6478 "from pg_aggregate "
6479 "where oid = '%u'::oid",
6480 agginfo->aggfn.dobj.catId.oid);
6484 appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
6486 "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
6488 "agginitval1 as agginitval, "
6489 "aggbasetype = 0 as anybasetype, "
6490 "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
6491 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
6492 "from pg_aggregate "
6493 "where oid = '%u'::oid",
6494 agginfo->aggfn.dobj.catId.oid);
6497 res = PQexec(g_conn, query->data);
6498 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6500 /* Expecting a single result only */
6501 ntups = PQntuples(res);
6504 write_msg(NULL, "Got %d rows instead of one from: %s",
6505 ntups, query->data);
6509 i_aggtransfn = PQfnumber(res, "aggtransfn");
6510 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
6511 i_aggsortop = PQfnumber(res, "aggsortop");
6512 i_aggtranstype = PQfnumber(res, "aggtranstype");
6513 i_agginitval = PQfnumber(res, "agginitval");
6514 i_anybasetype = PQfnumber(res, "anybasetype");
6515 i_fmtbasetype = PQfnumber(res, "fmtbasetype");
6516 i_convertok = PQfnumber(res, "convertok");
6518 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
6519 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
6520 aggsortop = PQgetvalue(res, 0, i_aggsortop);
6521 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
6522 agginitval = PQgetvalue(res, 0, i_agginitval);
6523 /* we save anybasetype for format_aggregate_signature */
6524 agginfo->anybasetype = (PQgetvalue(res, 0, i_anybasetype)[0] == 't');
6525 /* we save fmtbasetype for format_aggregate_signature */
6526 agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
6527 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
6529 aggsig = format_aggregate_signature(agginfo, fout, true);
6530 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
6534 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
6539 if (g_fout->remoteVersion >= 70300)
6541 /* If using 7.3's regproc or regtype, data is already quoted */
6542 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6543 agginfo->anybasetype ? "'any'" :
6544 agginfo->fmtbasetype,
6548 else if (g_fout->remoteVersion >= 70100)
6550 /* format_type quotes, regproc does not */
6551 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6552 agginfo->anybasetype ? "'any'" :
6553 agginfo->fmtbasetype,
6559 /* need quotes all around */
6560 appendPQExpBuffer(details, " BASETYPE = %s,\n",
6561 agginfo->anybasetype ? "'any'" :
6562 fmtId(agginfo->fmtbasetype));
6563 appendPQExpBuffer(details, " SFUNC = %s,\n",
6565 appendPQExpBuffer(details, " STYPE = %s",
6566 fmtId(aggtranstype));
6569 if (!PQgetisnull(res, 0, i_agginitval))
6571 appendPQExpBuffer(details, ",\n INITCOND = ");
6572 appendStringLiteral(details, agginitval, true);
6575 if (strcmp(aggfinalfn, "-") != 0)
6577 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
6581 aggsortop = convertOperatorReference(aggsortop);
6584 appendPQExpBuffer(details, ",\n SORTOP = %s",
6589 * DROP must be fully qualified in case same name appears in
6592 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
6593 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
6596 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
6597 fmtId(agginfo->aggfn.dobj.name),
6600 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6602 agginfo->aggfn.dobj.namespace->dobj.name,
6604 agginfo->aggfn.usename,
6605 false, "AGGREGATE", q->data, delq->data, NULL,
6606 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
6609 /* Dump Aggregate Comments */
6610 resetPQExpBuffer(q);
6611 appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
6612 dumpComment(fout, q->data,
6613 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6614 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
6617 * Since there is no GRANT ON AGGREGATE syntax, we have to make the
6618 * ACL command look like a function's GRANT; in particular this
6619 * affects the syntax for aggregates on ANY.
6624 aggsig = format_function_signature(&agginfo->aggfn, true);
6625 aggsig_tag = format_function_signature(&agginfo->aggfn, false);
6627 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6630 agginfo->aggfn.dobj.namespace->dobj.name,
6631 agginfo->aggfn.usename, agginfo->aggfn.proacl);
6638 destroyPQExpBuffer(query);
6639 destroyPQExpBuffer(q);
6640 destroyPQExpBuffer(delq);
6641 destroyPQExpBuffer(details);
6646 * Write out grant/revoke information
6648 * 'objCatId' is the catalog ID of the underlying object.
6649 * 'objDumpId' is the dump ID of the underlying object.
6650 * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA.
6651 * 'name' is the formatted name of the object. Must be quoted etc. already.
6652 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
6653 * 'nspname' is the namespace the object is in (NULL if none).
6654 * 'owner' is the owner, NULL if there is no owner (for languages).
6655 * 'acls' is the string read out of the fooacl system catalog field;
6656 * it will be parsed here.
6660 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
6661 const char *type, const char *name,
6662 const char *tag, const char *nspname, const char *owner,
6667 /* Do nothing if ACL dump is not enabled */
6668 if (dataOnly || aclsSkip)
6671 sql = createPQExpBuffer();
6673 if (!buildACLCommands(name, type, acls, owner, fout->remoteVersion, sql))
6675 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
6681 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6685 false, "ACL", sql->data, "", NULL,
6689 destroyPQExpBuffer(sql);
6694 * write out to fout the declarations (not data) of a user-defined table
6697 dumpTable(Archive *fout, TableInfo *tbinfo)
6703 if (tbinfo->relkind == RELKIND_SEQUENCE)
6704 dumpSequence(fout, tbinfo);
6706 dumpTableSchema(fout, tbinfo);
6708 /* Handle the ACL here */
6709 namecopy = strdup(fmtId(tbinfo->dobj.name));
6710 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
6711 namecopy, tbinfo->dobj.name,
6712 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6720 * write the declaration (not data) of one user-defined table or view
6723 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
6725 PQExpBuffer query = createPQExpBuffer();
6726 PQExpBuffer q = createPQExpBuffer();
6727 PQExpBuffer delq = createPQExpBuffer();
6730 TableInfo **parents;
6731 int actual_atts; /* number of attrs in this CREATE statment */
6737 /* Make sure we are in proper schema */
6738 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
6740 /* Is it a table or a view? */
6741 if (tbinfo->relkind == RELKIND_VIEW)
6745 reltypename = "VIEW";
6747 /* Fetch the view definition */
6748 if (g_fout->remoteVersion >= 70300)
6750 /* Beginning in 7.3, viewname is not unique; rely on OID */
6751 appendPQExpBuffer(query,
6752 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) as viewdef",
6753 tbinfo->dobj.catId.oid);
6757 appendPQExpBuffer(query, "SELECT definition as viewdef "
6758 " from pg_views where viewname = ");
6759 appendStringLiteral(query, tbinfo->dobj.name, true);
6760 appendPQExpBuffer(query, ";");
6763 res = PQexec(g_conn, query->data);
6764 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6766 if (PQntuples(res) != 1)
6768 if (PQntuples(res) < 1)
6769 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
6772 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
6777 viewdef = PQgetvalue(res, 0, 0);
6779 if (strlen(viewdef) == 0)
6781 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
6787 * DROP must be fully qualified in case same name appears in
6790 appendPQExpBuffer(delq, "DROP VIEW %s.",
6791 fmtId(tbinfo->dobj.namespace->dobj.name));
6792 appendPQExpBuffer(delq, "%s;\n",
6793 fmtId(tbinfo->dobj.name));
6795 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
6796 fmtId(tbinfo->dobj.name), viewdef);
6802 reltypename = "TABLE";
6803 numParents = tbinfo->numParents;
6804 parents = tbinfo->parents;
6807 * DROP must be fully qualified in case same name appears in
6810 appendPQExpBuffer(delq, "DROP TABLE %s.",
6811 fmtId(tbinfo->dobj.namespace->dobj.name));
6812 appendPQExpBuffer(delq, "%s;\n",
6813 fmtId(tbinfo->dobj.name));
6815 appendPQExpBuffer(q, "CREATE TABLE %s (",
6816 fmtId(tbinfo->dobj.name));
6818 for (j = 0; j < tbinfo->numatts; j++)
6820 /* Is this one of the table's own attrs, and not dropped ? */
6821 if (!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j])
6823 /* Format properly if not first attr */
6824 if (actual_atts > 0)
6825 appendPQExpBuffer(q, ",");
6826 appendPQExpBuffer(q, "\n ");
6828 /* Attribute name */
6829 appendPQExpBuffer(q, "%s ",
6830 fmtId(tbinfo->attnames[j]));
6832 /* Attribute type */
6833 if (g_fout->remoteVersion >= 70100)
6835 char *typname = tbinfo->atttypnames[j];
6837 if (tbinfo->attisserial[j])
6839 if (strcmp(typname, "integer") == 0)
6841 else if (strcmp(typname, "bigint") == 0)
6842 typname = "bigserial";
6844 appendPQExpBuffer(q, "%s", typname);
6848 /* If no format_type, fake it */
6849 appendPQExpBuffer(q, "%s",
6850 myFormatType(tbinfo->atttypnames[j],
6851 tbinfo->atttypmod[j]));
6855 * Default value --- suppress if inherited, serial, or to
6856 * be printed separately.
6858 if (tbinfo->attrdefs[j] != NULL &&
6859 !tbinfo->inhAttrDef[j] &&
6860 !tbinfo->attisserial[j] &&
6861 !tbinfo->attrdefs[j]->separate)
6862 appendPQExpBuffer(q, " DEFAULT %s",
6863 tbinfo->attrdefs[j]->adef_expr);
6866 * Not Null constraint --- suppress if inherited
6868 * Note: we could suppress this for serial columns since
6869 * SERIAL implies NOT NULL. We choose not to for forward
6870 * compatibility, since there has been some talk of making
6871 * SERIAL not imply NOT NULL, in which case the explicit
6872 * specification would be needed.
6874 if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
6875 appendPQExpBuffer(q, " NOT NULL");
6882 * Add non-inherited CHECK constraints, if any.
6884 for (j = 0; j < tbinfo->ncheck; j++)
6886 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
6888 if (constr->coninherited || constr->separate)
6891 if (actual_atts > 0)
6892 appendPQExpBuffer(q, ",\n ");
6894 appendPQExpBuffer(q, "CONSTRAINT %s ",
6895 fmtId(constr->dobj.name));
6896 appendPQExpBuffer(q, "%s", constr->condef);
6901 appendPQExpBuffer(q, "\n)");
6905 appendPQExpBuffer(q, "\nINHERITS (");
6906 for (k = 0; k < numParents; k++)
6908 TableInfo *parentRel = parents[k];
6911 appendPQExpBuffer(q, ", ");
6912 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
6913 appendPQExpBuffer(q, "%s.",
6914 fmtId(parentRel->dobj.namespace->dobj.name));
6915 appendPQExpBuffer(q, "%s",
6916 fmtId(parentRel->dobj.name));
6918 appendPQExpBuffer(q, ")");
6921 appendPQExpBuffer(q, ";\n");
6923 /* Loop dumping statistics and storage statements */
6924 for (j = 0; j < tbinfo->numatts; j++)
6927 * Dump per-column statistics information. We only issue an
6928 * ALTER TABLE statement if the attstattarget entry for this
6929 * column is non-negative (i.e. it's not the default value)
6931 if (tbinfo->attstattarget[j] >= 0 &&
6932 !tbinfo->attisdropped[j])
6934 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6935 fmtId(tbinfo->dobj.name));
6936 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6937 fmtId(tbinfo->attnames[j]));
6938 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
6939 tbinfo->attstattarget[j]);
6943 * Dump per-column storage information. The statement is only
6944 * dumped if the storage has been changed from the type's
6947 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
6949 switch (tbinfo->attstorage[j])
6955 storage = "EXTERNAL";
6961 storage = "EXTENDED";
6968 * Only dump the statement if it's a storage type we
6971 if (storage != NULL)
6973 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6974 fmtId(tbinfo->dobj.name));
6975 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6976 fmtId(tbinfo->attnames[j]));
6977 appendPQExpBuffer(q, "SET STORAGE %s;\n",
6984 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
6986 tbinfo->dobj.namespace->dobj.name,
6987 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
6989 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
6990 reltypename, q->data, delq->data, NULL,
6991 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
6994 /* Dump Table Comments */
6995 dumpTableComment(fout, tbinfo, reltypename);
6997 /* Dump comments on inlined table constraints */
6998 for (j = 0; j < tbinfo->ncheck; j++)
7000 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
7002 if (constr->coninherited || constr->separate)
7005 dumpTableConstraintComment(fout, constr);
7008 destroyPQExpBuffer(query);
7009 destroyPQExpBuffer(q);
7010 destroyPQExpBuffer(delq);
7014 * dumpAttrDef --- dump an attribute's default-value declaration
7017 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
7019 TableInfo *tbinfo = adinfo->adtable;
7020 int adnum = adinfo->adnum;
7024 /* Only print it if "separate" mode is selected */
7025 if (!tbinfo->dump || !adinfo->separate || dataOnly)
7028 /* Don't print inherited or serial defaults, either */
7029 if (tbinfo->inhAttrDef[adnum - 1] || tbinfo->attisserial[adnum - 1])
7032 q = createPQExpBuffer();
7033 delq = createPQExpBuffer();
7035 appendPQExpBuffer(q, "ALTER TABLE %s ",
7036 fmtId(tbinfo->dobj.name));
7037 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
7038 fmtId(tbinfo->attnames[adnum - 1]),
7042 * DROP must be fully qualified in case same name appears in
7045 appendPQExpBuffer(delq, "ALTER TABLE %s.",
7046 fmtId(tbinfo->dobj.namespace->dobj.name));
7047 appendPQExpBuffer(delq, "%s ",
7048 fmtId(tbinfo->dobj.name));
7049 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
7050 fmtId(tbinfo->attnames[adnum - 1]));
7052 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
7053 tbinfo->attnames[adnum - 1],
7054 tbinfo->dobj.namespace->dobj.name,
7057 false, "DEFAULT", q->data, delq->data, NULL,
7058 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
7061 destroyPQExpBuffer(q);
7062 destroyPQExpBuffer(delq);
7066 * getAttrName: extract the correct name for an attribute
7068 * The array tblInfo->attnames[] only provides names of user attributes;
7069 * if a system attribute number is supplied, we have to fake it.
7070 * We also do a little bit of bounds checking for safety's sake.
7073 getAttrName(int attrnum, TableInfo *tblInfo)
7075 if (attrnum > 0 && attrnum <= tblInfo->numatts)
7076 return tblInfo->attnames[attrnum - 1];
7079 case SelfItemPointerAttributeNumber:
7081 case ObjectIdAttributeNumber:
7083 case MinTransactionIdAttributeNumber:
7085 case MinCommandIdAttributeNumber:
7087 case MaxTransactionIdAttributeNumber:
7089 case MaxCommandIdAttributeNumber:
7091 case TableOidAttributeNumber:
7094 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
7095 attrnum, tblInfo->dobj.name);
7097 return NULL; /* keep compiler quiet */
7102 * write out to fout a user-defined index
7105 dumpIndex(Archive *fout, IndxInfo *indxinfo)
7107 TableInfo *tbinfo = indxinfo->indextable;
7114 q = createPQExpBuffer();
7115 delq = createPQExpBuffer();
7118 * If there's an associated constraint, don't dump the index per se,
7119 * but do dump any comment for it. (This is safe because dependency
7120 * ordering will have ensured the constraint is emitted first.)
7122 if (indxinfo->indexconstraint == 0)
7124 /* Plain secondary index */
7125 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
7127 /* If the index is clustered, we need to record that. */
7128 if (indxinfo->indisclustered)
7130 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
7131 fmtId(tbinfo->dobj.name));
7132 appendPQExpBuffer(q, " ON %s;\n",
7133 fmtId(indxinfo->dobj.name));
7137 * DROP must be fully qualified in case same name appears in
7140 appendPQExpBuffer(delq, "DROP INDEX %s.",
7141 fmtId(tbinfo->dobj.namespace->dobj.name));
7142 appendPQExpBuffer(delq, "%s;\n",
7143 fmtId(indxinfo->dobj.name));
7145 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
7146 indxinfo->dobj.name,
7147 tbinfo->dobj.namespace->dobj.name,
7148 indxinfo->tablespace,
7149 tbinfo->usename, false,
7150 "INDEX", q->data, delq->data, NULL,
7151 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
7155 /* Dump Index Comments */
7156 resetPQExpBuffer(q);
7157 appendPQExpBuffer(q, "INDEX %s",
7158 fmtId(indxinfo->dobj.name));
7159 dumpComment(fout, q->data,
7160 tbinfo->dobj.namespace->dobj.name,
7162 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
7164 destroyPQExpBuffer(q);
7165 destroyPQExpBuffer(delq);
7170 * write out to fout a user-defined constraint
7173 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
7175 TableInfo *tbinfo = coninfo->contable;
7181 if (tbinfo && !tbinfo->dump)
7184 q = createPQExpBuffer();
7185 delq = createPQExpBuffer();
7187 if (coninfo->contype == 'p' || coninfo->contype == 'u')
7189 /* Index-related constraint */
7193 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
7195 if (indxinfo == NULL)
7197 write_msg(NULL, "missing index for constraint \"%s\"\n",
7198 coninfo->dobj.name);
7202 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
7203 fmtId(tbinfo->dobj.name));
7204 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s (",
7205 fmtId(coninfo->dobj.name),
7206 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
7208 for (k = 0; k < indxinfo->indnkeys; k++)
7210 int indkey = (int) indxinfo->indkeys[k];
7211 const char *attname;
7213 if (indkey == InvalidAttrNumber)
7215 attname = getAttrName(indkey, tbinfo);
7217 appendPQExpBuffer(q, "%s%s",
7218 (k == 0) ? "" : ", ",
7222 appendPQExpBuffer(q, ");\n");
7224 /* If the index is clustered, we need to record that. */
7225 if (indxinfo->indisclustered)
7227 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
7228 fmtId(tbinfo->dobj.name));
7229 appendPQExpBuffer(q, " ON %s;\n",
7230 fmtId(indxinfo->dobj.name));
7234 * DROP must be fully qualified in case same name appears in
7237 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7238 fmtId(tbinfo->dobj.namespace->dobj.name));
7239 appendPQExpBuffer(delq, "%s ",
7240 fmtId(tbinfo->dobj.name));
7241 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7242 fmtId(coninfo->dobj.name));
7244 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7246 tbinfo->dobj.namespace->dobj.name,
7247 indxinfo->tablespace,
7248 tbinfo->usename, false,
7249 "CONSTRAINT", q->data, delq->data, NULL,
7250 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7253 else if (coninfo->contype == 'f')
7256 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that
7257 * the current table data is not processed
7259 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
7260 fmtId(tbinfo->dobj.name));
7261 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7262 fmtId(coninfo->dobj.name),
7266 * DROP must be fully qualified in case same name appears in
7269 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7270 fmtId(tbinfo->dobj.namespace->dobj.name));
7271 appendPQExpBuffer(delq, "%s ",
7272 fmtId(tbinfo->dobj.name));
7273 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7274 fmtId(coninfo->dobj.name));
7276 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7278 tbinfo->dobj.namespace->dobj.name,
7280 tbinfo->usename, false,
7281 "FK CONSTRAINT", q->data, delq->data, NULL,
7282 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7285 else if (coninfo->contype == 'c' && tbinfo)
7287 /* CHECK constraint on a table */
7289 /* Ignore if not to be dumped separately */
7290 if (coninfo->separate)
7292 /* not ONLY since we want it to propagate to children */
7293 appendPQExpBuffer(q, "ALTER TABLE %s\n",
7294 fmtId(tbinfo->dobj.name));
7295 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7296 fmtId(coninfo->dobj.name),
7300 * DROP must be fully qualified in case same name appears in
7303 appendPQExpBuffer(delq, "ALTER TABLE %s.",
7304 fmtId(tbinfo->dobj.namespace->dobj.name));
7305 appendPQExpBuffer(delq, "%s ",
7306 fmtId(tbinfo->dobj.name));
7307 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7308 fmtId(coninfo->dobj.name));
7310 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7312 tbinfo->dobj.namespace->dobj.name,
7314 tbinfo->usename, false,
7315 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7316 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7320 else if (coninfo->contype == 'c' && tbinfo == NULL)
7322 /* CHECK constraint on a domain */
7323 TypeInfo *tinfo = coninfo->condomain;
7325 /* Ignore if not to be dumped separately, or if not dumping domain */
7326 if (coninfo->separate && tinfo->dobj.namespace->dump)
7328 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
7329 fmtId(tinfo->dobj.name));
7330 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7331 fmtId(coninfo->dobj.name),
7335 * DROP must be fully qualified in case same name appears in
7338 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
7339 fmtId(tinfo->dobj.namespace->dobj.name));
7340 appendPQExpBuffer(delq, "%s ",
7341 fmtId(tinfo->dobj.name));
7342 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7343 fmtId(coninfo->dobj.name));
7345 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7347 tinfo->dobj.namespace->dobj.name,
7349 tinfo->usename, false,
7350 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7351 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7357 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
7361 /* Dump Constraint Comments --- only works for table constraints */
7362 if (tbinfo && coninfo->separate)
7363 dumpTableConstraintComment(fout, coninfo);
7365 destroyPQExpBuffer(q);
7366 destroyPQExpBuffer(delq);
7370 * dumpTableConstraintComment --- dump a constraint's comment if any
7372 * This is split out because we need the function in two different places
7373 * depending on whether the constraint is dumped as part of CREATE TABLE
7374 * or as a separate ALTER command.
7377 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
7379 TableInfo *tbinfo = coninfo->contable;
7380 PQExpBuffer q = createPQExpBuffer();
7382 appendPQExpBuffer(q, "CONSTRAINT %s ",
7383 fmtId(coninfo->dobj.name));
7384 appendPQExpBuffer(q, "ON %s",
7385 fmtId(tbinfo->dobj.name));
7386 dumpComment(fout, q->data,
7387 tbinfo->dobj.namespace->dobj.name,
7389 coninfo->dobj.catId, 0,
7390 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
7392 destroyPQExpBuffer(q);
7397 * find the maximum oid and generate a COPY statement to set it
7400 setMaxOid(Archive *fout)
7406 if (fout->remoteVersion >= 70200)
7407 do_sql_command(g_conn,
7408 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer) WITH OIDS");
7410 do_sql_command(g_conn,
7411 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer)");
7412 res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
7413 check_sql_result(res, g_conn, "INSERT INTO pgdump_oid VALUES (0)",
7415 max_oid = PQoidValue(res);
7418 write_msg(NULL, "inserted invalid OID\n");
7422 do_sql_command(g_conn, "DROP TABLE pgdump_oid;");
7424 write_msg(NULL, "maximum system OID is %u\n", max_oid);
7425 snprintf(sql, sizeof(sql),
7426 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer) WITH OIDS;\n"
7427 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
7430 "DROP TABLE pgdump_oid;\n",
7433 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7434 "Max OID", NULL, NULL, "",
7435 false, "<Init>", sql, "", NULL,
7441 * findLastBuiltInOid -
7442 * find the last built in oid
7444 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
7445 * pg_database entry for the current database
7448 findLastBuiltinOid_V71(const char *dbname)
7453 PQExpBuffer query = createPQExpBuffer();
7455 resetPQExpBuffer(query);
7456 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
7457 appendStringLiteral(query, dbname, true);
7459 res = PQexec(g_conn, query->data);
7460 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7462 ntups = PQntuples(res);
7465 write_msg(NULL, "missing pg_database entry for this database\n");
7470 write_msg(NULL, "found more than one pg_database entry for this database\n");
7473 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
7475 destroyPQExpBuffer(query);
7480 * findLastBuiltInOid -
7481 * find the last built in oid
7483 * For 7.0, we do this by assuming that the last thing that initdb does is to
7484 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
7485 * initdb won't be changing anymore, it'll do.
7488 findLastBuiltinOid_V70(void)
7494 res = PQexec(g_conn,
7495 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
7496 check_sql_result(res, g_conn,
7497 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
7499 ntups = PQntuples(res);
7502 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
7507 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
7510 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
7516 dumpSequence(Archive *fout, TableInfo *tbinfo)
7528 PQExpBuffer query = createPQExpBuffer();
7529 PQExpBuffer delqry = createPQExpBuffer();
7531 /* Make sure we are in proper schema */
7532 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7534 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
7535 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
7537 appendPQExpBuffer(query,
7538 "SELECT sequence_name, last_value, increment_by, "
7539 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
7540 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
7542 "END AS max_value, "
7543 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
7544 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
7546 "END AS min_value, "
7547 "cache_value, is_cycled, is_called from %s",
7549 fmtId(tbinfo->dobj.name));
7551 res = PQexec(g_conn, query->data);
7552 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7554 if (PQntuples(res) != 1)
7556 write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
7557 tbinfo->dobj.name, PQntuples(res));
7561 /* Disable this check: it fails if sequence has been renamed */
7563 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
7565 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
7566 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
7571 last = PQgetvalue(res, 0, 1);
7572 incby = PQgetvalue(res, 0, 2);
7573 if (!PQgetisnull(res, 0, 3))
7574 maxv = PQgetvalue(res, 0, 3);
7575 if (!PQgetisnull(res, 0, 4))
7576 minv = PQgetvalue(res, 0, 4);
7577 cache = PQgetvalue(res, 0, 5);
7578 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
7579 called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
7582 * The logic we use for restoring sequences is as follows:
7584 * Add a basic CREATE SEQUENCE statement (use last_val for start if
7585 * called is false, else use min_val for start_val). Skip this if the
7586 * sequence came from a SERIAL column.
7588 * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
7589 * data. We do this for serial sequences too.
7592 if (!dataOnly && !OidIsValid(tbinfo->owning_tab))
7594 resetPQExpBuffer(delqry);
7597 * DROP must be fully qualified in case same name appears in
7600 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
7601 fmtId(tbinfo->dobj.namespace->dobj.name));
7602 appendPQExpBuffer(delqry, "%s;\n",
7603 fmtId(tbinfo->dobj.name));
7605 resetPQExpBuffer(query);
7606 appendPQExpBuffer(query,
7607 "CREATE SEQUENCE %s\n",
7608 fmtId(tbinfo->dobj.name));
7611 appendPQExpBuffer(query, " START WITH %s\n", last);
7613 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
7616 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
7618 appendPQExpBuffer(query, " NO MAXVALUE\n");
7621 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
7623 appendPQExpBuffer(query, " NO MINVALUE\n");
7625 appendPQExpBuffer(query,
7627 cache, (cycled ? "\n CYCLE" : ""));
7629 appendPQExpBuffer(query, ";\n");
7631 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7633 tbinfo->dobj.namespace->dobj.name,
7636 false, "SEQUENCE", query->data, delqry->data, NULL,
7637 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7643 TableInfo *owning_tab;
7645 resetPQExpBuffer(query);
7646 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
7649 * If this is a SERIAL sequence, then use the
7650 * pg_get_serial_sequence function to avoid hard-coding the
7651 * sequence name. Note that this implicitly assumes that the
7652 * sequence and its owning table are in the same schema, because
7653 * we don't schema-qualify the reference.
7655 if (OidIsValid(tbinfo->owning_tab) &&
7656 (owning_tab = findTableByOid(tbinfo->owning_tab)) != NULL)
7658 appendPQExpBuffer(query, "pg_catalog.pg_get_serial_sequence(");
7659 appendStringLiteral(query, fmtId(owning_tab->dobj.name), true);
7660 appendPQExpBuffer(query, ", ");
7661 appendStringLiteral(query, owning_tab->attnames[tbinfo->owning_col - 1], true);
7662 appendPQExpBuffer(query, ")");
7665 appendStringLiteral(query, fmtId(tbinfo->dobj.name), true);
7666 appendPQExpBuffer(query, ", %s, %s);\n",
7667 last, (called ? "true" : "false"));
7669 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7671 tbinfo->dobj.namespace->dobj.name,
7674 false, "SEQUENCE SET", query->data, "", NULL,
7675 &(tbinfo->dobj.dumpId), 1,
7681 /* Dump Sequence Comments */
7682 resetPQExpBuffer(query);
7683 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
7684 dumpComment(fout, query->data,
7685 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7686 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
7691 destroyPQExpBuffer(query);
7692 destroyPQExpBuffer(delqry);
7696 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
7698 TableInfo *tbinfo = tginfo->tgtable;
7707 query = createPQExpBuffer();
7708 delqry = createPQExpBuffer();
7711 * DROP must be fully qualified in case same name appears in
7714 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
7715 fmtId(tginfo->dobj.name));
7716 appendPQExpBuffer(delqry, "ON %s.",
7717 fmtId(tbinfo->dobj.namespace->dobj.name));
7718 appendPQExpBuffer(delqry, "%s;\n",
7719 fmtId(tbinfo->dobj.name));
7721 if (tginfo->tgisconstraint)
7723 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
7724 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
7728 appendPQExpBuffer(query, "CREATE TRIGGER ");
7729 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
7731 appendPQExpBuffer(query, "\n ");
7735 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
7736 appendPQExpBuffer(query, "BEFORE");
7738 appendPQExpBuffer(query, "AFTER");
7739 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
7741 appendPQExpBuffer(query, " INSERT");
7744 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
7747 appendPQExpBuffer(query, " OR DELETE");
7749 appendPQExpBuffer(query, " DELETE");
7752 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
7755 appendPQExpBuffer(query, " OR UPDATE");
7757 appendPQExpBuffer(query, " UPDATE");
7759 appendPQExpBuffer(query, " ON %s\n",
7760 fmtId(tbinfo->dobj.name));
7762 if (tginfo->tgisconstraint)
7764 if (OidIsValid(tginfo->tgconstrrelid))
7766 /* If we are using regclass, name is already quoted */
7767 if (g_fout->remoteVersion >= 70300)
7768 appendPQExpBuffer(query, " FROM %s\n ",
7769 tginfo->tgconstrrelname);
7771 appendPQExpBuffer(query, " FROM %s\n ",
7772 fmtId(tginfo->tgconstrrelname));
7774 if (!tginfo->tgdeferrable)
7775 appendPQExpBuffer(query, "NOT ");
7776 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
7777 if (tginfo->tginitdeferred)
7778 appendPQExpBuffer(query, "DEFERRED\n");
7780 appendPQExpBuffer(query, "IMMEDIATE\n");
7783 if (TRIGGER_FOR_ROW(tginfo->tgtype))
7784 appendPQExpBuffer(query, " FOR EACH ROW\n ");
7786 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
7788 /* In 7.3, result of regproc is already quoted */
7789 if (g_fout->remoteVersion >= 70300)
7790 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7793 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7794 fmtId(tginfo->tgfname));
7797 for (findx = 0; findx < tginfo->tgnargs; findx++)
7799 const char *s = p, *s2 = p;
7801 /* Set 'p' to end of arg string. marked by '\000' */
7804 p = strchr(p, '\\');
7807 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
7814 if (*p == '\\') /* is it '\\'? */
7819 if (p[0] == '0' && p[1] == '0' && p[2] == '0') /* is it '\000'? */
7827 appendPQExpBufferChar(query, ESCAPE_STRING_SYNTAX);
7831 appendPQExpBufferChar(query, '\'');
7834 if (*s == '\'') /* bytea already doubles backslashes */
7835 appendPQExpBufferChar(query, '\'');
7836 appendPQExpBufferChar(query, *s++);
7838 appendPQExpBufferChar(query, '\'');
7839 appendPQExpBuffer(query,
7840 (findx < tginfo->tgnargs - 1) ? ", " : "");
7843 appendPQExpBuffer(query, ");\n");
7845 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
7847 tbinfo->dobj.namespace->dobj.name,
7849 tbinfo->usename, false,
7850 "TRIGGER", query->data, delqry->data, NULL,
7851 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
7854 resetPQExpBuffer(query);
7855 appendPQExpBuffer(query, "TRIGGER %s ",
7856 fmtId(tginfo->dobj.name));
7857 appendPQExpBuffer(query, "ON %s",
7858 fmtId(tbinfo->dobj.name));
7860 dumpComment(fout, query->data,
7861 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7862 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
7864 destroyPQExpBuffer(query);
7865 destroyPQExpBuffer(delqry);
7873 dumpRule(Archive *fout, RuleInfo *rinfo)
7875 TableInfo *tbinfo = rinfo->ruletable;
7882 * Ignore rules for not-to-be-dumped tables
7884 if (tbinfo == NULL || !tbinfo->dump || dataOnly)
7888 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
7889 * we do not want to dump it as a separate object.
7891 if (!rinfo->separate)
7895 * Make sure we are in proper schema.
7897 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7899 query = createPQExpBuffer();
7900 cmd = createPQExpBuffer();
7901 delcmd = createPQExpBuffer();
7903 if (g_fout->remoteVersion >= 70300)
7905 appendPQExpBuffer(query,
7906 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
7907 rinfo->dobj.catId.oid);
7911 /* Rule name was unique before 7.3 ... */
7912 appendPQExpBuffer(query,
7913 "SELECT pg_get_ruledef('%s') AS definition",
7917 res = PQexec(g_conn, query->data);
7918 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7920 if (PQntuples(res) != 1)
7922 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
7923 rinfo->dobj.name, tbinfo->dobj.name);
7927 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
7930 * DROP must be fully qualified in case same name appears in
7933 appendPQExpBuffer(delcmd, "DROP RULE %s ",
7934 fmtId(rinfo->dobj.name));
7935 appendPQExpBuffer(delcmd, "ON %s.",
7936 fmtId(tbinfo->dobj.namespace->dobj.name));
7937 appendPQExpBuffer(delcmd, "%s;\n",
7938 fmtId(tbinfo->dobj.name));
7940 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
7942 tbinfo->dobj.namespace->dobj.name,
7944 tbinfo->usename, false,
7945 "RULE", cmd->data, delcmd->data, NULL,
7946 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
7949 /* Dump rule comments */
7950 resetPQExpBuffer(query);
7951 appendPQExpBuffer(query, "RULE %s",
7952 fmtId(rinfo->dobj.name));
7953 appendPQExpBuffer(query, " ON %s",
7954 fmtId(tbinfo->dobj.name));
7955 dumpComment(fout, query->data,
7956 tbinfo->dobj.namespace->dobj.name,
7958 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
7962 destroyPQExpBuffer(query);
7963 destroyPQExpBuffer(cmd);
7964 destroyPQExpBuffer(delcmd);
7968 * getDependencies --- obtain available dependency data
7971 getDependencies(void)
7982 DumpableObject *dobj,
7985 /* No dependency info available before 7.3 */
7986 if (g_fout->remoteVersion < 70300)
7990 write_msg(NULL, "reading dependency data\n");
7992 /* Make sure we are in proper schema */
7993 selectSourceSchema("pg_catalog");
7995 query = createPQExpBuffer();
7997 appendPQExpBuffer(query, "SELECT "
7998 "classid, objid, refclassid, refobjid, deptype "
8000 "WHERE deptype != 'p' "
8003 res = PQexec(g_conn, query->data);
8004 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8006 ntups = PQntuples(res);
8008 i_classid = PQfnumber(res, "classid");
8009 i_objid = PQfnumber(res, "objid");
8010 i_refclassid = PQfnumber(res, "refclassid");
8011 i_refobjid = PQfnumber(res, "refobjid");
8012 i_deptype = PQfnumber(res, "deptype");
8015 * Since we ordered the SELECT by referencing ID, we can expect that
8016 * multiple entries for the same object will appear together; this
8017 * saves on searches.
8021 for (i = 0; i < ntups; i++)
8027 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
8028 objId.oid = atooid(PQgetvalue(res, i, i_objid));
8029 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
8030 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
8031 deptype = *(PQgetvalue(res, i, i_deptype));
8034 dobj->catId.tableoid != objId.tableoid ||
8035 dobj->catId.oid != objId.oid)
8036 dobj = findObjectByCatalogId(objId);
8039 * Failure to find objects mentioned in pg_depend is not
8040 * unexpected, since for example we don't collect info about TOAST
8046 fprintf(stderr, "no referencing object %u %u\n",
8047 objId.tableoid, objId.oid);
8052 refdobj = findObjectByCatalogId(refobjId);
8054 if (refdobj == NULL)
8057 fprintf(stderr, "no referenced object %u %u\n",
8058 refobjId.tableoid, refobjId.oid);
8064 * Ordinarily, table rowtypes have implicit dependencies on their
8065 * tables. However, for a composite type the implicit dependency
8066 * goes the other way in pg_depend; which is the right thing for
8067 * DROP but it doesn't produce the dependency ordering we need.
8068 * So in that one case, we reverse the direction of the dependency.
8070 if (deptype == 'i' &&
8071 dobj->objType == DO_TABLE &&
8072 refdobj->objType == DO_TYPE)
8073 addObjectDependency(refdobj, dobj->dumpId);
8074 else /* normal case */
8075 addObjectDependency(dobj, refdobj->dumpId);
8080 destroyPQExpBuffer(query);
8085 * selectSourceSchema - make the specified schema the active search path
8086 * in the source database.
8088 * NB: pg_catalog is explicitly searched after the specified schema;
8089 * so user names are only qualified if they are cross-schema references,
8090 * and system names are only qualified if they conflict with a user name
8091 * in the current schema.
8093 * Whenever the selected schema is not pg_catalog, be careful to qualify
8094 * references to system catalogs and types in our emitted commands!
8097 selectSourceSchema(const char *schemaName)
8099 static char *curSchemaName = NULL;
8102 /* Not relevant if fetching from pre-7.3 DB */
8103 if (g_fout->remoteVersion < 70300)
8105 /* Ignore null schema names */
8106 if (schemaName == NULL || *schemaName == '\0')
8108 /* Optimize away repeated selection of same schema */
8109 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
8112 query = createPQExpBuffer();
8113 appendPQExpBuffer(query, "SET search_path = %s",
8115 if (strcmp(schemaName, "pg_catalog") != 0)
8116 appendPQExpBuffer(query, ", pg_catalog");
8118 do_sql_command(g_conn, query->data);
8120 destroyPQExpBuffer(query);
8122 free(curSchemaName);
8123 curSchemaName = strdup(schemaName);
8127 * getFormattedTypeName - retrieve a nicely-formatted type name for the
8130 * NB: in 7.3 and up the result may depend on the currently-selected
8131 * schema; this is why we don't try to cache the names.
8134 getFormattedTypeName(Oid oid, OidOptions opts)
8143 if ((opts & zeroAsOpaque) != 0)
8144 return strdup(g_opaque_type);
8145 else if ((opts & zeroAsAny) != 0)
8146 return strdup("'any'");
8147 else if ((opts & zeroAsStar) != 0)
8149 else if ((opts & zeroAsNone) != 0)
8150 return strdup("NONE");
8153 query = createPQExpBuffer();
8154 if (g_fout->remoteVersion >= 70300)
8156 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
8159 else if (g_fout->remoteVersion >= 70100)
8161 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
8166 appendPQExpBuffer(query, "SELECT typname "
8168 "WHERE oid = '%u'::oid",
8172 res = PQexec(g_conn, query->data);
8173 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8175 /* Expecting a single result only */
8176 ntups = PQntuples(res);
8179 write_msg(NULL, "query yielded %d rows instead of one: %s\n",
8180 ntups, query->data);
8184 if (g_fout->remoteVersion >= 70100)
8186 /* already quoted */
8187 result = strdup(PQgetvalue(res, 0, 0));
8191 /* may need to quote it */
8192 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
8196 destroyPQExpBuffer(query);
8202 * myFormatType --- local implementation of format_type for use with 7.0.
8205 myFormatType(const char *typname, int32 typmod)
8208 bool isarray = false;
8209 PQExpBuffer buf = createPQExpBuffer();
8211 /* Handle array types */
8212 if (typname[0] == '_')
8218 /* Show lengths on bpchar and varchar */
8219 if (!strcmp(typname, "bpchar"))
8221 int len = (typmod - VARHDRSZ);
8223 appendPQExpBuffer(buf, "character");
8225 appendPQExpBuffer(buf, "(%d)",
8228 else if (!strcmp(typname, "varchar"))
8230 appendPQExpBuffer(buf, "character varying");
8232 appendPQExpBuffer(buf, "(%d)",
8235 else if (!strcmp(typname, "numeric"))
8237 appendPQExpBuffer(buf, "numeric");
8244 tmp_typmod = typmod - VARHDRSZ;
8245 precision = (tmp_typmod >> 16) & 0xffff;
8246 scale = tmp_typmod & 0xffff;
8247 appendPQExpBuffer(buf, "(%d,%d)",
8253 * char is an internal single-byte data type; Let's make sure we force
8254 * it through with quotes. - thomas 1998-12-13
8256 else if (strcmp(typname, "char") == 0)
8257 appendPQExpBuffer(buf, "\"char\"");
8259 appendPQExpBuffer(buf, "%s", fmtId(typname));
8261 /* Append array qualifier for array types */
8263 appendPQExpBuffer(buf, "[]");
8265 result = strdup(buf->data);
8266 destroyPQExpBuffer(buf);
8272 * fmtQualifiedId - convert a qualified name to the proper format for
8273 * the source database.
8275 * Like fmtId, use the result before calling again.
8278 fmtQualifiedId(const char *schema, const char *id)
8280 static PQExpBuffer id_return = NULL;
8282 if (id_return) /* first time through? */
8283 resetPQExpBuffer(id_return);
8285 id_return = createPQExpBuffer();
8287 /* Suppress schema name if fetching from pre-7.3 DB */
8288 if (g_fout->remoteVersion >= 70300 && schema && *schema)
8290 appendPQExpBuffer(id_return, "%s.",
8293 appendPQExpBuffer(id_return, "%s",
8296 return id_return->data;
8300 * Return a column list clause for the given relation.
8302 * Special case: if there are no undropped columns in the relation, return
8303 * "", not an invalid "()" column list.
8306 fmtCopyColumnList(const TableInfo *ti)
8308 static PQExpBuffer q = NULL;
8309 int numatts = ti->numatts;
8310 char **attnames = ti->attnames;
8311 bool *attisdropped = ti->attisdropped;
8315 if (q) /* first time through? */
8316 resetPQExpBuffer(q);
8318 q = createPQExpBuffer();
8320 appendPQExpBuffer(q, "(");
8322 for (i = 0; i < numatts; i++)
8324 if (attisdropped[i])
8327 appendPQExpBuffer(q, ", ");
8328 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
8333 return ""; /* no undropped columns */
8335 appendPQExpBuffer(q, ")");
8340 * Convenience subroutine to execute a SQL command and check for
8341 * COMMAND_OK status.
8344 do_sql_command(PGconn *conn, const char *query)
8348 res = PQexec(conn, query);
8349 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
8354 * Convenience subroutine to verify a SQL command succeeded,
8355 * and exit with a useful error message if not.
8358 check_sql_result(PGresult *res, PGconn *conn, const char *query,
8359 ExecStatusType expected)
8363 if (res && PQresultStatus(res) == expected)
8366 write_msg(NULL, "SQL command failed\n");
8368 err = PQresultErrorMessage(res);
8370 err = PQerrorMessage(conn);
8371 write_msg(NULL, "Error message from server: %s", err);
8372 write_msg(NULL, "The command was: %s\n", query);