1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2003, 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.373 2004/06/03 00:07:36 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"
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"
63 #define _(x) gettext((x))
72 const char *descr; /* comment for an object */
73 Oid classoid; /* object class (catalog OID) */
74 Oid objoid; /* object OID */
75 int objsubid; /* subobject (table column #) */
80 bool g_verbose; /* User wants verbose narration of our
82 Archive *g_fout; /* the script file */
83 PGconn *g_conn; /* the database connection */
85 /* various user-settable parameters */
86 bool dumpInserts; /* dump data using proper insert strings */
87 bool attrNames; /* put attr names into insert strings */
92 /* obsolete as of 7.3: */
93 static Oid g_last_builtin_oid; /* value of the last builtin oid */
95 static char *selectTableName = NULL; /* name of a single table to dump */
96 static char *selectSchemaName = NULL; /* name of a single schema to dump */
98 char g_opaque_type[10]; /* name for the opaque type */
100 /* placeholders for the delimiters for comments */
101 char g_comment_start[10];
102 char g_comment_end[10];
104 static const CatalogId nilCatalogId = { 0, 0 };
106 /* these are to avoid passing around info for findNamespace() */
107 static NamespaceInfo *g_namespaces;
108 static int g_numNamespaces;
110 /* flag to turn on/off dollar quoting */
111 static int disable_dollar_quoting = 0;
114 static void help(const char *progname);
115 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
116 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
117 static void dumpComment(Archive *fout, const char *target,
118 const char *namespace, const char *owner,
119 CatalogId catalogId, int subid, DumpId dumpId);
120 static int findComments(Archive *fout, Oid classoid, Oid objoid,
121 CommentItem **items);
122 static int collectComments(Archive *fout, CommentItem **items);
123 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
124 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
125 static void dumpType(Archive *fout, TypeInfo *tinfo);
126 static void dumpBaseType(Archive *fout, TypeInfo *tinfo);
127 static void dumpDomain(Archive *fout, TypeInfo *tinfo);
128 static void dumpCompositeType(Archive *fout, TypeInfo *tinfo);
129 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
130 static void dumpFunc(Archive *fout, FuncInfo *finfo);
131 static void dumpCast(Archive *fout, CastInfo *cast);
132 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
133 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
134 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
135 static void dumpRule(Archive *fout, RuleInfo *rinfo);
136 static void dumpAgg(Archive *fout, AggInfo *agginfo);
137 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
138 static void dumpTable(Archive *fout, TableInfo *tbinfo);
139 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
140 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
141 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
142 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
143 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
145 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
146 const char *type, const char *name,
147 const char *tag, const char *nspname, const char *owner,
150 static void getDependencies(void);
151 static void getDomainConstraints(TypeInfo *tinfo);
152 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
153 static char *format_function_signature(FuncInfo *finfo, char **argnames,
155 static const char *convertRegProcReference(const char *proc);
156 static const char *convertOperatorReference(const char *opr);
157 static Oid findLastBuiltinOid_V71(const char *);
158 static Oid findLastBuiltinOid_V70(void);
159 static void setMaxOid(Archive *fout);
160 static void selectSourceSchema(const char *schemaName);
161 static char *getFormattedTypeName(Oid oid, OidOptions opts);
162 static char *myFormatType(const char *typname, int32 typmod);
163 static const char *fmtQualifiedId(const char *schema, const char *id);
164 static int dumpBlobs(Archive *AH, void *arg);
165 static void dumpDatabase(Archive *AH);
166 static void dumpEncoding(Archive *AH);
167 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
168 static const char *fmtCopyColumnList(const TableInfo *ti);
169 static void do_sql_command(PGconn *conn, const char *query);
170 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
171 ExecStatusType expected);
175 main(int argc, char **argv)
178 const char *filename = NULL;
179 const char *format = "p";
180 const char *dbname = NULL;
181 const char *pghost = NULL;
182 const char *pgport = NULL;
183 const char *username = NULL;
187 DumpableObject **dobjs;
190 bool force_password = false;
191 int compressLevel = -1;
192 bool ignore_version = false;
195 int outputCreate = 0;
197 int outputNoOwner = 0;
198 static int use_setsessauth = 0;
199 static int disable_triggers = 0;
200 char *outputSuperuser = NULL;
202 RestoreOptions *ropt;
204 static struct option long_options[] = {
205 {"data-only", no_argument, NULL, 'a'},
206 {"blobs", no_argument, NULL, 'b'},
207 {"clean", no_argument, NULL, 'c'},
208 {"create", no_argument, NULL, 'C'},
209 {"file", required_argument, NULL, 'f'},
210 {"format", required_argument, NULL, 'F'},
211 {"inserts", no_argument, NULL, 'd'},
212 {"attribute-inserts", no_argument, NULL, 'D'},
213 {"column-inserts", no_argument, NULL, 'D'},
214 {"host", required_argument, NULL, 'h'},
215 {"ignore-version", no_argument, NULL, 'i'},
216 {"no-reconnect", no_argument, NULL, 'R'},
217 {"oids", no_argument, NULL, 'o'},
218 {"no-owner", no_argument, NULL, 'O'},
219 {"port", required_argument, NULL, 'p'},
220 {"schema", required_argument, NULL, 'n'},
221 {"schema-only", no_argument, NULL, 's'},
222 {"superuser", required_argument, NULL, 'S'},
223 {"table", required_argument, NULL, 't'},
224 {"password", no_argument, NULL, 'W'},
225 {"username", required_argument, NULL, 'U'},
226 {"verbose", no_argument, NULL, 'v'},
227 {"no-privileges", no_argument, NULL, 'x'},
228 {"no-acl", no_argument, NULL, 'x'},
229 {"compress", required_argument, NULL, 'Z'},
230 {"help", no_argument, NULL, '?'},
231 {"version", no_argument, NULL, 'V'},
234 * the following options don't have an equivalent short option
235 * letter, but are available as '-X long-name'
237 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
238 {"disable-triggers", no_argument, &disable_triggers, 1},
239 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
245 set_pglocale_pgservice(argv[0], "pg_dump");
249 strcpy(g_comment_start, "-- ");
250 g_comment_end[0] = '\0';
251 strcpy(g_opaque_type, "opaque");
253 dataOnly = schemaOnly = dumpInserts = attrNames = false;
255 progname = get_progname(argv[0]);
257 /* Set default options based on progname */
258 if (strcmp(progname, "pg_backup") == 0)
266 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
271 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
273 puts("pg_dump (PostgreSQL) " PG_VERSION);
278 while ((c = getopt_long(argc, argv, "abcCdDf:F:h:in:oOp:RsS:t:uU:vWxX:Z:",
279 long_options, &optindex)) != -1)
283 case 'a': /* Dump data only */
287 case 'b': /* Dump blobs */
291 case 'c': /* clean (i.e., drop) schema prior to
296 case 'C': /* Create DB */
300 case 'd': /* dump data as proper insert strings */
304 case 'D': /* dump data as proper insert strings with
318 case 'h': /* server host */
322 case 'i': /* ignore database version mismatch */
323 ignore_version = true;
326 case 'n': /* Dump data for this schema only */
327 selectSchemaName = strdup(optarg);
330 case 'o': /* Dump oids */
334 case 'O': /* Don't reconnect to match owner */
338 case 'p': /* server port */
343 /* no-op, still accepted for backwards compatibility */
346 case 's': /* dump schema only */
350 case 'S': /* Username for superuser in plain text
352 outputSuperuser = strdup(optarg);
355 case 't': /* Dump data for this table only */
356 selectTableName = strdup(optarg);
360 force_password = true;
361 username = simple_prompt("User name: ", 100, true);
368 case 'v': /* verbose */
373 force_password = true;
376 case 'x': /* skip ACL dump */
381 * Option letters were getting scarce, so I invented this
382 * new scheme: '-X feature' turns on some feature. Compare
383 * to the -f option in GCC. You should also add an
384 * equivalent GNU-style option --feature. Features that
385 * require arguments should use '-X feature=foo'.
388 if (strcmp(optarg, "disable-dollar-quoting") == 0)
389 disable_dollar_quoting = 1;
390 else if (strcmp(optarg, "disable-triggers") == 0)
391 disable_triggers = 1;
392 else if (strcmp(optarg, "use-set-session-authorization") == 0)
393 /* no-op, still allowed for compatibility */ ;
397 _("%s: invalid -X option -- %s\n"),
399 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
404 case 'Z': /* Compression Level */
405 compressLevel = atoi(optarg);
407 /* This covers the long options equivalent to -X xxx. */
413 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
418 if (optind < (argc - 1))
420 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
421 progname, argv[optind + 1]);
422 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
427 /* Get database name from command line */
429 dbname = argv[optind];
431 if (dataOnly && schemaOnly)
433 write_msg(NULL, "options \"schema only\" (-s) and \"data only\" (-a) cannot be used together\n");
437 if (dataOnly && outputClean)
439 write_msg(NULL, "options \"clean\" (-c) and \"data only\" (-a) cannot be used together\n");
443 if (outputBlobs && selectTableName != NULL)
445 write_msg(NULL, "large-object output not supported for a single table\n");
446 write_msg(NULL, "use a full dump instead\n");
450 if (outputBlobs && selectSchemaName != NULL)
452 write_msg(NULL, "large-object output not supported for a single schema\n");
453 write_msg(NULL, "use a full dump instead\n");
457 if (dumpInserts == true && oids == true)
459 write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together\n");
460 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
464 if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
466 write_msg(NULL, "large-object output is not supported for plain-text dump files\n");
467 write_msg(NULL, "(Use a different output format.)\n");
471 /* open the output file */
476 g_fout = CreateArchive(filename, archCustom, compressLevel);
481 g_fout = CreateArchive(filename, archFiles, compressLevel);
487 g_fout = CreateArchive(filename, archNull, 0);
492 g_fout = CreateArchive(filename, archTar, compressLevel);
496 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
502 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
506 /* Let the archiver know how noisy to be */
507 g_fout->verbose = g_verbose;
509 g_fout->minRemoteVersion = 70000; /* we can handle back to 7.0 */
510 g_fout->maxRemoteVersion = parse_version(PG_VERSION);
511 if (g_fout->maxRemoteVersion < 0)
513 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
518 * Open the database using the Archiver, so it knows about it. Errors
521 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
522 username, force_password, ignore_version);
525 * Start serializable transaction to dump consistent data.
527 do_sql_command(g_conn, "BEGIN");
529 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
531 /* Set the datestyle to ISO to ensure the dump's portability */
532 do_sql_command(g_conn, "SET DATESTYLE = ISO");
535 * If supported, set extra_float_digits so that we can dump float data
536 * exactly (given correctly implemented float I/O code, anyway)
538 if (g_fout->remoteVersion >= 70400)
539 do_sql_command(g_conn, "SET extra_float_digits TO 2");
541 /* Find the last built-in OID, if needed */
542 if (g_fout->remoteVersion < 70300)
544 if (g_fout->remoteVersion >= 70100)
545 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
547 g_last_builtin_oid = findLastBuiltinOid_V70();
549 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
553 * Now scan the database and create DumpableObject structs for all the
554 * objects we intend to dump.
556 tblinfo = getSchemaData(&numTables, schemaOnly, dataOnly);
559 getTableData(tblinfo, numTables, oids);
563 /* This is just a placeholder to allow correct sorting of blobs */
564 DumpableObject *blobobj;
566 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
567 blobobj->objType = DO_BLOBS;
568 blobobj->catId = nilCatalogId;
569 AssignDumpId(blobobj);
570 blobobj->name = strdup("BLOBS");
574 * Collect dependency data to assist in ordering the objects.
579 * Sort the objects into a safe dump order (no forward references).
581 * In 7.3 or later, we can rely on dependency information to help us
582 * determine a safe order, so the initial sort is mostly for cosmetic
583 * purposes: we sort by name to ensure that logically identical schemas
584 * will dump identically. Before 7.3 we don't have dependencies and
585 * we use OID ordering as an (unreliable) guide to creation order.
587 getDumpableObjects(&dobjs, &numObjs);
589 if (g_fout->remoteVersion >= 70300)
590 sortDumpableObjectsByTypeName(dobjs, numObjs);
592 sortDumpableObjectsByTypeOid(dobjs, numObjs);
594 sortDumpableObjects(dobjs, numObjs);
597 * Create archive TOC entries for all the objects to be dumped,
601 /* First the special encoding entry. */
602 dumpEncoding(g_fout);
604 /* The database item is always second. */
606 dumpDatabase(g_fout);
608 /* Max OID is next. */
612 /* Now the rearrangeable objects. */
613 for (i = 0; i < numObjs; i++)
615 dumpDumpableObject(g_fout, dobjs[i]);
619 * And finally we can do the actual output.
623 ropt = NewRestoreOptions();
624 ropt->filename = (char *) filename;
625 ropt->dropSchema = outputClean;
626 ropt->aclsSkip = aclsSkip;
627 ropt->superuser = outputSuperuser;
628 ropt->create = outputCreate;
629 ropt->noOwner = outputNoOwner;
630 ropt->disable_triggers = disable_triggers;
632 if (compressLevel == -1)
633 ropt->compression = 0;
635 ropt->compression = compressLevel;
637 ropt->suppressDumpWarnings = true; /* We've already shown
640 RestoreArchive(g_fout, ropt);
643 CloseArchive(g_fout);
652 help(const char *progname)
654 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
655 printf(_("Usage:\n"));
656 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
658 printf(_("\nGeneral options:\n"));
659 printf(_(" -f, --file=FILENAME output file name\n"));
660 printf(_(" -F, --format=c|t|p output file format (custom, tar, plain text)\n"));
661 printf(_(" -i, --ignore-version proceed even when server version mismatches\n"
662 " pg_dump version\n"));
663 printf(_(" -v, --verbose verbose mode\n"));
664 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
665 printf(_(" --help show this help, then exit\n"));
666 printf(_(" --version output version information, then exit\n"));
668 printf(_("\nOptions controlling the output content:\n"));
669 printf(_(" -a, --data-only dump only the data, not the schema\n"));
670 printf(_(" -b, --blobs include large objects in dump\n"));
671 printf(_(" -c, --clean clean (drop) schema prior to create\n"));
672 printf(_(" -C, --create include commands to create database in dump\n"));
673 printf(_(" -d, --inserts dump data as INSERT, rather than COPY, commands\n"));
674 printf(_(" -D, --column-inserts dump data as INSERT commands with column names\n"));
675 printf(_(" -n, --schema=SCHEMA dump the named schema only\n"));
676 printf(_(" -o, --oids include OIDs in dump\n"));
677 printf(_(" -O, --no-owner do not output commands to set object ownership\n"
678 " in plain text format\n"));
679 printf(_(" -s, --schema-only dump only the schema, no data\n"));
680 printf(_(" -S, --superuser=NAME specify the superuser user name to use in\n"
681 " plain text format\n"));
682 printf(_(" -t, --table=TABLE dump the named table only\n"));
683 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
684 printf(_(" -X disable-dollar-quoting, --disable-dollar-quoting\n"
685 " disable dollar quoting, use SQL standard quoting\n"));
686 printf(_(" -X disable-triggers, --disable-triggers\n"
687 " disable triggers during data-only restore\n"));
689 printf(_("\nConnection options:\n"));
690 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
691 printf(_(" -p, --port=PORT database server port number\n"));
692 printf(_(" -U, --username=NAME connect as specified database user\n"));
693 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
695 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
696 "variable value is used.\n\n"));
697 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
705 write_msg(NULL, "*** aborted because of error\n");
710 * selectDumpableNamespace: policy-setting subroutine
711 * Mark a namespace as to be dumped or not
714 selectDumpableNamespace(NamespaceInfo *nsinfo)
717 * If a specific table is being dumped, do not dump any complete
718 * namespaces. If a specific namespace is being dumped, dump just
719 * that namespace. Otherwise, dump all non-system namespaces.
721 if (selectTableName != NULL)
722 nsinfo->dump = false;
723 else if (selectSchemaName != NULL)
725 if (strcmp(nsinfo->dobj.name, selectSchemaName) == 0)
728 nsinfo->dump = false;
730 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
731 strcmp(nsinfo->dobj.name, "information_schema") == 0)
732 nsinfo->dump = false;
738 * selectDumpableTable: policy-setting subroutine
739 * Mark a table as to be dumped or not
742 selectDumpableTable(TableInfo *tbinfo)
745 * Always dump if dumping parent namespace; else, if a particular
746 * tablename has been specified, dump matching table name; else, do
749 tbinfo->dump = false;
750 if (tbinfo->dobj.namespace->dump)
752 else if (selectTableName != NULL &&
753 strcmp(tbinfo->dobj.name, selectTableName) == 0)
755 /* If both -s and -t specified, must match both to dump */
756 if (selectSchemaName == NULL)
758 else if (strcmp(tbinfo->dobj.namespace->dobj.name, selectSchemaName) == 0)
764 * Dump a table's contents for loading using the COPY command
765 * - this routine is called by the Archiver when it wants the table
769 #define COPYBUFSIZ 8192
772 dumpTableData_copy(Archive *fout, void *dcontext)
774 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
775 TableInfo *tbinfo = tdinfo->tdtable;
776 const char *classname = tbinfo->dobj.name;
777 const bool hasoids = tbinfo->hasoids;
778 const bool oids = tdinfo->oids;
779 PQExpBuffer q = createPQExpBuffer();
783 char copybuf[COPYBUFSIZ];
784 const char *column_list;
787 write_msg(NULL, "dumping contents of table %s\n", classname);
790 * Make sure we are in proper schema. We will qualify the table name
791 * below anyway (in case its name conflicts with a pg_catalog table);
792 * but this ensures reproducible results in case the table contains
793 * regproc, regclass, etc columns.
795 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
798 * If possible, specify the column list explicitly so that we have no
799 * possibility of retrieving data in the wrong column order. (The
800 * default column ordering of COPY will not be what we want in certain
801 * corner cases involving ADD COLUMN and inheritance.)
803 if (g_fout->remoteVersion >= 70300)
804 column_list = fmtCopyColumnList(tbinfo);
806 column_list = ""; /* can't select columns in COPY */
810 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
811 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
817 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
818 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
822 res = PQexec(g_conn, q->data);
823 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
829 ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
831 if (copybuf[0] == '\\' &&
835 copydone = true; /* don't print this... */
839 archputs(copybuf, fout);
846 archputs("\n", fout);
856 * There was considerable discussion in late July, 2000 regarding
857 * slowing down pg_dump when backing up large tables. Users with
858 * both slow & fast (muti-processor) machines experienced
859 * performance degradation when doing a backup.
861 * Initial attempts based on sleeping for a number of ms for each ms
862 * of work were deemed too complex, then a simple 'sleep in each
863 * loop' implementation was suggested. The latter failed because
864 * the loop was too tight. Finally, the following was implemented:
866 * If throttle is non-zero, then See how long since the last sleep.
867 * Work out how long to sleep (based on ratio). If sleep is more
868 * than 100ms, then sleep reset timer EndIf EndIf
870 * where the throttle value was the number of ms to sleep per ms of
871 * work. The calculation was done in each loop.
873 * Most of the hard work is done in the backend, and this solution
874 * still did not work particularly well: on slow machines, the
875 * ratio was 50:1, and on medium paced machines, 1:1, and on fast
876 * multi-processor machines, it had little or no effect, for
877 * reasons that were unclear.
879 * Further discussion ensued, and the proposal was dropped.
881 * For those people who want this feature, it can be implemented
882 * using gettimeofday in each loop, calculating the time since
883 * last sleep, multiplying that by the sleep ratio, then if the
884 * result is more than a preset 'minimum sleep time' (say 100ms),
885 * call the 'select' function to sleep for a subsecond period ie.
887 * select(0, NULL, NULL, NULL, &tvi);
889 * This will return after the interval specified in the structure
890 * tvi. Finally, call gettimeofday again to save the 'last sleep
894 archprintf(fout, "\\.\n\n\n");
896 ret = PQendcopy(g_conn);
899 write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
900 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
901 write_msg(NULL, "The command was: %s\n", q->data);
906 destroyPQExpBuffer(q);
911 dumpTableData_insert(Archive *fout, void *dcontext)
913 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
914 TableInfo *tbinfo = tdinfo->tdtable;
915 const char *classname = tbinfo->dobj.name;
916 PQExpBuffer q = createPQExpBuffer();
923 * Make sure we are in proper schema. We will qualify the table name
924 * below anyway (in case its name conflicts with a pg_catalog table);
925 * but this ensures reproducible results in case the table contains
926 * regproc, regclass, etc columns.
928 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
930 if (fout->remoteVersion >= 70100)
932 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
933 "SELECT * FROM ONLY %s",
934 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
939 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
941 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
945 res = PQexec(g_conn, q->data);
946 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
952 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
953 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
955 nfields = PQnfields(res);
956 for (tuple = 0; tuple < PQntuples(res); tuple++)
958 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
961 /* corner case for zero-column table */
962 archprintf(fout, "DEFAULT VALUES;\n");
965 if (attrNames == true)
968 appendPQExpBuffer(q, "(");
969 for (field = 0; field < nfields; field++)
972 appendPQExpBuffer(q, ", ");
973 appendPQExpBuffer(q, fmtId(PQfname(res, field)));
975 appendPQExpBuffer(q, ") ");
976 archprintf(fout, "%s", q->data);
978 archprintf(fout, "VALUES (");
979 for (field = 0; field < nfields; field++)
982 archprintf(fout, ", ");
983 if (PQgetisnull(res, tuple, field))
985 archprintf(fout, "NULL");
989 /* XXX This code is partially duplicated in ruleutils.c */
990 switch (PQftype(res, field))
1001 * These types are printed without quotes
1002 * unless they contain values that aren't
1003 * accepted by the scanner unquoted (e.g.,
1004 * 'NaN'). Note that strtod() and friends
1005 * might accept NaN, so we can't use that to
1008 * In reality we only need to defend against
1009 * infinity and NaN, so we need not get too
1010 * crazy about pattern matching here.
1012 const char *s = PQgetvalue(res, tuple, field);
1014 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1015 archprintf(fout, "%s", s);
1017 archprintf(fout, "'%s'", s);
1023 archprintf(fout, "B'%s'",
1024 PQgetvalue(res, tuple, field));
1028 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1029 archprintf(fout, "true");
1031 archprintf(fout, "false");
1035 /* All other types are printed as string literals. */
1036 resetPQExpBuffer(q);
1037 appendStringLiteral(q, PQgetvalue(res, tuple, field), false);
1038 archprintf(fout, "%s", q->data);
1042 archprintf(fout, ");\n");
1044 } while (PQntuples(res) > 0);
1048 archprintf(fout, "\n\n");
1050 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1052 destroyPQExpBuffer(q);
1059 * dump the contents of a single table
1061 * Actually, this just makes an ArchiveEntry for the table contents.
1064 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1066 TableInfo *tbinfo = tdinfo->tdtable;
1067 PQExpBuffer copyBuf = createPQExpBuffer();
1068 DataDumperPtr dumpFn;
1073 /* Dump/restore using COPY */
1074 dumpFn = dumpTableData_copy;
1075 /* must use 2 steps here 'cause fmtId is nonreentrant */
1076 appendPQExpBuffer(copyBuf, "COPY %s ",
1077 fmtId(tbinfo->dobj.name));
1078 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1079 fmtCopyColumnList(tbinfo),
1080 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1081 copyStmt = copyBuf->data;
1085 /* Restore using INSERT */
1086 dumpFn = dumpTableData_insert;
1090 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1092 tbinfo->dobj.namespace->dobj.name,
1093 tbinfo->usename, false,
1094 "TABLE DATA", "", "", copyStmt,
1095 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1098 destroyPQExpBuffer(copyBuf);
1103 * set up dumpable objects representing the contents of tables
1106 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1110 for (i = 0; i < numTables; i++)
1112 /* Skip VIEWs (no data to dump) */
1113 if (tblinfo[i].relkind == RELKIND_VIEW)
1115 /* Skip SEQUENCEs (handled elsewhere) */
1116 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1119 if (tblinfo[i].dump)
1121 TableDataInfo *tdinfo;
1123 tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1125 tdinfo->dobj.objType = DO_TABLE_DATA;
1127 * Note: use tableoid 0 so that this object won't be mistaken
1128 * for something that pg_depend entries apply to.
1130 tdinfo->dobj.catId.tableoid = 0;
1131 tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1132 AssignDumpId(&tdinfo->dobj);
1133 tdinfo->dobj.name = tblinfo[i].dobj.name;
1134 tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1135 tdinfo->tdtable = &(tblinfo[i]);
1136 tdinfo->oids = oids;
1137 addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1145 * dump the database definition
1148 dumpDatabase(Archive *AH)
1150 PQExpBuffer dbQry = createPQExpBuffer();
1151 PQExpBuffer delQry = createPQExpBuffer();
1152 PQExpBuffer creaQry = createPQExpBuffer();
1162 const char *datname,
1167 datname = PQdb(g_conn);
1170 write_msg(NULL, "saving database definition\n");
1172 /* Make sure we are in proper schema */
1173 selectSourceSchema("pg_catalog");
1175 /* Get the database owner and parameters from pg_database */
1176 if (g_fout->remoteVersion >= 70100)
1178 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1179 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1180 "pg_encoding_to_char(encoding) as encoding, "
1183 "WHERE datname = ");
1184 appendStringLiteral(dbQry, datname, true);
1189 * In 7.0, datpath is either the same as datname, or the user-given
1190 * location with "/" and the datname appended. We must strip this
1191 * junk off to produce a correct LOCATION value.
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 "CASE WHEN length(datpath) > length(datname) THEN "
1199 "substr(datpath,1,length(datpath)-length(datname)-1) "
1200 "ELSE '' END as datpath "
1202 "WHERE datname = ");
1203 appendStringLiteral(dbQry, datname, true);
1206 res = PQexec(g_conn, dbQry->data);
1207 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1209 ntups = PQntuples(res);
1213 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1220 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1225 i_tableoid = PQfnumber(res, "tableoid");
1226 i_oid = PQfnumber(res, "oid");
1227 i_dba = PQfnumber(res, "dba");
1228 i_encoding = PQfnumber(res, "encoding");
1229 i_datpath = PQfnumber(res, "datpath");
1231 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1232 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1233 dba = PQgetvalue(res, 0, i_dba);
1234 encoding = PQgetvalue(res, 0, i_encoding);
1235 datpath = PQgetvalue(res, 0, i_datpath);
1237 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1239 if (strlen(datpath) > 0)
1241 appendPQExpBuffer(creaQry, " LOCATION = ");
1242 appendStringLiteral(creaQry, datpath, true);
1244 if (strlen(encoding) > 0)
1246 appendPQExpBuffer(creaQry, " ENCODING = ");
1247 appendStringLiteral(creaQry, encoding, true);
1249 appendPQExpBuffer(creaQry, ";\n");
1251 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1254 dbDumpId = createDumpId();
1257 dbCatId, /* catalog ID */
1258 dbDumpId, /* dump ID */
1260 NULL, /* Namespace */
1262 false, /* with oids */
1263 "DATABASE", /* Desc */
1264 creaQry->data, /* Create */
1265 delQry->data, /* Del */
1270 NULL); /* Dumper Arg */
1272 /* Dump DB comment if any */
1273 resetPQExpBuffer(dbQry);
1274 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1275 dumpComment(AH, dbQry->data, NULL, "",
1276 dbCatId, 0, dbDumpId);
1280 destroyPQExpBuffer(dbQry);
1281 destroyPQExpBuffer(delQry);
1282 destroyPQExpBuffer(creaQry);
1287 * dumpEncoding: put the correct encoding into the archive
1290 dumpEncoding(Archive *AH)
1295 /* Can't read the encoding from pre-7.3 servers (SHOW isn't a query) */
1296 if (AH->remoteVersion < 70300)
1300 write_msg(NULL, "saving encoding\n");
1302 qry = createPQExpBuffer();
1304 appendPQExpBuffer(qry, "SHOW client_encoding");
1306 res = PQexec(g_conn, qry->data);
1308 check_sql_result(res, g_conn, qry->data, PGRES_TUPLES_OK);
1310 resetPQExpBuffer(qry);
1312 appendPQExpBuffer(qry, "SET client_encoding = ");
1313 appendStringLiteral(qry, PQgetvalue(res, 0, 0), true);
1314 appendPQExpBuffer(qry, ";\n");
1316 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1317 "ENCODING", NULL, "",
1318 false, "ENCODING", qry->data, "", NULL,
1324 destroyPQExpBuffer(qry);
1334 #define loBufSize 16384
1335 #define loFetchSize 1000
1338 dumpBlobs(Archive *AH, void *arg)
1340 PQExpBuffer oidQry = createPQExpBuffer();
1341 PQExpBuffer oidFetchQry = createPQExpBuffer();
1345 char buf[loBufSize];
1350 write_msg(NULL, "saving large objects\n");
1352 /* Make sure we are in proper schema */
1353 selectSourceSchema("pg_catalog");
1355 /* Cursor to get all BLOB tables */
1356 if (AH->remoteVersion >= 70100)
1357 appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject");
1359 appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT oid from pg_class where relkind = 'l'");
1361 res = PQexec(g_conn, oidQry->data);
1362 check_sql_result(res, g_conn, oidQry->data, PGRES_COMMAND_OK);
1364 /* Fetch for cursor */
1365 appendPQExpBuffer(oidFetchQry, "Fetch %d in blobOid", loFetchSize);
1372 res = PQexec(g_conn, oidFetchQry->data);
1373 check_sql_result(res, g_conn, oidFetchQry->data, PGRES_TUPLES_OK);
1375 /* Process the tuples, if any */
1376 for (i = 0; i < PQntuples(res); i++)
1378 blobOid = atooid(PQgetvalue(res, i, 0));
1380 loFd = lo_open(g_conn, blobOid, INV_READ);
1383 write_msg(NULL, "dumpBlobs(): could not open large object: %s",
1384 PQerrorMessage(g_conn));
1388 StartBlob(AH, blobOid);
1390 /* Now read it in chunks, sending data to archive */
1393 cnt = lo_read(g_conn, loFd, buf, loBufSize);
1396 write_msg(NULL, "dumpBlobs(): error reading large object: %s",
1397 PQerrorMessage(g_conn));
1401 WriteData(AH, buf, cnt);
1405 lo_close(g_conn, loFd);
1407 EndBlob(AH, blobOid);
1410 } while (PQntuples(res) > 0);
1412 destroyPQExpBuffer(oidQry);
1413 destroyPQExpBuffer(oidFetchQry);
1420 * read all namespaces in the system catalogs and return them in the
1421 * NamespaceInfo* structure
1423 * numNamespaces is set to the number of namespaces read in
1426 getNamespaces(int *numNamespaces)
1432 NamespaceInfo *nsinfo;
1440 * Before 7.3, there are no real namespaces; create two dummy entries,
1441 * one for user stuff and one for system stuff.
1443 if (g_fout->remoteVersion < 70300)
1445 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
1447 nsinfo[0].dobj.objType = DO_NAMESPACE;
1448 nsinfo[0].dobj.catId.tableoid = 0;
1449 nsinfo[0].dobj.catId.oid = 0;
1450 AssignDumpId(&nsinfo[0].dobj);
1451 nsinfo[0].dobj.name = strdup("");
1452 nsinfo[0].usename = strdup("");
1453 nsinfo[0].nspacl = strdup("");
1455 selectDumpableNamespace(&nsinfo[0]);
1457 nsinfo[1].dobj.objType = DO_NAMESPACE;
1458 nsinfo[1].dobj.catId.tableoid = 0;
1459 nsinfo[1].dobj.catId.oid = 1;
1460 AssignDumpId(&nsinfo[1].dobj);
1461 nsinfo[1].dobj.name = strdup("pg_catalog");
1462 nsinfo[1].usename = strdup("");
1463 nsinfo[1].nspacl = strdup("");
1465 selectDumpableNamespace(&nsinfo[1]);
1467 g_namespaces = nsinfo;
1468 g_numNamespaces = *numNamespaces = 2;
1473 query = createPQExpBuffer();
1475 /* Make sure we are in proper schema */
1476 selectSourceSchema("pg_catalog");
1479 * we fetch all namespaces including system ones, so that every object
1480 * we read in can be linked to a containing namespace.
1482 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1483 "(select usename from pg_user where nspowner = usesysid) as usename, "
1485 "FROM pg_namespace");
1487 res = PQexec(g_conn, query->data);
1488 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1490 ntups = PQntuples(res);
1492 nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1494 i_tableoid = PQfnumber(res, "tableoid");
1495 i_oid = PQfnumber(res, "oid");
1496 i_nspname = PQfnumber(res, "nspname");
1497 i_usename = PQfnumber(res, "usename");
1498 i_nspacl = PQfnumber(res, "nspacl");
1500 for (i = 0; i < ntups; i++)
1502 nsinfo[i].dobj.objType = DO_NAMESPACE;
1503 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1504 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1505 AssignDumpId(&nsinfo[i].dobj);
1506 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
1507 nsinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1508 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1510 /* Decide whether to dump this namespace */
1511 selectDumpableNamespace(&nsinfo[i]);
1513 if (strlen(nsinfo[i].usename) == 0)
1514 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
1515 nsinfo[i].dobj.name);
1519 * If the user attempted to dump a specific namespace, check to ensure
1520 * that the specified namespace actually exists.
1522 if (selectSchemaName)
1524 for (i = 0; i < ntups; i++)
1525 if (strcmp(nsinfo[i].dobj.name, selectSchemaName) == 0)
1528 /* Didn't find a match */
1531 write_msg(NULL, "specified schema \"%s\" does not exist\n",
1538 destroyPQExpBuffer(query);
1540 g_namespaces = nsinfo;
1541 g_numNamespaces = *numNamespaces = ntups;
1548 * given a namespace OID and an object OID, look up the info read by
1551 * NB: for pre-7.3 source database, we use object OID to guess whether it's
1552 * a system object or not. In 7.3 and later there is no guessing.
1554 static NamespaceInfo *
1555 findNamespace(Oid nsoid, Oid objoid)
1559 if (g_fout->remoteVersion >= 70300)
1561 for (i = 0; i < g_numNamespaces; i++)
1563 NamespaceInfo *nsinfo = &g_namespaces[i];
1565 if (nsoid == nsinfo->dobj.catId.oid)
1568 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
1573 /* This code depends on the layout set up by getNamespaces. */
1574 if (objoid > g_last_builtin_oid)
1575 i = 0; /* user object */
1577 i = 1; /* system object */
1578 return &g_namespaces[i];
1581 return NULL; /* keep compiler quiet */
1586 * read all types in the system catalogs and return them in the
1587 * TypeInfo* structure
1589 * numTypes is set to the number of types read in
1591 * NB: this must run after getFuncs() because we assume we can do
1595 getTypes(int *numTypes)
1600 PQExpBuffer query = createPQExpBuffer();
1616 * we include even the built-in types because those may be used as
1617 * array elements by user-defined types
1619 * we filter out the built-in types when we dump out the types
1621 * same approach for undefined (shell) types
1624 /* Make sure we are in proper schema */
1625 selectSourceSchema("pg_catalog");
1627 if (g_fout->remoteVersion >= 70300)
1629 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1631 "(select usename from pg_user where typowner = usesysid) as usename, "
1632 "typinput::oid as typinput, "
1633 "typoutput::oid as typoutput, typelem, typrelid, "
1634 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1635 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1636 "typtype, typisdefined "
1639 else if (g_fout->remoteVersion >= 70100)
1641 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1642 "0::oid as typnamespace, "
1643 "(select usename from pg_user where typowner = usesysid) as usename, "
1644 "typinput::oid as typinput, "
1645 "typoutput::oid as typoutput, typelem, typrelid, "
1646 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1647 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1648 "typtype, typisdefined "
1653 appendPQExpBuffer(query, "SELECT "
1654 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
1656 "0::oid as typnamespace, "
1657 "(select usename from pg_user where typowner = usesysid) as usename, "
1658 "typinput::oid as typinput, "
1659 "typoutput::oid as typoutput, typelem, typrelid, "
1660 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1661 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1662 "typtype, typisdefined "
1666 res = PQexec(g_conn, query->data);
1667 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1669 ntups = PQntuples(res);
1671 tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1673 i_tableoid = PQfnumber(res, "tableoid");
1674 i_oid = PQfnumber(res, "oid");
1675 i_typname = PQfnumber(res, "typname");
1676 i_typnamespace = PQfnumber(res, "typnamespace");
1677 i_usename = PQfnumber(res, "usename");
1678 i_typinput = PQfnumber(res, "typinput");
1679 i_typoutput = PQfnumber(res, "typoutput");
1680 i_typelem = PQfnumber(res, "typelem");
1681 i_typrelid = PQfnumber(res, "typrelid");
1682 i_typrelkind = PQfnumber(res, "typrelkind");
1683 i_typtype = PQfnumber(res, "typtype");
1684 i_typisdefined = PQfnumber(res, "typisdefined");
1686 for (i = 0; i < ntups; i++)
1691 tinfo[i].dobj.objType = DO_TYPE;
1692 tinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1693 tinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1694 AssignDumpId(&tinfo[i].dobj);
1695 tinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
1696 tinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
1697 tinfo[i].dobj.catId.oid);
1698 tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1699 tinfo[i].typinput = atooid(PQgetvalue(res, i, i_typinput));
1700 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
1701 tinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
1702 tinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
1703 tinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
1704 tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
1707 * If it's a table's rowtype, use special type code to facilitate
1708 * sorting into the desired order. (We don't want to consider it
1709 * an ordinary type because that would bring the table up into the
1710 * datatype part of the dump order.)
1712 if (OidIsValid(tinfo[i].typrelid) && tinfo[i].typrelkind != 'c')
1713 tinfo[i].dobj.objType = DO_TABLE_TYPE;
1716 * check for user-defined array types, omit system generated ones
1718 if (OidIsValid(tinfo[i].typelem) &&
1719 tinfo[i].dobj.name[0] != '_')
1720 tinfo[i].isArray = true;
1722 tinfo[i].isArray = false;
1724 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
1725 tinfo[i].isDefined = true;
1727 tinfo[i].isDefined = false;
1730 * If it's a domain, fetch info about its constraints, if any
1732 tinfo[i].nDomChecks = 0;
1733 tinfo[i].domChecks = NULL;
1734 if (tinfo[i].typtype == 'd')
1735 getDomainConstraints(&(tinfo[i]));
1738 * Make sure there are dependencies from the type to its input and
1739 * output functions. (We don't worry about typsend, typreceive, or
1740 * typanalyze since those are only valid in 7.4 and later, wherein
1741 * the standard dependency mechanism will pick them up.)
1743 funcInfo = findFuncByOid(tinfo[i].typinput);
1745 addObjectDependency(&tinfo[i].dobj,
1746 funcInfo->dobj.dumpId);
1747 funcInfo = findFuncByOid(typoutput);
1749 addObjectDependency(&tinfo[i].dobj,
1750 funcInfo->dobj.dumpId);
1752 if (strlen(tinfo[i].usename) == 0 && tinfo[i].isDefined)
1753 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
1754 tinfo[i].dobj.name);
1761 destroyPQExpBuffer(query);
1768 * read all operators in the system catalogs and return them in the
1769 * OprInfo* structure
1771 * numOprs is set to the number of operators read in
1774 getOperators(int *numOprs)
1779 PQExpBuffer query = createPQExpBuffer();
1789 * find all operators, including builtin operators; we filter out
1790 * system-defined operators at dump-out time.
1793 /* Make sure we are in proper schema */
1794 selectSourceSchema("pg_catalog");
1796 if (g_fout->remoteVersion >= 70300)
1798 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1800 "(select usename from pg_user where oprowner = usesysid) as usename, "
1801 "oprcode::oid as oprcode "
1802 "FROM pg_operator");
1804 else if (g_fout->remoteVersion >= 70100)
1806 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1807 "0::oid as oprnamespace, "
1808 "(select usename from pg_user where oprowner = usesysid) as usename, "
1809 "oprcode::oid as oprcode "
1810 "FROM pg_operator");
1814 appendPQExpBuffer(query, "SELECT "
1815 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
1817 "0::oid as oprnamespace, "
1818 "(select usename from pg_user where oprowner = usesysid) as usename, "
1819 "oprcode::oid as oprcode "
1820 "FROM pg_operator");
1823 res = PQexec(g_conn, query->data);
1824 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1826 ntups = PQntuples(res);
1829 oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
1831 i_tableoid = PQfnumber(res, "tableoid");
1832 i_oid = PQfnumber(res, "oid");
1833 i_oprname = PQfnumber(res, "oprname");
1834 i_oprnamespace = PQfnumber(res, "oprnamespace");
1835 i_usename = PQfnumber(res, "usename");
1836 i_oprcode = PQfnumber(res, "oprcode");
1838 for (i = 0; i < ntups; i++)
1840 oprinfo[i].dobj.objType = DO_OPERATOR;
1841 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1842 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1843 AssignDumpId(&oprinfo[i].dobj);
1844 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
1845 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
1846 oprinfo[i].dobj.catId.oid);
1847 oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1848 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
1850 if (strlen(oprinfo[i].usename) == 0)
1851 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
1852 oprinfo[i].dobj.name);
1857 destroyPQExpBuffer(query);
1864 * read all conversions in the system catalogs and return them in the
1865 * ConvInfo* structure
1867 * numConversions is set to the number of conversions read in
1870 getConversions(int *numConversions)
1875 PQExpBuffer query = createPQExpBuffer();
1883 /* Conversions didn't exist pre-7.3 */
1884 if (g_fout->remoteVersion < 70300) {
1885 *numConversions = 0;
1890 * find all conversions, including builtin conversions; we filter out
1891 * system-defined conversions at dump-out time.
1894 /* Make sure we are in proper schema */
1895 selectSourceSchema("pg_catalog");
1897 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
1899 "(select usename from pg_user where conowner = usesysid) as usename "
1900 "FROM pg_conversion");
1902 res = PQexec(g_conn, query->data);
1903 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1905 ntups = PQntuples(res);
1906 *numConversions = ntups;
1908 convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
1910 i_tableoid = PQfnumber(res, "tableoid");
1911 i_oid = PQfnumber(res, "oid");
1912 i_conname = PQfnumber(res, "conname");
1913 i_connamespace = PQfnumber(res, "connamespace");
1914 i_usename = PQfnumber(res, "usename");
1916 for (i = 0; i < ntups; i++)
1918 convinfo[i].dobj.objType = DO_CONVERSION;
1919 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1920 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1921 AssignDumpId(&convinfo[i].dobj);
1922 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
1923 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
1924 convinfo[i].dobj.catId.oid);
1925 convinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1930 destroyPQExpBuffer(query);
1937 * read all opclasses in the system catalogs and return them in the
1938 * OpclassInfo* structure
1940 * numOpclasses is set to the number of opclasses read in
1943 getOpclasses(int *numOpclasses)
1948 PQExpBuffer query = createPQExpBuffer();
1949 OpclassInfo *opcinfo;
1957 * find all opclasses, including builtin opclasses; we filter out
1958 * system-defined opclasses at dump-out time.
1961 /* Make sure we are in proper schema */
1962 selectSourceSchema("pg_catalog");
1964 if (g_fout->remoteVersion >= 70300)
1966 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
1968 "(select usename from pg_user where opcowner = usesysid) as usename "
1971 else if (g_fout->remoteVersion >= 70100)
1973 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
1974 "0::oid as opcnamespace, "
1975 "''::name as usename "
1980 appendPQExpBuffer(query, "SELECT "
1981 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
1983 "0::oid as opcnamespace, "
1984 "''::name as usename "
1988 res = PQexec(g_conn, query->data);
1989 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1991 ntups = PQntuples(res);
1992 *numOpclasses = ntups;
1994 opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
1996 i_tableoid = PQfnumber(res, "tableoid");
1997 i_oid = PQfnumber(res, "oid");
1998 i_opcname = PQfnumber(res, "opcname");
1999 i_opcnamespace = PQfnumber(res, "opcnamespace");
2000 i_usename = PQfnumber(res, "usename");
2002 for (i = 0; i < ntups; i++)
2004 opcinfo[i].dobj.objType = DO_OPCLASS;
2005 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2006 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2007 AssignDumpId(&opcinfo[i].dobj);
2008 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
2009 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
2010 opcinfo[i].dobj.catId.oid);
2011 opcinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2013 if (g_fout->remoteVersion >= 70300)
2015 if (strlen(opcinfo[i].usename) == 0)
2016 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
2017 opcinfo[i].dobj.name);
2023 destroyPQExpBuffer(query);
2030 * read all the user-defined aggregates in the system catalogs and
2031 * return them in the AggInfo* structure
2033 * numAggs is set to the number of aggregates read in
2036 getAggregates(int *numAggs)
2041 PQExpBuffer query = createPQExpBuffer();
2051 /* Make sure we are in proper schema */
2052 selectSourceSchema("pg_catalog");
2054 /* find all user-defined aggregates */
2056 if (g_fout->remoteVersion >= 70300)
2058 appendPQExpBuffer(query, "SELECT tableoid, oid, proname as aggname, "
2059 "pronamespace as aggnamespace, "
2060 "proargtypes[0] as aggbasetype, "
2061 "(select usename from pg_user where proowner = usesysid) as usename, "
2065 "AND pronamespace != "
2066 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2068 else if (g_fout->remoteVersion >= 70100)
2070 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
2071 "0::oid as aggnamespace, "
2073 "(select usename from pg_user where aggowner = usesysid) as usename, "
2075 "FROM pg_aggregate "
2076 "where oid > '%u'::oid",
2077 g_last_builtin_oid);
2081 appendPQExpBuffer(query, "SELECT "
2082 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
2084 "0::oid as aggnamespace, "
2086 "(select usename from pg_user where aggowner = usesysid) as usename, "
2088 "FROM pg_aggregate "
2089 "where oid > '%u'::oid",
2090 g_last_builtin_oid);
2093 res = PQexec(g_conn, query->data);
2094 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2096 ntups = PQntuples(res);
2099 agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
2101 i_tableoid = PQfnumber(res, "tableoid");
2102 i_oid = PQfnumber(res, "oid");
2103 i_aggname = PQfnumber(res, "aggname");
2104 i_aggnamespace = PQfnumber(res, "aggnamespace");
2105 i_aggbasetype = PQfnumber(res, "aggbasetype");
2106 i_usename = PQfnumber(res, "usename");
2107 i_aggacl = PQfnumber(res, "aggacl");
2109 for (i = 0; i < ntups; i++)
2111 agginfo[i].aggfn.dobj.objType = DO_AGG;
2112 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2113 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2114 AssignDumpId(&agginfo[i].aggfn.dobj);
2115 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
2116 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
2117 agginfo[i].aggfn.dobj.catId.oid);
2118 agginfo[i].aggfn.usename = strdup(PQgetvalue(res, i, i_usename));
2119 if (strlen(agginfo[i].aggfn.usename) == 0)
2120 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
2121 agginfo[i].aggfn.dobj.name);
2122 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
2123 agginfo[i].aggfn.nargs = 1;
2124 agginfo[i].aggfn.argtypes = (Oid *) malloc(sizeof(Oid));
2125 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_aggbasetype));
2126 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
2127 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
2128 agginfo[i].anybasetype = false; /* computed when it's dumped */
2129 agginfo[i].fmtbasetype = NULL; /* computed when it's dumped */
2134 destroyPQExpBuffer(query);
2141 * read all the user-defined functions in the system catalogs and
2142 * return them in the FuncInfo* structure
2144 * numFuncs is set to the number of functions read in
2147 getFuncs(int *numFuncs)
2152 PQExpBuffer query = createPQExpBuffer();
2165 /* Make sure we are in proper schema */
2166 selectSourceSchema("pg_catalog");
2168 /* find all user-defined funcs */
2170 if (g_fout->remoteVersion >= 70300)
2172 appendPQExpBuffer(query,
2173 "SELECT tableoid, oid, proname, prolang, "
2174 "pronargs, proargtypes, prorettype, proacl, "
2176 "(select usename from pg_user where proowner = usesysid) as usename "
2178 "WHERE NOT proisagg "
2179 "AND pronamespace != "
2180 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2182 else if (g_fout->remoteVersion >= 70100)
2184 appendPQExpBuffer(query,
2185 "SELECT tableoid, oid, proname, prolang, "
2186 "pronargs, proargtypes, prorettype, "
2187 "'{=X}' as proacl, "
2188 "0::oid as pronamespace, "
2189 "(select usename from pg_user where proowner = usesysid) as usename "
2191 "where pg_proc.oid > '%u'::oid",
2192 g_last_builtin_oid);
2196 appendPQExpBuffer(query,
2198 "(SELECT oid FROM pg_class WHERE relname = 'pg_proc') AS tableoid, "
2199 "oid, proname, prolang, "
2200 "pronargs, proargtypes, prorettype, "
2201 "'{=X}' as proacl, "
2202 "0::oid as pronamespace, "
2203 "(select usename from pg_user where proowner = usesysid) as usename "
2205 "where pg_proc.oid > '%u'::oid",
2206 g_last_builtin_oid);
2209 res = PQexec(g_conn, query->data);
2210 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2212 ntups = PQntuples(res);
2216 finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
2218 i_tableoid = PQfnumber(res, "tableoid");
2219 i_oid = PQfnumber(res, "oid");
2220 i_proname = PQfnumber(res, "proname");
2221 i_pronamespace = PQfnumber(res, "pronamespace");
2222 i_usename = PQfnumber(res, "usename");
2223 i_prolang = PQfnumber(res, "prolang");
2224 i_pronargs = PQfnumber(res, "pronargs");
2225 i_proargtypes = PQfnumber(res, "proargtypes");
2226 i_prorettype = PQfnumber(res, "prorettype");
2227 i_proacl = PQfnumber(res, "proacl");
2229 for (i = 0; i < ntups; i++)
2231 finfo[i].dobj.objType = DO_FUNC;
2232 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2233 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2234 AssignDumpId(&finfo[i].dobj);
2235 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
2236 finfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
2237 finfo[i].dobj.catId.oid);
2238 finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2239 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2240 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
2241 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
2242 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
2243 if (finfo[i].nargs == 0)
2244 finfo[i].argtypes = NULL;
2247 finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
2248 parseOidArray(PQgetvalue(res, i, i_proargtypes),
2249 finfo[i].argtypes, finfo[i].nargs);
2252 if (strlen(finfo[i].usename) == 0)
2253 write_msg(NULL, "WARNING: owner of function \"%s\" appears to be invalid\n",
2254 finfo[i].dobj.name);
2259 destroyPQExpBuffer(query);
2266 * read all the user-defined tables (no indexes, no catalogs)
2267 * in the system catalogs return them in the TableInfo* structure
2269 * numTables is set to the number of tables read in
2272 getTables(int *numTables)
2277 PQExpBuffer query = createPQExpBuffer();
2278 PQExpBuffer delqry = createPQExpBuffer();
2279 PQExpBuffer lockquery = createPQExpBuffer();
2296 /* Make sure we are in proper schema */
2297 selectSourceSchema("pg_catalog");
2300 * Find all the tables (including views and sequences).
2302 * We include system catalogs, so that we can work if a user table is
2303 * defined to inherit from a system catalog (pretty weird, but...)
2305 * We ignore tables that are not type 'r' (ordinary relation) or 'S'
2306 * (sequence) or 'v' (view).
2308 * Note: in this phase we should collect only a minimal amount of
2309 * information about each table, basically just enough to decide if it
2310 * is interesting. We must fetch all tables in this phase because
2311 * otherwise we cannot correctly identify inherited columns, serial
2315 if (g_fout->remoteVersion >= 70300)
2318 * Left join to pick up dependency info linking sequences to their
2319 * serial column, if any
2321 appendPQExpBuffer(query,
2322 "SELECT c.tableoid, c.oid, relname, "
2323 "relacl, relkind, relnamespace, "
2324 "(select usename from pg_user where relowner = usesysid) as usename, "
2325 "relchecks, reltriggers, "
2326 "relhasindex, relhasrules, relhasoids, "
2327 "d.refobjid as owning_tab, "
2328 "d.refobjsubid as owning_col "
2330 "left join pg_depend d on "
2331 "(c.relkind = '%c' and "
2332 "d.classid = c.tableoid and d.objid = c.oid and "
2333 "d.objsubid = 0 and "
2334 "d.refclassid = c.tableoid and d.deptype = 'i') "
2335 "where relkind in ('%c', '%c', '%c') "
2338 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2340 else if (g_fout->remoteVersion >= 70200)
2342 appendPQExpBuffer(query,
2343 "SELECT tableoid, oid, relname, relacl, relkind, "
2344 "0::oid as relnamespace, "
2345 "(select usename from pg_user where relowner = usesysid) as usename, "
2346 "relchecks, reltriggers, "
2347 "relhasindex, relhasrules, relhasoids, "
2348 "NULL::oid as owning_tab, "
2349 "NULL::int4 as owning_col "
2351 "where relkind in ('%c', '%c', '%c') "
2353 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2355 else if (g_fout->remoteVersion >= 70100)
2357 /* all tables have oids in 7.1 */
2358 appendPQExpBuffer(query,
2359 "SELECT tableoid, oid, relname, relacl, relkind, "
2360 "0::oid as relnamespace, "
2361 "(select usename from pg_user where relowner = usesysid) as usename, "
2362 "relchecks, reltriggers, "
2363 "relhasindex, relhasrules, "
2364 "'t'::bool as relhasoids, "
2365 "NULL::oid as owning_tab, "
2366 "NULL::int4 as owning_col "
2368 "where relkind in ('%c', '%c', '%c') "
2370 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2375 * Before 7.1, view relkind was not set to 'v', so we must check
2376 * if we have a view by looking for a rule in pg_rewrite.
2378 appendPQExpBuffer(query,
2380 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2381 "oid, relname, relacl, "
2382 "CASE WHEN relhasrules and relkind = 'r' "
2383 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
2384 " r.ev_class = c.oid AND r.ev_type = '1') "
2385 "THEN '%c'::\"char\" "
2386 "ELSE relkind END AS relkind,"
2387 "0::oid as relnamespace, "
2388 "(select usename from pg_user where relowner = usesysid) as usename, "
2389 "relchecks, reltriggers, "
2390 "relhasindex, relhasrules, "
2391 "'t'::bool as relhasoids, "
2392 "NULL::oid as owning_tab, "
2393 "NULL::int4 as owning_col "
2395 "where relkind in ('%c', '%c') "
2398 RELKIND_RELATION, RELKIND_SEQUENCE);
2401 res = PQexec(g_conn, query->data);
2402 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2404 ntups = PQntuples(res);
2409 * Extract data from result and lock dumpable tables. We do the
2410 * locking before anything else, to minimize the window wherein a
2411 * table could disappear under us.
2413 * Note that we have to save info about all tables here, even when
2414 * dumping only one, because we don't yet know which tables might be
2415 * inheritance ancestors of the target table.
2417 tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
2419 i_reltableoid = PQfnumber(res, "tableoid");
2420 i_reloid = PQfnumber(res, "oid");
2421 i_relname = PQfnumber(res, "relname");
2422 i_relnamespace = PQfnumber(res, "relnamespace");
2423 i_relacl = PQfnumber(res, "relacl");
2424 i_relkind = PQfnumber(res, "relkind");
2425 i_usename = PQfnumber(res, "usename");
2426 i_relchecks = PQfnumber(res, "relchecks");
2427 i_reltriggers = PQfnumber(res, "reltriggers");
2428 i_relhasindex = PQfnumber(res, "relhasindex");
2429 i_relhasrules = PQfnumber(res, "relhasrules");
2430 i_relhasoids = PQfnumber(res, "relhasoids");
2431 i_owning_tab = PQfnumber(res, "owning_tab");
2432 i_owning_col = PQfnumber(res, "owning_col");
2434 for (i = 0; i < ntups; i++)
2436 tblinfo[i].dobj.objType = DO_TABLE;
2437 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
2438 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
2439 AssignDumpId(&tblinfo[i].dobj);
2440 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
2441 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
2442 tblinfo[i].dobj.catId.oid);
2443 tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2444 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
2445 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
2446 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
2447 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
2448 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
2449 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
2450 tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2451 if (PQgetisnull(res, i, i_owning_tab))
2453 tblinfo[i].owning_tab = InvalidOid;
2454 tblinfo[i].owning_col = 0;
2458 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
2459 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
2462 /* other fields were zeroed above */
2465 * Decide whether we want to dump this table. Sequences owned by
2466 * serial columns are never dumpable on their own; we will
2467 * transpose their owning table's dump flag to them below.
2469 if (OidIsValid(tblinfo[i].owning_tab))
2470 tblinfo[i].dump = false;
2472 selectDumpableTable(&tblinfo[i]);
2473 tblinfo[i].interesting = tblinfo[i].dump;
2476 * Read-lock target tables to make sure they aren't DROPPED or
2477 * altered in schema before we get around to dumping them.
2479 * Note that we don't explicitly lock parents of the target tables;
2480 * we assume our lock on the child is enough to prevent schema
2481 * alterations to parent tables.
2483 * NOTE: it'd be kinda nice to lock views and sequences too, not only
2484 * plain tables, but the backend doesn't presently allow that.
2486 if (tblinfo[i].dump && tblinfo[i].relkind == RELKIND_RELATION)
2488 resetPQExpBuffer(lockquery);
2489 appendPQExpBuffer(lockquery,
2490 "LOCK TABLE %s IN ACCESS SHARE MODE",
2491 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
2492 tblinfo[i].dobj.name));
2493 do_sql_command(g_conn, lockquery->data);
2496 /* Emit notice if join for owner failed */
2497 if (strlen(tblinfo[i].usename) == 0)
2498 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
2499 tblinfo[i].dobj.name);
2503 * If the user is attempting to dump a specific table, check to ensure
2504 * that the specified table actually exists. (This is a bit simplistic
2505 * since we don't fully check the combination of -n and -t switches.)
2507 if (selectTableName)
2509 for (i = 0; i < ntups; i++)
2510 if (strcmp(tblinfo[i].dobj.name, selectTableName) == 0)
2513 /* Didn't find a match */
2516 write_msg(NULL, "specified table \"%s\" does not exist\n",
2523 destroyPQExpBuffer(query);
2524 destroyPQExpBuffer(delqry);
2525 destroyPQExpBuffer(lockquery);
2532 * read all the inheritance information
2533 * from the system catalogs return them in the InhInfo* structure
2535 * numInherits is set to the number of pairs read in
2538 getInherits(int *numInherits)
2543 PQExpBuffer query = createPQExpBuffer();
2549 /* Make sure we are in proper schema */
2550 selectSourceSchema("pg_catalog");
2552 /* find all the inheritance information */
2554 appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2556 res = PQexec(g_conn, query->data);
2557 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2559 ntups = PQntuples(res);
2561 *numInherits = ntups;
2563 inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
2565 i_inhrelid = PQfnumber(res, "inhrelid");
2566 i_inhparent = PQfnumber(res, "inhparent");
2568 for (i = 0; i < ntups; i++)
2570 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
2571 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
2576 destroyPQExpBuffer(query);
2583 * get information about every index on a dumpable table
2585 * Note: index data is not returned directly to the caller, but it
2586 * does get entered into the DumpableObject tables.
2589 getIndexes(TableInfo tblinfo[], int numTables)
2593 PQExpBuffer query = createPQExpBuffer();
2596 ConstraintInfo *constrinfo;
2610 for (i = 0; i < numTables; i++)
2612 TableInfo *tbinfo = &tblinfo[i];
2614 /* Only plain tables have indexes */
2615 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
2622 write_msg(NULL, "reading indexes for table \"%s\"\n",
2625 /* Make sure we are in proper schema so indexdef is right */
2626 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2629 * The point of the messy-looking outer join is to find a
2630 * constraint that is related by an internal dependency link to
2631 * the index. If we find one, create a CONSTRAINT entry linked
2632 * to the INDEX entry. We assume an index won't have more than
2633 * one internal dependency.
2635 resetPQExpBuffer(query);
2636 if (g_fout->remoteVersion >= 70300)
2638 appendPQExpBuffer(query,
2639 "SELECT t.tableoid, t.oid, "
2640 "t.relname as indexname, "
2641 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2642 "t.relnatts as indnkeys, "
2643 "i.indkey, i.indisclustered, "
2644 "c.contype, c.conname, "
2645 "c.tableoid as contableoid, "
2647 "FROM pg_catalog.pg_index i "
2648 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2649 "LEFT JOIN pg_catalog.pg_depend d "
2650 "ON (d.classid = t.tableoid "
2651 "AND d.objid = t.oid "
2652 "AND d.deptype = 'i') "
2653 "LEFT JOIN pg_catalog.pg_constraint c "
2654 "ON (d.refclassid = c.tableoid "
2655 "AND d.refobjid = c.oid) "
2656 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2657 "ORDER BY indexname",
2658 tbinfo->dobj.catId.oid);
2660 else if (g_fout->remoteVersion >= 70100)
2662 appendPQExpBuffer(query,
2663 "SELECT t.tableoid, t.oid, "
2664 "t.relname as indexname, "
2665 "pg_get_indexdef(i.indexrelid) as indexdef, "
2666 "t.relnatts as indnkeys, "
2667 "i.indkey, false as indisclustered, "
2668 "CASE WHEN i.indisprimary THEN 'p'::char "
2669 "ELSE '0'::char END as contype, "
2670 "t.relname as conname, "
2671 "0::oid as contableoid, "
2673 "FROM pg_index i, pg_class t "
2674 "WHERE t.oid = i.indexrelid "
2675 "AND i.indrelid = '%u'::oid "
2676 "ORDER BY indexname",
2677 tbinfo->dobj.catId.oid);
2681 appendPQExpBuffer(query,
2683 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2685 "t.relname as indexname, "
2686 "pg_get_indexdef(i.indexrelid) as indexdef, "
2687 "t.relnatts as indnkeys, "
2688 "i.indkey, false as indisclustered, "
2689 "CASE WHEN i.indisprimary THEN 'p'::char "
2690 "ELSE '0'::char END as contype, "
2691 "t.relname as conname, "
2692 "0::oid as contableoid, "
2694 "FROM pg_index i, pg_class t "
2695 "WHERE t.oid = i.indexrelid "
2696 "AND i.indrelid = '%u'::oid "
2697 "ORDER BY indexname",
2698 tbinfo->dobj.catId.oid);
2701 res = PQexec(g_conn, query->data);
2702 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2704 ntups = PQntuples(res);
2706 i_tableoid = PQfnumber(res, "tableoid");
2707 i_oid = PQfnumber(res, "oid");
2708 i_indexname = PQfnumber(res, "indexname");
2709 i_indexdef = PQfnumber(res, "indexdef");
2710 i_indnkeys = PQfnumber(res, "indnkeys");
2711 i_indkey = PQfnumber(res, "indkey");
2712 i_indisclustered = PQfnumber(res, "indisclustered");
2713 i_contype = PQfnumber(res, "contype");
2714 i_conname = PQfnumber(res, "conname");
2715 i_contableoid = PQfnumber(res, "contableoid");
2716 i_conoid = PQfnumber(res, "conoid");
2718 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
2719 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2721 for (j = 0; j < ntups; j++)
2725 indxinfo[j].dobj.objType = DO_INDEX;
2726 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
2727 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
2728 AssignDumpId(&indxinfo[j].dobj);
2729 indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
2730 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2731 indxinfo[j].indextable = tbinfo;
2732 indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
2733 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
2735 * In pre-7.4 releases, indkeys may contain more entries than
2736 * indnkeys says (since indnkeys will be 1 for a functional
2737 * index). We don't actually care about this case since we don't
2738 * examine indkeys except for indexes associated with PRIMARY
2739 * and UNIQUE constraints, which are never functional indexes.
2740 * But we have to allocate enough space to keep parseOidArray
2743 indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
2744 parseOidArray(PQgetvalue(res, j, i_indkey),
2745 indxinfo[j].indkeys, INDEX_MAX_KEYS);
2746 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
2747 contype = *(PQgetvalue(res, j, i_contype));
2749 if (contype == 'p' || contype == 'u')
2752 * If we found a constraint matching the index, create an
2755 * In a pre-7.3 database, we take this path iff the index was
2756 * marked indisprimary.
2758 constrinfo[j].dobj.objType = DO_CONSTRAINT;
2759 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2760 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2761 AssignDumpId(&constrinfo[j].dobj);
2762 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2763 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2764 constrinfo[j].contable = tbinfo;
2765 constrinfo[j].condomain = NULL;
2766 constrinfo[j].contype = contype;
2767 constrinfo[j].condef = NULL;
2768 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
2769 constrinfo[j].coninherited = false;
2770 constrinfo[j].separate = true;
2772 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
2774 /* If pre-7.3 DB, better make sure table comes first */
2775 addObjectDependency(&constrinfo[j].dobj,
2776 tbinfo->dobj.dumpId);
2780 /* Plain secondary index */
2781 indxinfo[j].indexconstraint = 0;
2788 destroyPQExpBuffer(query);
2794 * Get info about constraints on dumpable tables.
2796 * Currently handles foreign keys only.
2797 * Unique and primary key constraints are handled with indexes,
2798 * while check constraints are processed in getTableAttrs().
2801 getConstraints(TableInfo tblinfo[], int numTables)
2805 ConstraintInfo *constrinfo;
2814 /* pg_constraint was created in 7.3, so nothing to do if older */
2815 if (g_fout->remoteVersion < 70300)
2818 query = createPQExpBuffer();
2820 for (i = 0; i < numTables; i++)
2822 TableInfo *tbinfo = &tblinfo[i];
2824 if (tbinfo->ntrig == 0 || !tbinfo->dump)
2828 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
2832 * select table schema to ensure constraint expr is qualified if
2835 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2837 resetPQExpBuffer(query);
2838 appendPQExpBuffer(query,
2839 "SELECT tableoid, oid, conname, "
2840 "pg_catalog.pg_get_constraintdef(oid) as condef "
2841 "FROM pg_catalog.pg_constraint "
2842 "WHERE conrelid = '%u'::pg_catalog.oid "
2843 "AND contype = 'f'",
2844 tbinfo->dobj.catId.oid);
2845 res = PQexec(g_conn, query->data);
2846 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2848 ntups = PQntuples(res);
2850 i_contableoid = PQfnumber(res, "tableoid");
2851 i_conoid = PQfnumber(res, "oid");
2852 i_conname = PQfnumber(res, "conname");
2853 i_condef = PQfnumber(res, "condef");
2855 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2857 for (j = 0; j < ntups; j++)
2859 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
2860 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2861 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2862 AssignDumpId(&constrinfo[j].dobj);
2863 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2864 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2865 constrinfo[j].contable = tbinfo;
2866 constrinfo[j].condomain = NULL;
2867 constrinfo[j].contype = 'f';
2868 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
2869 constrinfo[j].conindex = 0;
2870 constrinfo[j].coninherited = false;
2871 constrinfo[j].separate = true;
2877 destroyPQExpBuffer(query);
2881 * getDomainConstraints
2883 * Get info about constraints on a domain.
2886 getDomainConstraints(TypeInfo *tinfo)
2889 ConstraintInfo *constrinfo;
2898 /* pg_constraint was created in 7.3, so nothing to do if older */
2899 if (g_fout->remoteVersion < 70300)
2903 * select appropriate schema to ensure names in constraint are properly
2906 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
2908 query = createPQExpBuffer();
2910 if (g_fout->remoteVersion >= 70400)
2911 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
2912 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
2913 "FROM pg_catalog.pg_constraint "
2914 "WHERE contypid = '%u'::pg_catalog.oid "
2916 tinfo->dobj.catId.oid);
2918 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
2919 "'CHECK (' || consrc || ')' AS consrc "
2920 "FROM pg_catalog.pg_constraint "
2921 "WHERE contypid = '%u'::pg_catalog.oid "
2923 tinfo->dobj.catId.oid);
2925 res = PQexec(g_conn, query->data);
2926 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2928 ntups = PQntuples(res);
2930 i_tableoid = PQfnumber(res, "tableoid");
2931 i_oid = PQfnumber(res, "oid");
2932 i_conname = PQfnumber(res, "conname");
2933 i_consrc = PQfnumber(res, "consrc");
2935 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2937 tinfo->nDomChecks = ntups;
2938 tinfo->domChecks = constrinfo;
2940 for (i = 0; i < ntups; i++)
2942 constrinfo[i].dobj.objType = DO_CONSTRAINT;
2943 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2944 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2945 AssignDumpId(&constrinfo[i].dobj);
2946 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
2947 constrinfo[i].dobj.namespace = tinfo->dobj.namespace;
2948 constrinfo[i].contable = NULL;
2949 constrinfo[i].condomain = tinfo;
2950 constrinfo[i].contype = 'c';
2951 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
2952 constrinfo[i].conindex = 0;
2953 constrinfo[i].coninherited = false;
2954 constrinfo[i].separate = false;
2956 * Make the domain depend on the constraint, ensuring it won't
2957 * be output till any constraint dependencies are OK.
2959 addObjectDependency(&tinfo->dobj,
2960 constrinfo[i].dobj.dumpId);
2965 destroyPQExpBuffer(query);
2970 * get basic information about every rule in the system
2972 * numRules is set to the number of rules read in
2975 getRules(int *numRules)
2980 PQExpBuffer query = createPQExpBuffer();
2989 /* Make sure we are in proper schema */
2990 selectSourceSchema("pg_catalog");
2992 if (g_fout->remoteVersion >= 70100)
2994 appendPQExpBuffer(query, "SELECT "
2995 "tableoid, oid, rulename, "
2996 "ev_class as ruletable, ev_type, is_instead "
3002 appendPQExpBuffer(query, "SELECT "
3003 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
3005 "ev_class as ruletable, ev_type, is_instead "
3010 res = PQexec(g_conn, query->data);
3011 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3013 ntups = PQntuples(res);
3017 ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
3019 i_tableoid = PQfnumber(res, "tableoid");
3020 i_oid = PQfnumber(res, "oid");
3021 i_rulename = PQfnumber(res, "rulename");
3022 i_ruletable = PQfnumber(res, "ruletable");
3023 i_ev_type = PQfnumber(res, "ev_type");
3024 i_is_instead = PQfnumber(res, "is_instead");
3026 for (i = 0; i < ntups; i++)
3030 ruleinfo[i].dobj.objType = DO_RULE;
3031 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3032 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3033 AssignDumpId(&ruleinfo[i].dobj);
3034 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
3035 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
3036 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
3037 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
3038 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
3039 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
3040 if (ruleinfo[i].ruletable)
3043 * If the table is a view, force its ON SELECT rule to be sorted
3044 * before the view itself --- this ensures that any dependencies
3045 * for the rule affect the table's positioning. Other rules
3046 * are forced to appear after their table.
3048 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
3049 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
3050 addObjectDependency(&ruleinfo[i].ruletable->dobj,
3051 ruleinfo[i].dobj.dumpId);
3053 addObjectDependency(&ruleinfo[i].dobj,
3054 ruleinfo[i].ruletable->dobj.dumpId);
3060 destroyPQExpBuffer(query);
3067 * get information about every trigger on a dumpable table
3069 * Note: trigger data is not returned directly to the caller, but it
3070 * does get entered into the DumpableObject tables.
3073 getTriggers(TableInfo tblinfo[], int numTables)
3077 PQExpBuffer query = createPQExpBuffer();
3079 TriggerInfo *tginfo;
3095 for (i = 0; i < numTables; i++)
3097 TableInfo *tbinfo = &tblinfo[i];
3099 if (tbinfo->ntrig == 0 || !tbinfo->dump)
3103 write_msg(NULL, "reading triggers for table \"%s\"\n",
3107 * select table schema to ensure regproc name is qualified if
3110 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3112 resetPQExpBuffer(query);
3113 if (g_fout->remoteVersion >= 70300)
3116 * We ignore triggers that are tied to a foreign-key
3119 appendPQExpBuffer(query,
3121 "tgfoid::pg_catalog.regproc as tgfname, "
3122 "tgtype, tgnargs, tgargs, "
3123 "tgisconstraint, tgconstrname, tgdeferrable, "
3124 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3125 "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
3126 "from pg_catalog.pg_trigger t "
3127 "where tgrelid = '%u'::pg_catalog.oid "
3128 "and (not tgisconstraint "
3130 " (SELECT 1 FROM pg_catalog.pg_depend d "
3131 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
3132 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
3133 tbinfo->dobj.catId.oid);
3135 else if (g_fout->remoteVersion >= 70100)
3137 appendPQExpBuffer(query,
3138 "SELECT tgname, tgfoid::regproc as tgfname, "
3139 "tgtype, tgnargs, tgargs, "
3140 "tgisconstraint, tgconstrname, tgdeferrable, "
3141 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3142 "(select relname from pg_class where oid = tgconstrrelid) "
3143 " as tgconstrrelname "
3145 "where tgrelid = '%u'::oid",
3146 tbinfo->dobj.catId.oid);
3150 appendPQExpBuffer(query,
3151 "SELECT tgname, tgfoid::regproc as tgfname, "
3152 "tgtype, tgnargs, tgargs, "
3153 "tgisconstraint, tgconstrname, tgdeferrable, "
3154 "tgconstrrelid, tginitdeferred, "
3155 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
3158 "(select relname from pg_class where oid = tgconstrrelid) "
3159 " as tgconstrrelname "
3161 "where tgrelid = '%u'::oid",
3162 tbinfo->dobj.catId.oid);
3164 res = PQexec(g_conn, query->data);
3165 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3167 ntups = PQntuples(res);
3170 * We may have less triggers than recorded due to having ignored
3171 * foreign-key triggers
3173 if (ntups > tbinfo->ntrig)
3175 write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
3176 tbinfo->ntrig, tbinfo->dobj.name, ntups);
3179 i_tableoid = PQfnumber(res, "tableoid");
3180 i_oid = PQfnumber(res, "oid");
3181 i_tgname = PQfnumber(res, "tgname");
3182 i_tgfname = PQfnumber(res, "tgfname");
3183 i_tgtype = PQfnumber(res, "tgtype");
3184 i_tgnargs = PQfnumber(res, "tgnargs");
3185 i_tgargs = PQfnumber(res, "tgargs");
3186 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
3187 i_tgconstrname = PQfnumber(res, "tgconstrname");
3188 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
3189 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
3190 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
3191 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
3193 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
3195 for (j = 0; j < ntups; j++)
3197 tginfo[j].dobj.objType = DO_TRIGGER;
3198 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3199 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3200 AssignDumpId(&tginfo[j].dobj);
3201 tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
3202 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
3203 tginfo[j].tgtable = tbinfo;
3204 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
3205 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
3206 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
3207 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
3208 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
3209 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
3210 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
3212 if (tginfo[j].tgisconstraint)
3214 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
3215 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
3216 if (OidIsValid(tginfo[j].tgconstrrelid))
3218 if (PQgetisnull(res, j, i_tgconstrrelname))
3220 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
3221 tginfo[j].dobj.name, tbinfo->dobj.name,
3222 tginfo[j].tgconstrrelid);
3225 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
3228 tginfo[j].tgconstrrelname = NULL;
3232 tginfo[j].tgconstrname = NULL;
3233 tginfo[j].tgconstrrelid = InvalidOid;
3234 tginfo[j].tgconstrrelname = NULL;
3241 destroyPQExpBuffer(query);
3246 * get basic information about every procedural language in the system
3248 * numProcLangs is set to the number of langs read in
3250 * NB: this must run after getFuncs() because we assume we can do
3254 getProcLangs(int *numProcLangs)
3259 PQExpBuffer query = createPQExpBuffer();
3260 ProcLangInfo *planginfo;
3265 int i_lanplcallfoid;
3266 int i_lanvalidator = -1;
3269 /* Make sure we are in proper schema */
3270 selectSourceSchema("pg_catalog");
3272 if (g_fout->remoteVersion >= 70100)
3274 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
3280 appendPQExpBuffer(query, "SELECT "
3281 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
3282 "oid, * FROM pg_language "
3287 res = PQexec(g_conn, query->data);
3288 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3290 ntups = PQntuples(res);
3292 *numProcLangs = ntups;
3294 planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
3296 i_tableoid = PQfnumber(res, "tableoid");
3297 i_oid = PQfnumber(res, "oid");
3298 i_lanname = PQfnumber(res, "lanname");
3299 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
3300 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
3301 if (g_fout->remoteVersion >= 70300)
3303 i_lanvalidator = PQfnumber(res, "lanvalidator");
3304 i_lanacl = PQfnumber(res, "lanacl");
3307 for (i = 0; i < ntups; i++)
3309 planginfo[i].dobj.objType = DO_PROCLANG;
3310 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3311 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3312 AssignDumpId(&planginfo[i].dobj);
3314 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
3315 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
3316 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
3317 if (g_fout->remoteVersion >= 70300)
3319 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
3320 planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
3326 planginfo[i].lanvalidator = InvalidOid;
3327 planginfo[i].lanacl = strdup("{=U}");
3329 * We need to make a dependency to ensure the function will
3330 * be dumped first. (In 7.3 and later the regular dependency
3331 * mechanism will handle this for us.)
3333 funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
3335 addObjectDependency(&planginfo[i].dobj,
3336 funcInfo->dobj.dumpId);
3342 destroyPQExpBuffer(query);
3349 * get basic information about every cast in the system
3351 * numCasts is set to the number of casts read in
3354 getCasts(int *numCasts)
3359 PQExpBuffer query = createPQExpBuffer();
3368 /* Make sure we are in proper schema */
3369 selectSourceSchema("pg_catalog");
3371 if (g_fout->remoteVersion >= 70300)
3373 appendPQExpBuffer(query, "SELECT tableoid, oid, "
3374 "castsource, casttarget, castfunc, castcontext "
3375 "FROM pg_cast ORDER BY 3,4");
3379 appendPQExpBuffer(query, "SELECT 0 as tableoid, p.oid, "
3380 "t1.oid as castsource, t2.oid as casttarget, "
3381 "p.oid as castfunc, 'e' as castcontext "
3382 "FROM pg_type t1, pg_type t2, pg_proc p "
3383 "WHERE p.pronargs = 1 AND "
3384 "p.proargtypes[0] = t1.oid AND "
3385 "p.prorettype = t2.oid AND p.proname = t2.typname "
3389 res = PQexec(g_conn, query->data);
3390 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3392 ntups = PQntuples(res);
3396 castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
3398 i_tableoid = PQfnumber(res, "tableoid");
3399 i_oid = PQfnumber(res, "oid");
3400 i_castsource = PQfnumber(res, "castsource");
3401 i_casttarget = PQfnumber(res, "casttarget");
3402 i_castfunc = PQfnumber(res, "castfunc");
3403 i_castcontext = PQfnumber(res, "castcontext");
3405 for (i = 0; i < ntups; i++)
3407 PQExpBufferData namebuf;
3408 TypeInfo *sTypeInfo;
3409 TypeInfo *tTypeInfo;
3411 castinfo[i].dobj.objType = DO_CAST;
3412 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3413 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3414 AssignDumpId(&castinfo[i].dobj);
3415 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
3416 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
3417 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
3418 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
3421 * Try to name cast as concatenation of typnames. This is only
3422 * used for purposes of sorting. If we fail to find either type,
3423 * the name will be an empty string.
3425 initPQExpBuffer(&namebuf);
3426 sTypeInfo = findTypeByOid(castinfo[i].castsource);
3427 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
3428 if (sTypeInfo && tTypeInfo)
3429 appendPQExpBuffer(&namebuf, "%s %s",
3430 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
3431 castinfo[i].dobj.name = namebuf.data;
3433 if (OidIsValid(castinfo[i].castfunc))
3436 * We need to make a dependency to ensure the function will
3437 * be dumped first. (In 7.3 and later the regular dependency
3438 * mechanism will handle this for us.)
3442 funcInfo = findFuncByOid(castinfo[i].castfunc);
3444 addObjectDependency(&castinfo[i].dobj,
3445 funcInfo->dobj.dumpId);
3451 destroyPQExpBuffer(query);
3458 * for each interesting table, read info about its attributes
3459 * (names, types, default values, CHECK constraints, etc)
3461 * This is implemented in a very inefficient way right now, looping
3462 * through the tblinfo and doing a join per table to find the attrs and their
3463 * types. However, because we want type names and so forth to be named
3464 * relative to the schema of each table, we couldn't do it in just one
3465 * query. (Maybe one query per schema?)
3470 getTableAttrs(TableInfo *tblinfo, int numTables)
3475 PQExpBuffer q = createPQExpBuffer();
3480 int i_attstattarget;
3491 for (i = 0; i < numTables; i++)
3493 TableInfo *tbinfo = &tblinfo[i];
3495 /* Don't bother to collect info for sequences */
3496 if (tbinfo->relkind == RELKIND_SEQUENCE)
3499 /* Don't bother with uninteresting tables, either */
3500 if (!tbinfo->interesting)
3504 * Make sure we are in proper schema for this table; this allows
3505 * correct retrieval of formatted type names and default exprs
3507 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3509 /* find all the user attributes and their types */
3512 * we must read the attribute names in attribute number order!
3513 * because we will use the attnum to index into the attnames array
3514 * later. We actually ask to order by "attrelid, attnum" because
3515 * (at least up to 7.3) the planner is not smart enough to realize
3516 * it needn't re-sort the output of an indexscan on
3517 * pg_attribute_relid_attnum_index.
3520 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
3523 resetPQExpBuffer(q);
3525 if (g_fout->remoteVersion >= 70300)
3527 /* need left join here to not fail on dropped columns ... */
3528 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, "
3529 "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, "
3530 "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname "
3531 "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t "
3532 "on a.atttypid = t.oid "
3533 "where a.attrelid = '%u'::pg_catalog.oid "
3534 "and a.attnum > 0::pg_catalog.int2 "
3535 "order by a.attrelid, a.attnum",
3536 tbinfo->dobj.catId.oid);
3538 else if (g_fout->remoteVersion >= 70100)
3541 * attstattarget doesn't exist in 7.1. It does exist in 7.2,
3542 * but we don't dump it because we can't tell whether it's
3543 * been explicitly set or was just a default.
3545 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, "
3546 "a.attnotnull, a.atthasdef, false as attisdropped, false as attislocal, "
3547 "format_type(t.oid,a.atttypmod) as atttypname "
3548 "from pg_attribute a left join pg_type t "
3549 "on a.atttypid = t.oid "
3550 "where a.attrelid = '%u'::oid "
3551 "and a.attnum > 0::int2 "
3552 "order by a.attrelid, a.attnum",
3553 tbinfo->dobj.catId.oid);
3557 /* format_type not available before 7.1 */
3558 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, "
3559 "attnotnull, atthasdef, false as attisdropped, false as attislocal, "
3560 "(select typname from pg_type where oid = atttypid) as atttypname "
3561 "from pg_attribute a "
3562 "where attrelid = '%u'::oid "
3563 "and attnum > 0::int2 "
3564 "order by attrelid, attnum",
3565 tbinfo->dobj.catId.oid);
3568 res = PQexec(g_conn, q->data);
3569 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3571 ntups = PQntuples(res);
3573 i_attnum = PQfnumber(res, "attnum");
3574 i_attname = PQfnumber(res, "attname");
3575 i_atttypname = PQfnumber(res, "atttypname");
3576 i_atttypmod = PQfnumber(res, "atttypmod");
3577 i_attstattarget = PQfnumber(res, "attstattarget");
3578 i_attstorage = PQfnumber(res, "attstorage");
3579 i_typstorage = PQfnumber(res, "typstorage");
3580 i_attnotnull = PQfnumber(res, "attnotnull");
3581 i_atthasdef = PQfnumber(res, "atthasdef");
3582 i_attisdropped = PQfnumber(res, "attisdropped");
3583 i_attislocal = PQfnumber(res, "attislocal");
3585 tbinfo->numatts = ntups;
3586 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
3587 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
3588 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
3589 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
3590 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
3591 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
3592 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
3593 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
3594 tbinfo->attisserial = (bool *) malloc(ntups * sizeof(bool));
3595 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
3596 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
3597 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
3598 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
3599 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
3600 hasdefaults = false;
3602 for (j = 0; j < ntups; j++)
3604 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
3606 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
3610 tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
3611 tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
3612 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
3613 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
3614 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
3615 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
3616 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
3617 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
3618 tbinfo->attisserial[j] = false; /* fix below */
3619 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
3620 tbinfo->attrdefs[j] = NULL; /* fix below */
3621 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
3623 /* these flags will be set in flagInhAttrs() */
3624 tbinfo->inhAttrs[j] = false;
3625 tbinfo->inhAttrDef[j] = false;
3626 tbinfo->inhNotNull[j] = false;
3632 * Get info about column defaults
3636 AttrDefInfo *attrdefs;
3640 write_msg(NULL, "finding default expressions of table \"%s\"\n",
3643 resetPQExpBuffer(q);
3644 if (g_fout->remoteVersion >= 70300)
3646 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
3647 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
3648 "FROM pg_catalog.pg_attrdef "
3649 "WHERE adrelid = '%u'::pg_catalog.oid",
3650 tbinfo->dobj.catId.oid);
3652 else if (g_fout->remoteVersion >= 70200)
3654 /* 7.2 did not have OIDs in pg_attrdef */
3655 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, adnum, "
3656 "pg_get_expr(adbin, adrelid) AS adsrc "
3658 "WHERE adrelid = '%u'::oid",
3659 tbinfo->dobj.catId.oid);
3661 else if (g_fout->remoteVersion >= 70100)
3663 /* no pg_get_expr, so must rely on adsrc */
3664 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
3666 "WHERE adrelid = '%u'::oid",
3667 tbinfo->dobj.catId.oid);
3671 /* no pg_get_expr, no tableoid either */
3672 appendPQExpBuffer(q, "SELECT "
3673 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
3674 "oid, adnum, adsrc "
3676 "WHERE adrelid = '%u'::oid",
3677 tbinfo->dobj.catId.oid);
3679 res = PQexec(g_conn, q->data);
3680 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3682 numDefaults = PQntuples(res);
3683 attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
3685 for (j = 0; j < numDefaults; j++)
3689 attrdefs[j].dobj.objType = DO_ATTRDEF;
3690 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3691 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3692 AssignDumpId(&attrdefs[j].dobj);
3693 attrdefs[j].adtable = tbinfo;
3694 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
3695 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
3697 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
3698 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
3701 * Defaults on a VIEW must always be dumped as separate
3702 * ALTER TABLE commands. Defaults on regular tables are
3703 * dumped as part of the CREATE TABLE if possible. To check
3704 * if it's safe, we mark the default as needing to appear
3705 * before the CREATE.
3707 if (tbinfo->relkind == RELKIND_VIEW)
3709 attrdefs[j].separate = true;
3710 /* needed in case pre-7.3 DB: */
3711 addObjectDependency(&attrdefs[j].dobj,
3712 tbinfo->dobj.dumpId);
3716 attrdefs[j].separate = false;
3717 addObjectDependency(&tbinfo->dobj,
3718 attrdefs[j].dobj.dumpId);
3721 if (adnum <= 0 || adnum > ntups)
3723 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
3724 adnum, tbinfo->dobj.name);
3727 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
3733 * Get info about table CHECK constraints
3735 if (tbinfo->ncheck > 0)
3737 ConstraintInfo *constrs;
3741 write_msg(NULL, "finding check constraints for table \"%s\"\n",
3744 resetPQExpBuffer(q);
3745 if (g_fout->remoteVersion >= 70400)
3747 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3748 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3749 "FROM pg_catalog.pg_constraint "
3750 "WHERE conrelid = '%u'::pg_catalog.oid "
3751 " AND contype = 'c' "
3753 tbinfo->dobj.catId.oid);
3755 else if (g_fout->remoteVersion >= 70300)
3757 /* no pg_get_constraintdef, must use consrc */
3758 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3759 "'CHECK (' || consrc || ')' AS consrc "
3760 "FROM pg_catalog.pg_constraint "
3761 "WHERE conrelid = '%u'::pg_catalog.oid "
3762 " AND contype = 'c' "
3764 tbinfo->dobj.catId.oid);
3766 else if (g_fout->remoteVersion >= 70200)
3768 /* 7.2 did not have OIDs in pg_relcheck */
3769 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, "
3770 "rcname AS conname, "
3771 "'CHECK (' || rcsrc || ')' AS consrc "
3773 "WHERE rcrelid = '%u'::oid "
3775 tbinfo->dobj.catId.oid);
3777 else if (g_fout->remoteVersion >= 70100)
3779 appendPQExpBuffer(q, "SELECT tableoid, oid, "
3780 "rcname AS conname, "
3781 "'CHECK (' || rcsrc || ')' AS consrc "
3783 "WHERE rcrelid = '%u'::oid "
3785 tbinfo->dobj.catId.oid);
3789 /* no tableoid in 7.0 */
3790 appendPQExpBuffer(q, "SELECT "
3791 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
3792 "oid, rcname AS conname, "
3793 "'CHECK (' || rcsrc || ')' AS consrc "
3795 "WHERE rcrelid = '%u'::oid "
3797 tbinfo->dobj.catId.oid);
3799 res = PQexec(g_conn, q->data);
3800 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3802 numConstrs = PQntuples(res);
3803 if (numConstrs != tbinfo->ncheck)
3805 write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
3806 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
3807 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
3811 constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
3812 tbinfo->checkexprs = constrs;
3814 for (j = 0; j < numConstrs; j++)
3816 constrs[j].dobj.objType = DO_CONSTRAINT;
3817 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3818 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3819 AssignDumpId(&constrs[j].dobj);
3820 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
3821 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
3822 constrs[j].contable = tbinfo;
3823 constrs[j].condomain = NULL;
3824 constrs[j].contype = 'c';
3825 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
3826 constrs[j].conindex = 0;
3827 constrs[j].coninherited = false;
3828 constrs[j].separate = false;
3829 addObjectDependency(&tbinfo->dobj,
3830 constrs[j].dobj.dumpId);
3832 * If the constraint is inherited, this will be detected
3833 * later. We also detect later if the constraint must be
3834 * split out from the table definition.
3841 * Check to see if any columns are serial columns. Our first
3842 * quick filter is that it must be integer or bigint with a
3843 * default. If so, we scan to see if we found a sequence linked
3844 * to this column. If we did, mark the column and sequence
3847 for (j = 0; j < ntups; j++)
3850 * Note assumption that format_type will show these types as
3851 * exactly "integer" and "bigint" regardless of schema path.
3852 * This is correct in 7.3 but needs to be watched.
3854 if (strcmp(tbinfo->atttypnames[j], "integer") != 0 &&
3855 strcmp(tbinfo->atttypnames[j], "bigint") != 0)
3857 if (tbinfo->attrdefs[j] == NULL)
3859 for (k = 0; k < numTables; k++)
3861 TableInfo *seqinfo = &tblinfo[k];
3863 if (OidIsValid(seqinfo->owning_tab) &&
3864 seqinfo->owning_tab == tbinfo->dobj.catId.oid &&
3865 seqinfo->owning_col == j + 1)
3868 * Found a match. Copy the table's interesting and
3869 * dumpable flags to the sequence.
3871 tbinfo->attisserial[j] = true;
3872 seqinfo->interesting = tbinfo->interesting;
3873 seqinfo->dump = tbinfo->dump;
3880 destroyPQExpBuffer(q);
3887 * This routine is used to dump any comments associated with the
3888 * object handed to this routine. The routine takes a constant character
3889 * string for the target part of the comment-creation command, plus
3890 * the namespace and owner of the object (for labeling the ArchiveEntry),
3891 * plus catalog ID and subid which are the lookup key for pg_description,
3892 * plus the dump ID for the object (for setting a dependency).
3893 * If a matching pg_description entry is found, it is dumped.
3896 dumpComment(Archive *fout, const char *target,
3897 const char *namespace, const char *owner,
3898 CatalogId catalogId, int subid, DumpId dumpId)
3900 CommentItem *comments;
3903 /* Comments are SCHEMA not data */
3907 /* Search for comments associated with catalogId, using table */
3908 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
3911 /* Is there one matching the subid? */
3912 while (ncomments > 0)
3914 if (comments->objsubid == subid)
3920 /* If a comment exists, build COMMENT ON statement */
3923 PQExpBuffer query = createPQExpBuffer();
3925 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
3926 appendStringLiteral(query, comments->descr, false);
3927 appendPQExpBuffer(query, ";\n");
3929 ArchiveEntry(fout, nilCatalogId, createDumpId(),
3930 target, namespace, owner, false,
3931 "COMMENT", query->data, "", NULL,
3935 destroyPQExpBuffer(query);
3940 * dumpTableComment --
3942 * As above, but dump comments for both the specified table (or view)
3946 dumpTableComment(Archive *fout, TableInfo *tbinfo,
3947 const char *reltypename)
3949 CommentItem *comments;
3954 /* Comments are SCHEMA not data */
3958 /* Search for comments associated with relation, using table */
3959 ncomments = findComments(fout,
3960 tbinfo->dobj.catId.tableoid,
3961 tbinfo->dobj.catId.oid,
3964 /* If comments exist, build COMMENT ON statements */
3968 query = createPQExpBuffer();
3969 target = createPQExpBuffer();
3971 while (ncomments > 0)
3973 const char *descr = comments->descr;
3974 int objsubid = comments->objsubid;
3978 resetPQExpBuffer(target);
3979 appendPQExpBuffer(target, "%s %s", reltypename,
3980 fmtId(tbinfo->dobj.name));
3982 resetPQExpBuffer(query);
3983 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
3984 appendStringLiteral(query, descr, false);
3985 appendPQExpBuffer(query, ";\n");
3987 ArchiveEntry(fout, nilCatalogId, createDumpId(),
3989 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
3990 false, "COMMENT", query->data, "", NULL,
3991 &(tbinfo->dobj.dumpId), 1,
3994 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
3996 resetPQExpBuffer(target);
3997 appendPQExpBuffer(target, "COLUMN %s.",
3998 fmtId(tbinfo->dobj.name));
3999 appendPQExpBuffer(target, "%s",
4000 fmtId(tbinfo->attnames[objsubid - 1]));
4002 resetPQExpBuffer(query);
4003 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4004 appendStringLiteral(query, descr, false);
4005 appendPQExpBuffer(query, ";\n");
4007 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4009 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
4010 false, "COMMENT", query->data, "", NULL,
4011 &(tbinfo->dobj.dumpId), 1,
4019 destroyPQExpBuffer(query);
4020 destroyPQExpBuffer(target);
4026 * Find the comment(s), if any, associated with the given object. All the
4027 * objsubid values associated with the given classoid/objoid are found with
4031 findComments(Archive *fout, Oid classoid, Oid objoid,
4032 CommentItem **items)
4034 /* static storage for table of comments */
4035 static CommentItem *comments = NULL;
4036 static int ncomments = -1;
4038 CommentItem *middle = NULL;
4043 /* Get comments if we didn't already */
4045 ncomments = collectComments(fout, &comments);
4048 * Pre-7.2, pg_description does not contain classoid, so collectComments
4049 * just stores a zero. If there's a collision on object OID, well, you
4050 * get duplicate comments.
4052 if (fout->remoteVersion < 70200)
4056 * Do binary search to find some item matching the object.
4059 high = &comments[ncomments-1];
4062 middle = low + (high - low) / 2;
4064 if (classoid < middle->classoid)
4066 else if (classoid > middle->classoid)
4068 else if (objoid < middle->objoid)
4070 else if (objoid > middle->objoid)
4073 break; /* found a match */
4076 if (low > high) /* no matches */
4083 * Now determine how many items match the object. The search loop
4084 * invariant still holds: only items between low and high inclusive
4088 while (middle > low)
4090 if (classoid != middle[-1].classoid ||
4091 objoid != middle[-1].objoid)
4100 while (middle <= high)
4102 if (classoid != middle->classoid ||
4103 objoid != middle->objoid)
4113 * collectComments --
4115 * Construct a table of all comments available for database objects.
4116 * We used to do per-object queries for the comments, but it's much faster
4117 * to pull them all over at once, and on most databases the memory cost
4120 * The table is sorted by classoid/objid/objsubid for speed in lookup.
4123 collectComments(Archive *fout, CommentItem **items)
4133 CommentItem *comments;
4136 * Note we do NOT change source schema here; preserve the caller's
4140 query = createPQExpBuffer();
4142 if (fout->remoteVersion >= 70300)
4144 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4145 "FROM pg_catalog.pg_description "
4146 "ORDER BY classoid, objoid, objsubid");
4148 else if (fout->remoteVersion >= 70200)
4150 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4151 "FROM pg_description "
4152 "ORDER BY classoid, objoid, objsubid");
4156 /* Note: this will fail to find attribute comments in pre-7.2... */
4157 appendPQExpBuffer(query, "SELECT description, 0 as classoid, objoid, 0 as objsubid "
4158 "FROM pg_description "
4162 res = PQexec(g_conn, query->data);
4163 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4165 /* Construct lookup table containing OIDs in numeric form */
4167 i_description = PQfnumber(res, "description");
4168 i_classoid = PQfnumber(res, "classoid");
4169 i_objoid = PQfnumber(res, "objoid");
4170 i_objsubid = PQfnumber(res, "objsubid");
4172 ntups = PQntuples(res);
4174 comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
4176 for (i = 0; i < ntups; i++)
4178 comments[i].descr = PQgetvalue(res, i, i_description);
4179 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
4180 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
4181 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
4184 /* Do NOT free the PGresult since we are keeping pointers into it */
4185 destroyPQExpBuffer(query);
4192 * dumpDumpableObject
4194 * This routine and its subsidiaries are responsible for creating
4195 * ArchiveEntries (TOC objects) for each object to be dumped.
4198 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
4200 switch (dobj->objType)
4203 dumpNamespace(fout, (NamespaceInfo *) dobj);
4206 dumpType(fout, (TypeInfo *) dobj);
4209 dumpFunc(fout, (FuncInfo *) dobj);
4212 dumpAgg(fout, (AggInfo *) dobj);
4215 dumpOpr(fout, (OprInfo *) dobj);
4218 dumpOpclass(fout, (OpclassInfo *) dobj);
4221 dumpConversion(fout, (ConvInfo *) dobj);
4224 dumpTable(fout, (TableInfo *) dobj);
4227 dumpAttrDef(fout, (AttrDefInfo *) dobj);
4230 dumpIndex(fout, (IndxInfo *) dobj);
4233 dumpRule(fout, (RuleInfo *) dobj);
4236 dumpTrigger(fout, (TriggerInfo *) dobj);
4239 dumpConstraint(fout, (ConstraintInfo *) dobj);
4241 case DO_FK_CONSTRAINT:
4242 dumpConstraint(fout, (ConstraintInfo *) dobj);
4245 dumpProcLang(fout, (ProcLangInfo *) dobj);
4248 dumpCast(fout, (CastInfo *) dobj);
4251 dumpTableData(fout, (TableDataInfo *) dobj);
4254 /* table rowtypes are never dumped separately */
4257 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4258 dobj->name, NULL, "",
4259 false, "BLOBS", "", "", NULL,
4268 * writes out to fout the queries to recreate a user-defined namespace
4271 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
4277 /* skip if not to be dumped */
4278 if (!nspinfo->dump || dataOnly)
4281 /* don't dump dummy namespace from pre-7.3 source */
4282 if (strlen(nspinfo->dobj.name) == 0)
4285 q = createPQExpBuffer();
4286 delq = createPQExpBuffer();
4288 qnspname = strdup(fmtId(nspinfo->dobj.name));
4291 * If it's the PUBLIC namespace, suppress the CREATE SCHEMA record
4292 * for it, since we expect PUBLIC to exist already in the
4293 * destination database. But do emit ACL in case it's not standard,
4296 * Note that ownership is shown in the AUTHORIZATION clause,
4297 * while the archive entry is listed with empty owner (causing
4298 * it to be emitted with SET SESSION AUTHORIZATION DEFAULT).
4299 * This seems the best way of dealing with schemas owned by
4300 * users without CREATE SCHEMA privilege. Further hacking has
4301 * to be applied for --no-owner mode, though!
4303 if (strcmp(nspinfo->dobj.name, "public") != 0)
4305 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
4307 appendPQExpBuffer(q, "CREATE SCHEMA %s AUTHORIZATION %s;\n",
4308 qnspname, fmtId(nspinfo->usename));
4310 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
4313 false, "SCHEMA", q->data, delq->data, NULL,
4314 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
4318 /* Dump Schema Comments */
4319 resetPQExpBuffer(q);
4320 appendPQExpBuffer(q, "SCHEMA %s", qnspname);
4321 dumpComment(fout, q->data,
4322 NULL, nspinfo->usename,
4323 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
4325 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
4326 qnspname, nspinfo->dobj.name, NULL,
4327 nspinfo->usename, nspinfo->nspacl);
4331 destroyPQExpBuffer(q);
4332 destroyPQExpBuffer(delq);
4337 * writes out to fout the queries to recreate a user-defined type
4340 dumpType(Archive *fout, TypeInfo *tinfo)
4342 /* Dump only types in dumpable namespaces */
4343 if (!tinfo->dobj.namespace->dump || dataOnly)
4346 /* skip complex types, except for standalone composite types */
4347 /* (note: this test should now be unnecessary) */
4348 if (OidIsValid(tinfo->typrelid) && tinfo->typrelkind != 'c')
4351 /* skip undefined placeholder types */
4352 if (!tinfo->isDefined)
4355 /* skip all array types that start w/ underscore */
4356 if ((tinfo->dobj.name[0] == '_') &&
4357 OidIsValid(tinfo->typelem))
4360 /* Dump out in proper style */
4361 if (tinfo->typtype == 'b')
4362 dumpBaseType(fout, tinfo);
4363 else if (tinfo->typtype == 'd')
4364 dumpDomain(fout, tinfo);
4365 else if (tinfo->typtype == 'c')
4366 dumpCompositeType(fout, tinfo);
4371 * writes out to fout the queries to recreate a user-defined base type
4374 dumpBaseType(Archive *fout, TypeInfo *tinfo)
4376 PQExpBuffer q = createPQExpBuffer();
4377 PQExpBuffer delq = createPQExpBuffer();
4378 PQExpBuffer query = createPQExpBuffer();
4398 /* Set proper schema search path so regproc references list correctly */
4399 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4401 /* Fetch type-specific details */
4402 if (fout->remoteVersion >= 70500)
4404 appendPQExpBuffer(query, "SELECT typlen, "
4405 "typinput, typoutput, typreceive, typsend, "
4407 "typinput::pg_catalog.oid as typinputoid, "
4408 "typoutput::pg_catalog.oid as typoutputoid, "
4409 "typreceive::pg_catalog.oid as typreceiveoid, "
4410 "typsend::pg_catalog.oid as typsendoid, "
4411 "typanalyze::pg_catalog.oid as typanalyzeoid, "
4412 "typdelim, typdefault, typbyval, typalign, "
4414 "FROM pg_catalog.pg_type "
4415 "WHERE oid = '%u'::pg_catalog.oid",
4416 tinfo->dobj.catId.oid);
4418 else if (fout->remoteVersion >= 70400)
4420 appendPQExpBuffer(query, "SELECT typlen, "
4421 "typinput, typoutput, typreceive, typsend, "
4422 "'-' as typanalyze, "
4423 "typinput::pg_catalog.oid as typinputoid, "
4424 "typoutput::pg_catalog.oid as typoutputoid, "
4425 "typreceive::pg_catalog.oid as typreceiveoid, "
4426 "typsend::pg_catalog.oid as typsendoid, "
4427 "0 as typanalyzeoid, "
4428 "typdelim, typdefault, typbyval, typalign, "
4430 "FROM pg_catalog.pg_type "
4431 "WHERE oid = '%u'::pg_catalog.oid",
4432 tinfo->dobj.catId.oid);
4434 else if (fout->remoteVersion >= 70300)
4436 appendPQExpBuffer(query, "SELECT typlen, "
4437 "typinput, typoutput, "
4438 "'-' as typreceive, '-' as typsend, "
4439 "'-' as typanalyze, "
4440 "typinput::pg_catalog.oid as typinputoid, "
4441 "typoutput::pg_catalog.oid as typoutputoid, "
4442 "0 as typreceiveoid, 0 as typsendoid, "
4443 "0 as typanalyzeoid, "
4444 "typdelim, typdefault, typbyval, typalign, "
4446 "FROM pg_catalog.pg_type "
4447 "WHERE oid = '%u'::pg_catalog.oid",
4448 tinfo->dobj.catId.oid);
4450 else if (fout->remoteVersion >= 70100)
4453 * Note: although pre-7.3 catalogs contain typreceive and typsend,
4454 * ignore them because they are not right.
4456 appendPQExpBuffer(query, "SELECT typlen, "
4457 "typinput, typoutput, "
4458 "'-' as typreceive, '-' as typsend, "
4459 "'-' as typanalyze, "
4460 "typinput::oid as typinputoid, "
4461 "typoutput::oid as typoutputoid, "
4462 "0 as typreceiveoid, 0 as typsendoid, "
4463 "0 as typanalyzeoid, "
4464 "typdelim, typdefault, typbyval, typalign, "
4467 "WHERE oid = '%u'::oid",
4468 tinfo->dobj.catId.oid);
4472 appendPQExpBuffer(query, "SELECT typlen, "
4473 "typinput, typoutput, "
4474 "'-' as typreceive, '-' as typsend, "
4475 "'-' as typanalyze, "
4476 "typinput::oid as typinputoid, "
4477 "typoutput::oid as typoutputoid, "
4478 "0 as typreceiveoid, 0 as typsendoid, "
4479 "0 as typanalyzeoid, "
4480 "typdelim, typdefault, typbyval, typalign, "
4481 "'p'::char as typstorage "
4483 "WHERE oid = '%u'::oid",
4484 tinfo->dobj.catId.oid);
4487 res = PQexec(g_conn, query->data);
4488 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4490 /* Expecting a single result only */
4491 ntups = PQntuples(res);
4494 write_msg(NULL, "Got %d rows instead of one from: %s",
4495 ntups, query->data);
4499 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
4500 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
4501 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
4502 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
4503 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
4504 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
4505 typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
4506 typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
4507 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
4508 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
4509 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
4510 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
4511 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4514 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4515 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
4516 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
4517 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
4520 * DROP must be fully qualified in case same name appears in
4523 appendPQExpBuffer(delq, "DROP TYPE %s.",
4524 fmtId(tinfo->dobj.namespace->dobj.name));
4525 appendPQExpBuffer(delq, "%s CASCADE;\n",
4526 fmtId(tinfo->dobj.name));
4528 appendPQExpBuffer(q,
4529 "CREATE TYPE %s (\n"
4530 " INTERNALLENGTH = %s",
4531 fmtId(tinfo->dobj.name),
4532 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
4534 if (fout->remoteVersion >= 70300)
4536 /* regproc result is correctly quoted as of 7.3 */
4537 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
4538 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
4539 if (OidIsValid(typreceiveoid))
4540 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
4541 if (OidIsValid(typsendoid))
4542 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
4543 if (OidIsValid(typanalyzeoid))
4544 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
4548 /* regproc delivers an unquoted name before 7.3 */
4549 /* cannot combine these because fmtId uses static result area */
4550 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
4551 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
4552 /* no chance that receive/send/analyze need be printed */
4555 if (typdefault != NULL)
4557 appendPQExpBuffer(q, ",\n DEFAULT = ");
4558 appendStringLiteral(q, typdefault, true);
4565 /* reselect schema in case changed by function dump */
4566 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4567 elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
4568 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
4572 if (typdelim && strcmp(typdelim, ",") != 0)
4574 appendPQExpBuffer(q, ",\n DELIMITER = ");
4575 appendStringLiteral(q, typdelim, true);
4578 if (strcmp(typalign, "c") == 0)
4579 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
4580 else if (strcmp(typalign, "s") == 0)
4581 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
4582 else if (strcmp(typalign, "i") == 0)
4583 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
4584 else if (strcmp(typalign, "d") == 0)
4585 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
4587 if (strcmp(typstorage, "p") == 0)
4588 appendPQExpBuffer(q, ",\n STORAGE = plain");
4589 else if (strcmp(typstorage, "e") == 0)
4590 appendPQExpBuffer(q, ",\n STORAGE = external");
4591 else if (strcmp(typstorage, "x") == 0)
4592 appendPQExpBuffer(q, ",\n STORAGE = extended");
4593 else if (strcmp(typstorage, "m") == 0)
4594 appendPQExpBuffer(q, ",\n STORAGE = main");
4596 if (strcmp(typbyval, "t") == 0)
4597 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
4599 appendPQExpBuffer(q, "\n);\n");
4601 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4603 tinfo->dobj.namespace->dobj.name,
4604 tinfo->usename, false,
4605 "TYPE", q->data, delq->data, NULL,
4606 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4609 /* Dump Type Comments */
4610 resetPQExpBuffer(q);
4612 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4613 dumpComment(fout, q->data,
4614 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4615 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4618 destroyPQExpBuffer(q);
4619 destroyPQExpBuffer(delq);
4620 destroyPQExpBuffer(query);
4625 * writes out to fout the queries to recreate a user-defined domain
4628 dumpDomain(Archive *fout, TypeInfo *tinfo)
4630 PQExpBuffer q = createPQExpBuffer();
4631 PQExpBuffer delq = createPQExpBuffer();
4632 PQExpBuffer query = createPQExpBuffer();
4640 /* Set proper schema search path so type references list correctly */
4641 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4643 /* Fetch domain specific details */
4644 /* We assume here that remoteVersion must be at least 70300 */
4645 appendPQExpBuffer(query, "SELECT typnotnull, "
4646 "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
4648 "FROM pg_catalog.pg_type "
4649 "WHERE oid = '%u'::pg_catalog.oid",
4650 tinfo->dobj.catId.oid);
4652 res = PQexec(g_conn, query->data);
4653 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4655 /* Expecting a single result only */
4656 ntups = PQntuples(res);
4659 write_msg(NULL, "Got %d rows instead of one from: %s",
4660 ntups, query->data);
4664 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
4665 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
4666 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4669 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4671 appendPQExpBuffer(q,
4672 "CREATE DOMAIN %s AS %s",
4673 fmtId(tinfo->dobj.name),
4676 if (typnotnull[0] == 't')
4677 appendPQExpBuffer(q, " NOT NULL");
4680 appendPQExpBuffer(q, " DEFAULT %s", typdefault);
4685 * Add any CHECK constraints for the domain
4687 for (i = 0; i < tinfo->nDomChecks; i++)
4689 ConstraintInfo *domcheck = &(tinfo->domChecks[i]);
4691 if (!domcheck->separate)
4692 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
4693 fmtId(domcheck->dobj.name), domcheck->condef);
4696 appendPQExpBuffer(q, ";\n");
4699 * DROP must be fully qualified in case same name appears in
4702 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
4703 fmtId(tinfo->dobj.namespace->dobj.name));
4704 appendPQExpBuffer(delq, "%s;\n",
4705 fmtId(tinfo->dobj.name));
4707 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4709 tinfo->dobj.namespace->dobj.name,
4710 tinfo->usename, false,
4711 "DOMAIN", q->data, delq->data, NULL,
4712 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4715 /* Dump Domain Comments */
4716 resetPQExpBuffer(q);
4718 appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->dobj.name));
4719 dumpComment(fout, q->data,
4720 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4721 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4723 destroyPQExpBuffer(q);
4724 destroyPQExpBuffer(delq);
4725 destroyPQExpBuffer(query);
4730 * writes out to fout the queries to recreate a user-defined stand-alone
4734 dumpCompositeType(Archive *fout, TypeInfo *tinfo)
4736 PQExpBuffer q = createPQExpBuffer();
4737 PQExpBuffer delq = createPQExpBuffer();
4738 PQExpBuffer query = createPQExpBuffer();
4745 /* Set proper schema search path so type references list correctly */
4746 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4748 /* Fetch type specific details */
4749 /* We assume here that remoteVersion must be at least 70300 */
4751 appendPQExpBuffer(query, "SELECT a.attname, "
4752 "pg_catalog.format_type(a.atttypid, a.atttypmod) as atttypdefn "
4753 "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
4754 "WHERE t.oid = '%u'::pg_catalog.oid "
4755 "AND a.attrelid = t.typrelid "
4756 "AND NOT a.attisdropped "
4757 "ORDER BY a.attnum ",
4758 tinfo->dobj.catId.oid);
4760 res = PQexec(g_conn, query->data);
4761 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4763 /* Expecting at least a single result */
4764 ntups = PQntuples(res);
4767 write_msg(NULL, "query yielded no rows: %s\n", query->data);
4771 i_attname = PQfnumber(res, "attname");
4772 i_atttypdefn = PQfnumber(res, "atttypdefn");
4774 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
4775 fmtId(tinfo->dobj.name));
4777 for (i = 0; i < ntups; i++)
4782 attname = PQgetvalue(res, i, i_attname);
4783 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
4785 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
4787 appendPQExpBuffer(q, ",");
4789 appendPQExpBuffer(q, "\n);\n");
4792 * DROP must be fully qualified in case same name appears in
4795 appendPQExpBuffer(delq, "DROP TYPE %s.",
4796 fmtId(tinfo->dobj.namespace->dobj.name));
4797 appendPQExpBuffer(delq, "%s;\n",
4798 fmtId(tinfo->dobj.name));
4800 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4802 tinfo->dobj.namespace->dobj.name,
4803 tinfo->usename, false,
4804 "TYPE", q->data, delq->data, NULL,
4805 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4809 /* Dump Type Comments */
4810 resetPQExpBuffer(q);
4812 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4813 dumpComment(fout, q->data,
4814 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4815 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4818 destroyPQExpBuffer(q);
4819 destroyPQExpBuffer(delq);
4820 destroyPQExpBuffer(query);
4825 * writes out to fout the queries to recreate a user-defined
4826 * procedural language
4829 dumpProcLang(Archive *fout, ProcLangInfo *plang)
4835 FuncInfo *validatorInfo = NULL;
4841 * Current theory is to dump PLs iff their underlying functions
4842 * will be dumped (are in a dumpable namespace, or have a
4843 * non-system OID in pre-7.3 databases). Actually, we treat the
4844 * PL itself as being in the underlying function's namespace,
4845 * though it isn't really. This avoids searchpath problems for
4846 * the HANDLER clause.
4848 * If the underlying function is in the pg_catalog namespace,
4849 * we won't have loaded it into finfo[] at all; therefore,
4850 * treat failure to find it in finfo[] as indicating we shouldn't
4851 * dump it, not as an error condition. Ditto for the validator.
4854 funcInfo = findFuncByOid(plang->lanplcallfoid);
4855 if (funcInfo == NULL)
4858 if (!funcInfo->dobj.namespace->dump)
4861 if (OidIsValid(plang->lanvalidator))
4863 validatorInfo = findFuncByOid(plang->lanvalidator);
4864 if (validatorInfo == NULL)
4868 defqry = createPQExpBuffer();
4869 delqry = createPQExpBuffer();
4871 qlanname = strdup(fmtId(plang->dobj.name));
4873 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
4876 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
4877 plang->lanpltrusted ? "TRUSTED " : "",
4879 appendPQExpBuffer(defqry, " HANDLER %s",
4880 fmtId(funcInfo->dobj.name));
4881 if (OidIsValid(plang->lanvalidator))
4883 appendPQExpBuffer(defqry, " VALIDATOR ");
4884 /* Cope with possibility that validator is in different schema */
4885 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
4886 appendPQExpBuffer(defqry, "%s.",
4887 fmtId(validatorInfo->dobj.namespace->dobj.name));
4888 appendPQExpBuffer(defqry, "%s",
4889 fmtId(validatorInfo->dobj.name));
4891 appendPQExpBuffer(defqry, ";\n");
4893 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
4895 funcInfo->dobj.namespace->dobj.name, "",
4896 false, "PROCEDURAL LANGUAGE",
4897 defqry->data, delqry->data, NULL,
4898 plang->dobj.dependencies, plang->dobj.nDeps,
4901 /* Dump Proc Lang Comments */
4902 resetPQExpBuffer(defqry);
4904 appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
4905 dumpComment(fout, defqry->data,
4907 plang->dobj.catId, 0, plang->dobj.dumpId);
4909 if (plang->lanpltrusted)
4910 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
4911 qlanname, plang->dobj.name,
4912 funcInfo->dobj.namespace->dobj.name,
4913 NULL, plang->lanacl);
4917 destroyPQExpBuffer(defqry);
4918 destroyPQExpBuffer(delqry);
4922 * format_function_signature: generate function name and argument list
4924 * The argument type names are qualified if needed. The function name
4925 * is never qualified.
4927 * argnames may be NULL if no names are available.
4930 format_function_signature(FuncInfo *finfo, char **argnames,
4936 initPQExpBuffer(&fn);
4938 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
4940 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
4941 for (j = 0; j < finfo->nargs; j++)
4946 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
4948 argname = argnames ? argnames[j] : (char *) NULL;
4949 if (argname && argname[0] == '\0')
4952 appendPQExpBuffer(&fn, "%s%s%s%s",
4953 (j > 0) ? ", " : "",
4954 argname ? fmtId(argname) : "",
4959 appendPQExpBuffer(&fn, ")");
4966 * dump out one function
4969 dumpFunc(Archive *fout, FuncInfo *finfo)
4988 char **argnamearray = NULL;
4990 /* Dump only funcs in dumpable namespaces */
4991 if (!finfo->dobj.namespace->dump || dataOnly)
4994 query = createPQExpBuffer();
4995 q = createPQExpBuffer();
4996 delqry = createPQExpBuffer();
4997 asPart = createPQExpBuffer();
4999 /* Set proper schema search path so type references list correctly */
5000 selectSourceSchema(finfo->dobj.namespace->dobj.name);
5002 /* Fetch function-specific details */
5003 if (g_fout->remoteVersion >= 70500)
5005 appendPQExpBuffer(query,
5006 "SELECT proretset, prosrc, probin, "
5008 "provolatile, proisstrict, prosecdef, "
5009 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5010 "FROM pg_catalog.pg_proc "
5011 "WHERE oid = '%u'::pg_catalog.oid",
5012 finfo->dobj.catId.oid);
5014 else if (g_fout->remoteVersion >= 70300)
5016 appendPQExpBuffer(query,
5017 "SELECT proretset, prosrc, probin, "
5018 "null::text as proargnames, "
5019 "provolatile, proisstrict, prosecdef, "
5020 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5021 "FROM pg_catalog.pg_proc "
5022 "WHERE oid = '%u'::pg_catalog.oid",
5023 finfo->dobj.catId.oid);
5025 else if (g_fout->remoteVersion >= 70100)
5027 appendPQExpBuffer(query,
5028 "SELECT proretset, prosrc, probin, "
5029 "null::text as proargnames, "
5030 "case when proiscachable then 'i' else 'v' end as provolatile, "
5032 "'f'::boolean as prosecdef, "
5033 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5035 "WHERE oid = '%u'::oid",
5036 finfo->dobj.catId.oid);
5040 appendPQExpBuffer(query,
5041 "SELECT proretset, prosrc, probin, "
5042 "null::text as proargnames, "
5043 "case when proiscachable then 'i' else 'v' end as provolatile, "
5044 "'f'::boolean as proisstrict, "
5045 "'f'::boolean as prosecdef, "
5046 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5048 "WHERE oid = '%u'::oid",
5049 finfo->dobj.catId.oid);
5052 res = PQexec(g_conn, query->data);
5053 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5055 /* Expecting a single result only */
5056 ntups = PQntuples(res);
5059 write_msg(NULL, "Got %d rows instead of one from: %s",
5060 ntups, query->data);
5064 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
5065 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
5066 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
5067 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
5068 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
5069 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
5070 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
5071 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
5074 * See backend/commands/define.c for details of how the 'AS' clause is
5077 if (strcmp(probin, "-") != 0)
5079 appendPQExpBuffer(asPart, "AS ");
5080 appendStringLiteral(asPart, probin, true);
5081 if (strcmp(prosrc, "-") != 0)
5083 appendPQExpBuffer(asPart, ", ");
5085 * where we have bin, use dollar quoting if allowed and src
5086 * contains quote or backslash; else use regular quoting.
5088 if (disable_dollar_quoting)
5089 appendStringLiteral(asPart, prosrc, false);
5091 appendStringLiteralDQOpt(asPart, prosrc, false, NULL);
5096 if (strcmp(prosrc, "-") != 0)
5098 appendPQExpBuffer(asPart, "AS ");
5099 /* with no bin, dollar quote src unconditionally if allowed */
5100 if (disable_dollar_quoting)
5101 appendStringLiteral(asPart, prosrc, false);
5103 appendStringLiteralDQ(asPart, prosrc, NULL);
5107 if (proargnames && *proargnames)
5111 if (!parsePGArray(proargnames, &argnamearray, &nitems) ||
5112 nitems != finfo->nargs)
5114 write_msg(NULL, "WARNING: could not parse proargnames array\n");
5117 argnamearray = NULL;
5121 funcsig = format_function_signature(finfo, argnamearray, true);
5122 funcsig_tag = format_function_signature(finfo, NULL, false);
5125 * DROP must be fully qualified in case same name appears in
5128 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
5129 fmtId(finfo->dobj.namespace->dobj.name),
5132 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
5134 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
5135 appendPQExpBuffer(q, "RETURNS %s%s\n %s\n LANGUAGE %s",
5136 (proretset[0] == 't') ? "SETOF " : "",
5143 if (provolatile[0] != PROVOLATILE_VOLATILE)
5145 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
5146 appendPQExpBuffer(q, " IMMUTABLE");
5147 else if (provolatile[0] == PROVOLATILE_STABLE)
5148 appendPQExpBuffer(q, " STABLE");
5149 else if (provolatile[0] != PROVOLATILE_VOLATILE)
5151 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
5157 if (proisstrict[0] == 't')
5158 appendPQExpBuffer(q, " STRICT");
5160 if (prosecdef[0] == 't')
5161 appendPQExpBuffer(q, " SECURITY DEFINER");
5163 appendPQExpBuffer(q, ";\n");
5165 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
5167 finfo->dobj.namespace->dobj.name,
5168 finfo->usename, false,
5169 "FUNCTION", q->data, delqry->data, NULL,
5170 finfo->dobj.dependencies, finfo->dobj.nDeps,
5173 /* Dump Function Comments */
5174 resetPQExpBuffer(q);
5175 appendPQExpBuffer(q, "FUNCTION %s", funcsig);
5176 dumpComment(fout, q->data,
5177 finfo->dobj.namespace->dobj.name, finfo->usename,
5178 finfo->dobj.catId, 0, finfo->dobj.dumpId);
5180 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
5181 funcsig, funcsig_tag,
5182 finfo->dobj.namespace->dobj.name,
5183 finfo->usename, finfo->proacl);
5187 destroyPQExpBuffer(query);
5188 destroyPQExpBuffer(q);
5189 destroyPQExpBuffer(delqry);
5190 destroyPQExpBuffer(asPart);
5199 * Dump a user-defined cast
5202 dumpCast(Archive *fout, CastInfo *cast)
5206 PQExpBuffer castsig;
5207 FuncInfo *funcInfo = NULL;
5208 TypeInfo *sourceInfo;
5209 TypeInfo *targetInfo;
5214 if (OidIsValid(cast->castfunc))
5216 funcInfo = findFuncByOid(cast->castfunc);
5217 if (funcInfo == NULL)
5222 * As per discussion we dump casts if one or more of the underlying
5223 * objects (the conversion function and the two data types) are not
5224 * builtin AND if all of the non-builtin objects namespaces are
5225 * included in the dump. Builtin meaning, the namespace name does
5226 * not start with "pg_".
5228 sourceInfo = findTypeByOid(cast->castsource);
5229 targetInfo = findTypeByOid(cast->casttarget);
5231 if (sourceInfo == NULL || targetInfo == NULL)
5235 * Skip this cast if all objects are from pg_
5237 if ((funcInfo == NULL ||
5238 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
5239 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
5240 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
5244 * Skip cast if function isn't from pg_ and that namespace is
5248 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5249 !funcInfo->dobj.namespace->dump)
5253 * Same for the Source type
5255 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5256 !sourceInfo->dobj.namespace->dump)
5260 * and the target type.
5262 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5263 !targetInfo->dobj.namespace->dump)
5266 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
5267 selectSourceSchema("pg_catalog");
5269 defqry = createPQExpBuffer();
5270 delqry = createPQExpBuffer();
5271 castsig = createPQExpBuffer();
5273 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
5274 getFormattedTypeName(cast->castsource, zeroAsNone),
5275 getFormattedTypeName(cast->casttarget, zeroAsNone));
5277 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
5278 getFormattedTypeName(cast->castsource, zeroAsNone),
5279 getFormattedTypeName(cast->casttarget, zeroAsNone));
5281 if (!OidIsValid(cast->castfunc))
5282 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
5286 * Always qualify the function name, in case it is not in pg_catalog
5287 * schema (format_function_signature won't qualify it).
5289 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
5290 fmtId(funcInfo->dobj.namespace->dobj.name));
5291 appendPQExpBuffer(defqry, "%s",
5292 format_function_signature(funcInfo, NULL, true));
5295 if (cast->castcontext == 'a')
5296 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
5297 else if (cast->castcontext == 'i')
5298 appendPQExpBuffer(defqry, " AS IMPLICIT");
5299 appendPQExpBuffer(defqry, ";\n");
5301 appendPQExpBuffer(castsig, "CAST (%s AS %s)",
5302 getFormattedTypeName(cast->castsource, zeroAsNone),
5303 getFormattedTypeName(cast->casttarget, zeroAsNone));
5305 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
5308 false, "CAST", defqry->data, delqry->data, NULL,
5309 cast->dobj.dependencies, cast->dobj.nDeps,
5312 /* Dump Cast Comments */
5313 resetPQExpBuffer(defqry);
5314 appendPQExpBuffer(defqry, "CAST (%s AS %s)",
5315 getFormattedTypeName(cast->castsource, zeroAsNone),
5316 getFormattedTypeName(cast->casttarget, zeroAsNone));
5317 dumpComment(fout, defqry->data,
5319 cast->dobj.catId, 0, cast->dobj.dumpId);
5321 destroyPQExpBuffer(defqry);
5322 destroyPQExpBuffer(delqry);
5323 destroyPQExpBuffer(castsig);
5328 * write out a single operator definition
5331 dumpOpr(Archive *fout, OprInfo *oprinfo)
5337 PQExpBuffer details;
5368 /* Dump only operators in dumpable namespaces */
5369 if (!oprinfo->dobj.namespace->dump || dataOnly)
5373 * some operators are invalid because they were the result of user
5374 * defining operators before commutators exist
5376 if (!OidIsValid(oprinfo->oprcode))
5379 query = createPQExpBuffer();
5380 q = createPQExpBuffer();
5381 delq = createPQExpBuffer();
5382 oprid = createPQExpBuffer();
5383 details = createPQExpBuffer();
5385 /* Make sure we are in proper schema so regoperator works correctly */
5386 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
5388 if (g_fout->remoteVersion >= 70300)
5390 appendPQExpBuffer(query, "SELECT oprkind, "
5391 "oprcode::pg_catalog.regprocedure, "
5392 "oprleft::pg_catalog.regtype, "
5393 "oprright::pg_catalog.regtype, "
5394 "oprcom::pg_catalog.regoperator, "
5395 "oprnegate::pg_catalog.regoperator, "
5396 "oprrest::pg_catalog.regprocedure, "
5397 "oprjoin::pg_catalog.regprocedure, "
5399 "oprlsortop::pg_catalog.regoperator, "
5400 "oprrsortop::pg_catalog.regoperator, "
5401 "oprltcmpop::pg_catalog.regoperator, "
5402 "oprgtcmpop::pg_catalog.regoperator "
5403 "from pg_catalog.pg_operator "
5404 "where oid = '%u'::pg_catalog.oid",
5405 oprinfo->dobj.catId.oid);
5407 else if (g_fout->remoteVersion >= 70100)
5409 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5410 "CASE WHEN oprleft = 0 THEN '-' "
5411 "ELSE format_type(oprleft, NULL) END as oprleft, "
5412 "CASE WHEN oprright = 0 THEN '-' "
5413 "ELSE format_type(oprright, NULL) END as oprright, "
5414 "oprcom, oprnegate, oprrest, oprjoin, "
5415 "oprcanhash, oprlsortop, oprrsortop, "
5416 "0 as oprltcmpop, 0 as oprgtcmpop "
5418 "where oid = '%u'::oid",
5419 oprinfo->dobj.catId.oid);
5423 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5424 "CASE WHEN oprleft = 0 THEN '-'::name "
5425 "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
5426 "CASE WHEN oprright = 0 THEN '-'::name "
5427 "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
5428 "oprcom, oprnegate, oprrest, oprjoin, "
5429 "oprcanhash, oprlsortop, oprrsortop, "
5430 "0 as oprltcmpop, 0 as oprgtcmpop "
5432 "where oid = '%u'::oid",
5433 oprinfo->dobj.catId.oid);
5436 res = PQexec(g_conn, query->data);
5437 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5439 /* Expecting a single result only */
5440 ntups = PQntuples(res);
5443 write_msg(NULL, "Got %d rows instead of one from: %s",
5444 ntups, query->data);
5448 i_oprkind = PQfnumber(res, "oprkind");
5449 i_oprcode = PQfnumber(res, "oprcode");
5450 i_oprleft = PQfnumber(res, "oprleft");
5451 i_oprright = PQfnumber(res, "oprright");
5452 i_oprcom = PQfnumber(res, "oprcom");
5453 i_oprnegate = PQfnumber(res, "oprnegate");
5454 i_oprrest = PQfnumber(res, "oprrest");
5455 i_oprjoin = PQfnumber(res, "oprjoin");
5456 i_oprcanhash = PQfnumber(res, "oprcanhash");
5457 i_oprlsortop = PQfnumber(res, "oprlsortop");
5458 i_oprrsortop = PQfnumber(res, "oprrsortop");
5459 i_oprltcmpop = PQfnumber(res, "oprltcmpop");
5460 i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");
5462 oprkind = PQgetvalue(res, 0, i_oprkind);
5463 oprcode = PQgetvalue(res, 0, i_oprcode);
5464 oprleft = PQgetvalue(res, 0, i_oprleft);
5465 oprright = PQgetvalue(res, 0, i_oprright);
5466 oprcom = PQgetvalue(res, 0, i_oprcom);
5467 oprnegate = PQgetvalue(res, 0, i_oprnegate);
5468 oprrest = PQgetvalue(res, 0, i_oprrest);
5469 oprjoin = PQgetvalue(res, 0, i_oprjoin);
5470 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
5471 oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
5472 oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
5473 oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
5474 oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);
5476 appendPQExpBuffer(details, " PROCEDURE = %s",
5477 convertRegProcReference(oprcode));
5479 appendPQExpBuffer(oprid, "%s (",
5480 oprinfo->dobj.name);
5483 * right unary means there's a left arg and left unary means there's a
5486 if (strcmp(oprkind, "r") == 0 ||
5487 strcmp(oprkind, "b") == 0)
5489 if (g_fout->remoteVersion >= 70100)
5492 name = fmtId(oprleft);
5493 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
5494 appendPQExpBuffer(oprid, "%s", name);
5497 appendPQExpBuffer(oprid, "NONE");
5499 if (strcmp(oprkind, "l") == 0 ||
5500 strcmp(oprkind, "b") == 0)
5502 if (g_fout->remoteVersion >= 70100)
5505 name = fmtId(oprright);
5506 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
5507 appendPQExpBuffer(oprid, ", %s)", name);
5510 appendPQExpBuffer(oprid, ", NONE)");
5512 name = convertOperatorReference(oprcom);
5514 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
5516 name = convertOperatorReference(oprnegate);
5518 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
5520 if (strcmp(oprcanhash, "t") == 0)
5521 appendPQExpBuffer(details, ",\n HASHES");
5523 name = convertRegProcReference(oprrest);
5525 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
5527 name = convertRegProcReference(oprjoin);
5529 appendPQExpBuffer(details, ",\n JOIN = %s", name);
5531 name = convertOperatorReference(oprlsortop);
5533 appendPQExpBuffer(details, ",\n SORT1 = %s", name);
5535 name = convertOperatorReference(oprrsortop);
5537 appendPQExpBuffer(details, ",\n SORT2 = %s", name);
5539 name = convertOperatorReference(oprltcmpop);
5541 appendPQExpBuffer(details, ",\n LTCMP = %s", name);
5543 name = convertOperatorReference(oprgtcmpop);
5545 appendPQExpBuffer(details, ",\n GTCMP = %s", name);
5548 * DROP must be fully qualified in case same name appears in
5551 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
5552 fmtId(oprinfo->dobj.namespace->dobj.name),
5555 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
5556 oprinfo->dobj.name, details->data);
5558 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
5560 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5561 false, "OPERATOR", q->data, delq->data, NULL,
5562 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
5565 /* Dump Operator Comments */
5566 resetPQExpBuffer(q);
5567 appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
5568 dumpComment(fout, q->data,
5569 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5570 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
5574 destroyPQExpBuffer(query);
5575 destroyPQExpBuffer(q);
5576 destroyPQExpBuffer(delq);
5577 destroyPQExpBuffer(oprid);
5578 destroyPQExpBuffer(details);
5582 * Convert a function reference obtained from pg_operator
5584 * Returns what to print, or NULL if function references is InvalidOid
5586 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
5587 * argument-types part. In prior versions, the input is a REGPROC display.
5590 convertRegProcReference(const char *proc)
5592 /* In all cases "-" means a null reference */
5593 if (strcmp(proc, "-") == 0)
5596 if (g_fout->remoteVersion >= 70300)
5602 name = strdup(proc);
5603 /* find non-double-quoted left paren */
5605 for (paren = name; *paren; paren++)
5607 if (*paren == '(' && !inquote)
5618 /* REGPROC before 7.3 does not quote its result */
5623 * Convert an operator cross-reference obtained from pg_operator
5625 * Returns what to print, or NULL to print nothing
5627 * In 7.3 the input is a REGOPERATOR display; we have to strip the
5628 * argument-types part. In prior versions, the input is just a
5629 * numeric OID, which we search our operator list for.
5632 convertOperatorReference(const char *opr)
5636 /* In all cases "0" means a null reference */
5637 if (strcmp(opr, "0") == 0)
5640 if (g_fout->remoteVersion >= 70300)
5647 /* find non-double-quoted left paren */
5649 for (paren = name; *paren; paren++)
5651 if (*paren == '(' && !inquote)
5662 oprInfo = findOprByOid(atooid(opr));
5663 if (oprInfo == NULL)
5665 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
5669 return oprInfo->dobj.name;
5674 * write out a single operator class definition
5677 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
5705 /* Dump only opclasses in dumpable namespaces */
5706 if (!opcinfo->dobj.namespace->dump || dataOnly)
5710 * XXX currently we do not implement dumping of operator classes from
5711 * pre-7.3 databases. This could be done but it seems not worth the
5714 if (g_fout->remoteVersion < 70300)
5717 query = createPQExpBuffer();
5718 q = createPQExpBuffer();
5719 delq = createPQExpBuffer();
5721 /* Make sure we are in proper schema so regoperator works correctly */
5722 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
5724 /* Get additional fields from the pg_opclass row */
5725 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
5726 "opckeytype::pg_catalog.regtype, "
5728 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
5729 "FROM pg_catalog.pg_opclass "
5730 "WHERE oid = '%u'::pg_catalog.oid",
5731 opcinfo->dobj.catId.oid);
5733 res = PQexec(g_conn, query->data);
5734 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5736 /* Expecting a single result only */
5737 ntups = PQntuples(res);
5740 write_msg(NULL, "Got %d rows instead of one from: %s",
5741 ntups, query->data);
5745 i_opcintype = PQfnumber(res, "opcintype");
5746 i_opckeytype = PQfnumber(res, "opckeytype");
5747 i_opcdefault = PQfnumber(res, "opcdefault");
5748 i_amname = PQfnumber(res, "amname");
5750 opcintype = PQgetvalue(res, 0, i_opcintype);
5751 opckeytype = PQgetvalue(res, 0, i_opckeytype);
5752 opcdefault = PQgetvalue(res, 0, i_opcdefault);
5753 /* amname will still be needed after we PQclear res */
5754 amname = strdup(PQgetvalue(res, 0, i_amname));
5757 * DROP must be fully qualified in case same name appears in
5760 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
5761 fmtId(opcinfo->dobj.namespace->dobj.name));
5762 appendPQExpBuffer(delq, ".%s",
5763 fmtId(opcinfo->dobj.name));
5764 appendPQExpBuffer(delq, " USING %s;\n",
5767 /* Build the fixed portion of the CREATE command */
5768 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
5769 fmtId(opcinfo->dobj.name));
5770 if (strcmp(opcdefault, "t") == 0)
5771 appendPQExpBuffer(q, "DEFAULT ");
5772 appendPQExpBuffer(q, "FOR TYPE %s USING %s AS\n ",
5778 if (strcmp(opckeytype, "-") != 0)
5780 appendPQExpBuffer(q, "STORAGE %s",
5788 * Now fetch and print the OPERATOR entries (pg_amop rows).
5790 resetPQExpBuffer(query);
5792 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
5793 "amopopr::pg_catalog.regoperator "
5794 "FROM pg_catalog.pg_amop "
5795 "WHERE amopclaid = '%u'::pg_catalog.oid "
5796 "ORDER BY amopstrategy",
5797 opcinfo->dobj.catId.oid);
5799 res = PQexec(g_conn, query->data);
5800 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5802 ntups = PQntuples(res);
5804 i_amopstrategy = PQfnumber(res, "amopstrategy");
5805 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
5806 i_amopopr = PQfnumber(res, "amopopr");
5808 for (i = 0; i < ntups; i++)
5810 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
5811 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
5812 amopopr = PQgetvalue(res, i, i_amopopr);
5815 appendPQExpBuffer(q, " ,\n ");
5817 appendPQExpBuffer(q, "OPERATOR %s %s",
5818 amopstrategy, amopopr);
5819 if (strcmp(amopreqcheck, "t") == 0)
5820 appendPQExpBuffer(q, " RECHECK");
5828 * Now fetch and print the FUNCTION entries (pg_amproc rows).
5830 resetPQExpBuffer(query);
5832 appendPQExpBuffer(query, "SELECT amprocnum, "
5833 "amproc::pg_catalog.regprocedure "
5834 "FROM pg_catalog.pg_amproc "
5835 "WHERE amopclaid = '%u'::pg_catalog.oid "
5836 "ORDER BY amprocnum",
5837 opcinfo->dobj.catId.oid);
5839 res = PQexec(g_conn, query->data);
5840 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5842 ntups = PQntuples(res);
5844 i_amprocnum = PQfnumber(res, "amprocnum");
5845 i_amproc = PQfnumber(res, "amproc");
5847 for (i = 0; i < ntups; i++)
5849 amprocnum = PQgetvalue(res, i, i_amprocnum);
5850 amproc = PQgetvalue(res, i, i_amproc);
5853 appendPQExpBuffer(q, " ,\n ");
5855 appendPQExpBuffer(q, "FUNCTION %s %s",
5863 appendPQExpBuffer(q, ";\n");
5865 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
5867 opcinfo->dobj.namespace->dobj.name, opcinfo->usename,
5868 false, "OPERATOR CLASS", q->data, delq->data, NULL,
5869 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
5872 /* Dump Operator Class Comments */
5873 resetPQExpBuffer(q);
5874 appendPQExpBuffer(q, "OPERATOR CLASS %s",
5875 fmtId(opcinfo->dobj.name));
5876 appendPQExpBuffer(q, " USING %s",
5878 dumpComment(fout, q->data,
5879 NULL, opcinfo->usename,
5880 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
5883 destroyPQExpBuffer(query);
5884 destroyPQExpBuffer(q);
5885 destroyPQExpBuffer(delq);
5890 * write out a single conversion definition
5893 dumpConversion(Archive *fout, ConvInfo *convinfo)
5898 PQExpBuffer details;
5902 int i_conforencoding;
5903 int i_contoencoding;
5906 const char *conname;
5907 const char *conforencoding;
5908 const char *contoencoding;
5909 const char *conproc;
5912 /* Dump only conversions in dumpable namespaces */
5913 if (!convinfo->dobj.namespace->dump || dataOnly)
5916 query = createPQExpBuffer();
5917 q = createPQExpBuffer();
5918 delq = createPQExpBuffer();
5919 details = createPQExpBuffer();
5921 /* Make sure we are in proper schema */
5922 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
5924 /* Get conversion-specific details */
5925 appendPQExpBuffer(query, "SELECT conname, "
5926 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
5927 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
5928 "conproc, condefault "
5929 "FROM pg_catalog.pg_conversion c "
5930 "WHERE c.oid = '%u'::pg_catalog.oid",
5931 convinfo->dobj.catId.oid);
5933 res = PQexec(g_conn, query->data);
5934 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5936 /* Expecting a single result only */
5937 ntups = PQntuples(res);
5940 write_msg(NULL, "Got %d rows instead of one from: %s",
5941 ntups, query->data);
5945 i_conname = PQfnumber(res, "conname");
5946 i_conforencoding = PQfnumber(res, "conforencoding");
5947 i_contoencoding = PQfnumber(res, "contoencoding");
5948 i_conproc = PQfnumber(res, "conproc");
5949 i_condefault = PQfnumber(res, "condefault");
5951 conname = PQgetvalue(res, 0, i_conname);
5952 conforencoding = PQgetvalue(res, 0, i_conforencoding);
5953 contoencoding = PQgetvalue(res, 0, i_contoencoding);
5954 conproc = PQgetvalue(res, 0, i_conproc);
5955 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
5958 * DROP must be fully qualified in case same name appears in
5961 appendPQExpBuffer(delq, "DROP CONVERSION %s",
5962 fmtId(convinfo->dobj.namespace->dobj.name));
5963 appendPQExpBuffer(delq, ".%s;\n",
5964 fmtId(convinfo->dobj.name));
5966 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
5967 (condefault) ? "DEFAULT " : "",
5968 fmtId(convinfo->dobj.name));
5969 appendStringLiteral(q, conforencoding, true);
5970 appendPQExpBuffer(q, " TO ");
5971 appendStringLiteral(q, contoencoding, true);
5972 /* regproc is automatically quoted in 7.3 and above */
5973 appendPQExpBuffer(q, " FROM %s;\n", conproc);
5975 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
5976 convinfo->dobj.name,
5977 convinfo->dobj.namespace->dobj.name, convinfo->usename,
5978 false, "CONVERSION", q->data, delq->data, NULL,
5979 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
5982 /* Dump Conversion Comments */
5983 resetPQExpBuffer(q);
5984 appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
5985 dumpComment(fout, q->data,
5986 convinfo->dobj.namespace->dobj.name, convinfo->usename,
5987 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
5991 destroyPQExpBuffer(query);
5992 destroyPQExpBuffer(q);
5993 destroyPQExpBuffer(delq);
5994 destroyPQExpBuffer(details);
5998 * format_aggregate_signature: generate aggregate name and argument list
6000 * The argument type names are qualified if needed. The aggregate name
6001 * is never qualified.
6004 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
6006 PQExpBufferData buf;
6008 initPQExpBuffer(&buf);
6010 appendPQExpBuffer(&buf, "%s",
6011 fmtId(agginfo->aggfn.dobj.name));
6013 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
6015 /* If using regtype or format_type, fmtbasetype is already quoted */
6016 if (fout->remoteVersion >= 70100)
6018 if (agginfo->anybasetype)
6019 appendPQExpBuffer(&buf, "(*)");
6021 appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
6025 if (agginfo->anybasetype)
6026 appendPQExpBuffer(&buf, "(*)");
6028 appendPQExpBuffer(&buf, "(%s)",
6029 fmtId(agginfo->fmtbasetype));
6037 * write out a single aggregate definition
6040 dumpAgg(Archive *fout, AggInfo *agginfo)
6045 PQExpBuffer details;
6057 const char *aggtransfn;
6058 const char *aggfinalfn;
6059 const char *aggtranstype;
6060 const char *agginitval;
6063 /* Dump only aggs in dumpable namespaces */
6064 if (!agginfo->aggfn.dobj.namespace->dump || dataOnly)
6067 query = createPQExpBuffer();
6068 q = createPQExpBuffer();
6069 delq = createPQExpBuffer();
6070 details = createPQExpBuffer();
6072 /* Make sure we are in proper schema */
6073 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
6075 /* Get aggregate-specific details */
6076 if (g_fout->remoteVersion >= 70300)
6078 appendPQExpBuffer(query, "SELECT aggtransfn, "
6079 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6081 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6082 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6083 "'t'::boolean as convertok "
6084 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6085 "where a.aggfnoid = p.oid "
6086 "and p.oid = '%u'::pg_catalog.oid",
6087 agginfo->aggfn.dobj.catId.oid);
6089 else if (g_fout->remoteVersion >= 70100)
6091 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
6092 "format_type(aggtranstype, NULL) as aggtranstype, "
6094 "aggbasetype = 0 as anybasetype, "
6095 "CASE WHEN aggbasetype = 0 THEN '-' "
6096 "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
6097 "'t'::boolean as convertok "
6098 "from pg_aggregate "
6099 "where oid = '%u'::oid",
6100 agginfo->aggfn.dobj.catId.oid);
6104 appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
6106 "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
6107 "agginitval1 as agginitval, "
6108 "aggbasetype = 0 as anybasetype, "
6109 "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
6110 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
6111 "from pg_aggregate "
6112 "where oid = '%u'::oid",
6113 agginfo->aggfn.dobj.catId.oid);
6116 res = PQexec(g_conn, query->data);
6117 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6119 /* Expecting a single result only */
6120 ntups = PQntuples(res);
6123 write_msg(NULL, "Got %d rows instead of one from: %s",
6124 ntups, query->data);
6128 i_aggtransfn = PQfnumber(res, "aggtransfn");
6129 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
6130 i_aggtranstype = PQfnumber(res, "aggtranstype");
6131 i_agginitval = PQfnumber(res, "agginitval");
6132 i_anybasetype = PQfnumber(res, "anybasetype");
6133 i_fmtbasetype = PQfnumber(res, "fmtbasetype");
6134 i_convertok = PQfnumber(res, "convertok");
6136 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
6137 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
6138 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
6139 agginitval = PQgetvalue(res, 0, i_agginitval);
6140 /* we save anybasetype for format_aggregate_signature */
6141 agginfo->anybasetype = (PQgetvalue(res, 0, i_anybasetype)[0] == 't');
6142 /* we save fmtbasetype for format_aggregate_signature */
6143 agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
6144 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
6146 aggsig = format_aggregate_signature(agginfo, fout, true);
6147 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
6151 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
6156 if (g_fout->remoteVersion >= 70300)
6158 /* If using 7.3's regproc or regtype, data is already quoted */
6159 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6160 agginfo->anybasetype ? "'any'" :
6161 agginfo->fmtbasetype,
6165 else if (g_fout->remoteVersion >= 70100)
6167 /* format_type quotes, regproc does not */
6168 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6169 agginfo->anybasetype ? "'any'" :
6170 agginfo->fmtbasetype,
6176 /* need quotes all around */
6177 appendPQExpBuffer(details, " BASETYPE = %s,\n",
6178 agginfo->anybasetype ? "'any'" :
6179 fmtId(agginfo->fmtbasetype));
6180 appendPQExpBuffer(details, " SFUNC = %s,\n",
6182 appendPQExpBuffer(details, " STYPE = %s",
6183 fmtId(aggtranstype));
6186 if (!PQgetisnull(res, 0, i_agginitval))
6188 appendPQExpBuffer(details, ",\n INITCOND = ");
6189 appendStringLiteral(details, agginitval, true);
6192 if (strcmp(aggfinalfn, "-") != 0)
6194 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
6199 * DROP must be fully qualified in case same name appears in
6202 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
6203 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
6206 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
6207 fmtId(agginfo->aggfn.dobj.name),
6210 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6212 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6213 false, "AGGREGATE", q->data, delq->data, NULL,
6214 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
6217 /* Dump Aggregate Comments */
6218 resetPQExpBuffer(q);
6219 appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
6220 dumpComment(fout, q->data,
6221 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6222 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
6225 * Since there is no GRANT ON AGGREGATE syntax, we have to make the
6226 * ACL command look like a function's GRANT; in particular this affects
6227 * the syntax for aggregates on ANY.
6232 aggsig = format_function_signature(&agginfo->aggfn, NULL, true);
6233 aggsig_tag = format_function_signature(&agginfo->aggfn, NULL, false);
6235 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6238 agginfo->aggfn.dobj.namespace->dobj.name,
6239 agginfo->aggfn.usename, agginfo->aggfn.proacl);
6246 destroyPQExpBuffer(query);
6247 destroyPQExpBuffer(q);
6248 destroyPQExpBuffer(delq);
6249 destroyPQExpBuffer(details);
6254 * Write out grant/revoke information
6256 * 'objCatId' is the catalog ID of the underlying object.
6257 * 'objDumpId' is the dump ID of the underlying object.
6258 * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA.
6259 * 'name' is the formatted name of the object. Must be quoted etc. already.
6260 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
6261 * 'nspname' is the namespace the object is in (NULL if none).
6262 * 'owner' is the owner, NULL if there is no owner (for languages).
6263 * 'acls' is the string read out of the fooacl system catalog field;
6264 * it will be parsed here.
6268 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
6269 const char *type, const char *name,
6270 const char *tag, const char *nspname, const char *owner,
6275 /* Do nothing if ACL dump is not enabled */
6276 if (dataOnly || aclsSkip)
6279 sql = createPQExpBuffer();
6281 if (!buildACLCommands(name, type, acls, owner, fout->remoteVersion, sql))
6283 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
6289 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6292 false, "ACL", sql->data, "", NULL,
6296 destroyPQExpBuffer(sql);
6301 * write out to fout the declarations (not data) of a user-defined table
6304 dumpTable(Archive *fout, TableInfo *tbinfo)
6310 if (tbinfo->relkind == RELKIND_SEQUENCE)
6311 dumpSequence(fout, tbinfo);
6313 dumpTableSchema(fout, tbinfo);
6315 /* Handle the ACL here */
6316 namecopy = strdup(fmtId(tbinfo->dobj.name));
6317 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
6318 namecopy, tbinfo->dobj.name,
6319 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6327 * write the declaration (not data) of one user-defined table or view
6330 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
6332 PQExpBuffer query = createPQExpBuffer();
6333 PQExpBuffer q = createPQExpBuffer();
6334 PQExpBuffer delq = createPQExpBuffer();
6337 TableInfo **parents;
6338 int actual_atts; /* number of attrs in this CREATE statment */
6344 /* Make sure we are in proper schema */
6345 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
6347 /* Is it a table or a view? */
6348 if (tbinfo->relkind == RELKIND_VIEW)
6352 reltypename = "VIEW";
6354 /* Fetch the view definition */
6355 if (g_fout->remoteVersion >= 70300)
6357 /* Beginning in 7.3, viewname is not unique; rely on OID */
6358 appendPQExpBuffer(query,
6359 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) as viewdef",
6360 tbinfo->dobj.catId.oid);
6364 appendPQExpBuffer(query, "SELECT definition as viewdef "
6365 " from pg_views where viewname = ");
6366 appendStringLiteral(query, tbinfo->dobj.name, true);
6367 appendPQExpBuffer(query, ";");
6370 res = PQexec(g_conn, query->data);
6371 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6373 if (PQntuples(res) != 1)
6375 if (PQntuples(res) < 1)
6376 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
6379 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
6384 viewdef = PQgetvalue(res, 0, 0);
6386 if (strlen(viewdef) == 0)
6388 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
6394 * DROP must be fully qualified in case same name appears in
6397 appendPQExpBuffer(delq, "DROP VIEW %s.",
6398 fmtId(tbinfo->dobj.namespace->dobj.name));
6399 appendPQExpBuffer(delq, "%s;\n",
6400 fmtId(tbinfo->dobj.name));
6402 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
6403 fmtId(tbinfo->dobj.name), viewdef);
6409 reltypename = "TABLE";
6410 numParents = tbinfo->numParents;
6411 parents = tbinfo->parents;
6414 * DROP must be fully qualified in case same name appears in
6417 appendPQExpBuffer(delq, "DROP TABLE %s.",
6418 fmtId(tbinfo->dobj.namespace->dobj.name));
6419 appendPQExpBuffer(delq, "%s;\n",
6420 fmtId(tbinfo->dobj.name));
6422 appendPQExpBuffer(q, "CREATE TABLE %s (",
6423 fmtId(tbinfo->dobj.name));
6425 for (j = 0; j < tbinfo->numatts; j++)
6427 /* Is this one of the table's own attrs, and not dropped ? */
6428 if (!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j])
6430 /* Format properly if not first attr */
6431 if (actual_atts > 0)
6432 appendPQExpBuffer(q, ",");
6433 appendPQExpBuffer(q, "\n ");
6435 /* Attribute name */
6436 appendPQExpBuffer(q, "%s ",
6437 fmtId(tbinfo->attnames[j]));
6439 /* Attribute type */
6440 if (g_fout->remoteVersion >= 70100)
6442 char *typname = tbinfo->atttypnames[j];
6444 if (tbinfo->attisserial[j])
6446 if (strcmp(typname, "integer") == 0)
6448 else if (strcmp(typname, "bigint") == 0)
6449 typname = "bigserial";
6451 appendPQExpBuffer(q, "%s", typname);
6455 /* If no format_type, fake it */
6456 appendPQExpBuffer(q, "%s",
6457 myFormatType(tbinfo->atttypnames[j],
6458 tbinfo->atttypmod[j]));
6462 * Default value --- suppress if inherited, serial,
6463 * or to be printed separately.
6465 if (tbinfo->attrdefs[j] != NULL &&
6466 !tbinfo->inhAttrDef[j] &&
6467 !tbinfo->attisserial[j] &&
6468 !tbinfo->attrdefs[j]->separate)
6469 appendPQExpBuffer(q, " DEFAULT %s",
6470 tbinfo->attrdefs[j]->adef_expr);
6473 * Not Null constraint --- suppress if inherited
6475 * Note: we could suppress this for serial columns since
6476 * SERIAL implies NOT NULL. We choose not to for forward
6477 * compatibility, since there has been some talk of making
6478 * SERIAL not imply NOT NULL, in which case the explicit
6479 * specification would be needed.
6481 if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
6482 appendPQExpBuffer(q, " NOT NULL");
6489 * Add non-inherited CHECK constraints, if any.
6491 for (j = 0; j < tbinfo->ncheck; j++)
6493 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
6495 if (constr->coninherited || constr->separate)
6498 if (actual_atts > 0)
6499 appendPQExpBuffer(q, ",\n ");
6501 appendPQExpBuffer(q, "CONSTRAINT %s ",
6502 fmtId(constr->dobj.name));
6503 appendPQExpBuffer(q, "%s", constr->condef);
6508 appendPQExpBuffer(q, "\n)");
6512 appendPQExpBuffer(q, "\nINHERITS (");
6513 for (k = 0; k < numParents; k++)
6515 TableInfo *parentRel = parents[k];
6518 appendPQExpBuffer(q, ", ");
6519 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
6520 appendPQExpBuffer(q, "%s.",
6521 fmtId(parentRel->dobj.namespace->dobj.name));
6522 appendPQExpBuffer(q, "%s",
6523 fmtId(parentRel->dobj.name));
6525 appendPQExpBuffer(q, ")");
6528 appendPQExpBuffer(q, ";\n");
6530 /* Loop dumping statistics and storage statements */
6531 for (j = 0; j < tbinfo->numatts; j++)
6534 * Dump per-column statistics information. We only issue an
6535 * ALTER TABLE statement if the attstattarget entry for this
6536 * column is non-negative (i.e. it's not the default value)
6538 if (tbinfo->attstattarget[j] >= 0 &&
6539 !tbinfo->attisdropped[j])
6541 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6542 fmtId(tbinfo->dobj.name));
6543 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6544 fmtId(tbinfo->attnames[j]));
6545 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
6546 tbinfo->attstattarget[j]);
6550 * Dump per-column storage information. The statement is only
6551 * dumped if the storage has been changed from the type's
6554 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
6556 switch (tbinfo->attstorage[j])
6562 storage = "EXTERNAL";
6568 storage = "EXTENDED";
6575 * Only dump the statement if it's a storage type we
6578 if (storage != NULL)
6580 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6581 fmtId(tbinfo->dobj.name));
6582 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6583 fmtId(tbinfo->attnames[j]));
6584 appendPQExpBuffer(q, "SET STORAGE %s;\n",
6591 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
6593 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6594 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
6595 reltypename, q->data, delq->data, NULL,
6596 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
6599 /* Dump Table Comments */
6600 dumpTableComment(fout, tbinfo, reltypename);
6602 destroyPQExpBuffer(query);
6603 destroyPQExpBuffer(q);
6604 destroyPQExpBuffer(delq);
6608 * dumpAttrDef --- dump an attribute's default-value declaration
6611 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
6613 TableInfo *tbinfo = adinfo->adtable;
6614 int adnum = adinfo->adnum;
6618 /* Only print it if "separate" mode is selected */
6619 if (!tbinfo->dump || !adinfo->separate || dataOnly)
6622 /* Don't print inherited or serial defaults, either */
6623 if (tbinfo->inhAttrDef[adnum-1] || tbinfo->attisserial[adnum-1])
6626 q = createPQExpBuffer();
6627 delq = createPQExpBuffer();
6629 appendPQExpBuffer(q, "ALTER TABLE %s ",
6630 fmtId(tbinfo->dobj.name));
6631 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
6632 fmtId(tbinfo->attnames[adnum - 1]),
6636 * DROP must be fully qualified in case same name appears
6639 appendPQExpBuffer(delq, "ALTER TABLE %s.",
6640 fmtId(tbinfo->dobj.namespace->dobj.name));
6641 appendPQExpBuffer(delq, "%s ",
6642 fmtId(tbinfo->dobj.name));
6643 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
6644 fmtId(tbinfo->attnames[adnum - 1]));
6646 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
6647 tbinfo->attnames[adnum - 1],
6648 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6649 false, "DEFAULT", q->data, delq->data, NULL,
6650 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
6653 destroyPQExpBuffer(q);
6654 destroyPQExpBuffer(delq);
6658 * getAttrName: extract the correct name for an attribute
6660 * The array tblInfo->attnames[] only provides names of user attributes;
6661 * if a system attribute number is supplied, we have to fake it.
6662 * We also do a little bit of bounds checking for safety's sake.
6665 getAttrName(int attrnum, TableInfo *tblInfo)
6667 if (attrnum > 0 && attrnum <= tblInfo->numatts)
6668 return tblInfo->attnames[attrnum - 1];
6671 case SelfItemPointerAttributeNumber:
6673 case ObjectIdAttributeNumber:
6675 case MinTransactionIdAttributeNumber:
6677 case MinCommandIdAttributeNumber:
6679 case MaxTransactionIdAttributeNumber:
6681 case MaxCommandIdAttributeNumber:
6683 case TableOidAttributeNumber:
6686 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
6687 attrnum, tblInfo->dobj.name);
6689 return NULL; /* keep compiler quiet */
6694 * write out to fout a user-defined index
6697 dumpIndex(Archive *fout, IndxInfo *indxinfo)
6699 TableInfo *tbinfo = indxinfo->indextable;
6706 q = createPQExpBuffer();
6707 delq = createPQExpBuffer();
6710 * If there's an associated constraint, don't dump the index per se,
6711 * but do dump any comment for it.
6713 if (indxinfo->indexconstraint == 0)
6715 /* Plain secondary index */
6716 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
6718 /* If the index is clustered, we need to record that. */
6719 if (indxinfo->indisclustered)
6721 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6722 fmtId(tbinfo->dobj.name));
6723 appendPQExpBuffer(q, " ON %s;\n",
6724 fmtId(indxinfo->dobj.name));
6728 * DROP must be fully qualified in case same name appears
6731 appendPQExpBuffer(delq, "DROP INDEX %s.",
6732 fmtId(tbinfo->dobj.namespace->dobj.name));
6733 appendPQExpBuffer(delq, "%s;\n",
6734 fmtId(indxinfo->dobj.name));
6736 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
6737 indxinfo->dobj.name,
6738 tbinfo->dobj.namespace->dobj.name,
6739 tbinfo->usename, false,
6740 "INDEX", q->data, delq->data, NULL,
6741 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
6745 /* Dump Index Comments */
6746 resetPQExpBuffer(q);
6747 appendPQExpBuffer(q, "INDEX %s",
6748 fmtId(indxinfo->dobj.name));
6749 dumpComment(fout, q->data,
6750 tbinfo->dobj.namespace->dobj.name,
6752 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
6754 destroyPQExpBuffer(q);
6755 destroyPQExpBuffer(delq);
6760 * write out to fout a user-defined constraint
6763 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
6765 TableInfo *tbinfo = coninfo->contable;
6771 if (tbinfo && !tbinfo->dump)
6774 q = createPQExpBuffer();
6775 delq = createPQExpBuffer();
6777 if (coninfo->contype == 'p' || coninfo->contype == 'u')
6779 /* Index-related constraint */
6783 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
6785 if (indxinfo == NULL)
6787 write_msg(NULL, "missing index for constraint %s\n",
6788 coninfo->dobj.name);
6792 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6793 fmtId(tbinfo->dobj.name));
6794 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s (",
6795 fmtId(coninfo->dobj.name),
6796 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
6798 for (k = 0; k < indxinfo->indnkeys; k++)
6800 int indkey = (int) indxinfo->indkeys[k];
6801 const char *attname;
6803 if (indkey == InvalidAttrNumber)
6805 attname = getAttrName(indkey, tbinfo);
6807 appendPQExpBuffer(q, "%s%s",
6808 (k == 0) ? "" : ", ",
6812 appendPQExpBuffer(q, ");\n");
6814 /* If the index is clustered, we need to record that. */
6815 if (indxinfo->indisclustered)
6817 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6818 fmtId(tbinfo->dobj.name));
6819 appendPQExpBuffer(q, " ON %s;\n",
6820 fmtId(indxinfo->dobj.name));
6824 * DROP must be fully qualified in case same name appears
6827 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
6828 fmtId(tbinfo->dobj.namespace->dobj.name));
6829 appendPQExpBuffer(delq, "%s ",
6830 fmtId(tbinfo->dobj.name));
6831 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6832 fmtId(coninfo->dobj.name));
6834 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
6836 tbinfo->dobj.namespace->dobj.name,
6837 tbinfo->usename, false,
6838 "CONSTRAINT", q->data, delq->data, NULL,
6839 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
6842 else if (coninfo->contype == 'f')
6845 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that
6846 * the current table data is not processed
6848 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6849 fmtId(tbinfo->dobj.name));
6850 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
6851 fmtId(coninfo->dobj.name),
6855 * DROP must be fully qualified in case same name appears in
6858 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
6859 fmtId(tbinfo->dobj.namespace->dobj.name));
6860 appendPQExpBuffer(delq, "%s ",
6861 fmtId(tbinfo->dobj.name));
6862 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6863 fmtId(coninfo->dobj.name));
6865 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
6867 tbinfo->dobj.namespace->dobj.name,
6868 tbinfo->usename, false,
6869 "FK CONSTRAINT", q->data, delq->data, NULL,
6870 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
6873 else if (coninfo->contype == 'c' && tbinfo)
6875 /* CHECK constraint on a table */
6877 /* Ignore if not to be dumped separately */
6878 if (coninfo->separate)
6880 /* not ONLY since we want it to propagate to children */
6881 appendPQExpBuffer(q, "ALTER TABLE %s\n",
6882 fmtId(tbinfo->dobj.name));
6883 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
6884 fmtId(coninfo->dobj.name),
6888 * DROP must be fully qualified in case same name appears in
6891 appendPQExpBuffer(delq, "ALTER TABLE %s.",
6892 fmtId(tbinfo->dobj.namespace->dobj.name));
6893 appendPQExpBuffer(delq, "%s ",
6894 fmtId(tbinfo->dobj.name));
6895 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6896 fmtId(coninfo->dobj.name));
6898 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
6900 tbinfo->dobj.namespace->dobj.name,
6901 tbinfo->usename, false,
6902 "CHECK CONSTRAINT", q->data, delq->data, NULL,
6903 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
6907 else if (coninfo->contype == 'c' && tbinfo == NULL)
6909 /* CHECK constraint on a domain */
6910 TypeInfo *tinfo = coninfo->condomain;
6912 /* Ignore if not to be dumped separately, or if not dumping domain */
6913 if (coninfo->separate && tinfo->dobj.namespace->dump)
6915 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
6916 fmtId(tinfo->dobj.name));
6917 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
6918 fmtId(coninfo->dobj.name),
6922 * DROP must be fully qualified in case same name appears in
6925 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
6926 fmtId(tinfo->dobj.namespace->dobj.name));
6927 appendPQExpBuffer(delq, "%s ",
6928 fmtId(tinfo->dobj.name));
6929 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6930 fmtId(coninfo->dobj.name));
6932 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
6934 tinfo->dobj.namespace->dobj.name,
6935 tinfo->usename, false,
6936 "CHECK CONSTRAINT", q->data, delq->data, NULL,
6937 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
6943 write_msg(NULL, "unexpected constraint type\n");
6947 /* Dump Constraint Comments --- only works for table constraints */
6950 resetPQExpBuffer(q);
6951 appendPQExpBuffer(q, "CONSTRAINT %s ",
6952 fmtId(coninfo->dobj.name));
6953 appendPQExpBuffer(q, "ON %s",
6954 fmtId(tbinfo->dobj.name));
6955 dumpComment(fout, q->data,
6956 tbinfo->dobj.namespace->dobj.name,
6958 coninfo->dobj.catId, 0, coninfo->dobj.dumpId);
6961 destroyPQExpBuffer(q);
6962 destroyPQExpBuffer(delq);
6967 * find the maximum oid and generate a COPY statement to set it
6971 setMaxOid(Archive *fout)
6977 do_sql_command(g_conn,
6978 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer)");
6979 res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
6980 check_sql_result(res, g_conn, "INSERT INTO pgdump_oid VALUES (0)",
6982 max_oid = PQoidValue(res);
6985 write_msg(NULL, "inserted invalid OID\n");
6989 do_sql_command(g_conn, "DROP TABLE pgdump_oid;");
6991 write_msg(NULL, "maximum system OID is %u\n", max_oid);
6992 snprintf(sql, sizeof(sql),
6993 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer);\n"
6994 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
6997 "DROP TABLE pgdump_oid;\n",
7000 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7001 "Max OID", NULL, "",
7002 false, "<Init>", sql, "", NULL,
7008 * findLastBuiltInOid -
7009 * find the last built in oid
7011 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
7012 * pg_database entry for the current database
7015 findLastBuiltinOid_V71(const char *dbname)
7020 PQExpBuffer query = createPQExpBuffer();
7022 resetPQExpBuffer(query);
7023 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
7024 appendStringLiteral(query, dbname, true);
7026 res = PQexec(g_conn, query->data);
7027 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7029 ntups = PQntuples(res);
7032 write_msg(NULL, "missing pg_database entry for this database\n");
7037 write_msg(NULL, "found more than one pg_database entry for this database\n");
7040 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
7042 destroyPQExpBuffer(query);
7047 * findLastBuiltInOid -
7048 * find the last built in oid
7050 * For 7.0, we do this by assuming that the last thing that initdb does is to
7051 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
7052 * initdb won't be changing anymore, it'll do.
7055 findLastBuiltinOid_V70(void)
7061 res = PQexec(g_conn,
7062 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
7063 check_sql_result(res, g_conn,
7064 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
7066 ntups = PQntuples(res);
7069 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
7074 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
7077 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
7083 dumpSequence(Archive *fout, TableInfo *tbinfo)
7095 PQExpBuffer query = createPQExpBuffer();
7096 PQExpBuffer delqry = createPQExpBuffer();
7098 /* Make sure we are in proper schema */
7099 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7101 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
7102 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
7104 appendPQExpBuffer(query,
7105 "SELECT sequence_name, last_value, increment_by, "
7106 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
7107 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
7109 "END AS max_value, "
7110 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
7111 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
7113 "END AS min_value, "
7114 "cache_value, is_cycled, is_called from %s",
7116 fmtId(tbinfo->dobj.name));
7118 res = PQexec(g_conn, query->data);
7119 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7121 if (PQntuples(res) != 1)
7123 write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
7124 tbinfo->dobj.name, PQntuples(res));
7128 /* Disable this check: it fails if sequence has been renamed */
7130 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
7132 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
7133 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
7138 last = PQgetvalue(res, 0, 1);
7139 incby = PQgetvalue(res, 0, 2);
7140 if (!PQgetisnull(res, 0, 3))
7141 maxv = PQgetvalue(res, 0, 3);
7142 if (!PQgetisnull(res, 0, 4))
7143 minv = PQgetvalue(res, 0, 4);
7144 cache = PQgetvalue(res, 0, 5);
7145 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
7146 called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
7149 * The logic we use for restoring sequences is as follows:
7151 * Add a basic CREATE SEQUENCE statement (use last_val for start if
7152 * called is false, else use min_val for start_val). Skip this if the
7153 * sequence came from a SERIAL column.
7155 * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
7156 * data. We do this for serial sequences too.
7159 if (!dataOnly && !OidIsValid(tbinfo->owning_tab))
7161 resetPQExpBuffer(delqry);
7164 * DROP must be fully qualified in case same name appears in
7167 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
7168 fmtId(tbinfo->dobj.namespace->dobj.name));
7169 appendPQExpBuffer(delqry, "%s;\n",
7170 fmtId(tbinfo->dobj.name));
7172 resetPQExpBuffer(query);
7173 appendPQExpBuffer(query,
7174 "CREATE SEQUENCE %s\n",
7175 fmtId(tbinfo->dobj.name));
7178 appendPQExpBuffer(query, " START WITH %s\n", last);
7180 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
7183 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
7185 appendPQExpBuffer(query, " NO MAXVALUE\n");
7188 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
7190 appendPQExpBuffer(query, " NO MINVALUE\n");
7192 appendPQExpBuffer(query,
7194 cache, (cycled ? "\n CYCLE" : ""));
7196 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7198 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7199 false, "SEQUENCE", query->data, delqry->data, NULL,
7200 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7206 resetPQExpBuffer(query);
7207 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
7208 appendStringLiteral(query, fmtId(tbinfo->dobj.name), true);
7209 appendPQExpBuffer(query, ", %s, %s);\n",
7210 last, (called ? "true" : "false"));
7212 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7214 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7215 false, "SEQUENCE SET", query->data, "", NULL,
7216 &(tbinfo->dobj.dumpId), 1,
7222 /* Dump Sequence Comments */
7223 resetPQExpBuffer(query);
7224 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
7225 dumpComment(fout, query->data,
7226 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7227 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
7232 destroyPQExpBuffer(query);
7233 destroyPQExpBuffer(delqry);
7237 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
7239 TableInfo *tbinfo = tginfo->tgtable;
7248 query = createPQExpBuffer();
7249 delqry = createPQExpBuffer();
7252 * DROP must be fully qualified in case same name appears in
7255 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
7256 fmtId(tginfo->dobj.name));
7257 appendPQExpBuffer(delqry, "ON %s.",
7258 fmtId(tbinfo->dobj.namespace->dobj.name));
7259 appendPQExpBuffer(delqry, "%s;\n",
7260 fmtId(tbinfo->dobj.name));
7262 if (tginfo->tgisconstraint)
7264 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
7265 appendPQExpBuffer(query, fmtId(tginfo->tgconstrname));
7269 appendPQExpBuffer(query, "CREATE TRIGGER ");
7270 appendPQExpBuffer(query, fmtId(tginfo->dobj.name));
7272 appendPQExpBuffer(query, "\n ");
7276 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
7277 appendPQExpBuffer(query, "BEFORE");
7279 appendPQExpBuffer(query, "AFTER");
7280 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
7282 appendPQExpBuffer(query, " INSERT");
7285 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
7288 appendPQExpBuffer(query, " OR DELETE");
7290 appendPQExpBuffer(query, " DELETE");
7293 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
7296 appendPQExpBuffer(query, " OR UPDATE");
7298 appendPQExpBuffer(query, " UPDATE");
7300 appendPQExpBuffer(query, " ON %s\n",
7301 fmtId(tbinfo->dobj.name));
7303 if (tginfo->tgisconstraint)
7305 if (OidIsValid(tginfo->tgconstrrelid))
7307 /* If we are using regclass, name is already quoted */
7308 if (g_fout->remoteVersion >= 70300)
7309 appendPQExpBuffer(query, " FROM %s\n ",
7310 tginfo->tgconstrrelname);
7312 appendPQExpBuffer(query, " FROM %s\n ",
7313 fmtId(tginfo->tgconstrrelname));
7315 if (!tginfo->tgdeferrable)
7316 appendPQExpBuffer(query, "NOT ");
7317 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
7318 if (tginfo->tginitdeferred)
7319 appendPQExpBuffer(query, "DEFERRED\n");
7321 appendPQExpBuffer(query, "IMMEDIATE\n");
7324 if (TRIGGER_FOR_ROW(tginfo->tgtype))
7325 appendPQExpBuffer(query, " FOR EACH ROW\n ");
7327 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
7329 /* In 7.3, result of regproc is already quoted */
7330 if (g_fout->remoteVersion >= 70300)
7331 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7334 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7335 fmtId(tginfo->tgfname));
7338 for (findx = 0; findx < tginfo->tgnargs; findx++)
7344 p = strchr(p, '\\');
7347 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
7359 if (p[0] == '0' && p[1] == '0' && p[2] == '0')
7363 appendPQExpBufferChar(query, '\'');
7367 appendPQExpBufferChar(query, '\\');
7368 appendPQExpBufferChar(query, *s++);
7370 appendPQExpBufferChar(query, '\'');
7371 appendPQExpBuffer(query,
7372 (findx < tginfo->tgnargs - 1) ? ", " : "");
7375 appendPQExpBuffer(query, ");\n");
7377 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
7379 tbinfo->dobj.namespace->dobj.name,
7380 tbinfo->usename, false,
7381 "TRIGGER", query->data, delqry->data, NULL,
7382 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
7385 resetPQExpBuffer(query);
7386 appendPQExpBuffer(query, "TRIGGER %s ",
7387 fmtId(tginfo->dobj.name));
7388 appendPQExpBuffer(query, "ON %s",
7389 fmtId(tbinfo->dobj.name));
7391 dumpComment(fout, query->data,
7392 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7393 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
7395 destroyPQExpBuffer(query);
7396 destroyPQExpBuffer(delqry);
7404 dumpRule(Archive *fout, RuleInfo *rinfo)
7406 TableInfo *tbinfo = rinfo->ruletable;
7413 * Ignore rules for not-to-be-dumped tables
7415 if (tbinfo == NULL || !tbinfo->dump || dataOnly)
7419 * If it is an ON SELECT rule, we do not need to dump it because
7420 * it will be handled via CREATE VIEW for the table.
7422 if (rinfo->ev_type == '1' && rinfo->is_instead)
7426 * Make sure we are in proper schema.
7428 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7430 query = createPQExpBuffer();
7431 cmd = createPQExpBuffer();
7432 delcmd = createPQExpBuffer();
7434 if (g_fout->remoteVersion >= 70300)
7436 appendPQExpBuffer(query,
7437 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
7438 rinfo->dobj.catId.oid);
7442 /* Rule name was unique before 7.3 ... */
7443 appendPQExpBuffer(query,
7444 "SELECT pg_get_ruledef('%s') AS definition",
7448 res = PQexec(g_conn, query->data);
7449 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7451 if (PQntuples(res) != 1)
7453 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
7454 rinfo->dobj.name, tbinfo->dobj.name);
7458 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
7461 * DROP must be fully qualified in case same name appears in
7464 appendPQExpBuffer(delcmd, "DROP RULE %s ",
7465 fmtId(rinfo->dobj.name));
7466 appendPQExpBuffer(delcmd, "ON %s.",
7467 fmtId(tbinfo->dobj.namespace->dobj.name));
7468 appendPQExpBuffer(delcmd, "%s;\n",
7469 fmtId(tbinfo->dobj.name));
7471 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
7473 tbinfo->dobj.namespace->dobj.name,
7474 tbinfo->usename, false,
7475 "RULE", cmd->data, delcmd->data, NULL,
7476 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
7479 /* Dump rule comments */
7480 resetPQExpBuffer(query);
7481 appendPQExpBuffer(query, "RULE %s",
7482 fmtId(rinfo->dobj.name));
7483 appendPQExpBuffer(query, " ON %s",
7484 fmtId(tbinfo->dobj.name));
7485 dumpComment(fout, query->data,
7486 tbinfo->dobj.namespace->dobj.name,
7488 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
7492 destroyPQExpBuffer(query);
7493 destroyPQExpBuffer(cmd);
7494 destroyPQExpBuffer(delcmd);
7498 * getDependencies --- obtain available dependency data
7501 getDependencies(void)
7512 DumpableObject *dobj,
7515 /* No dependency info available before 7.3 */
7516 if (g_fout->remoteVersion < 70300)
7520 write_msg(NULL, "fetching dependency data\n");
7522 /* Make sure we are in proper schema */
7523 selectSourceSchema("pg_catalog");
7525 query = createPQExpBuffer();
7527 appendPQExpBuffer(query, "SELECT "
7528 "classid, objid, refclassid, refobjid, deptype "
7530 "WHERE deptype != 'p' "
7533 res = PQexec(g_conn, query->data);
7534 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7536 ntups = PQntuples(res);
7538 i_classid = PQfnumber(res, "classid");
7539 i_objid = PQfnumber(res, "objid");
7540 i_refclassid = PQfnumber(res, "refclassid");
7541 i_refobjid = PQfnumber(res, "refobjid");
7542 i_deptype = PQfnumber(res, "deptype");
7545 * Since we ordered the SELECT by referencing ID, we can expect that
7546 * multiple entries for the same object will appear together; this
7547 * saves on searches.
7551 for (i = 0; i < ntups; i++)
7557 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
7558 objId.oid = atooid(PQgetvalue(res, i, i_objid));
7559 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
7560 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
7561 deptype = *(PQgetvalue(res, i, i_deptype));
7564 dobj->catId.tableoid != objId.tableoid ||
7565 dobj->catId.oid != objId.oid)
7566 dobj = findObjectByCatalogId(objId);
7569 * Failure to find objects mentioned in pg_depend is not unexpected,
7570 * since for example we don't collect info about TOAST tables.
7575 fprintf(stderr, "no referencing object %u %u\n",
7576 objId.tableoid, objId.oid);
7581 refdobj = findObjectByCatalogId(refobjId);
7583 if (refdobj == NULL)
7586 fprintf(stderr, "no referenced object %u %u\n",
7587 refobjId.tableoid, refobjId.oid);
7592 addObjectDependency(dobj, refdobj->dumpId);
7597 destroyPQExpBuffer(query);
7602 * selectSourceSchema - make the specified schema the active search path
7603 * in the source database.
7605 * NB: pg_catalog is explicitly searched after the specified schema;
7606 * so user names are only qualified if they are cross-schema references,
7607 * and system names are only qualified if they conflict with a user name
7608 * in the current schema.
7610 * Whenever the selected schema is not pg_catalog, be careful to qualify
7611 * references to system catalogs and types in our emitted commands!
7614 selectSourceSchema(const char *schemaName)
7616 static char *curSchemaName = NULL;
7619 /* Not relevant if fetching from pre-7.3 DB */
7620 if (g_fout->remoteVersion < 70300)
7622 /* Ignore null schema names */
7623 if (schemaName == NULL || *schemaName == '\0')
7625 /* Optimize away repeated selection of same schema */
7626 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
7629 query = createPQExpBuffer();
7630 appendPQExpBuffer(query, "SET search_path = %s",
7632 if (strcmp(schemaName, "pg_catalog") != 0)
7633 appendPQExpBuffer(query, ", pg_catalog");
7635 do_sql_command(g_conn, query->data);
7637 destroyPQExpBuffer(query);
7639 free(curSchemaName);
7640 curSchemaName = strdup(schemaName);
7644 * getFormattedTypeName - retrieve a nicely-formatted type name for the
7647 * NB: in 7.3 and up the result may depend on the currently-selected
7648 * schema; this is why we don't try to cache the names.
7651 getFormattedTypeName(Oid oid, OidOptions opts)
7660 if ((opts & zeroAsOpaque) != 0)
7661 return strdup(g_opaque_type);
7662 else if ((opts & zeroAsAny) != 0)
7663 return strdup("'any'");
7664 else if ((opts & zeroAsStar) != 0)
7666 else if ((opts & zeroAsNone) != 0)
7667 return strdup("NONE");
7670 query = createPQExpBuffer();
7671 if (g_fout->remoteVersion >= 70300)
7673 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
7676 else if (g_fout->remoteVersion >= 70100)
7678 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
7683 appendPQExpBuffer(query, "SELECT typname "
7685 "WHERE oid = '%u'::oid",
7689 res = PQexec(g_conn, query->data);
7690 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7692 /* Expecting a single result only */
7693 ntups = PQntuples(res);
7696 write_msg(NULL, "query yielded %d rows instead of one: %s\n",
7697 ntups, query->data);
7701 if (g_fout->remoteVersion >= 70100)
7703 /* already quoted */
7704 result = strdup(PQgetvalue(res, 0, 0));
7708 /* may need to quote it */
7709 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
7713 destroyPQExpBuffer(query);
7719 * myFormatType --- local implementation of format_type for use with 7.0.
7722 myFormatType(const char *typname, int32 typmod)
7725 bool isarray = false;
7726 PQExpBuffer buf = createPQExpBuffer();
7728 /* Handle array types */
7729 if (typname[0] == '_')
7735 /* Show lengths on bpchar and varchar */
7736 if (!strcmp(typname, "bpchar"))
7738 int len = (typmod - VARHDRSZ);
7740 appendPQExpBuffer(buf, "character");
7742 appendPQExpBuffer(buf, "(%d)",
7745 else if (!strcmp(typname, "varchar"))
7747 appendPQExpBuffer(buf, "character varying");
7749 appendPQExpBuffer(buf, "(%d)",
7752 else if (!strcmp(typname, "numeric"))
7754 appendPQExpBuffer(buf, "numeric");
7761 tmp_typmod = typmod - VARHDRSZ;
7762 precision = (tmp_typmod >> 16) & 0xffff;
7763 scale = tmp_typmod & 0xffff;
7764 appendPQExpBuffer(buf, "(%d,%d)",
7770 * char is an internal single-byte data type; Let's make sure we force
7771 * it through with quotes. - thomas 1998-12-13
7773 else if (strcmp(typname, "char") == 0)
7774 appendPQExpBuffer(buf, "\"char\"");
7776 appendPQExpBuffer(buf, "%s", fmtId(typname));
7778 /* Append array qualifier for array types */
7780 appendPQExpBuffer(buf, "[]");
7782 result = strdup(buf->data);
7783 destroyPQExpBuffer(buf);
7789 * fmtQualifiedId - convert a qualified name to the proper format for
7790 * the source database.
7792 * Like fmtId, use the result before calling again.
7795 fmtQualifiedId(const char *schema, const char *id)
7797 static PQExpBuffer id_return = NULL;
7799 if (id_return) /* first time through? */
7800 resetPQExpBuffer(id_return);
7802 id_return = createPQExpBuffer();
7804 /* Suppress schema name if fetching from pre-7.3 DB */
7805 if (g_fout->remoteVersion >= 70300 && schema && *schema)
7807 appendPQExpBuffer(id_return, "%s.",
7810 appendPQExpBuffer(id_return, "%s",
7813 return id_return->data;
7817 * Return a column list clause for the given relation.
7819 * Special case: if there are no undropped columns in the relation, return
7820 * "", not an invalid "()" column list.
7823 fmtCopyColumnList(const TableInfo *ti)
7825 static PQExpBuffer q = NULL;
7826 int numatts = ti->numatts;
7827 char **attnames = ti->attnames;
7828 bool *attisdropped = ti->attisdropped;
7832 if (q) /* first time through? */
7833 resetPQExpBuffer(q);
7835 q = createPQExpBuffer();
7837 appendPQExpBuffer(q, "(");
7839 for (i = 0; i < numatts; i++)
7841 if (attisdropped[i])
7844 appendPQExpBuffer(q, ", ");
7845 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
7850 return ""; /* no undropped columns */
7852 appendPQExpBuffer(q, ")");
7857 * Convenience subroutine to execute a SQL command and check for
7858 * COMMAND_OK status.
7861 do_sql_command(PGconn *conn, const char *query)
7865 res = PQexec(conn, query);
7866 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
7871 * Convenience subroutine to verify a SQL command succeeded,
7872 * and exit with a useful error message if not.
7875 check_sql_result(PGresult *res, PGconn *conn, const char *query,
7876 ExecStatusType expected)
7880 if (res && PQresultStatus(res) == expected)
7883 write_msg(NULL, "SQL command failed\n");
7885 err = PQresultErrorMessage(res);
7887 err = PQerrorMessage(conn);
7888 write_msg(NULL, "Error message from server: %s", err);
7889 write_msg(NULL, "The command was: %s\n", query);