1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2004, 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.386 2004/08/29 05:06:53 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 ...
41 #include "getopt_long.h"
47 #include "access/attnum.h"
48 #include "access/htup.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_proc.h"
51 #include "catalog/pg_trigger.h"
52 #include "catalog/pg_type.h"
54 #include "commands/sequence.h"
57 #include "libpq/libpq-fs.h"
60 #include "pg_backup.h"
61 #include "pg_backup_archiver.h"
62 #include "dumputils.h"
64 #define _(x) gettext((x))
73 const char *descr; /* comment for an object */
74 Oid classoid; /* object class (catalog OID) */
75 Oid objoid; /* object OID */
76 int objsubid; /* subobject (table column #) */
81 bool g_verbose; /* User wants verbose narration of our
83 Archive *g_fout; /* the script file */
84 PGconn *g_conn; /* the database connection */
86 /* various user-settable parameters */
87 bool dumpInserts; /* dump data using proper insert strings */
88 bool attrNames; /* put attr names into insert strings */
93 /* obsolete as of 7.3: */
94 static Oid g_last_builtin_oid; /* value of the last builtin oid */
96 static char *selectTableName = NULL; /* name of a single table to dump */
97 static char *selectSchemaName = NULL; /* name of a single schema to dump */
99 char g_opaque_type[10]; /* name for the opaque type */
101 /* placeholders for the delimiters for comments */
102 char g_comment_start[10];
103 char g_comment_end[10];
105 static const CatalogId nilCatalogId = {0, 0};
107 /* these are to avoid passing around info for findNamespace() */
108 static NamespaceInfo *g_namespaces;
109 static int g_numNamespaces;
111 /* flag to turn on/off dollar quoting */
112 static int disable_dollar_quoting = 0;
115 static void help(const char *progname);
116 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
117 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
118 static void dumpComment(Archive *fout, const char *target,
119 const char *namespace, const char *owner,
120 CatalogId catalogId, int subid, DumpId dumpId);
121 static int findComments(Archive *fout, Oid classoid, Oid objoid,
122 CommentItem **items);
123 static int collectComments(Archive *fout, CommentItem **items);
124 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
125 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
126 static void dumpType(Archive *fout, TypeInfo *tinfo);
127 static void dumpBaseType(Archive *fout, TypeInfo *tinfo);
128 static void dumpDomain(Archive *fout, TypeInfo *tinfo);
129 static void dumpCompositeType(Archive *fout, TypeInfo *tinfo);
130 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
131 static void dumpFunc(Archive *fout, FuncInfo *finfo);
132 static void dumpCast(Archive *fout, CastInfo *cast);
133 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
134 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
135 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
136 static void dumpRule(Archive *fout, RuleInfo *rinfo);
137 static void dumpAgg(Archive *fout, AggInfo *agginfo);
138 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
139 static void dumpTable(Archive *fout, TableInfo *tbinfo);
140 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
141 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
142 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
143 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
144 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
146 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
147 const char *type, const char *name,
148 const char *tag, const char *nspname, const char *owner,
151 static void getDependencies(void);
152 static void getDomainConstraints(TypeInfo *tinfo);
153 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
154 static char *format_function_signature(FuncInfo *finfo, char **argnames,
156 static const char *convertRegProcReference(const char *proc);
157 static const char *convertOperatorReference(const char *opr);
158 static Oid findLastBuiltinOid_V71(const char *);
159 static Oid findLastBuiltinOid_V70(void);
160 static void setMaxOid(Archive *fout);
161 static void selectSourceSchema(const char *schemaName);
162 static char *getFormattedTypeName(Oid oid, OidOptions opts);
163 static char *myFormatType(const char *typname, int32 typmod);
164 static const char *fmtQualifiedId(const char *schema, const char *id);
165 static int dumpBlobs(Archive *AH, void *arg);
166 static void dumpDatabase(Archive *AH);
167 static void dumpTimestamp(Archive *AH, char *msg);
168 static void dumpEncoding(Archive *AH);
169 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
170 static const char *fmtCopyColumnList(const TableInfo *ti);
171 static void do_sql_command(PGconn *conn, const char *query);
172 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
173 ExecStatusType expected);
177 main(int argc, char **argv)
180 const char *filename = NULL;
181 const char *format = "p";
182 const char *dbname = NULL;
183 const char *pghost = NULL;
184 const char *pgport = NULL;
185 const char *username = NULL;
189 DumpableObject **dobjs;
192 bool force_password = false;
193 int compressLevel = -1;
194 bool ignore_version = false;
197 int outputCreate = 0;
199 int outputNoOwner = 0;
200 static int use_setsessauth = 0;
201 static int disable_triggers = 0;
202 char *outputSuperuser = NULL;
204 RestoreOptions *ropt;
206 static struct option long_options[] = {
207 {"data-only", no_argument, NULL, 'a'},
208 {"blobs", no_argument, NULL, 'b'},
209 {"clean", no_argument, NULL, 'c'},
210 {"create", no_argument, NULL, 'C'},
211 {"file", required_argument, NULL, 'f'},
212 {"format", required_argument, NULL, 'F'},
213 {"inserts", no_argument, NULL, 'd'},
214 {"attribute-inserts", no_argument, NULL, 'D'},
215 {"column-inserts", no_argument, NULL, 'D'},
216 {"host", required_argument, NULL, 'h'},
217 {"ignore-version", no_argument, NULL, 'i'},
218 {"no-reconnect", no_argument, NULL, 'R'},
219 {"oids", no_argument, NULL, 'o'},
220 {"no-owner", no_argument, NULL, 'O'},
221 {"port", required_argument, NULL, 'p'},
222 {"schema", required_argument, NULL, 'n'},
223 {"schema-only", no_argument, NULL, 's'},
224 {"superuser", required_argument, NULL, 'S'},
225 {"table", required_argument, NULL, 't'},
226 {"password", no_argument, NULL, 'W'},
227 {"username", required_argument, NULL, 'U'},
228 {"verbose", no_argument, NULL, 'v'},
229 {"no-privileges", no_argument, NULL, 'x'},
230 {"no-acl", no_argument, NULL, 'x'},
231 {"compress", required_argument, NULL, 'Z'},
232 {"help", no_argument, NULL, '?'},
233 {"version", no_argument, NULL, 'V'},
236 * the following options don't have an equivalent short option
237 * letter, but are available as '-X long-name'
239 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
240 {"disable-triggers", no_argument, &disable_triggers, 1},
241 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
247 set_pglocale_pgservice(argv[0], "pg_dump");
251 strcpy(g_comment_start, "-- ");
252 g_comment_end[0] = '\0';
253 strcpy(g_opaque_type, "opaque");
255 dataOnly = schemaOnly = dumpInserts = attrNames = false;
257 progname = get_progname(argv[0]);
259 /* Set default options based on progname */
260 if (strcmp(progname, "pg_backup") == 0)
268 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
273 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
275 puts("pg_dump (PostgreSQL) " PG_VERSION);
280 while ((c = getopt_long(argc, argv, "abcCdDf:F:h:in:oOp:RsS:t:uU:vWxX:Z:",
281 long_options, &optindex)) != -1)
285 case 'a': /* Dump data only */
289 case 'b': /* Dump blobs */
293 case 'c': /* clean (i.e., drop) schema prior to
298 case 'C': /* Create DB */
302 case 'd': /* dump data as proper insert strings */
306 case 'D': /* dump data as proper insert strings with
320 case 'h': /* server host */
324 case 'i': /* ignore database version mismatch */
325 ignore_version = true;
328 case 'n': /* Dump data for this schema only */
329 selectSchemaName = strdup(optarg);
332 case 'o': /* Dump oids */
336 case 'O': /* Don't reconnect to match owner */
340 case 'p': /* server port */
345 /* no-op, still accepted for backwards compatibility */
348 case 's': /* dump schema only */
352 case 'S': /* Username for superuser in plain text
354 outputSuperuser = strdup(optarg);
357 case 't': /* Dump data for this table only */
358 selectTableName = strdup(optarg);
362 force_password = true;
363 username = simple_prompt("User name: ", 100, true);
370 case 'v': /* verbose */
375 force_password = true;
378 case 'x': /* skip ACL dump */
383 * Option letters were getting scarce, so I invented this
384 * new scheme: '-X feature' turns on some feature. Compare
385 * to the -f option in GCC. You should also add an
386 * equivalent GNU-style option --feature. Features that
387 * require arguments should use '-X feature=foo'.
390 if (strcmp(optarg, "disable-dollar-quoting") == 0)
391 disable_dollar_quoting = 1;
392 else if (strcmp(optarg, "disable-triggers") == 0)
393 disable_triggers = 1;
394 else if (strcmp(optarg, "use-set-session-authorization") == 0)
399 _("%s: invalid -X option -- %s\n"),
401 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
406 case 'Z': /* Compression Level */
407 compressLevel = atoi(optarg);
409 /* This covers the long options equivalent to -X xxx. */
415 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
420 if (optind < (argc - 1))
422 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
423 progname, argv[optind + 1]);
424 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
429 /* Get database name from command line */
431 dbname = argv[optind];
433 if (dataOnly && schemaOnly)
435 write_msg(NULL, "options \"schema only\" (-s) and \"data only\" (-a) cannot be used together\n");
439 if (dataOnly && outputClean)
441 write_msg(NULL, "options \"clean\" (-c) and \"data only\" (-a) cannot be used together\n");
445 if (outputBlobs && selectTableName != NULL)
447 write_msg(NULL, "large-object output not supported for a single table\n");
448 write_msg(NULL, "use a full dump instead\n");
452 if (outputBlobs && selectSchemaName != NULL)
454 write_msg(NULL, "large-object output not supported for a single schema\n");
455 write_msg(NULL, "use a full dump instead\n");
459 if (dumpInserts == true && oids == true)
461 write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together\n");
462 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
466 if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
468 write_msg(NULL, "large-object output is not supported for plain-text dump files\n");
469 write_msg(NULL, "(Use a different output format.)\n");
473 /* open the output file */
478 g_fout = CreateArchive(filename, archCustom, compressLevel);
483 g_fout = CreateArchive(filename, archFiles, compressLevel);
489 g_fout = CreateArchive(filename, archNull, 0);
494 g_fout = CreateArchive(filename, archTar, compressLevel);
498 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
504 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
508 /* Let the archiver know how noisy to be */
509 g_fout->verbose = g_verbose;
511 g_fout->minRemoteVersion = 70000; /* we can handle back to 7.0 */
512 g_fout->maxRemoteVersion = parse_version(PG_VERSION);
513 if (g_fout->maxRemoteVersion < 0)
515 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
520 * Open the database using the Archiver, so it knows about it. Errors
523 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
524 username, force_password, ignore_version);
527 * Start serializable transaction to dump consistent data.
529 do_sql_command(g_conn, "BEGIN");
531 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
533 /* Set the datestyle to ISO to ensure the dump's portability */
534 do_sql_command(g_conn, "SET DATESTYLE = ISO");
537 * If supported, set extra_float_digits so that we can dump float data
538 * exactly (given correctly implemented float I/O code, anyway)
540 if (g_fout->remoteVersion >= 70400)
541 do_sql_command(g_conn, "SET extra_float_digits TO 2");
543 /* Find the last built-in OID, if needed */
544 if (g_fout->remoteVersion < 70300)
546 if (g_fout->remoteVersion >= 70100)
547 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
549 g_last_builtin_oid = findLastBuiltinOid_V70();
551 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
555 * Now scan the database and create DumpableObject structs for all the
556 * objects we intend to dump.
558 tblinfo = getSchemaData(&numTables, schemaOnly, dataOnly);
561 getTableData(tblinfo, numTables, oids);
565 /* This is just a placeholder to allow correct sorting of blobs */
566 DumpableObject *blobobj;
568 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
569 blobobj->objType = DO_BLOBS;
570 blobobj->catId = nilCatalogId;
571 AssignDumpId(blobobj);
572 blobobj->name = strdup("BLOBS");
576 * Collect dependency data to assist in ordering the objects.
581 * Sort the objects into a safe dump order (no forward references).
583 * In 7.3 or later, we can rely on dependency information to help us
584 * determine a safe order, so the initial sort is mostly for cosmetic
585 * purposes: we sort by name to ensure that logically identical
586 * schemas will dump identically. Before 7.3 we don't have
587 * dependencies and we use OID ordering as an (unreliable) guide to
590 getDumpableObjects(&dobjs, &numObjs);
592 if (g_fout->remoteVersion >= 70300)
593 sortDumpableObjectsByTypeName(dobjs, numObjs);
595 sortDumpableObjectsByTypeOid(dobjs, numObjs);
597 sortDumpableObjects(dobjs, numObjs);
600 * Create archive TOC entries for all the objects to be dumped, in a
605 dumpTimestamp(g_fout, "Started on");
607 /* First the special encoding entry. */
608 dumpEncoding(g_fout);
610 /* The database item is always second. */
612 dumpDatabase(g_fout);
614 /* Max OID is next. */
618 /* Now the rearrangeable objects. */
619 for (i = 0; i < numObjs; i++)
620 dumpDumpableObject(g_fout, dobjs[i]);
623 dumpTimestamp(g_fout, "Completed on");
626 * And finally we can do the actual output.
630 ropt = NewRestoreOptions();
631 ropt->filename = (char *) filename;
632 ropt->dropSchema = outputClean;
633 ropt->aclsSkip = aclsSkip;
634 ropt->superuser = outputSuperuser;
635 ropt->create = outputCreate;
636 ropt->noOwner = outputNoOwner;
637 ropt->disable_triggers = disable_triggers;
638 ropt->use_setsessauth = use_setsessauth;
640 if (compressLevel == -1)
641 ropt->compression = 0;
643 ropt->compression = compressLevel;
645 ropt->suppressDumpWarnings = true; /* We've already shown
648 RestoreArchive(g_fout, ropt);
651 CloseArchive(g_fout);
660 help(const char *progname)
662 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
663 printf(_("Usage:\n"));
664 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
666 printf(_("\nGeneral options:\n"));
667 printf(_(" -f, --file=FILENAME output file name\n"));
668 printf(_(" -F, --format=c|t|p output file format (custom, tar, plain text)\n"));
669 printf(_(" -i, --ignore-version proceed even when server version mismatches\n"
670 " pg_dump version\n"));
671 printf(_(" -v, --verbose verbose mode\n"));
672 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
673 printf(_(" --help show this help, then exit\n"));
674 printf(_(" --version output version information, then exit\n"));
676 printf(_("\nOptions controlling the output content:\n"));
677 printf(_(" -a, --data-only dump only the data, not the schema\n"));
678 printf(_(" -b, --blobs include large objects in dump\n"));
679 printf(_(" -c, --clean clean (drop) schema prior to create\n"));
680 printf(_(" -C, --create include commands to create database in dump\n"));
681 printf(_(" -d, --inserts dump data as INSERT, rather than COPY, commands\n"));
682 printf(_(" -D, --column-inserts dump data as INSERT commands with column names\n"));
683 printf(_(" -n, --schema=SCHEMA dump the named schema only\n"));
684 printf(_(" -o, --oids include OIDs in dump\n"));
685 printf(_(" -O, --no-owner do not output commands to set object ownership\n"
686 " in plain text format\n"));
687 printf(_(" -s, --schema-only dump only the schema, no data\n"));
688 printf(_(" -S, --superuser=NAME specify the superuser user name to use in\n"
689 " plain text format\n"));
690 printf(_(" -t, --table=TABLE dump the named table only\n"));
691 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
692 printf(_(" -X disable-dollar-quoting, --disable-dollar-quoting\n"
693 " disable dollar quoting, use SQL standard quoting\n"));
694 printf(_(" -X disable-triggers, --disable-triggers\n"
695 " disable triggers during data-only restore\n"));
696 printf(_(" -X use-set-session-authorization, --use-set-session-authorization\n"
697 " use SESSION AUTHORIZATION commands instead of\n"
698 " OWNER TO commands\n"));
700 printf(_("\nConnection options:\n"));
701 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
702 printf(_(" -p, --port=PORT database server port number\n"));
703 printf(_(" -U, --username=NAME connect as specified database user\n"));
704 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
706 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
707 "variable value is used.\n\n"));
708 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
716 write_msg(NULL, "*** aborted because of error\n");
721 * selectDumpableNamespace: policy-setting subroutine
722 * Mark a namespace as to be dumped or not
725 selectDumpableNamespace(NamespaceInfo *nsinfo)
728 * If a specific table is being dumped, do not dump any complete
729 * namespaces. If a specific namespace is being dumped, dump just
730 * that namespace. Otherwise, dump all non-system namespaces.
732 if (selectTableName != NULL)
733 nsinfo->dump = false;
734 else if (selectSchemaName != NULL)
736 if (strcmp(nsinfo->dobj.name, selectSchemaName) == 0)
739 nsinfo->dump = false;
741 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
742 strcmp(nsinfo->dobj.name, "information_schema") == 0)
743 nsinfo->dump = false;
749 * selectDumpableTable: policy-setting subroutine
750 * Mark a table as to be dumped or not
753 selectDumpableTable(TableInfo *tbinfo)
756 * Always dump if dumping parent namespace; else, if a particular
757 * tablename has been specified, dump matching table name; else, do
760 tbinfo->dump = false;
761 if (tbinfo->dobj.namespace->dump)
763 else if (selectTableName != NULL &&
764 strcmp(tbinfo->dobj.name, selectTableName) == 0)
766 /* If both -s and -t specified, must match both to dump */
767 if (selectSchemaName == NULL)
769 else if (strcmp(tbinfo->dobj.namespace->dobj.name, selectSchemaName) == 0)
775 * Dump a table's contents for loading using the COPY command
776 * - this routine is called by the Archiver when it wants the table
780 #define COPYBUFSIZ 8192
783 dumpTableData_copy(Archive *fout, void *dcontext)
785 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
786 TableInfo *tbinfo = tdinfo->tdtable;
787 const char *classname = tbinfo->dobj.name;
788 const bool hasoids = tbinfo->hasoids;
789 const bool oids = tdinfo->oids;
790 PQExpBuffer q = createPQExpBuffer();
794 char copybuf[COPYBUFSIZ];
795 const char *column_list;
798 write_msg(NULL, "dumping contents of table %s\n", classname);
801 * Make sure we are in proper schema. We will qualify the table name
802 * below anyway (in case its name conflicts with a pg_catalog table);
803 * but this ensures reproducible results in case the table contains
804 * regproc, regclass, etc columns.
806 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
809 * If possible, specify the column list explicitly so that we have no
810 * possibility of retrieving data in the wrong column order. (The
811 * default column ordering of COPY will not be what we want in certain
812 * corner cases involving ADD COLUMN and inheritance.)
814 if (g_fout->remoteVersion >= 70300)
815 column_list = fmtCopyColumnList(tbinfo);
817 column_list = ""; /* can't select columns in COPY */
821 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
822 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
828 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
829 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
833 res = PQexec(g_conn, q->data);
834 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
840 ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
842 if (copybuf[0] == '\\' &&
846 copydone = true; /* don't print this... */
850 archputs(copybuf, fout);
857 archputs("\n", fout);
867 * There was considerable discussion in late July, 2000 regarding
868 * slowing down pg_dump when backing up large tables. Users with
869 * both slow & fast (muti-processor) machines experienced
870 * performance degradation when doing a backup.
872 * Initial attempts based on sleeping for a number of ms for each ms
873 * of work were deemed too complex, then a simple 'sleep in each
874 * loop' implementation was suggested. The latter failed because
875 * the loop was too tight. Finally, the following was implemented:
877 * If throttle is non-zero, then See how long since the last sleep.
878 * Work out how long to sleep (based on ratio). If sleep is more
879 * than 100ms, then sleep reset timer EndIf EndIf
881 * where the throttle value was the number of ms to sleep per ms of
882 * work. The calculation was done in each loop.
884 * Most of the hard work is done in the backend, and this solution
885 * still did not work particularly well: on slow machines, the
886 * ratio was 50:1, and on medium paced machines, 1:1, and on fast
887 * multi-processor machines, it had little or no effect, for
888 * reasons that were unclear.
890 * Further discussion ensued, and the proposal was dropped.
892 * For those people who want this feature, it can be implemented
893 * using gettimeofday in each loop, calculating the time since
894 * last sleep, multiplying that by the sleep ratio, then if the
895 * result is more than a preset 'minimum sleep time' (say 100ms),
896 * call the 'select' function to sleep for a subsecond period ie.
898 * select(0, NULL, NULL, NULL, &tvi);
900 * This will return after the interval specified in the structure
901 * tvi. Finally, call gettimeofday again to save the 'last sleep
905 archprintf(fout, "\\.\n\n\n");
907 ret = PQendcopy(g_conn);
910 write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
911 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
912 write_msg(NULL, "The command was: %s\n", q->data);
917 destroyPQExpBuffer(q);
922 dumpTableData_insert(Archive *fout, void *dcontext)
924 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
925 TableInfo *tbinfo = tdinfo->tdtable;
926 const char *classname = tbinfo->dobj.name;
927 PQExpBuffer q = createPQExpBuffer();
934 * Make sure we are in proper schema. We will qualify the table name
935 * below anyway (in case its name conflicts with a pg_catalog table);
936 * but this ensures reproducible results in case the table contains
937 * regproc, regclass, etc columns.
939 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
941 if (fout->remoteVersion >= 70100)
943 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
944 "SELECT * FROM ONLY %s",
945 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
950 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
952 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
956 res = PQexec(g_conn, q->data);
957 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
963 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
964 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
966 nfields = PQnfields(res);
967 for (tuple = 0; tuple < PQntuples(res); tuple++)
969 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
972 /* corner case for zero-column table */
973 archprintf(fout, "DEFAULT VALUES;\n");
976 if (attrNames == true)
979 appendPQExpBuffer(q, "(");
980 for (field = 0; field < nfields; field++)
983 appendPQExpBuffer(q, ", ");
984 appendPQExpBuffer(q, fmtId(PQfname(res, field)));
986 appendPQExpBuffer(q, ") ");
987 archprintf(fout, "%s", q->data);
989 archprintf(fout, "VALUES (");
990 for (field = 0; field < nfields; field++)
993 archprintf(fout, ", ");
994 if (PQgetisnull(res, tuple, field))
996 archprintf(fout, "NULL");
1000 /* XXX This code is partially duplicated in ruleutils.c */
1001 switch (PQftype(res, field))
1012 * These types are printed without quotes
1013 * unless they contain values that aren't
1014 * accepted by the scanner unquoted (e.g.,
1015 * 'NaN'). Note that strtod() and friends
1016 * might accept NaN, so we can't use that to
1019 * In reality we only need to defend against
1020 * infinity and NaN, so we need not get too
1021 * crazy about pattern matching here.
1023 const char *s = PQgetvalue(res, tuple, field);
1025 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1026 archprintf(fout, "%s", s);
1028 archprintf(fout, "'%s'", s);
1034 archprintf(fout, "B'%s'",
1035 PQgetvalue(res, tuple, field));
1039 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1040 archprintf(fout, "true");
1042 archprintf(fout, "false");
1046 /* All other types are printed as string literals. */
1047 resetPQExpBuffer(q);
1048 appendStringLiteral(q, PQgetvalue(res, tuple, field), false);
1049 archprintf(fout, "%s", q->data);
1053 archprintf(fout, ");\n");
1055 } while (PQntuples(res) > 0);
1059 archprintf(fout, "\n\n");
1061 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1063 destroyPQExpBuffer(q);
1070 * dump the contents of a single table
1072 * Actually, this just makes an ArchiveEntry for the table contents.
1075 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1077 TableInfo *tbinfo = tdinfo->tdtable;
1078 PQExpBuffer copyBuf = createPQExpBuffer();
1079 DataDumperPtr dumpFn;
1084 /* Dump/restore using COPY */
1085 dumpFn = dumpTableData_copy;
1086 /* must use 2 steps here 'cause fmtId is nonreentrant */
1087 appendPQExpBuffer(copyBuf, "COPY %s ",
1088 fmtId(tbinfo->dobj.name));
1089 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1090 fmtCopyColumnList(tbinfo),
1091 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1092 copyStmt = copyBuf->data;
1096 /* Restore using INSERT */
1097 dumpFn = dumpTableData_insert;
1101 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1103 tbinfo->dobj.namespace->dobj.name,
1104 tbinfo->usename, false,
1105 "TABLE DATA", "", "", copyStmt,
1106 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1109 destroyPQExpBuffer(copyBuf);
1114 * set up dumpable objects representing the contents of tables
1117 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1121 for (i = 0; i < numTables; i++)
1123 /* Skip VIEWs (no data to dump) */
1124 if (tblinfo[i].relkind == RELKIND_VIEW)
1126 /* Skip SEQUENCEs (handled elsewhere) */
1127 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1130 if (tblinfo[i].dump)
1132 TableDataInfo *tdinfo;
1134 tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1136 tdinfo->dobj.objType = DO_TABLE_DATA;
1139 * Note: use tableoid 0 so that this object won't be mistaken
1140 * for something that pg_depend entries apply to.
1142 tdinfo->dobj.catId.tableoid = 0;
1143 tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1144 AssignDumpId(&tdinfo->dobj);
1145 tdinfo->dobj.name = tblinfo[i].dobj.name;
1146 tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1147 tdinfo->tdtable = &(tblinfo[i]);
1148 tdinfo->oids = oids;
1149 addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1157 * dump the database definition
1160 dumpDatabase(Archive *AH)
1162 PQExpBuffer dbQry = createPQExpBuffer();
1163 PQExpBuffer delQry = createPQExpBuffer();
1164 PQExpBuffer creaQry = createPQExpBuffer();
1174 const char *datname,
1179 datname = PQdb(g_conn);
1182 write_msg(NULL, "saving database definition\n");
1184 /* Make sure we are in proper schema */
1185 selectSourceSchema("pg_catalog");
1187 /* Get the database owner and parameters from pg_database */
1188 if (g_fout->remoteVersion >= 80000)
1190 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1191 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1192 "pg_encoding_to_char(encoding) as encoding, "
1193 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) as tablespace "
1195 "WHERE datname = ");
1196 appendStringLiteral(dbQry, datname, true);
1198 else if (g_fout->remoteVersion >= 70100)
1200 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1201 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1202 "pg_encoding_to_char(encoding) as encoding, "
1203 "NULL as tablespace "
1205 "WHERE datname = ");
1206 appendStringLiteral(dbQry, datname, true);
1210 appendPQExpBuffer(dbQry, "SELECT "
1211 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1213 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1214 "pg_encoding_to_char(encoding) as encoding, "
1215 "NULL as tablespace "
1217 "WHERE datname = ");
1218 appendStringLiteral(dbQry, datname, true);
1221 res = PQexec(g_conn, dbQry->data);
1222 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1224 ntups = PQntuples(res);
1228 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1235 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1240 i_tableoid = PQfnumber(res, "tableoid");
1241 i_oid = PQfnumber(res, "oid");
1242 i_dba = PQfnumber(res, "dba");
1243 i_encoding = PQfnumber(res, "encoding");
1244 i_tablespace = PQfnumber(res, "tablespace");
1246 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1247 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1248 dba = PQgetvalue(res, 0, i_dba);
1249 encoding = PQgetvalue(res, 0, i_encoding);
1250 tablespace = PQgetvalue(res, 0, i_tablespace);
1252 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1254 if (strlen(encoding) > 0)
1256 appendPQExpBuffer(creaQry, " ENCODING = ");
1257 appendStringLiteral(creaQry, encoding, true);
1259 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1260 appendPQExpBuffer(creaQry, " TABLESPACE = %s", fmtId(tablespace));
1261 appendPQExpBuffer(creaQry, ";\n");
1263 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1266 dbDumpId = createDumpId();
1269 dbCatId, /* catalog ID */
1270 dbDumpId, /* dump ID */
1272 NULL, /* Namespace */
1274 false, /* with oids */
1275 "DATABASE", /* Desc */
1276 creaQry->data, /* Create */
1277 delQry->data, /* Del */
1282 NULL); /* Dumper Arg */
1284 /* Dump DB comment if any */
1285 resetPQExpBuffer(dbQry);
1286 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1287 dumpComment(AH, dbQry->data, NULL, "",
1288 dbCatId, 0, dbDumpId);
1292 destroyPQExpBuffer(dbQry);
1293 destroyPQExpBuffer(delQry);
1294 destroyPQExpBuffer(creaQry);
1302 dumpTimestamp(Archive *AH, char *msg)
1305 time_t now = time(NULL);
1307 if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&now)) != 0)
1309 PQExpBuffer qry = createPQExpBuffer();
1311 appendPQExpBuffer(qry, "-- ");
1312 appendPQExpBuffer(qry, msg);
1313 appendPQExpBuffer(qry, " ");
1314 appendPQExpBuffer(qry, buf);
1315 appendPQExpBuffer(qry, "\n");
1317 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1318 "DUMP TIMESTAMP", NULL, "",
1319 false, "DUMP TIMESTAMP", qry->data, "", NULL,
1322 destroyPQExpBuffer(qry);
1328 * dumpEncoding: put the correct encoding into the archive
1331 dumpEncoding(Archive *AH)
1336 /* Can't read the encoding from pre-7.3 servers (SHOW isn't a query) */
1337 if (AH->remoteVersion < 70300)
1341 write_msg(NULL, "saving encoding\n");
1343 qry = createPQExpBuffer();
1345 appendPQExpBuffer(qry, "SHOW client_encoding");
1347 res = PQexec(g_conn, qry->data);
1349 check_sql_result(res, g_conn, qry->data, PGRES_TUPLES_OK);
1351 resetPQExpBuffer(qry);
1353 appendPQExpBuffer(qry, "SET client_encoding = ");
1354 appendStringLiteral(qry, PQgetvalue(res, 0, 0), true);
1355 appendPQExpBuffer(qry, ";\n");
1357 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1358 "ENCODING", NULL, "",
1359 false, "ENCODING", qry->data, "", NULL,
1365 destroyPQExpBuffer(qry);
1375 #define loBufSize 16384
1376 #define loFetchSize 1000
1379 dumpBlobs(Archive *AH, void *arg)
1381 PQExpBuffer oidQry = createPQExpBuffer();
1382 PQExpBuffer oidFetchQry = createPQExpBuffer();
1386 char buf[loBufSize];
1391 write_msg(NULL, "saving large objects\n");
1393 /* Make sure we are in proper schema */
1394 selectSourceSchema("pg_catalog");
1396 /* Cursor to get all BLOB tables */
1397 if (AH->remoteVersion >= 70100)
1398 appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject");
1400 appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT oid from pg_class where relkind = 'l'");
1402 res = PQexec(g_conn, oidQry->data);
1403 check_sql_result(res, g_conn, oidQry->data, PGRES_COMMAND_OK);
1405 /* Fetch for cursor */
1406 appendPQExpBuffer(oidFetchQry, "Fetch %d in blobOid", loFetchSize);
1413 res = PQexec(g_conn, oidFetchQry->data);
1414 check_sql_result(res, g_conn, oidFetchQry->data, PGRES_TUPLES_OK);
1416 /* Process the tuples, if any */
1417 for (i = 0; i < PQntuples(res); i++)
1419 blobOid = atooid(PQgetvalue(res, i, 0));
1421 loFd = lo_open(g_conn, blobOid, INV_READ);
1424 write_msg(NULL, "dumpBlobs(): could not open large object: %s",
1425 PQerrorMessage(g_conn));
1429 StartBlob(AH, blobOid);
1431 /* Now read it in chunks, sending data to archive */
1434 cnt = lo_read(g_conn, loFd, buf, loBufSize);
1437 write_msg(NULL, "dumpBlobs(): error reading large object: %s",
1438 PQerrorMessage(g_conn));
1442 WriteData(AH, buf, cnt);
1446 lo_close(g_conn, loFd);
1448 EndBlob(AH, blobOid);
1451 } while (PQntuples(res) > 0);
1453 destroyPQExpBuffer(oidQry);
1454 destroyPQExpBuffer(oidFetchQry);
1461 * read all namespaces in the system catalogs and return them in the
1462 * NamespaceInfo* structure
1464 * numNamespaces is set to the number of namespaces read in
1467 getNamespaces(int *numNamespaces)
1473 NamespaceInfo *nsinfo;
1478 int i_nsptablespace;
1482 * Before 7.3, there are no real namespaces; create two dummy entries,
1483 * one for user stuff and one for system stuff.
1485 if (g_fout->remoteVersion < 70300)
1487 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
1489 nsinfo[0].dobj.objType = DO_NAMESPACE;
1490 nsinfo[0].dobj.catId.tableoid = 0;
1491 nsinfo[0].dobj.catId.oid = 0;
1492 AssignDumpId(&nsinfo[0].dobj);
1493 nsinfo[0].dobj.name = strdup("public");
1494 nsinfo[0].usename = strdup("");
1495 nsinfo[0].nspacl = strdup("");
1496 nsinfo[0].nsptablespace = strdup("");
1498 selectDumpableNamespace(&nsinfo[0]);
1500 nsinfo[1].dobj.objType = DO_NAMESPACE;
1501 nsinfo[1].dobj.catId.tableoid = 0;
1502 nsinfo[1].dobj.catId.oid = 1;
1503 AssignDumpId(&nsinfo[1].dobj);
1504 nsinfo[1].dobj.name = strdup("pg_catalog");
1505 nsinfo[1].usename = strdup("");
1506 nsinfo[1].nspacl = strdup("");
1507 nsinfo[0].nsptablespace = strdup("");
1509 selectDumpableNamespace(&nsinfo[1]);
1511 g_namespaces = nsinfo;
1512 g_numNamespaces = *numNamespaces = 2;
1517 query = createPQExpBuffer();
1519 /* Make sure we are in proper schema */
1520 selectSourceSchema("pg_catalog");
1523 * we fetch all namespaces including system ones, so that every object
1524 * we read in can be linked to a containing namespace.
1526 if (g_fout->remoteVersion >= 80000)
1528 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1529 "(select usename from pg_user where nspowner = usesysid) as usename, "
1531 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = nsptablespace) AS nsptablespace "
1532 "FROM pg_namespace");
1536 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1537 "(select usename from pg_user where nspowner = usesysid) as usename, "
1538 "nspacl, NULL AS nsptablespace "
1539 "FROM pg_namespace");
1542 res = PQexec(g_conn, query->data);
1543 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1545 ntups = PQntuples(res);
1547 nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1549 i_tableoid = PQfnumber(res, "tableoid");
1550 i_oid = PQfnumber(res, "oid");
1551 i_nspname = PQfnumber(res, "nspname");
1552 i_usename = PQfnumber(res, "usename");
1553 i_nspacl = PQfnumber(res, "nspacl");
1554 i_nsptablespace = PQfnumber(res, "nsptablespace");
1556 for (i = 0; i < ntups; i++)
1558 nsinfo[i].dobj.objType = DO_NAMESPACE;
1559 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1560 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1561 AssignDumpId(&nsinfo[i].dobj);
1562 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
1563 nsinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1564 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1565 nsinfo[i].nsptablespace = strdup(PQgetvalue(res, i, i_nsptablespace));
1567 /* Decide whether to dump this namespace */
1568 selectDumpableNamespace(&nsinfo[i]);
1570 if (strlen(nsinfo[i].usename) == 0)
1571 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
1572 nsinfo[i].dobj.name);
1576 * If the user attempted to dump a specific namespace, check to ensure
1577 * that the specified namespace actually exists.
1579 if (selectSchemaName)
1581 for (i = 0; i < ntups; i++)
1582 if (strcmp(nsinfo[i].dobj.name, selectSchemaName) == 0)
1585 /* Didn't find a match */
1588 write_msg(NULL, "specified schema \"%s\" does not exist\n",
1595 destroyPQExpBuffer(query);
1597 g_namespaces = nsinfo;
1598 g_numNamespaces = *numNamespaces = ntups;
1605 * given a namespace OID and an object OID, look up the info read by
1608 * NB: for pre-7.3 source database, we use object OID to guess whether it's
1609 * a system object or not. In 7.3 and later there is no guessing.
1611 static NamespaceInfo *
1612 findNamespace(Oid nsoid, Oid objoid)
1616 if (g_fout->remoteVersion >= 70300)
1618 for (i = 0; i < g_numNamespaces; i++)
1620 NamespaceInfo *nsinfo = &g_namespaces[i];
1622 if (nsoid == nsinfo->dobj.catId.oid)
1625 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
1630 /* This code depends on the layout set up by getNamespaces. */
1631 if (objoid > g_last_builtin_oid)
1632 i = 0; /* user object */
1634 i = 1; /* system object */
1635 return &g_namespaces[i];
1638 return NULL; /* keep compiler quiet */
1643 * read all types in the system catalogs and return them in the
1644 * TypeInfo* structure
1646 * numTypes is set to the number of types read in
1648 * NB: this must run after getFuncs() because we assume we can do
1652 getTypes(int *numTypes)
1657 PQExpBuffer query = createPQExpBuffer();
1673 * we include even the built-in types because those may be used as
1674 * array elements by user-defined types
1676 * we filter out the built-in types when we dump out the types
1678 * same approach for undefined (shell) types
1681 /* Make sure we are in proper schema */
1682 selectSourceSchema("pg_catalog");
1684 if (g_fout->remoteVersion >= 70300)
1686 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1688 "(select usename from pg_user where typowner = usesysid) as usename, "
1689 "typinput::oid as typinput, "
1690 "typoutput::oid as typoutput, typelem, typrelid, "
1691 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1692 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1693 "typtype, typisdefined "
1696 else if (g_fout->remoteVersion >= 70100)
1698 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1699 "0::oid as typnamespace, "
1700 "(select usename from pg_user where typowner = usesysid) as usename, "
1701 "typinput::oid as typinput, "
1702 "typoutput::oid as typoutput, typelem, typrelid, "
1703 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1704 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1705 "typtype, typisdefined "
1710 appendPQExpBuffer(query, "SELECT "
1711 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
1713 "0::oid as typnamespace, "
1714 "(select usename from pg_user where typowner = usesysid) as usename, "
1715 "typinput::oid as typinput, "
1716 "typoutput::oid as typoutput, typelem, typrelid, "
1717 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1718 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1719 "typtype, typisdefined "
1723 res = PQexec(g_conn, query->data);
1724 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1726 ntups = PQntuples(res);
1728 tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1730 i_tableoid = PQfnumber(res, "tableoid");
1731 i_oid = PQfnumber(res, "oid");
1732 i_typname = PQfnumber(res, "typname");
1733 i_typnamespace = PQfnumber(res, "typnamespace");
1734 i_usename = PQfnumber(res, "usename");
1735 i_typinput = PQfnumber(res, "typinput");
1736 i_typoutput = PQfnumber(res, "typoutput");
1737 i_typelem = PQfnumber(res, "typelem");
1738 i_typrelid = PQfnumber(res, "typrelid");
1739 i_typrelkind = PQfnumber(res, "typrelkind");
1740 i_typtype = PQfnumber(res, "typtype");
1741 i_typisdefined = PQfnumber(res, "typisdefined");
1743 for (i = 0; i < ntups; i++)
1748 tinfo[i].dobj.objType = DO_TYPE;
1749 tinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1750 tinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1751 AssignDumpId(&tinfo[i].dobj);
1752 tinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
1753 tinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
1754 tinfo[i].dobj.catId.oid);
1755 tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1756 tinfo[i].typinput = atooid(PQgetvalue(res, i, i_typinput));
1757 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
1758 tinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
1759 tinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
1760 tinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
1761 tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
1764 * If it's a table's rowtype, use special type code to facilitate
1765 * sorting into the desired order. (We don't want to consider it
1766 * an ordinary type because that would bring the table up into the
1767 * datatype part of the dump order.)
1769 if (OidIsValid(tinfo[i].typrelid) && tinfo[i].typrelkind != 'c')
1770 tinfo[i].dobj.objType = DO_TABLE_TYPE;
1773 * check for user-defined array types, omit system generated ones
1775 if (OidIsValid(tinfo[i].typelem) &&
1776 tinfo[i].dobj.name[0] != '_')
1777 tinfo[i].isArray = true;
1779 tinfo[i].isArray = false;
1781 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
1782 tinfo[i].isDefined = true;
1784 tinfo[i].isDefined = false;
1787 * If it's a domain, fetch info about its constraints, if any
1789 tinfo[i].nDomChecks = 0;
1790 tinfo[i].domChecks = NULL;
1791 if (tinfo[i].typtype == 'd')
1792 getDomainConstraints(&(tinfo[i]));
1795 * Make sure there are dependencies from the type to its input and
1796 * output functions. (We don't worry about typsend, typreceive,
1797 * or typanalyze since those are only valid in 7.4 and later,
1798 * wherein the standard dependency mechanism will pick them up.)
1800 funcInfo = findFuncByOid(tinfo[i].typinput);
1802 addObjectDependency(&tinfo[i].dobj,
1803 funcInfo->dobj.dumpId);
1804 funcInfo = findFuncByOid(typoutput);
1806 addObjectDependency(&tinfo[i].dobj,
1807 funcInfo->dobj.dumpId);
1809 if (strlen(tinfo[i].usename) == 0 && tinfo[i].isDefined)
1810 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
1811 tinfo[i].dobj.name);
1818 destroyPQExpBuffer(query);
1825 * read all operators in the system catalogs and return them in the
1826 * OprInfo* structure
1828 * numOprs is set to the number of operators read in
1831 getOperators(int *numOprs)
1836 PQExpBuffer query = createPQExpBuffer();
1846 * find all operators, including builtin operators; we filter out
1847 * system-defined operators at dump-out time.
1850 /* Make sure we are in proper schema */
1851 selectSourceSchema("pg_catalog");
1853 if (g_fout->remoteVersion >= 70300)
1855 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1857 "(select usename from pg_user where oprowner = usesysid) as usename, "
1858 "oprcode::oid as oprcode "
1859 "FROM pg_operator");
1861 else if (g_fout->remoteVersion >= 70100)
1863 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1864 "0::oid as oprnamespace, "
1865 "(select usename from pg_user where oprowner = usesysid) as usename, "
1866 "oprcode::oid as oprcode "
1867 "FROM pg_operator");
1871 appendPQExpBuffer(query, "SELECT "
1872 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
1874 "0::oid as oprnamespace, "
1875 "(select usename from pg_user where oprowner = usesysid) as usename, "
1876 "oprcode::oid as oprcode "
1877 "FROM pg_operator");
1880 res = PQexec(g_conn, query->data);
1881 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1883 ntups = PQntuples(res);
1886 oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
1888 i_tableoid = PQfnumber(res, "tableoid");
1889 i_oid = PQfnumber(res, "oid");
1890 i_oprname = PQfnumber(res, "oprname");
1891 i_oprnamespace = PQfnumber(res, "oprnamespace");
1892 i_usename = PQfnumber(res, "usename");
1893 i_oprcode = PQfnumber(res, "oprcode");
1895 for (i = 0; i < ntups; i++)
1897 oprinfo[i].dobj.objType = DO_OPERATOR;
1898 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1899 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1900 AssignDumpId(&oprinfo[i].dobj);
1901 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
1902 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
1903 oprinfo[i].dobj.catId.oid);
1904 oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1905 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
1907 if (strlen(oprinfo[i].usename) == 0)
1908 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
1909 oprinfo[i].dobj.name);
1914 destroyPQExpBuffer(query);
1921 * read all conversions in the system catalogs and return them in the
1922 * ConvInfo* structure
1924 * numConversions is set to the number of conversions read in
1927 getConversions(int *numConversions)
1932 PQExpBuffer query = createPQExpBuffer();
1940 /* Conversions didn't exist pre-7.3 */
1941 if (g_fout->remoteVersion < 70300)
1943 *numConversions = 0;
1948 * find all conversions, including builtin conversions; we filter out
1949 * system-defined conversions at dump-out time.
1952 /* Make sure we are in proper schema */
1953 selectSourceSchema("pg_catalog");
1955 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
1957 "(select usename from pg_user where conowner = usesysid) as usename "
1958 "FROM pg_conversion");
1960 res = PQexec(g_conn, query->data);
1961 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1963 ntups = PQntuples(res);
1964 *numConversions = ntups;
1966 convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
1968 i_tableoid = PQfnumber(res, "tableoid");
1969 i_oid = PQfnumber(res, "oid");
1970 i_conname = PQfnumber(res, "conname");
1971 i_connamespace = PQfnumber(res, "connamespace");
1972 i_usename = PQfnumber(res, "usename");
1974 for (i = 0; i < ntups; i++)
1976 convinfo[i].dobj.objType = DO_CONVERSION;
1977 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1978 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1979 AssignDumpId(&convinfo[i].dobj);
1980 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
1981 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
1982 convinfo[i].dobj.catId.oid);
1983 convinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1988 destroyPQExpBuffer(query);
1995 * read all opclasses in the system catalogs and return them in the
1996 * OpclassInfo* structure
1998 * numOpclasses is set to the number of opclasses read in
2001 getOpclasses(int *numOpclasses)
2006 PQExpBuffer query = createPQExpBuffer();
2007 OpclassInfo *opcinfo;
2015 * find all opclasses, including builtin opclasses; we filter out
2016 * system-defined opclasses at dump-out time.
2019 /* Make sure we are in proper schema */
2020 selectSourceSchema("pg_catalog");
2022 if (g_fout->remoteVersion >= 70300)
2024 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2026 "(select usename from pg_user where opcowner = usesysid) as usename "
2029 else if (g_fout->remoteVersion >= 70100)
2031 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2032 "0::oid as opcnamespace, "
2033 "''::name as usename "
2038 appendPQExpBuffer(query, "SELECT "
2039 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2041 "0::oid as opcnamespace, "
2042 "''::name as usename "
2046 res = PQexec(g_conn, query->data);
2047 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2049 ntups = PQntuples(res);
2050 *numOpclasses = ntups;
2052 opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2054 i_tableoid = PQfnumber(res, "tableoid");
2055 i_oid = PQfnumber(res, "oid");
2056 i_opcname = PQfnumber(res, "opcname");
2057 i_opcnamespace = PQfnumber(res, "opcnamespace");
2058 i_usename = PQfnumber(res, "usename");
2060 for (i = 0; i < ntups; i++)
2062 opcinfo[i].dobj.objType = DO_OPCLASS;
2063 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2064 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2065 AssignDumpId(&opcinfo[i].dobj);
2066 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
2067 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
2068 opcinfo[i].dobj.catId.oid);
2069 opcinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2071 if (g_fout->remoteVersion >= 70300)
2073 if (strlen(opcinfo[i].usename) == 0)
2074 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
2075 opcinfo[i].dobj.name);
2081 destroyPQExpBuffer(query);
2088 * read all the user-defined aggregates in the system catalogs and
2089 * return them in the AggInfo* structure
2091 * numAggs is set to the number of aggregates read in
2094 getAggregates(int *numAggs)
2099 PQExpBuffer query = createPQExpBuffer();
2109 /* Make sure we are in proper schema */
2110 selectSourceSchema("pg_catalog");
2112 /* find all user-defined aggregates */
2114 if (g_fout->remoteVersion >= 70300)
2116 appendPQExpBuffer(query, "SELECT tableoid, oid, proname as aggname, "
2117 "pronamespace as aggnamespace, "
2118 "proargtypes[0] as aggbasetype, "
2119 "(select usename from pg_user where proowner = usesysid) as usename, "
2123 "AND pronamespace != "
2124 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2126 else if (g_fout->remoteVersion >= 70100)
2128 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
2129 "0::oid as aggnamespace, "
2131 "(select usename from pg_user where aggowner = usesysid) as usename, "
2133 "FROM pg_aggregate "
2134 "where oid > '%u'::oid",
2135 g_last_builtin_oid);
2139 appendPQExpBuffer(query, "SELECT "
2140 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
2142 "0::oid as aggnamespace, "
2144 "(select usename from pg_user where aggowner = usesysid) as usename, "
2146 "FROM pg_aggregate "
2147 "where oid > '%u'::oid",
2148 g_last_builtin_oid);
2151 res = PQexec(g_conn, query->data);
2152 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2154 ntups = PQntuples(res);
2157 agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
2159 i_tableoid = PQfnumber(res, "tableoid");
2160 i_oid = PQfnumber(res, "oid");
2161 i_aggname = PQfnumber(res, "aggname");
2162 i_aggnamespace = PQfnumber(res, "aggnamespace");
2163 i_aggbasetype = PQfnumber(res, "aggbasetype");
2164 i_usename = PQfnumber(res, "usename");
2165 i_aggacl = PQfnumber(res, "aggacl");
2167 for (i = 0; i < ntups; i++)
2169 agginfo[i].aggfn.dobj.objType = DO_AGG;
2170 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2171 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2172 AssignDumpId(&agginfo[i].aggfn.dobj);
2173 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
2174 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
2175 agginfo[i].aggfn.dobj.catId.oid);
2176 agginfo[i].aggfn.usename = strdup(PQgetvalue(res, i, i_usename));
2177 if (strlen(agginfo[i].aggfn.usename) == 0)
2178 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
2179 agginfo[i].aggfn.dobj.name);
2180 agginfo[i].aggfn.lang = InvalidOid; /* not currently
2182 agginfo[i].aggfn.nargs = 1;
2183 agginfo[i].aggfn.argtypes = (Oid *) malloc(sizeof(Oid));
2184 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_aggbasetype));
2185 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
2186 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
2187 agginfo[i].anybasetype = false; /* computed when it's dumped */
2188 agginfo[i].fmtbasetype = NULL; /* computed when it's dumped */
2193 destroyPQExpBuffer(query);
2200 * read all the user-defined functions in the system catalogs and
2201 * return them in the FuncInfo* structure
2203 * numFuncs is set to the number of functions read in
2206 getFuncs(int *numFuncs)
2211 PQExpBuffer query = createPQExpBuffer();
2224 /* Make sure we are in proper schema */
2225 selectSourceSchema("pg_catalog");
2227 /* find all user-defined funcs */
2229 if (g_fout->remoteVersion >= 70300)
2231 appendPQExpBuffer(query,
2232 "SELECT tableoid, oid, proname, prolang, "
2233 "pronargs, proargtypes, prorettype, proacl, "
2235 "(select usename from pg_user where proowner = usesysid) as usename "
2237 "WHERE NOT proisagg "
2238 "AND pronamespace != "
2239 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2241 else if (g_fout->remoteVersion >= 70100)
2243 appendPQExpBuffer(query,
2244 "SELECT tableoid, oid, proname, prolang, "
2245 "pronargs, proargtypes, prorettype, "
2246 "'{=X}' as proacl, "
2247 "0::oid as pronamespace, "
2248 "(select usename from pg_user where proowner = usesysid) as usename "
2250 "where pg_proc.oid > '%u'::oid",
2251 g_last_builtin_oid);
2255 appendPQExpBuffer(query,
2257 "(SELECT oid FROM pg_class WHERE relname = 'pg_proc') AS tableoid, "
2258 "oid, proname, prolang, "
2259 "pronargs, proargtypes, prorettype, "
2260 "'{=X}' as proacl, "
2261 "0::oid as pronamespace, "
2262 "(select usename from pg_user where proowner = usesysid) as usename "
2264 "where pg_proc.oid > '%u'::oid",
2265 g_last_builtin_oid);
2268 res = PQexec(g_conn, query->data);
2269 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2271 ntups = PQntuples(res);
2275 finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
2277 i_tableoid = PQfnumber(res, "tableoid");
2278 i_oid = PQfnumber(res, "oid");
2279 i_proname = PQfnumber(res, "proname");
2280 i_pronamespace = PQfnumber(res, "pronamespace");
2281 i_usename = PQfnumber(res, "usename");
2282 i_prolang = PQfnumber(res, "prolang");
2283 i_pronargs = PQfnumber(res, "pronargs");
2284 i_proargtypes = PQfnumber(res, "proargtypes");
2285 i_prorettype = PQfnumber(res, "prorettype");
2286 i_proacl = PQfnumber(res, "proacl");
2288 for (i = 0; i < ntups; i++)
2290 finfo[i].dobj.objType = DO_FUNC;
2291 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2292 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2293 AssignDumpId(&finfo[i].dobj);
2294 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
2295 finfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
2296 finfo[i].dobj.catId.oid);
2297 finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2298 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2299 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
2300 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
2301 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
2302 if (finfo[i].nargs == 0)
2303 finfo[i].argtypes = NULL;
2306 finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
2307 parseOidArray(PQgetvalue(res, i, i_proargtypes),
2308 finfo[i].argtypes, finfo[i].nargs);
2311 if (strlen(finfo[i].usename) == 0)
2312 write_msg(NULL, "WARNING: owner of function \"%s\" appears to be invalid\n",
2313 finfo[i].dobj.name);
2318 destroyPQExpBuffer(query);
2325 * read all the user-defined tables (no indexes, no catalogs)
2326 * in the system catalogs return them in the TableInfo* structure
2328 * numTables is set to the number of tables read in
2331 getTables(int *numTables)
2336 PQExpBuffer query = createPQExpBuffer();
2337 PQExpBuffer delqry = createPQExpBuffer();
2338 PQExpBuffer lockquery = createPQExpBuffer();
2354 int i_reltablespace;
2356 /* Make sure we are in proper schema */
2357 selectSourceSchema("pg_catalog");
2360 * Find all the tables (including views and sequences).
2362 * We include system catalogs, so that we can work if a user table is
2363 * defined to inherit from a system catalog (pretty weird, but...)
2365 * We ignore tables that are not type 'r' (ordinary relation) or 'S'
2366 * (sequence) or 'v' (view).
2368 * Note: in this phase we should collect only a minimal amount of
2369 * information about each table, basically just enough to decide if it
2370 * is interesting. We must fetch all tables in this phase because
2371 * otherwise we cannot correctly identify inherited columns, serial
2375 if (g_fout->remoteVersion >= 80000)
2378 * Left join to pick up dependency info linking sequences to their
2379 * serial column, if any
2381 appendPQExpBuffer(query,
2382 "SELECT c.tableoid, c.oid, relname, "
2383 "relacl, relkind, relnamespace, "
2384 "(select usename from pg_user where relowner = usesysid) as usename, "
2385 "relchecks, reltriggers, "
2386 "relhasindex, relhasrules, relhasoids, "
2387 "d.refobjid as owning_tab, "
2388 "d.refobjsubid as owning_col, "
2389 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace "
2391 "left join pg_depend d on "
2392 "(c.relkind = '%c' and "
2393 "d.classid = c.tableoid and d.objid = c.oid and "
2394 "d.objsubid = 0 and "
2395 "d.refclassid = c.tableoid and d.deptype = 'i') "
2396 "where relkind in ('%c', '%c', '%c') "
2399 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2401 else if (g_fout->remoteVersion >= 70300)
2404 * Left join to pick up dependency info linking sequences to their
2405 * serial column, if any
2407 appendPQExpBuffer(query,
2408 "SELECT c.tableoid, c.oid, relname, "
2409 "relacl, relkind, relnamespace, "
2410 "(select usename from pg_user where relowner = usesysid) as usename, "
2411 "relchecks, reltriggers, "
2412 "relhasindex, relhasrules, relhasoids, "
2413 "d.refobjid as owning_tab, "
2414 "d.refobjsubid as owning_col, "
2415 "NULL as reltablespace "
2417 "left join pg_depend d on "
2418 "(c.relkind = '%c' and "
2419 "d.classid = c.tableoid and d.objid = c.oid and "
2420 "d.objsubid = 0 and "
2421 "d.refclassid = c.tableoid and d.deptype = 'i') "
2422 "where relkind in ('%c', '%c', '%c') "
2425 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2427 else if (g_fout->remoteVersion >= 70200)
2429 appendPQExpBuffer(query,
2430 "SELECT tableoid, oid, relname, relacl, relkind, "
2431 "0::oid as relnamespace, "
2432 "(select usename from pg_user where relowner = usesysid) as usename, "
2433 "relchecks, reltriggers, "
2434 "relhasindex, relhasrules, relhasoids, "
2435 "NULL::oid as owning_tab, "
2436 "NULL::int4 as owning_col, "
2437 "NULL as reltablespace "
2439 "where relkind in ('%c', '%c', '%c') "
2441 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2443 else if (g_fout->remoteVersion >= 70100)
2445 /* all tables have oids in 7.1 */
2446 appendPQExpBuffer(query,
2447 "SELECT tableoid, oid, relname, relacl, relkind, "
2448 "0::oid as relnamespace, "
2449 "(select usename from pg_user where relowner = usesysid) as usename, "
2450 "relchecks, reltriggers, "
2451 "relhasindex, relhasrules, "
2452 "'t'::bool as relhasoids, "
2453 "NULL::oid as owning_tab, "
2454 "NULL::int4 as owning_col, "
2455 "NULL as reltablespace "
2457 "where relkind in ('%c', '%c', '%c') "
2459 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2464 * Before 7.1, view relkind was not set to 'v', so we must check
2465 * if we have a view by looking for a rule in pg_rewrite.
2467 appendPQExpBuffer(query,
2469 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2470 "oid, relname, relacl, "
2471 "CASE WHEN relhasrules and relkind = 'r' "
2472 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
2473 " r.ev_class = c.oid AND r.ev_type = '1') "
2474 "THEN '%c'::\"char\" "
2475 "ELSE relkind END AS relkind,"
2476 "0::oid as relnamespace, "
2477 "(select usename from pg_user where relowner = usesysid) as usename, "
2478 "relchecks, reltriggers, "
2479 "relhasindex, relhasrules, "
2480 "'t'::bool as relhasoids, "
2481 "NULL::oid as owning_tab, "
2482 "NULL::int4 as owning_col, "
2483 "NULL as reltablespace "
2485 "where relkind in ('%c', '%c') "
2488 RELKIND_RELATION, RELKIND_SEQUENCE);
2491 res = PQexec(g_conn, query->data);
2492 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2494 ntups = PQntuples(res);
2499 * Extract data from result and lock dumpable tables. We do the
2500 * locking before anything else, to minimize the window wherein a
2501 * table could disappear under us.
2503 * Note that we have to save info about all tables here, even when
2504 * dumping only one, because we don't yet know which tables might be
2505 * inheritance ancestors of the target table.
2507 tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
2509 i_reltableoid = PQfnumber(res, "tableoid");
2510 i_reloid = PQfnumber(res, "oid");
2511 i_relname = PQfnumber(res, "relname");
2512 i_relnamespace = PQfnumber(res, "relnamespace");
2513 i_relacl = PQfnumber(res, "relacl");
2514 i_relkind = PQfnumber(res, "relkind");
2515 i_usename = PQfnumber(res, "usename");
2516 i_relchecks = PQfnumber(res, "relchecks");
2517 i_reltriggers = PQfnumber(res, "reltriggers");
2518 i_relhasindex = PQfnumber(res, "relhasindex");
2519 i_relhasrules = PQfnumber(res, "relhasrules");
2520 i_relhasoids = PQfnumber(res, "relhasoids");
2521 i_owning_tab = PQfnumber(res, "owning_tab");
2522 i_owning_col = PQfnumber(res, "owning_col");
2523 i_reltablespace = PQfnumber(res, "reltablespace");
2525 for (i = 0; i < ntups; i++)
2527 tblinfo[i].dobj.objType = DO_TABLE;
2528 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
2529 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
2530 AssignDumpId(&tblinfo[i].dobj);
2531 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
2532 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
2533 tblinfo[i].dobj.catId.oid);
2534 tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2535 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
2536 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
2537 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
2538 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
2539 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
2540 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
2541 tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2542 if (PQgetisnull(res, i, i_owning_tab))
2544 tblinfo[i].owning_tab = InvalidOid;
2545 tblinfo[i].owning_col = 0;
2549 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
2550 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
2552 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
2554 /* other fields were zeroed above */
2557 * Decide whether we want to dump this table. Sequences owned by
2558 * serial columns are never dumpable on their own; we will
2559 * transpose their owning table's dump flag to them below.
2561 if (OidIsValid(tblinfo[i].owning_tab))
2562 tblinfo[i].dump = false;
2564 selectDumpableTable(&tblinfo[i]);
2565 tblinfo[i].interesting = tblinfo[i].dump;
2568 * Read-lock target tables to make sure they aren't DROPPED or
2569 * altered in schema before we get around to dumping them.
2571 * Note that we don't explicitly lock parents of the target tables;
2572 * we assume our lock on the child is enough to prevent schema
2573 * alterations to parent tables.
2575 * NOTE: it'd be kinda nice to lock views and sequences too, not only
2576 * plain tables, but the backend doesn't presently allow that.
2578 if (tblinfo[i].dump && tblinfo[i].relkind == RELKIND_RELATION)
2580 resetPQExpBuffer(lockquery);
2581 appendPQExpBuffer(lockquery,
2582 "LOCK TABLE %s IN ACCESS SHARE MODE",
2583 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
2584 tblinfo[i].dobj.name));
2585 do_sql_command(g_conn, lockquery->data);
2588 /* Emit notice if join for owner failed */
2589 if (strlen(tblinfo[i].usename) == 0)
2590 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
2591 tblinfo[i].dobj.name);
2595 * If the user is attempting to dump a specific table, check to ensure
2596 * that the specified table actually exists. (This is a bit
2597 * simplistic since we don't fully check the combination of -n and -t
2600 if (selectTableName)
2602 for (i = 0; i < ntups; i++)
2603 if (strcmp(tblinfo[i].dobj.name, selectTableName) == 0)
2606 /* Didn't find a match */
2609 write_msg(NULL, "specified table \"%s\" does not exist\n",
2616 destroyPQExpBuffer(query);
2617 destroyPQExpBuffer(delqry);
2618 destroyPQExpBuffer(lockquery);
2625 * read all the inheritance information
2626 * from the system catalogs return them in the InhInfo* structure
2628 * numInherits is set to the number of pairs read in
2631 getInherits(int *numInherits)
2636 PQExpBuffer query = createPQExpBuffer();
2642 /* Make sure we are in proper schema */
2643 selectSourceSchema("pg_catalog");
2645 /* find all the inheritance information */
2647 appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2649 res = PQexec(g_conn, query->data);
2650 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2652 ntups = PQntuples(res);
2654 *numInherits = ntups;
2656 inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
2658 i_inhrelid = PQfnumber(res, "inhrelid");
2659 i_inhparent = PQfnumber(res, "inhparent");
2661 for (i = 0; i < ntups; i++)
2663 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
2664 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
2669 destroyPQExpBuffer(query);
2676 * get information about every index on a dumpable table
2678 * Note: index data is not returned directly to the caller, but it
2679 * does get entered into the DumpableObject tables.
2682 getIndexes(TableInfo tblinfo[], int numTables)
2686 PQExpBuffer query = createPQExpBuffer();
2689 ConstraintInfo *constrinfo;
2704 for (i = 0; i < numTables; i++)
2706 TableInfo *tbinfo = &tblinfo[i];
2708 /* Only plain tables have indexes */
2709 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
2716 write_msg(NULL, "reading indexes for table \"%s\"\n",
2719 /* Make sure we are in proper schema so indexdef is right */
2720 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2723 * The point of the messy-looking outer join is to find a
2724 * constraint that is related by an internal dependency link to
2725 * the index. If we find one, create a CONSTRAINT entry linked to
2726 * the INDEX entry. We assume an index won't have more than one
2727 * internal dependency.
2729 resetPQExpBuffer(query);
2730 if (g_fout->remoteVersion >= 80000)
2732 appendPQExpBuffer(query,
2733 "SELECT t.tableoid, t.oid, "
2734 "t.relname as indexname, "
2735 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2736 "t.relnatts as indnkeys, "
2737 "i.indkey, i.indisclustered, "
2738 "c.contype, c.conname, "
2739 "c.tableoid as contableoid, "
2741 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) as tablespace "
2742 "FROM pg_catalog.pg_index i "
2743 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2744 "LEFT JOIN pg_catalog.pg_depend d "
2745 "ON (d.classid = t.tableoid "
2746 "AND d.objid = t.oid "
2747 "AND d.deptype = 'i') "
2748 "LEFT JOIN pg_catalog.pg_constraint c "
2749 "ON (d.refclassid = c.tableoid "
2750 "AND d.refobjid = c.oid) "
2751 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2752 "ORDER BY indexname",
2753 tbinfo->dobj.catId.oid);
2755 else if (g_fout->remoteVersion >= 70300)
2757 appendPQExpBuffer(query,
2758 "SELECT t.tableoid, t.oid, "
2759 "t.relname as indexname, "
2760 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2761 "t.relnatts as indnkeys, "
2762 "i.indkey, i.indisclustered, "
2763 "c.contype, c.conname, "
2764 "c.tableoid as contableoid, "
2766 "NULL as tablespace "
2767 "FROM pg_catalog.pg_index i "
2768 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2769 "LEFT JOIN pg_catalog.pg_depend d "
2770 "ON (d.classid = t.tableoid "
2771 "AND d.objid = t.oid "
2772 "AND d.deptype = 'i') "
2773 "LEFT JOIN pg_catalog.pg_constraint c "
2774 "ON (d.refclassid = c.tableoid "
2775 "AND d.refobjid = c.oid) "
2776 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2777 "ORDER BY indexname",
2778 tbinfo->dobj.catId.oid);
2780 else if (g_fout->remoteVersion >= 70100)
2782 appendPQExpBuffer(query,
2783 "SELECT t.tableoid, t.oid, "
2784 "t.relname as indexname, "
2785 "pg_get_indexdef(i.indexrelid) as indexdef, "
2786 "t.relnatts as indnkeys, "
2787 "i.indkey, false as indisclustered, "
2788 "CASE WHEN i.indisprimary THEN 'p'::char "
2789 "ELSE '0'::char END as contype, "
2790 "t.relname as conname, "
2791 "0::oid as contableoid, "
2793 "NULL as tablespace "
2794 "FROM pg_index i, pg_class t "
2795 "WHERE t.oid = i.indexrelid "
2796 "AND i.indrelid = '%u'::oid "
2797 "ORDER BY indexname",
2798 tbinfo->dobj.catId.oid);
2802 appendPQExpBuffer(query,
2804 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2806 "t.relname as indexname, "
2807 "pg_get_indexdef(i.indexrelid) as indexdef, "
2808 "t.relnatts as indnkeys, "
2809 "i.indkey, false as indisclustered, "
2810 "CASE WHEN i.indisprimary THEN 'p'::char "
2811 "ELSE '0'::char END as contype, "
2812 "t.relname as conname, "
2813 "0::oid as contableoid, "
2815 "NULL as tablespace "
2816 "FROM pg_index i, pg_class t "
2817 "WHERE t.oid = i.indexrelid "
2818 "AND i.indrelid = '%u'::oid "
2819 "ORDER BY indexname",
2820 tbinfo->dobj.catId.oid);
2823 res = PQexec(g_conn, query->data);
2824 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2826 ntups = PQntuples(res);
2828 i_tableoid = PQfnumber(res, "tableoid");
2829 i_oid = PQfnumber(res, "oid");
2830 i_indexname = PQfnumber(res, "indexname");
2831 i_indexdef = PQfnumber(res, "indexdef");
2832 i_indnkeys = PQfnumber(res, "indnkeys");
2833 i_indkey = PQfnumber(res, "indkey");
2834 i_indisclustered = PQfnumber(res, "indisclustered");
2835 i_contype = PQfnumber(res, "contype");
2836 i_conname = PQfnumber(res, "conname");
2837 i_contableoid = PQfnumber(res, "contableoid");
2838 i_conoid = PQfnumber(res, "conoid");
2839 i_tablespace = PQfnumber(res, "tablespace");
2841 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
2842 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2844 for (j = 0; j < ntups; j++)
2848 indxinfo[j].dobj.objType = DO_INDEX;
2849 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
2850 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
2851 AssignDumpId(&indxinfo[j].dobj);
2852 indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
2853 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2854 indxinfo[j].indextable = tbinfo;
2855 indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
2856 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
2857 indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
2860 * In pre-7.4 releases, indkeys may contain more entries than
2861 * indnkeys says (since indnkeys will be 1 for a functional
2862 * index). We don't actually care about this case since we
2863 * don't examine indkeys except for indexes associated with
2864 * PRIMARY and UNIQUE constraints, which are never functional
2865 * indexes. But we have to allocate enough space to keep
2866 * parseOidArray from complaining.
2868 indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
2869 parseOidArray(PQgetvalue(res, j, i_indkey),
2870 indxinfo[j].indkeys, INDEX_MAX_KEYS);
2871 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
2872 contype = *(PQgetvalue(res, j, i_contype));
2874 if (contype == 'p' || contype == 'u')
2877 * If we found a constraint matching the index, create an
2880 * In a pre-7.3 database, we take this path iff the index was
2881 * marked indisprimary.
2883 constrinfo[j].dobj.objType = DO_CONSTRAINT;
2884 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2885 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2886 AssignDumpId(&constrinfo[j].dobj);
2887 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2888 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2889 constrinfo[j].contable = tbinfo;
2890 constrinfo[j].condomain = NULL;
2891 constrinfo[j].contype = contype;
2892 constrinfo[j].condef = NULL;
2893 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
2894 constrinfo[j].coninherited = false;
2895 constrinfo[j].separate = true;
2897 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
2899 /* If pre-7.3 DB, better make sure table comes first */
2900 addObjectDependency(&constrinfo[j].dobj,
2901 tbinfo->dobj.dumpId);
2905 /* Plain secondary index */
2906 indxinfo[j].indexconstraint = 0;
2913 destroyPQExpBuffer(query);
2919 * Get info about constraints on dumpable tables.
2921 * Currently handles foreign keys only.
2922 * Unique and primary key constraints are handled with indexes,
2923 * while check constraints are processed in getTableAttrs().
2926 getConstraints(TableInfo tblinfo[], int numTables)
2930 ConstraintInfo *constrinfo;
2939 /* pg_constraint was created in 7.3, so nothing to do if older */
2940 if (g_fout->remoteVersion < 70300)
2943 query = createPQExpBuffer();
2945 for (i = 0; i < numTables; i++)
2947 TableInfo *tbinfo = &tblinfo[i];
2949 if (tbinfo->ntrig == 0 || !tbinfo->dump)
2953 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
2957 * select table schema to ensure constraint expr is qualified if
2960 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2962 resetPQExpBuffer(query);
2963 appendPQExpBuffer(query,
2964 "SELECT tableoid, oid, conname, "
2965 "pg_catalog.pg_get_constraintdef(oid) as condef "
2966 "FROM pg_catalog.pg_constraint "
2967 "WHERE conrelid = '%u'::pg_catalog.oid "
2968 "AND contype = 'f'",
2969 tbinfo->dobj.catId.oid);
2970 res = PQexec(g_conn, query->data);
2971 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2973 ntups = PQntuples(res);
2975 i_contableoid = PQfnumber(res, "tableoid");
2976 i_conoid = PQfnumber(res, "oid");
2977 i_conname = PQfnumber(res, "conname");
2978 i_condef = PQfnumber(res, "condef");
2980 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2982 for (j = 0; j < ntups; j++)
2984 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
2985 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2986 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2987 AssignDumpId(&constrinfo[j].dobj);
2988 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2989 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2990 constrinfo[j].contable = tbinfo;
2991 constrinfo[j].condomain = NULL;
2992 constrinfo[j].contype = 'f';
2993 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
2994 constrinfo[j].conindex = 0;
2995 constrinfo[j].coninherited = false;
2996 constrinfo[j].separate = true;
3002 destroyPQExpBuffer(query);
3006 * getDomainConstraints
3008 * Get info about constraints on a domain.
3011 getDomainConstraints(TypeInfo *tinfo)
3014 ConstraintInfo *constrinfo;
3023 /* pg_constraint was created in 7.3, so nothing to do if older */
3024 if (g_fout->remoteVersion < 70300)
3028 * select appropriate schema to ensure names in constraint are
3029 * properly qualified
3031 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
3033 query = createPQExpBuffer();
3035 if (g_fout->remoteVersion >= 70400)
3036 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3037 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3038 "FROM pg_catalog.pg_constraint "
3039 "WHERE contypid = '%u'::pg_catalog.oid "
3041 tinfo->dobj.catId.oid);
3043 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3044 "'CHECK (' || consrc || ')' AS consrc "
3045 "FROM pg_catalog.pg_constraint "
3046 "WHERE contypid = '%u'::pg_catalog.oid "
3048 tinfo->dobj.catId.oid);
3050 res = PQexec(g_conn, query->data);
3051 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3053 ntups = PQntuples(res);
3055 i_tableoid = PQfnumber(res, "tableoid");
3056 i_oid = PQfnumber(res, "oid");
3057 i_conname = PQfnumber(res, "conname");
3058 i_consrc = PQfnumber(res, "consrc");
3060 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3062 tinfo->nDomChecks = ntups;
3063 tinfo->domChecks = constrinfo;
3065 for (i = 0; i < ntups; i++)
3067 constrinfo[i].dobj.objType = DO_CONSTRAINT;
3068 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3069 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3070 AssignDumpId(&constrinfo[i].dobj);
3071 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
3072 constrinfo[i].dobj.namespace = tinfo->dobj.namespace;
3073 constrinfo[i].contable = NULL;
3074 constrinfo[i].condomain = tinfo;
3075 constrinfo[i].contype = 'c';
3076 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
3077 constrinfo[i].conindex = 0;
3078 constrinfo[i].coninherited = false;
3079 constrinfo[i].separate = false;
3082 * Make the domain depend on the constraint, ensuring it won't be
3083 * output till any constraint dependencies are OK.
3085 addObjectDependency(&tinfo->dobj,
3086 constrinfo[i].dobj.dumpId);
3091 destroyPQExpBuffer(query);
3096 * get basic information about every rule in the system
3098 * numRules is set to the number of rules read in
3101 getRules(int *numRules)
3106 PQExpBuffer query = createPQExpBuffer();
3115 /* Make sure we are in proper schema */
3116 selectSourceSchema("pg_catalog");
3118 if (g_fout->remoteVersion >= 70100)
3120 appendPQExpBuffer(query, "SELECT "
3121 "tableoid, oid, rulename, "
3122 "ev_class as ruletable, ev_type, is_instead "
3128 appendPQExpBuffer(query, "SELECT "
3129 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
3131 "ev_class as ruletable, ev_type, is_instead "
3136 res = PQexec(g_conn, query->data);
3137 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3139 ntups = PQntuples(res);
3143 ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
3145 i_tableoid = PQfnumber(res, "tableoid");
3146 i_oid = PQfnumber(res, "oid");
3147 i_rulename = PQfnumber(res, "rulename");
3148 i_ruletable = PQfnumber(res, "ruletable");
3149 i_ev_type = PQfnumber(res, "ev_type");
3150 i_is_instead = PQfnumber(res, "is_instead");
3152 for (i = 0; i < ntups; i++)
3156 ruleinfo[i].dobj.objType = DO_RULE;
3157 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3158 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3159 AssignDumpId(&ruleinfo[i].dobj);
3160 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
3161 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
3162 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
3163 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
3164 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
3165 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
3166 if (ruleinfo[i].ruletable)
3169 * If the table is a view, force its ON SELECT rule to be
3170 * sorted before the view itself --- this ensures that any
3171 * dependencies for the rule affect the table's positioning.
3172 * Other rules are forced to appear after their table.
3174 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
3175 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
3176 addObjectDependency(&ruleinfo[i].ruletable->dobj,
3177 ruleinfo[i].dobj.dumpId);
3179 addObjectDependency(&ruleinfo[i].dobj,
3180 ruleinfo[i].ruletable->dobj.dumpId);
3186 destroyPQExpBuffer(query);
3193 * get information about every trigger on a dumpable table
3195 * Note: trigger data is not returned directly to the caller, but it
3196 * does get entered into the DumpableObject tables.
3199 getTriggers(TableInfo tblinfo[], int numTables)
3203 PQExpBuffer query = createPQExpBuffer();
3205 TriggerInfo *tginfo;
3221 for (i = 0; i < numTables; i++)
3223 TableInfo *tbinfo = &tblinfo[i];
3225 if (tbinfo->ntrig == 0 || !tbinfo->dump)
3229 write_msg(NULL, "reading triggers for table \"%s\"\n",
3233 * select table schema to ensure regproc name is qualified if
3236 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3238 resetPQExpBuffer(query);
3239 if (g_fout->remoteVersion >= 70300)
3242 * We ignore triggers that are tied to a foreign-key
3245 appendPQExpBuffer(query,
3247 "tgfoid::pg_catalog.regproc as tgfname, "
3248 "tgtype, tgnargs, tgargs, "
3249 "tgisconstraint, tgconstrname, tgdeferrable, "
3250 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3251 "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
3252 "from pg_catalog.pg_trigger t "
3253 "where tgrelid = '%u'::pg_catalog.oid "
3254 "and (not tgisconstraint "
3256 " (SELECT 1 FROM pg_catalog.pg_depend d "
3257 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
3258 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
3259 tbinfo->dobj.catId.oid);
3261 else if (g_fout->remoteVersion >= 70100)
3263 appendPQExpBuffer(query,
3264 "SELECT tgname, tgfoid::regproc as tgfname, "
3265 "tgtype, tgnargs, tgargs, "
3266 "tgisconstraint, tgconstrname, tgdeferrable, "
3267 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3268 "(select relname from pg_class where oid = tgconstrrelid) "
3269 " as tgconstrrelname "
3271 "where tgrelid = '%u'::oid",
3272 tbinfo->dobj.catId.oid);
3276 appendPQExpBuffer(query,
3277 "SELECT tgname, tgfoid::regproc as tgfname, "
3278 "tgtype, tgnargs, tgargs, "
3279 "tgisconstraint, tgconstrname, tgdeferrable, "
3280 "tgconstrrelid, tginitdeferred, "
3281 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
3284 "(select relname from pg_class where oid = tgconstrrelid) "
3285 " as tgconstrrelname "
3287 "where tgrelid = '%u'::oid",
3288 tbinfo->dobj.catId.oid);
3290 res = PQexec(g_conn, query->data);
3291 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3293 ntups = PQntuples(res);
3296 * We may have less triggers than recorded due to having ignored
3297 * foreign-key triggers
3299 if (ntups > tbinfo->ntrig)
3301 write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
3302 tbinfo->ntrig, tbinfo->dobj.name, ntups);
3305 i_tableoid = PQfnumber(res, "tableoid");
3306 i_oid = PQfnumber(res, "oid");
3307 i_tgname = PQfnumber(res, "tgname");
3308 i_tgfname = PQfnumber(res, "tgfname");
3309 i_tgtype = PQfnumber(res, "tgtype");
3310 i_tgnargs = PQfnumber(res, "tgnargs");
3311 i_tgargs = PQfnumber(res, "tgargs");
3312 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
3313 i_tgconstrname = PQfnumber(res, "tgconstrname");
3314 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
3315 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
3316 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
3317 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
3319 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
3321 for (j = 0; j < ntups; j++)
3323 tginfo[j].dobj.objType = DO_TRIGGER;
3324 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3325 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3326 AssignDumpId(&tginfo[j].dobj);
3327 tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
3328 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
3329 tginfo[j].tgtable = tbinfo;
3330 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
3331 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
3332 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
3333 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
3334 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
3335 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
3336 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
3338 if (tginfo[j].tgisconstraint)
3340 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
3341 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
3342 if (OidIsValid(tginfo[j].tgconstrrelid))
3344 if (PQgetisnull(res, j, i_tgconstrrelname))
3346 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
3347 tginfo[j].dobj.name, tbinfo->dobj.name,
3348 tginfo[j].tgconstrrelid);
3351 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
3354 tginfo[j].tgconstrrelname = NULL;
3358 tginfo[j].tgconstrname = NULL;
3359 tginfo[j].tgconstrrelid = InvalidOid;
3360 tginfo[j].tgconstrrelname = NULL;
3367 destroyPQExpBuffer(query);
3372 * get basic information about every procedural language in the system
3374 * numProcLangs is set to the number of langs read in
3376 * NB: this must run after getFuncs() because we assume we can do
3380 getProcLangs(int *numProcLangs)
3385 PQExpBuffer query = createPQExpBuffer();
3386 ProcLangInfo *planginfo;
3391 int i_lanplcallfoid;
3392 int i_lanvalidator = -1;
3395 /* Make sure we are in proper schema */
3396 selectSourceSchema("pg_catalog");
3398 if (g_fout->remoteVersion >= 70100)
3400 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
3406 appendPQExpBuffer(query, "SELECT "
3407 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
3408 "oid, * FROM pg_language "
3413 res = PQexec(g_conn, query->data);
3414 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3416 ntups = PQntuples(res);
3418 *numProcLangs = ntups;
3420 planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
3422 i_tableoid = PQfnumber(res, "tableoid");
3423 i_oid = PQfnumber(res, "oid");
3424 i_lanname = PQfnumber(res, "lanname");
3425 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
3426 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
3427 if (g_fout->remoteVersion >= 70300)
3429 i_lanvalidator = PQfnumber(res, "lanvalidator");
3430 i_lanacl = PQfnumber(res, "lanacl");
3433 for (i = 0; i < ntups; i++)
3435 planginfo[i].dobj.objType = DO_PROCLANG;
3436 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3437 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3438 AssignDumpId(&planginfo[i].dobj);
3440 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
3441 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
3442 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
3443 if (g_fout->remoteVersion >= 70300)
3445 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
3446 planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
3452 planginfo[i].lanvalidator = InvalidOid;
3453 planginfo[i].lanacl = strdup("{=U}");
3456 * We need to make a dependency to ensure the function will be
3457 * dumped first. (In 7.3 and later the regular dependency
3458 * mechanism will handle this for us.)
3460 funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
3462 addObjectDependency(&planginfo[i].dobj,
3463 funcInfo->dobj.dumpId);
3469 destroyPQExpBuffer(query);
3476 * get basic information about every cast in the system
3478 * numCasts is set to the number of casts read in
3481 getCasts(int *numCasts)
3486 PQExpBuffer query = createPQExpBuffer();
3495 /* Make sure we are in proper schema */
3496 selectSourceSchema("pg_catalog");
3498 if (g_fout->remoteVersion >= 70300)
3500 appendPQExpBuffer(query, "SELECT tableoid, oid, "
3501 "castsource, casttarget, castfunc, castcontext "
3502 "FROM pg_cast ORDER BY 3,4");
3506 appendPQExpBuffer(query, "SELECT 0 as tableoid, p.oid, "
3507 "t1.oid as castsource, t2.oid as casttarget, "
3508 "p.oid as castfunc, 'e' as castcontext "
3509 "FROM pg_type t1, pg_type t2, pg_proc p "
3510 "WHERE p.pronargs = 1 AND "
3511 "p.proargtypes[0] = t1.oid AND "
3512 "p.prorettype = t2.oid AND p.proname = t2.typname "
3516 res = PQexec(g_conn, query->data);
3517 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3519 ntups = PQntuples(res);
3523 castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
3525 i_tableoid = PQfnumber(res, "tableoid");
3526 i_oid = PQfnumber(res, "oid");
3527 i_castsource = PQfnumber(res, "castsource");
3528 i_casttarget = PQfnumber(res, "casttarget");
3529 i_castfunc = PQfnumber(res, "castfunc");
3530 i_castcontext = PQfnumber(res, "castcontext");
3532 for (i = 0; i < ntups; i++)
3534 PQExpBufferData namebuf;
3535 TypeInfo *sTypeInfo;
3536 TypeInfo *tTypeInfo;
3538 castinfo[i].dobj.objType = DO_CAST;
3539 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3540 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3541 AssignDumpId(&castinfo[i].dobj);
3542 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
3543 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
3544 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
3545 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
3548 * Try to name cast as concatenation of typnames. This is only
3549 * used for purposes of sorting. If we fail to find either type,
3550 * the name will be an empty string.
3552 initPQExpBuffer(&namebuf);
3553 sTypeInfo = findTypeByOid(castinfo[i].castsource);
3554 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
3555 if (sTypeInfo && tTypeInfo)
3556 appendPQExpBuffer(&namebuf, "%s %s",
3557 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
3558 castinfo[i].dobj.name = namebuf.data;
3560 if (OidIsValid(castinfo[i].castfunc))
3563 * We need to make a dependency to ensure the function will be
3564 * dumped first. (In 7.3 and later the regular dependency
3565 * mechanism will handle this for us.)
3569 funcInfo = findFuncByOid(castinfo[i].castfunc);
3571 addObjectDependency(&castinfo[i].dobj,
3572 funcInfo->dobj.dumpId);
3578 destroyPQExpBuffer(query);
3585 * for each interesting table, read info about its attributes
3586 * (names, types, default values, CHECK constraints, etc)
3588 * This is implemented in a very inefficient way right now, looping
3589 * through the tblinfo and doing a join per table to find the attrs and their
3590 * types. However, because we want type names and so forth to be named
3591 * relative to the schema of each table, we couldn't do it in just one
3592 * query. (Maybe one query per schema?)
3597 getTableAttrs(TableInfo *tblinfo, int numTables)
3602 PQExpBuffer q = createPQExpBuffer();
3607 int i_attstattarget;
3618 for (i = 0; i < numTables; i++)
3620 TableInfo *tbinfo = &tblinfo[i];
3622 /* Don't bother to collect info for sequences */
3623 if (tbinfo->relkind == RELKIND_SEQUENCE)
3626 /* Don't bother with uninteresting tables, either */
3627 if (!tbinfo->interesting)
3631 * Make sure we are in proper schema for this table; this allows
3632 * correct retrieval of formatted type names and default exprs
3634 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3636 /* find all the user attributes and their types */
3639 * we must read the attribute names in attribute number order!
3640 * because we will use the attnum to index into the attnames array
3641 * later. We actually ask to order by "attrelid, attnum" because
3642 * (at least up to 7.3) the planner is not smart enough to realize
3643 * it needn't re-sort the output of an indexscan on
3644 * pg_attribute_relid_attnum_index.
3647 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
3650 resetPQExpBuffer(q);
3652 if (g_fout->remoteVersion >= 70300)
3654 /* need left join here to not fail on dropped columns ... */
3655 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, "
3656 "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, "
3657 "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname "
3658 "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t "
3659 "on a.atttypid = t.oid "
3660 "where a.attrelid = '%u'::pg_catalog.oid "
3661 "and a.attnum > 0::pg_catalog.int2 "
3662 "order by a.attrelid, a.attnum",
3663 tbinfo->dobj.catId.oid);
3665 else if (g_fout->remoteVersion >= 70100)
3668 * attstattarget doesn't exist in 7.1. It does exist in 7.2,
3669 * but we don't dump it because we can't tell whether it's
3670 * been explicitly set or was just a default.
3672 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, "
3673 "a.attnotnull, a.atthasdef, false as attisdropped, false as attislocal, "
3674 "format_type(t.oid,a.atttypmod) as atttypname "
3675 "from pg_attribute a left join pg_type t "
3676 "on a.atttypid = t.oid "
3677 "where a.attrelid = '%u'::oid "
3678 "and a.attnum > 0::int2 "
3679 "order by a.attrelid, a.attnum",
3680 tbinfo->dobj.catId.oid);
3684 /* format_type not available before 7.1 */
3685 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, "
3686 "attnotnull, atthasdef, false as attisdropped, false as attislocal, "
3687 "(select typname from pg_type where oid = atttypid) as atttypname "
3688 "from pg_attribute a "
3689 "where attrelid = '%u'::oid "
3690 "and attnum > 0::int2 "
3691 "order by attrelid, attnum",
3692 tbinfo->dobj.catId.oid);
3695 res = PQexec(g_conn, q->data);
3696 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3698 ntups = PQntuples(res);
3700 i_attnum = PQfnumber(res, "attnum");
3701 i_attname = PQfnumber(res, "attname");
3702 i_atttypname = PQfnumber(res, "atttypname");
3703 i_atttypmod = PQfnumber(res, "atttypmod");
3704 i_attstattarget = PQfnumber(res, "attstattarget");
3705 i_attstorage = PQfnumber(res, "attstorage");
3706 i_typstorage = PQfnumber(res, "typstorage");
3707 i_attnotnull = PQfnumber(res, "attnotnull");
3708 i_atthasdef = PQfnumber(res, "atthasdef");
3709 i_attisdropped = PQfnumber(res, "attisdropped");
3710 i_attislocal = PQfnumber(res, "attislocal");
3712 tbinfo->numatts = ntups;
3713 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
3714 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
3715 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
3716 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
3717 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
3718 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
3719 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
3720 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
3721 tbinfo->attisserial = (bool *) malloc(ntups * sizeof(bool));
3722 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
3723 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
3724 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
3725 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
3726 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
3727 hasdefaults = false;
3729 for (j = 0; j < ntups; j++)
3731 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
3733 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
3737 tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
3738 tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
3739 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
3740 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
3741 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
3742 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
3743 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
3744 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
3745 tbinfo->attisserial[j] = false; /* fix below */
3746 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
3747 tbinfo->attrdefs[j] = NULL; /* fix below */
3748 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
3750 /* these flags will be set in flagInhAttrs() */
3751 tbinfo->inhAttrs[j] = false;
3752 tbinfo->inhAttrDef[j] = false;
3753 tbinfo->inhNotNull[j] = false;
3759 * Get info about column defaults
3763 AttrDefInfo *attrdefs;
3767 write_msg(NULL, "finding default expressions of table \"%s\"\n",
3770 resetPQExpBuffer(q);
3771 if (g_fout->remoteVersion >= 70300)
3773 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
3774 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
3775 "FROM pg_catalog.pg_attrdef "
3776 "WHERE adrelid = '%u'::pg_catalog.oid",
3777 tbinfo->dobj.catId.oid);
3779 else if (g_fout->remoteVersion >= 70200)
3781 /* 7.2 did not have OIDs in pg_attrdef */
3782 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, adnum, "
3783 "pg_get_expr(adbin, adrelid) AS adsrc "
3785 "WHERE adrelid = '%u'::oid",
3786 tbinfo->dobj.catId.oid);
3788 else if (g_fout->remoteVersion >= 70100)
3790 /* no pg_get_expr, so must rely on adsrc */
3791 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
3793 "WHERE adrelid = '%u'::oid",
3794 tbinfo->dobj.catId.oid);
3798 /* no pg_get_expr, no tableoid either */
3799 appendPQExpBuffer(q, "SELECT "
3800 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
3801 "oid, adnum, adsrc "
3803 "WHERE adrelid = '%u'::oid",
3804 tbinfo->dobj.catId.oid);
3806 res = PQexec(g_conn, q->data);
3807 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3809 numDefaults = PQntuples(res);
3810 attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
3812 for (j = 0; j < numDefaults; j++)
3816 attrdefs[j].dobj.objType = DO_ATTRDEF;
3817 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3818 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3819 AssignDumpId(&attrdefs[j].dobj);
3820 attrdefs[j].adtable = tbinfo;
3821 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
3822 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
3824 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
3825 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
3828 * Defaults on a VIEW must always be dumped as separate
3829 * ALTER TABLE commands. Defaults on regular tables are
3830 * dumped as part of the CREATE TABLE if possible. To
3831 * check if it's safe, we mark the default as needing to
3832 * appear before the CREATE.
3834 if (tbinfo->relkind == RELKIND_VIEW)
3836 attrdefs[j].separate = true;
3837 /* needed in case pre-7.3 DB: */
3838 addObjectDependency(&attrdefs[j].dobj,
3839 tbinfo->dobj.dumpId);
3843 attrdefs[j].separate = false;
3844 addObjectDependency(&tbinfo->dobj,
3845 attrdefs[j].dobj.dumpId);
3848 if (adnum <= 0 || adnum > ntups)
3850 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
3851 adnum, tbinfo->dobj.name);
3854 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
3860 * Get info about table CHECK constraints
3862 if (tbinfo->ncheck > 0)
3864 ConstraintInfo *constrs;
3868 write_msg(NULL, "finding check constraints for table \"%s\"\n",
3871 resetPQExpBuffer(q);
3872 if (g_fout->remoteVersion >= 70400)
3874 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3875 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3876 "FROM pg_catalog.pg_constraint "
3877 "WHERE conrelid = '%u'::pg_catalog.oid "
3878 " AND contype = 'c' "
3880 tbinfo->dobj.catId.oid);
3882 else if (g_fout->remoteVersion >= 70300)
3884 /* no pg_get_constraintdef, must use consrc */
3885 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3886 "'CHECK (' || consrc || ')' AS consrc "
3887 "FROM pg_catalog.pg_constraint "
3888 "WHERE conrelid = '%u'::pg_catalog.oid "
3889 " AND contype = 'c' "
3891 tbinfo->dobj.catId.oid);
3893 else if (g_fout->remoteVersion >= 70200)
3895 /* 7.2 did not have OIDs in pg_relcheck */
3896 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, "
3897 "rcname AS conname, "
3898 "'CHECK (' || rcsrc || ')' AS consrc "
3900 "WHERE rcrelid = '%u'::oid "
3902 tbinfo->dobj.catId.oid);
3904 else if (g_fout->remoteVersion >= 70100)
3906 appendPQExpBuffer(q, "SELECT tableoid, oid, "
3907 "rcname AS conname, "
3908 "'CHECK (' || rcsrc || ')' AS consrc "
3910 "WHERE rcrelid = '%u'::oid "
3912 tbinfo->dobj.catId.oid);
3916 /* no tableoid in 7.0 */
3917 appendPQExpBuffer(q, "SELECT "
3918 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
3919 "oid, rcname AS conname, "
3920 "'CHECK (' || rcsrc || ')' AS consrc "
3922 "WHERE rcrelid = '%u'::oid "
3924 tbinfo->dobj.catId.oid);
3926 res = PQexec(g_conn, q->data);
3927 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3929 numConstrs = PQntuples(res);
3930 if (numConstrs != tbinfo->ncheck)
3932 write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
3933 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
3934 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
3938 constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
3939 tbinfo->checkexprs = constrs;
3941 for (j = 0; j < numConstrs; j++)
3943 constrs[j].dobj.objType = DO_CONSTRAINT;
3944 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3945 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3946 AssignDumpId(&constrs[j].dobj);
3947 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
3948 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
3949 constrs[j].contable = tbinfo;
3950 constrs[j].condomain = NULL;
3951 constrs[j].contype = 'c';
3952 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
3953 constrs[j].conindex = 0;
3954 constrs[j].coninherited = false;
3955 constrs[j].separate = false;
3956 addObjectDependency(&tbinfo->dobj,
3957 constrs[j].dobj.dumpId);
3960 * If the constraint is inherited, this will be detected
3961 * later. We also detect later if the constraint must be
3962 * split out from the table definition.
3969 * Check to see if any columns are serial columns. Our first
3970 * quick filter is that it must be integer or bigint with a
3971 * default. If so, we scan to see if we found a sequence linked
3972 * to this column. If we did, mark the column and sequence
3975 for (j = 0; j < ntups; j++)
3978 * Note assumption that format_type will show these types as
3979 * exactly "integer" and "bigint" regardless of schema path.
3980 * This is correct in 7.3 but needs to be watched.
3982 if (strcmp(tbinfo->atttypnames[j], "integer") != 0 &&
3983 strcmp(tbinfo->atttypnames[j], "bigint") != 0)
3985 if (tbinfo->attrdefs[j] == NULL)
3987 for (k = 0; k < numTables; k++)
3989 TableInfo *seqinfo = &tblinfo[k];
3991 if (OidIsValid(seqinfo->owning_tab) &&
3992 seqinfo->owning_tab == tbinfo->dobj.catId.oid &&
3993 seqinfo->owning_col == j + 1)
3996 * Found a match. Copy the table's interesting and
3997 * dumpable flags to the sequence.
3999 tbinfo->attisserial[j] = true;
4000 seqinfo->interesting = tbinfo->interesting;
4001 seqinfo->dump = tbinfo->dump;
4008 destroyPQExpBuffer(q);
4015 * This routine is used to dump any comments associated with the
4016 * object handed to this routine. The routine takes a constant character
4017 * string for the target part of the comment-creation command, plus
4018 * the namespace and owner of the object (for labeling the ArchiveEntry),
4019 * plus catalog ID and subid which are the lookup key for pg_description,
4020 * plus the dump ID for the object (for setting a dependency).
4021 * If a matching pg_description entry is found, it is dumped.
4024 dumpComment(Archive *fout, const char *target,
4025 const char *namespace, const char *owner,
4026 CatalogId catalogId, int subid, DumpId dumpId)
4028 CommentItem *comments;
4031 /* Comments are SCHEMA not data */
4035 /* Search for comments associated with catalogId, using table */
4036 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
4039 /* Is there one matching the subid? */
4040 while (ncomments > 0)
4042 if (comments->objsubid == subid)
4048 /* If a comment exists, build COMMENT ON statement */
4051 PQExpBuffer query = createPQExpBuffer();
4053 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
4054 appendStringLiteral(query, comments->descr, false);
4055 appendPQExpBuffer(query, ";\n");
4057 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4058 target, namespace, owner, false,
4059 "COMMENT", query->data, "", NULL,
4063 destroyPQExpBuffer(query);
4068 * dumpTableComment --
4070 * As above, but dump comments for both the specified table (or view)
4074 dumpTableComment(Archive *fout, TableInfo *tbinfo,
4075 const char *reltypename)
4077 CommentItem *comments;
4082 /* Comments are SCHEMA not data */
4086 /* Search for comments associated with relation, using table */
4087 ncomments = findComments(fout,
4088 tbinfo->dobj.catId.tableoid,
4089 tbinfo->dobj.catId.oid,
4092 /* If comments exist, build COMMENT ON statements */
4096 query = createPQExpBuffer();
4097 target = createPQExpBuffer();
4099 while (ncomments > 0)
4101 const char *descr = comments->descr;
4102 int objsubid = comments->objsubid;
4106 resetPQExpBuffer(target);
4107 appendPQExpBuffer(target, "%s %s", reltypename,
4108 fmtId(tbinfo->dobj.name));
4110 resetPQExpBuffer(query);
4111 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4112 appendStringLiteral(query, descr, false);
4113 appendPQExpBuffer(query, ";\n");
4115 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4117 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
4118 false, "COMMENT", query->data, "", NULL,
4119 &(tbinfo->dobj.dumpId), 1,
4122 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
4124 resetPQExpBuffer(target);
4125 appendPQExpBuffer(target, "COLUMN %s.",
4126 fmtId(tbinfo->dobj.name));
4127 appendPQExpBuffer(target, "%s",
4128 fmtId(tbinfo->attnames[objsubid - 1]));
4130 resetPQExpBuffer(query);
4131 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4132 appendStringLiteral(query, descr, false);
4133 appendPQExpBuffer(query, ";\n");
4135 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4137 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
4138 false, "COMMENT", query->data, "", NULL,
4139 &(tbinfo->dobj.dumpId), 1,
4147 destroyPQExpBuffer(query);
4148 destroyPQExpBuffer(target);
4154 * Find the comment(s), if any, associated with the given object. All the
4155 * objsubid values associated with the given classoid/objoid are found with
4159 findComments(Archive *fout, Oid classoid, Oid objoid,
4160 CommentItem **items)
4162 /* static storage for table of comments */
4163 static CommentItem *comments = NULL;
4164 static int ncomments = -1;
4166 CommentItem *middle = NULL;
4171 /* Get comments if we didn't already */
4173 ncomments = collectComments(fout, &comments);
4176 * Pre-7.2, pg_description does not contain classoid, so
4177 * collectComments just stores a zero. If there's a collision on
4178 * object OID, well, you get duplicate comments.
4180 if (fout->remoteVersion < 70200)
4184 * Do binary search to find some item matching the object.
4187 high = &comments[ncomments - 1];
4190 middle = low + (high - low) / 2;
4192 if (classoid < middle->classoid)
4194 else if (classoid > middle->classoid)
4196 else if (objoid < middle->objoid)
4198 else if (objoid > middle->objoid)
4201 break; /* found a match */
4204 if (low > high) /* no matches */
4211 * Now determine how many items match the object. The search loop
4212 * invariant still holds: only items between low and high inclusive
4216 while (middle > low)
4218 if (classoid != middle[-1].classoid ||
4219 objoid != middle[-1].objoid)
4228 while (middle <= high)
4230 if (classoid != middle->classoid ||
4231 objoid != middle->objoid)
4241 * collectComments --
4243 * Construct a table of all comments available for database objects.
4244 * We used to do per-object queries for the comments, but it's much faster
4245 * to pull them all over at once, and on most databases the memory cost
4248 * The table is sorted by classoid/objid/objsubid for speed in lookup.
4251 collectComments(Archive *fout, CommentItem **items)
4261 CommentItem *comments;
4264 * Note we do NOT change source schema here; preserve the caller's
4268 query = createPQExpBuffer();
4270 if (fout->remoteVersion >= 70300)
4272 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4273 "FROM pg_catalog.pg_description "
4274 "ORDER BY classoid, objoid, objsubid");
4276 else if (fout->remoteVersion >= 70200)
4278 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4279 "FROM pg_description "
4280 "ORDER BY classoid, objoid, objsubid");
4284 /* Note: this will fail to find attribute comments in pre-7.2... */
4285 appendPQExpBuffer(query, "SELECT description, 0 as classoid, objoid, 0 as objsubid "
4286 "FROM pg_description "
4290 res = PQexec(g_conn, query->data);
4291 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4293 /* Construct lookup table containing OIDs in numeric form */
4295 i_description = PQfnumber(res, "description");
4296 i_classoid = PQfnumber(res, "classoid");
4297 i_objoid = PQfnumber(res, "objoid");
4298 i_objsubid = PQfnumber(res, "objsubid");
4300 ntups = PQntuples(res);
4302 comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
4304 for (i = 0; i < ntups; i++)
4306 comments[i].descr = PQgetvalue(res, i, i_description);
4307 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
4308 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
4309 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
4312 /* Do NOT free the PGresult since we are keeping pointers into it */
4313 destroyPQExpBuffer(query);
4320 * dumpDumpableObject
4322 * This routine and its subsidiaries are responsible for creating
4323 * ArchiveEntries (TOC objects) for each object to be dumped.
4326 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
4328 switch (dobj->objType)
4331 dumpNamespace(fout, (NamespaceInfo *) dobj);
4334 dumpType(fout, (TypeInfo *) dobj);
4337 dumpFunc(fout, (FuncInfo *) dobj);
4340 dumpAgg(fout, (AggInfo *) dobj);
4343 dumpOpr(fout, (OprInfo *) dobj);
4346 dumpOpclass(fout, (OpclassInfo *) dobj);
4349 dumpConversion(fout, (ConvInfo *) dobj);
4352 dumpTable(fout, (TableInfo *) dobj);
4355 dumpAttrDef(fout, (AttrDefInfo *) dobj);
4358 dumpIndex(fout, (IndxInfo *) dobj);
4361 dumpRule(fout, (RuleInfo *) dobj);
4364 dumpTrigger(fout, (TriggerInfo *) dobj);
4367 dumpConstraint(fout, (ConstraintInfo *) dobj);
4369 case DO_FK_CONSTRAINT:
4370 dumpConstraint(fout, (ConstraintInfo *) dobj);
4373 dumpProcLang(fout, (ProcLangInfo *) dobj);
4376 dumpCast(fout, (CastInfo *) dobj);
4379 dumpTableData(fout, (TableDataInfo *) dobj);
4382 /* table rowtypes are never dumped separately */
4385 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4386 dobj->name, NULL, "",
4387 false, "BLOBS", "", "", NULL,
4396 * writes out to fout the queries to recreate a user-defined namespace
4399 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
4405 /* skip if not to be dumped */
4406 if (!nspinfo->dump || dataOnly)
4409 /* don't dump dummy namespace from pre-7.3 source */
4410 if (strlen(nspinfo->dobj.name) == 0)
4413 q = createPQExpBuffer();
4414 delq = createPQExpBuffer();
4416 qnspname = strdup(fmtId(nspinfo->dobj.name));
4419 * Note that ownership is shown in the AUTHORIZATION clause, while the
4420 * archive entry is listed with empty owner (causing it to be emitted
4421 * with SET SESSION AUTHORIZATION DEFAULT). This seems the best way of
4422 * dealing with schemas owned by users without CREATE SCHEMA
4423 * privilege. Further hacking has to be applied for --no-owner mode,
4426 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
4428 appendPQExpBuffer(q, "CREATE SCHEMA %s AUTHORIZATION %s",
4429 qnspname, fmtId(nspinfo->usename));
4431 /* Add tablespace qualifier, if not default */
4432 if (strlen(nspinfo->nsptablespace) != 0)
4433 appendPQExpBuffer(q, " TABLESPACE %s",
4434 fmtId(nspinfo->nsptablespace));
4436 appendPQExpBuffer(q, ";\n");
4438 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
4440 NULL, strcmp(nspinfo->dobj.name, "public") == 0 ? nspinfo->usename : "",
4441 false, "SCHEMA", q->data, delq->data, NULL,
4442 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
4445 /* Dump Schema Comments */
4446 resetPQExpBuffer(q);
4447 appendPQExpBuffer(q, "SCHEMA %s", qnspname);
4448 dumpComment(fout, q->data,
4449 NULL, nspinfo->usename,
4450 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
4452 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
4453 qnspname, nspinfo->dobj.name, NULL,
4454 nspinfo->usename, nspinfo->nspacl);
4458 destroyPQExpBuffer(q);
4459 destroyPQExpBuffer(delq);
4464 * writes out to fout the queries to recreate a user-defined type
4467 dumpType(Archive *fout, TypeInfo *tinfo)
4469 /* Dump only types in dumpable namespaces */
4470 if (!tinfo->dobj.namespace->dump || dataOnly)
4473 /* skip complex types, except for standalone composite types */
4474 /* (note: this test should now be unnecessary) */
4475 if (OidIsValid(tinfo->typrelid) && tinfo->typrelkind != 'c')
4478 /* skip undefined placeholder types */
4479 if (!tinfo->isDefined)
4482 /* skip all array types that start w/ underscore */
4483 if ((tinfo->dobj.name[0] == '_') &&
4484 OidIsValid(tinfo->typelem))
4487 /* Dump out in proper style */
4488 if (tinfo->typtype == 'b')
4489 dumpBaseType(fout, tinfo);
4490 else if (tinfo->typtype == 'd')
4491 dumpDomain(fout, tinfo);
4492 else if (tinfo->typtype == 'c')
4493 dumpCompositeType(fout, tinfo);
4498 * writes out to fout the queries to recreate a user-defined base type
4501 dumpBaseType(Archive *fout, TypeInfo *tinfo)
4503 PQExpBuffer q = createPQExpBuffer();
4504 PQExpBuffer delq = createPQExpBuffer();
4505 PQExpBuffer query = createPQExpBuffer();
4525 /* Set proper schema search path so regproc references list correctly */
4526 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4528 /* Fetch type-specific details */
4529 if (fout->remoteVersion >= 80000)
4531 appendPQExpBuffer(query, "SELECT typlen, "
4532 "typinput, typoutput, typreceive, typsend, "
4534 "typinput::pg_catalog.oid as typinputoid, "
4535 "typoutput::pg_catalog.oid as typoutputoid, "
4536 "typreceive::pg_catalog.oid as typreceiveoid, "
4537 "typsend::pg_catalog.oid as typsendoid, "
4538 "typanalyze::pg_catalog.oid as typanalyzeoid, "
4539 "typdelim, typdefault, typbyval, typalign, "
4541 "FROM pg_catalog.pg_type "
4542 "WHERE oid = '%u'::pg_catalog.oid",
4543 tinfo->dobj.catId.oid);
4545 else if (fout->remoteVersion >= 70400)
4547 appendPQExpBuffer(query, "SELECT typlen, "
4548 "typinput, typoutput, typreceive, typsend, "
4549 "'-' as typanalyze, "
4550 "typinput::pg_catalog.oid as typinputoid, "
4551 "typoutput::pg_catalog.oid as typoutputoid, "
4552 "typreceive::pg_catalog.oid as typreceiveoid, "
4553 "typsend::pg_catalog.oid as typsendoid, "
4554 "0 as typanalyzeoid, "
4555 "typdelim, typdefault, typbyval, typalign, "
4557 "FROM pg_catalog.pg_type "
4558 "WHERE oid = '%u'::pg_catalog.oid",
4559 tinfo->dobj.catId.oid);
4561 else if (fout->remoteVersion >= 70300)
4563 appendPQExpBuffer(query, "SELECT typlen, "
4564 "typinput, typoutput, "
4565 "'-' as typreceive, '-' as typsend, "
4566 "'-' as typanalyze, "
4567 "typinput::pg_catalog.oid as typinputoid, "
4568 "typoutput::pg_catalog.oid as typoutputoid, "
4569 "0 as typreceiveoid, 0 as typsendoid, "
4570 "0 as typanalyzeoid, "
4571 "typdelim, typdefault, typbyval, typalign, "
4573 "FROM pg_catalog.pg_type "
4574 "WHERE oid = '%u'::pg_catalog.oid",
4575 tinfo->dobj.catId.oid);
4577 else if (fout->remoteVersion >= 70100)
4580 * Note: although pre-7.3 catalogs contain typreceive and typsend,
4581 * ignore them because they are not right.
4583 appendPQExpBuffer(query, "SELECT typlen, "
4584 "typinput, typoutput, "
4585 "'-' as typreceive, '-' as typsend, "
4586 "'-' as typanalyze, "
4587 "typinput::oid as typinputoid, "
4588 "typoutput::oid as typoutputoid, "
4589 "0 as typreceiveoid, 0 as typsendoid, "
4590 "0 as typanalyzeoid, "
4591 "typdelim, typdefault, typbyval, typalign, "
4594 "WHERE oid = '%u'::oid",
4595 tinfo->dobj.catId.oid);
4599 appendPQExpBuffer(query, "SELECT typlen, "
4600 "typinput, typoutput, "
4601 "'-' as typreceive, '-' as typsend, "
4602 "'-' as typanalyze, "
4603 "typinput::oid as typinputoid, "
4604 "typoutput::oid as typoutputoid, "
4605 "0 as typreceiveoid, 0 as typsendoid, "
4606 "0 as typanalyzeoid, "
4607 "typdelim, typdefault, typbyval, typalign, "
4608 "'p'::char as typstorage "
4610 "WHERE oid = '%u'::oid",
4611 tinfo->dobj.catId.oid);
4614 res = PQexec(g_conn, query->data);
4615 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4617 /* Expecting a single result only */
4618 ntups = PQntuples(res);
4621 write_msg(NULL, "Got %d rows instead of one from: %s",
4622 ntups, query->data);
4626 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
4627 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
4628 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
4629 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
4630 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
4631 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
4632 typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
4633 typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
4634 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
4635 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
4636 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
4637 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
4638 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4641 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4642 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
4643 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
4644 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
4647 * DROP must be fully qualified in case same name appears in
4650 appendPQExpBuffer(delq, "DROP TYPE %s.",
4651 fmtId(tinfo->dobj.namespace->dobj.name));
4652 appendPQExpBuffer(delq, "%s CASCADE;\n",
4653 fmtId(tinfo->dobj.name));
4655 appendPQExpBuffer(q,
4656 "CREATE TYPE %s (\n"
4657 " INTERNALLENGTH = %s",
4658 fmtId(tinfo->dobj.name),
4659 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
4661 if (fout->remoteVersion >= 70300)
4663 /* regproc result is correctly quoted as of 7.3 */
4664 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
4665 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
4666 if (OidIsValid(typreceiveoid))
4667 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
4668 if (OidIsValid(typsendoid))
4669 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
4670 if (OidIsValid(typanalyzeoid))
4671 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
4675 /* regproc delivers an unquoted name before 7.3 */
4676 /* cannot combine these because fmtId uses static result area */
4677 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
4678 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
4679 /* no chance that receive/send/analyze need be printed */
4682 if (typdefault != NULL)
4684 appendPQExpBuffer(q, ",\n DEFAULT = ");
4685 appendStringLiteral(q, typdefault, true);
4692 /* reselect schema in case changed by function dump */
4693 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4694 elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
4695 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
4699 if (typdelim && strcmp(typdelim, ",") != 0)
4701 appendPQExpBuffer(q, ",\n DELIMITER = ");
4702 appendStringLiteral(q, typdelim, true);
4705 if (strcmp(typalign, "c") == 0)
4706 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
4707 else if (strcmp(typalign, "s") == 0)
4708 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
4709 else if (strcmp(typalign, "i") == 0)
4710 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
4711 else if (strcmp(typalign, "d") == 0)
4712 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
4714 if (strcmp(typstorage, "p") == 0)
4715 appendPQExpBuffer(q, ",\n STORAGE = plain");
4716 else if (strcmp(typstorage, "e") == 0)
4717 appendPQExpBuffer(q, ",\n STORAGE = external");
4718 else if (strcmp(typstorage, "x") == 0)
4719 appendPQExpBuffer(q, ",\n STORAGE = extended");
4720 else if (strcmp(typstorage, "m") == 0)
4721 appendPQExpBuffer(q, ",\n STORAGE = main");
4723 if (strcmp(typbyval, "t") == 0)
4724 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
4726 appendPQExpBuffer(q, "\n);\n");
4728 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4730 tinfo->dobj.namespace->dobj.name,
4731 tinfo->usename, false,
4732 "TYPE", q->data, delq->data, NULL,
4733 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4736 /* Dump Type Comments */
4737 resetPQExpBuffer(q);
4739 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4740 dumpComment(fout, q->data,
4741 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4742 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4745 destroyPQExpBuffer(q);
4746 destroyPQExpBuffer(delq);
4747 destroyPQExpBuffer(query);
4752 * writes out to fout the queries to recreate a user-defined domain
4755 dumpDomain(Archive *fout, TypeInfo *tinfo)
4757 PQExpBuffer q = createPQExpBuffer();
4758 PQExpBuffer delq = createPQExpBuffer();
4759 PQExpBuffer query = createPQExpBuffer();
4767 /* Set proper schema search path so type references list correctly */
4768 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4770 /* Fetch domain specific details */
4771 /* We assume here that remoteVersion must be at least 70300 */
4772 appendPQExpBuffer(query, "SELECT typnotnull, "
4773 "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
4775 "FROM pg_catalog.pg_type "
4776 "WHERE oid = '%u'::pg_catalog.oid",
4777 tinfo->dobj.catId.oid);
4779 res = PQexec(g_conn, query->data);
4780 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4782 /* Expecting a single result only */
4783 ntups = PQntuples(res);
4786 write_msg(NULL, "Got %d rows instead of one from: %s",
4787 ntups, query->data);
4791 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
4792 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
4793 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4796 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4798 appendPQExpBuffer(q,
4799 "CREATE DOMAIN %s AS %s",
4800 fmtId(tinfo->dobj.name),
4803 if (typnotnull[0] == 't')
4804 appendPQExpBuffer(q, " NOT NULL");
4807 appendPQExpBuffer(q, " DEFAULT %s", typdefault);
4812 * Add any CHECK constraints for the domain
4814 for (i = 0; i < tinfo->nDomChecks; i++)
4816 ConstraintInfo *domcheck = &(tinfo->domChecks[i]);
4818 if (!domcheck->separate)
4819 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
4820 fmtId(domcheck->dobj.name), domcheck->condef);
4823 appendPQExpBuffer(q, ";\n");
4826 * DROP must be fully qualified in case same name appears in
4829 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
4830 fmtId(tinfo->dobj.namespace->dobj.name));
4831 appendPQExpBuffer(delq, "%s;\n",
4832 fmtId(tinfo->dobj.name));
4834 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4836 tinfo->dobj.namespace->dobj.name,
4837 tinfo->usename, false,
4838 "DOMAIN", q->data, delq->data, NULL,
4839 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4842 /* Dump Domain Comments */
4843 resetPQExpBuffer(q);
4845 appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->dobj.name));
4846 dumpComment(fout, q->data,
4847 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4848 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4850 destroyPQExpBuffer(q);
4851 destroyPQExpBuffer(delq);
4852 destroyPQExpBuffer(query);
4857 * writes out to fout the queries to recreate a user-defined stand-alone
4861 dumpCompositeType(Archive *fout, TypeInfo *tinfo)
4863 PQExpBuffer q = createPQExpBuffer();
4864 PQExpBuffer delq = createPQExpBuffer();
4865 PQExpBuffer query = createPQExpBuffer();
4872 /* Set proper schema search path so type references list correctly */
4873 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4875 /* Fetch type specific details */
4876 /* We assume here that remoteVersion must be at least 70300 */
4878 appendPQExpBuffer(query, "SELECT a.attname, "
4879 "pg_catalog.format_type(a.atttypid, a.atttypmod) as atttypdefn "
4880 "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
4881 "WHERE t.oid = '%u'::pg_catalog.oid "
4882 "AND a.attrelid = t.typrelid "
4883 "AND NOT a.attisdropped "
4884 "ORDER BY a.attnum ",
4885 tinfo->dobj.catId.oid);
4887 res = PQexec(g_conn, query->data);
4888 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4890 /* Expecting at least a single result */
4891 ntups = PQntuples(res);
4894 write_msg(NULL, "query yielded no rows: %s\n", query->data);
4898 i_attname = PQfnumber(res, "attname");
4899 i_atttypdefn = PQfnumber(res, "atttypdefn");
4901 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
4902 fmtId(tinfo->dobj.name));
4904 for (i = 0; i < ntups; i++)
4909 attname = PQgetvalue(res, i, i_attname);
4910 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
4912 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
4914 appendPQExpBuffer(q, ",");
4916 appendPQExpBuffer(q, "\n);\n");
4919 * DROP must be fully qualified in case same name appears in
4922 appendPQExpBuffer(delq, "DROP TYPE %s.",
4923 fmtId(tinfo->dobj.namespace->dobj.name));
4924 appendPQExpBuffer(delq, "%s;\n",
4925 fmtId(tinfo->dobj.name));
4927 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4929 tinfo->dobj.namespace->dobj.name,
4930 tinfo->usename, false,
4931 "TYPE", q->data, delq->data, NULL,
4932 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4936 /* Dump Type Comments */
4937 resetPQExpBuffer(q);
4939 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4940 dumpComment(fout, q->data,
4941 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4942 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4945 destroyPQExpBuffer(q);
4946 destroyPQExpBuffer(delq);
4947 destroyPQExpBuffer(query);
4952 * writes out to fout the queries to recreate a user-defined
4953 * procedural language
4956 dumpProcLang(Archive *fout, ProcLangInfo *plang)
4962 FuncInfo *validatorInfo = NULL;
4968 * Current theory is to dump PLs iff their underlying functions will
4969 * be dumped (are in a dumpable namespace, or have a non-system OID in
4970 * pre-7.3 databases). Actually, we treat the PL itself as being in
4971 * the underlying function's namespace, though it isn't really. This
4972 * avoids searchpath problems for the HANDLER clause.
4974 * If the underlying function is in the pg_catalog namespace, we won't
4975 * have loaded it into finfo[] at all; therefore, treat failure to
4976 * find it in finfo[] as indicating we shouldn't dump it, not as an
4977 * error condition. Ditto for the validator.
4980 funcInfo = findFuncByOid(plang->lanplcallfoid);
4981 if (funcInfo == NULL)
4984 if (!funcInfo->dobj.namespace->dump)
4987 if (OidIsValid(plang->lanvalidator))
4989 validatorInfo = findFuncByOid(plang->lanvalidator);
4990 if (validatorInfo == NULL)
4994 defqry = createPQExpBuffer();
4995 delqry = createPQExpBuffer();
4997 qlanname = strdup(fmtId(plang->dobj.name));
4999 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
5002 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
5003 plang->lanpltrusted ? "TRUSTED " : "",
5005 appendPQExpBuffer(defqry, " HANDLER %s",
5006 fmtId(funcInfo->dobj.name));
5007 if (OidIsValid(plang->lanvalidator))
5009 appendPQExpBuffer(defqry, " VALIDATOR ");
5010 /* Cope with possibility that validator is in different schema */
5011 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
5012 appendPQExpBuffer(defqry, "%s.",
5013 fmtId(validatorInfo->dobj.namespace->dobj.name));
5014 appendPQExpBuffer(defqry, "%s",
5015 fmtId(validatorInfo->dobj.name));
5017 appendPQExpBuffer(defqry, ";\n");
5019 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
5021 funcInfo->dobj.namespace->dobj.name, "",
5022 false, "PROCEDURAL LANGUAGE",
5023 defqry->data, delqry->data, NULL,
5024 plang->dobj.dependencies, plang->dobj.nDeps,
5027 /* Dump Proc Lang Comments */
5028 resetPQExpBuffer(defqry);
5030 appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
5031 dumpComment(fout, defqry->data,
5033 plang->dobj.catId, 0, plang->dobj.dumpId);
5035 if (plang->lanpltrusted)
5036 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
5037 qlanname, plang->dobj.name,
5038 funcInfo->dobj.namespace->dobj.name,
5039 NULL, plang->lanacl);
5043 destroyPQExpBuffer(defqry);
5044 destroyPQExpBuffer(delqry);
5048 * format_function_signature: generate function name and argument list
5050 * The argument type names are qualified if needed. The function name
5051 * is never qualified.
5053 * argnames may be NULL if no names are available.
5056 format_function_signature(FuncInfo *finfo, char **argnames,
5062 initPQExpBuffer(&fn);
5064 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5066 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
5067 for (j = 0; j < finfo->nargs; j++)
5072 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
5074 argname = argnames ? argnames[j] : (char *) NULL;
5075 if (argname && argname[0] == '\0')
5078 appendPQExpBuffer(&fn, "%s%s%s%s",
5079 (j > 0) ? ", " : "",
5080 argname ? fmtId(argname) : "",
5085 appendPQExpBuffer(&fn, ")");
5092 * dump out one function
5095 dumpFunc(Archive *fout, FuncInfo *finfo)
5114 char **argnamearray = NULL;
5116 /* Dump only funcs in dumpable namespaces */
5117 if (!finfo->dobj.namespace->dump || dataOnly)
5120 query = createPQExpBuffer();
5121 q = createPQExpBuffer();
5122 delqry = createPQExpBuffer();
5123 asPart = createPQExpBuffer();
5125 /* Set proper schema search path so type references list correctly */
5126 selectSourceSchema(finfo->dobj.namespace->dobj.name);
5128 /* Fetch function-specific details */
5129 if (g_fout->remoteVersion >= 80000)
5131 appendPQExpBuffer(query,
5132 "SELECT proretset, prosrc, probin, "
5134 "provolatile, proisstrict, prosecdef, "
5135 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5136 "FROM pg_catalog.pg_proc "
5137 "WHERE oid = '%u'::pg_catalog.oid",
5138 finfo->dobj.catId.oid);
5140 else if (g_fout->remoteVersion >= 70300)
5142 appendPQExpBuffer(query,
5143 "SELECT proretset, prosrc, probin, "
5144 "null::text as proargnames, "
5145 "provolatile, proisstrict, prosecdef, "
5146 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5147 "FROM pg_catalog.pg_proc "
5148 "WHERE oid = '%u'::pg_catalog.oid",
5149 finfo->dobj.catId.oid);
5151 else if (g_fout->remoteVersion >= 70100)
5153 appendPQExpBuffer(query,
5154 "SELECT proretset, prosrc, probin, "
5155 "null::text as proargnames, "
5156 "case when proiscachable then 'i' else 'v' end as provolatile, "
5158 "'f'::boolean as prosecdef, "
5159 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5161 "WHERE oid = '%u'::oid",
5162 finfo->dobj.catId.oid);
5166 appendPQExpBuffer(query,
5167 "SELECT proretset, prosrc, probin, "
5168 "null::text as proargnames, "
5169 "case when proiscachable then 'i' else 'v' end as provolatile, "
5170 "'f'::boolean as proisstrict, "
5171 "'f'::boolean as prosecdef, "
5172 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5174 "WHERE oid = '%u'::oid",
5175 finfo->dobj.catId.oid);
5178 res = PQexec(g_conn, query->data);
5179 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5181 /* Expecting a single result only */
5182 ntups = PQntuples(res);
5185 write_msg(NULL, "Got %d rows instead of one from: %s",
5186 ntups, query->data);
5190 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
5191 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
5192 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
5193 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
5194 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
5195 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
5196 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
5197 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
5200 * See backend/commands/define.c for details of how the 'AS' clause is
5203 if (strcmp(probin, "-") != 0)
5205 appendPQExpBuffer(asPart, "AS ");
5206 appendStringLiteral(asPart, probin, true);
5207 if (strcmp(prosrc, "-") != 0)
5209 appendPQExpBuffer(asPart, ", ");
5212 * where we have bin, use dollar quoting if allowed and src
5213 * contains quote or backslash; else use regular quoting.
5215 if (disable_dollar_quoting)
5216 appendStringLiteral(asPart, prosrc, false);
5218 appendStringLiteralDQOpt(asPart, prosrc, false, NULL);
5223 if (strcmp(prosrc, "-") != 0)
5225 appendPQExpBuffer(asPart, "AS ");
5226 /* with no bin, dollar quote src unconditionally if allowed */
5227 if (disable_dollar_quoting)
5228 appendStringLiteral(asPart, prosrc, false);
5230 appendStringLiteralDQ(asPart, prosrc, NULL);
5234 if (proargnames && *proargnames)
5238 if (!parsePGArray(proargnames, &argnamearray, &nitems) ||
5239 nitems != finfo->nargs)
5241 write_msg(NULL, "WARNING: could not parse proargnames array\n");
5244 argnamearray = NULL;
5248 funcsig = format_function_signature(finfo, argnamearray, true);
5249 funcsig_tag = format_function_signature(finfo, NULL, false);
5252 * DROP must be fully qualified in case same name appears in
5255 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
5256 fmtId(finfo->dobj.namespace->dobj.name),
5259 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
5261 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
5262 appendPQExpBuffer(q, "RETURNS %s%s\n %s\n LANGUAGE %s",
5263 (proretset[0] == 't') ? "SETOF " : "",
5270 if (provolatile[0] != PROVOLATILE_VOLATILE)
5272 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
5273 appendPQExpBuffer(q, " IMMUTABLE");
5274 else if (provolatile[0] == PROVOLATILE_STABLE)
5275 appendPQExpBuffer(q, " STABLE");
5276 else if (provolatile[0] != PROVOLATILE_VOLATILE)
5278 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
5284 if (proisstrict[0] == 't')
5285 appendPQExpBuffer(q, " STRICT");
5287 if (prosecdef[0] == 't')
5288 appendPQExpBuffer(q, " SECURITY DEFINER");
5290 appendPQExpBuffer(q, ";\n");
5292 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
5294 finfo->dobj.namespace->dobj.name,
5295 finfo->usename, false,
5296 "FUNCTION", q->data, delqry->data, NULL,
5297 finfo->dobj.dependencies, finfo->dobj.nDeps,
5300 /* Dump Function Comments */
5301 resetPQExpBuffer(q);
5302 appendPQExpBuffer(q, "FUNCTION %s", funcsig);
5303 dumpComment(fout, q->data,
5304 finfo->dobj.namespace->dobj.name, finfo->usename,
5305 finfo->dobj.catId, 0, finfo->dobj.dumpId);
5307 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
5308 funcsig, funcsig_tag,
5309 finfo->dobj.namespace->dobj.name,
5310 finfo->usename, finfo->proacl);
5314 destroyPQExpBuffer(query);
5315 destroyPQExpBuffer(q);
5316 destroyPQExpBuffer(delqry);
5317 destroyPQExpBuffer(asPart);
5326 * Dump a user-defined cast
5329 dumpCast(Archive *fout, CastInfo *cast)
5333 PQExpBuffer castsig;
5334 FuncInfo *funcInfo = NULL;
5335 TypeInfo *sourceInfo;
5336 TypeInfo *targetInfo;
5341 if (OidIsValid(cast->castfunc))
5343 funcInfo = findFuncByOid(cast->castfunc);
5344 if (funcInfo == NULL)
5349 * As per discussion we dump casts if one or more of the underlying
5350 * objects (the conversion function and the two data types) are not
5351 * builtin AND if all of the non-builtin objects namespaces are
5352 * included in the dump. Builtin meaning, the namespace name does not
5355 sourceInfo = findTypeByOid(cast->castsource);
5356 targetInfo = findTypeByOid(cast->casttarget);
5358 if (sourceInfo == NULL || targetInfo == NULL)
5362 * Skip this cast if all objects are from pg_
5364 if ((funcInfo == NULL ||
5365 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
5366 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
5367 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
5371 * Skip cast if function isn't from pg_ and that namespace is not
5375 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5376 !funcInfo->dobj.namespace->dump)
5380 * Same for the Source type
5382 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5383 !sourceInfo->dobj.namespace->dump)
5387 * and the target type.
5389 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5390 !targetInfo->dobj.namespace->dump)
5393 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
5394 selectSourceSchema("pg_catalog");
5396 defqry = createPQExpBuffer();
5397 delqry = createPQExpBuffer();
5398 castsig = createPQExpBuffer();
5400 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
5401 getFormattedTypeName(cast->castsource, zeroAsNone),
5402 getFormattedTypeName(cast->casttarget, zeroAsNone));
5404 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
5405 getFormattedTypeName(cast->castsource, zeroAsNone),
5406 getFormattedTypeName(cast->casttarget, zeroAsNone));
5408 if (!OidIsValid(cast->castfunc))
5409 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
5413 * Always qualify the function name, in case it is not in
5414 * pg_catalog schema (format_function_signature won't qualify it).
5416 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
5417 fmtId(funcInfo->dobj.namespace->dobj.name));
5418 appendPQExpBuffer(defqry, "%s",
5419 format_function_signature(funcInfo, NULL, true));
5422 if (cast->castcontext == 'a')
5423 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
5424 else if (cast->castcontext == 'i')
5425 appendPQExpBuffer(defqry, " AS IMPLICIT");
5426 appendPQExpBuffer(defqry, ";\n");
5428 appendPQExpBuffer(castsig, "CAST (%s AS %s)",
5429 getFormattedTypeName(cast->castsource, zeroAsNone),
5430 getFormattedTypeName(cast->casttarget, zeroAsNone));
5432 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
5435 false, "CAST", defqry->data, delqry->data, NULL,
5436 cast->dobj.dependencies, cast->dobj.nDeps,
5439 /* Dump Cast Comments */
5440 resetPQExpBuffer(defqry);
5441 appendPQExpBuffer(defqry, "CAST (%s AS %s)",
5442 getFormattedTypeName(cast->castsource, zeroAsNone),
5443 getFormattedTypeName(cast->casttarget, zeroAsNone));
5444 dumpComment(fout, defqry->data,
5446 cast->dobj.catId, 0, cast->dobj.dumpId);
5448 destroyPQExpBuffer(defqry);
5449 destroyPQExpBuffer(delqry);
5450 destroyPQExpBuffer(castsig);
5455 * write out a single operator definition
5458 dumpOpr(Archive *fout, OprInfo *oprinfo)
5464 PQExpBuffer details;
5495 /* Dump only operators in dumpable namespaces */
5496 if (!oprinfo->dobj.namespace->dump || dataOnly)
5500 * some operators are invalid because they were the result of user
5501 * defining operators before commutators exist
5503 if (!OidIsValid(oprinfo->oprcode))
5506 query = createPQExpBuffer();
5507 q = createPQExpBuffer();
5508 delq = createPQExpBuffer();
5509 oprid = createPQExpBuffer();
5510 details = createPQExpBuffer();
5512 /* Make sure we are in proper schema so regoperator works correctly */
5513 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
5515 if (g_fout->remoteVersion >= 70300)
5517 appendPQExpBuffer(query, "SELECT oprkind, "
5518 "oprcode::pg_catalog.regprocedure, "
5519 "oprleft::pg_catalog.regtype, "
5520 "oprright::pg_catalog.regtype, "
5521 "oprcom::pg_catalog.regoperator, "
5522 "oprnegate::pg_catalog.regoperator, "
5523 "oprrest::pg_catalog.regprocedure, "
5524 "oprjoin::pg_catalog.regprocedure, "
5526 "oprlsortop::pg_catalog.regoperator, "
5527 "oprrsortop::pg_catalog.regoperator, "
5528 "oprltcmpop::pg_catalog.regoperator, "
5529 "oprgtcmpop::pg_catalog.regoperator "
5530 "from pg_catalog.pg_operator "
5531 "where oid = '%u'::pg_catalog.oid",
5532 oprinfo->dobj.catId.oid);
5534 else if (g_fout->remoteVersion >= 70100)
5536 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5537 "CASE WHEN oprleft = 0 THEN '-' "
5538 "ELSE format_type(oprleft, NULL) END as oprleft, "
5539 "CASE WHEN oprright = 0 THEN '-' "
5540 "ELSE format_type(oprright, NULL) END as oprright, "
5541 "oprcom, oprnegate, oprrest, oprjoin, "
5542 "oprcanhash, oprlsortop, oprrsortop, "
5543 "0 as oprltcmpop, 0 as oprgtcmpop "
5545 "where oid = '%u'::oid",
5546 oprinfo->dobj.catId.oid);
5550 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5551 "CASE WHEN oprleft = 0 THEN '-'::name "
5552 "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
5553 "CASE WHEN oprright = 0 THEN '-'::name "
5554 "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
5555 "oprcom, oprnegate, oprrest, oprjoin, "
5556 "oprcanhash, oprlsortop, oprrsortop, "
5557 "0 as oprltcmpop, 0 as oprgtcmpop "
5559 "where oid = '%u'::oid",
5560 oprinfo->dobj.catId.oid);
5563 res = PQexec(g_conn, query->data);
5564 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5566 /* Expecting a single result only */
5567 ntups = PQntuples(res);
5570 write_msg(NULL, "Got %d rows instead of one from: %s",
5571 ntups, query->data);
5575 i_oprkind = PQfnumber(res, "oprkind");
5576 i_oprcode = PQfnumber(res, "oprcode");
5577 i_oprleft = PQfnumber(res, "oprleft");
5578 i_oprright = PQfnumber(res, "oprright");
5579 i_oprcom = PQfnumber(res, "oprcom");
5580 i_oprnegate = PQfnumber(res, "oprnegate");
5581 i_oprrest = PQfnumber(res, "oprrest");
5582 i_oprjoin = PQfnumber(res, "oprjoin");
5583 i_oprcanhash = PQfnumber(res, "oprcanhash");
5584 i_oprlsortop = PQfnumber(res, "oprlsortop");
5585 i_oprrsortop = PQfnumber(res, "oprrsortop");
5586 i_oprltcmpop = PQfnumber(res, "oprltcmpop");
5587 i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");
5589 oprkind = PQgetvalue(res, 0, i_oprkind);
5590 oprcode = PQgetvalue(res, 0, i_oprcode);
5591 oprleft = PQgetvalue(res, 0, i_oprleft);
5592 oprright = PQgetvalue(res, 0, i_oprright);
5593 oprcom = PQgetvalue(res, 0, i_oprcom);
5594 oprnegate = PQgetvalue(res, 0, i_oprnegate);
5595 oprrest = PQgetvalue(res, 0, i_oprrest);
5596 oprjoin = PQgetvalue(res, 0, i_oprjoin);
5597 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
5598 oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
5599 oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
5600 oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
5601 oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);
5603 appendPQExpBuffer(details, " PROCEDURE = %s",
5604 convertRegProcReference(oprcode));
5606 appendPQExpBuffer(oprid, "%s (",
5607 oprinfo->dobj.name);
5610 * right unary means there's a left arg and left unary means there's a
5613 if (strcmp(oprkind, "r") == 0 ||
5614 strcmp(oprkind, "b") == 0)
5616 if (g_fout->remoteVersion >= 70100)
5619 name = fmtId(oprleft);
5620 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
5621 appendPQExpBuffer(oprid, "%s", name);
5624 appendPQExpBuffer(oprid, "NONE");
5626 if (strcmp(oprkind, "l") == 0 ||
5627 strcmp(oprkind, "b") == 0)
5629 if (g_fout->remoteVersion >= 70100)
5632 name = fmtId(oprright);
5633 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
5634 appendPQExpBuffer(oprid, ", %s)", name);
5637 appendPQExpBuffer(oprid, ", NONE)");
5639 name = convertOperatorReference(oprcom);
5641 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
5643 name = convertOperatorReference(oprnegate);
5645 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
5647 if (strcmp(oprcanhash, "t") == 0)
5648 appendPQExpBuffer(details, ",\n HASHES");
5650 name = convertRegProcReference(oprrest);
5652 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
5654 name = convertRegProcReference(oprjoin);
5656 appendPQExpBuffer(details, ",\n JOIN = %s", name);
5658 name = convertOperatorReference(oprlsortop);
5660 appendPQExpBuffer(details, ",\n SORT1 = %s", name);
5662 name = convertOperatorReference(oprrsortop);
5664 appendPQExpBuffer(details, ",\n SORT2 = %s", name);
5666 name = convertOperatorReference(oprltcmpop);
5668 appendPQExpBuffer(details, ",\n LTCMP = %s", name);
5670 name = convertOperatorReference(oprgtcmpop);
5672 appendPQExpBuffer(details, ",\n GTCMP = %s", name);
5675 * DROP must be fully qualified in case same name appears in
5678 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
5679 fmtId(oprinfo->dobj.namespace->dobj.name),
5682 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
5683 oprinfo->dobj.name, details->data);
5685 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
5687 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5688 false, "OPERATOR", q->data, delq->data, NULL,
5689 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
5692 /* Dump Operator Comments */
5693 resetPQExpBuffer(q);
5694 appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
5695 dumpComment(fout, q->data,
5696 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5697 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
5701 destroyPQExpBuffer(query);
5702 destroyPQExpBuffer(q);
5703 destroyPQExpBuffer(delq);
5704 destroyPQExpBuffer(oprid);
5705 destroyPQExpBuffer(details);
5709 * Convert a function reference obtained from pg_operator
5711 * Returns what to print, or NULL if function references is InvalidOid
5713 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
5714 * argument-types part. In prior versions, the input is a REGPROC display.
5717 convertRegProcReference(const char *proc)
5719 /* In all cases "-" means a null reference */
5720 if (strcmp(proc, "-") == 0)
5723 if (g_fout->remoteVersion >= 70300)
5729 name = strdup(proc);
5730 /* find non-double-quoted left paren */
5732 for (paren = name; *paren; paren++)
5734 if (*paren == '(' && !inquote)
5745 /* REGPROC before 7.3 does not quote its result */
5750 * Convert an operator cross-reference obtained from pg_operator
5752 * Returns what to print, or NULL to print nothing
5754 * In 7.3 the input is a REGOPERATOR display; we have to strip the
5755 * argument-types part. In prior versions, the input is just a
5756 * numeric OID, which we search our operator list for.
5759 convertOperatorReference(const char *opr)
5763 /* In all cases "0" means a null reference */
5764 if (strcmp(opr, "0") == 0)
5767 if (g_fout->remoteVersion >= 70300)
5774 /* find non-double-quoted left paren */
5776 for (paren = name; *paren; paren++)
5778 if (*paren == '(' && !inquote)
5789 oprInfo = findOprByOid(atooid(opr));
5790 if (oprInfo == NULL)
5792 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
5796 return oprInfo->dobj.name;
5801 * write out a single operator class definition
5804 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
5832 /* Dump only opclasses in dumpable namespaces */
5833 if (!opcinfo->dobj.namespace->dump || dataOnly)
5837 * XXX currently we do not implement dumping of operator classes from
5838 * pre-7.3 databases. This could be done but it seems not worth the
5841 if (g_fout->remoteVersion < 70300)
5844 query = createPQExpBuffer();
5845 q = createPQExpBuffer();
5846 delq = createPQExpBuffer();
5848 /* Make sure we are in proper schema so regoperator works correctly */
5849 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
5851 /* Get additional fields from the pg_opclass row */
5852 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
5853 "opckeytype::pg_catalog.regtype, "
5855 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
5856 "FROM pg_catalog.pg_opclass "
5857 "WHERE oid = '%u'::pg_catalog.oid",
5858 opcinfo->dobj.catId.oid);
5860 res = PQexec(g_conn, query->data);
5861 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5863 /* Expecting a single result only */
5864 ntups = PQntuples(res);
5867 write_msg(NULL, "Got %d rows instead of one from: %s",
5868 ntups, query->data);
5872 i_opcintype = PQfnumber(res, "opcintype");
5873 i_opckeytype = PQfnumber(res, "opckeytype");
5874 i_opcdefault = PQfnumber(res, "opcdefault");
5875 i_amname = PQfnumber(res, "amname");
5877 opcintype = PQgetvalue(res, 0, i_opcintype);
5878 opckeytype = PQgetvalue(res, 0, i_opckeytype);
5879 opcdefault = PQgetvalue(res, 0, i_opcdefault);
5880 /* amname will still be needed after we PQclear res */
5881 amname = strdup(PQgetvalue(res, 0, i_amname));
5884 * DROP must be fully qualified in case same name appears in
5887 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
5888 fmtId(opcinfo->dobj.namespace->dobj.name));
5889 appendPQExpBuffer(delq, ".%s",
5890 fmtId(opcinfo->dobj.name));
5891 appendPQExpBuffer(delq, " USING %s;\n",
5894 /* Build the fixed portion of the CREATE command */
5895 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
5896 fmtId(opcinfo->dobj.name));
5897 if (strcmp(opcdefault, "t") == 0)
5898 appendPQExpBuffer(q, "DEFAULT ");
5899 appendPQExpBuffer(q, "FOR TYPE %s USING %s AS\n ",
5905 if (strcmp(opckeytype, "-") != 0)
5907 appendPQExpBuffer(q, "STORAGE %s",
5915 * Now fetch and print the OPERATOR entries (pg_amop rows).
5917 resetPQExpBuffer(query);
5919 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
5920 "amopopr::pg_catalog.regoperator "
5921 "FROM pg_catalog.pg_amop "
5922 "WHERE amopclaid = '%u'::pg_catalog.oid "
5923 "ORDER BY amopstrategy",
5924 opcinfo->dobj.catId.oid);
5926 res = PQexec(g_conn, query->data);
5927 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5929 ntups = PQntuples(res);
5931 i_amopstrategy = PQfnumber(res, "amopstrategy");
5932 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
5933 i_amopopr = PQfnumber(res, "amopopr");
5935 for (i = 0; i < ntups; i++)
5937 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
5938 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
5939 amopopr = PQgetvalue(res, i, i_amopopr);
5942 appendPQExpBuffer(q, " ,\n ");
5944 appendPQExpBuffer(q, "OPERATOR %s %s",
5945 amopstrategy, amopopr);
5946 if (strcmp(amopreqcheck, "t") == 0)
5947 appendPQExpBuffer(q, " RECHECK");
5955 * Now fetch and print the FUNCTION entries (pg_amproc rows).
5957 resetPQExpBuffer(query);
5959 appendPQExpBuffer(query, "SELECT amprocnum, "
5960 "amproc::pg_catalog.regprocedure "
5961 "FROM pg_catalog.pg_amproc "
5962 "WHERE amopclaid = '%u'::pg_catalog.oid "
5963 "ORDER BY amprocnum",
5964 opcinfo->dobj.catId.oid);
5966 res = PQexec(g_conn, query->data);
5967 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5969 ntups = PQntuples(res);
5971 i_amprocnum = PQfnumber(res, "amprocnum");
5972 i_amproc = PQfnumber(res, "amproc");
5974 for (i = 0; i < ntups; i++)
5976 amprocnum = PQgetvalue(res, i, i_amprocnum);
5977 amproc = PQgetvalue(res, i, i_amproc);
5980 appendPQExpBuffer(q, " ,\n ");
5982 appendPQExpBuffer(q, "FUNCTION %s %s",
5990 appendPQExpBuffer(q, ";\n");
5992 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
5994 opcinfo->dobj.namespace->dobj.name, opcinfo->usename,
5995 false, "OPERATOR CLASS", q->data, delq->data, NULL,
5996 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
5999 /* Dump Operator Class Comments */
6000 resetPQExpBuffer(q);
6001 appendPQExpBuffer(q, "OPERATOR CLASS %s",
6002 fmtId(opcinfo->dobj.name));
6003 appendPQExpBuffer(q, " USING %s",
6005 dumpComment(fout, q->data,
6006 NULL, opcinfo->usename,
6007 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
6010 destroyPQExpBuffer(query);
6011 destroyPQExpBuffer(q);
6012 destroyPQExpBuffer(delq);
6017 * write out a single conversion definition
6020 dumpConversion(Archive *fout, ConvInfo *convinfo)
6025 PQExpBuffer details;
6029 int i_conforencoding;
6030 int i_contoencoding;
6033 const char *conname;
6034 const char *conforencoding;
6035 const char *contoencoding;
6036 const char *conproc;
6039 /* Dump only conversions in dumpable namespaces */
6040 if (!convinfo->dobj.namespace->dump || dataOnly)
6043 query = createPQExpBuffer();
6044 q = createPQExpBuffer();
6045 delq = createPQExpBuffer();
6046 details = createPQExpBuffer();
6048 /* Make sure we are in proper schema */
6049 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
6051 /* Get conversion-specific details */
6052 appendPQExpBuffer(query, "SELECT conname, "
6053 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
6054 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
6055 "conproc, condefault "
6056 "FROM pg_catalog.pg_conversion c "
6057 "WHERE c.oid = '%u'::pg_catalog.oid",
6058 convinfo->dobj.catId.oid);
6060 res = PQexec(g_conn, query->data);
6061 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6063 /* Expecting a single result only */
6064 ntups = PQntuples(res);
6067 write_msg(NULL, "Got %d rows instead of one from: %s",
6068 ntups, query->data);
6072 i_conname = PQfnumber(res, "conname");
6073 i_conforencoding = PQfnumber(res, "conforencoding");
6074 i_contoencoding = PQfnumber(res, "contoencoding");
6075 i_conproc = PQfnumber(res, "conproc");
6076 i_condefault = PQfnumber(res, "condefault");
6078 conname = PQgetvalue(res, 0, i_conname);
6079 conforencoding = PQgetvalue(res, 0, i_conforencoding);
6080 contoencoding = PQgetvalue(res, 0, i_contoencoding);
6081 conproc = PQgetvalue(res, 0, i_conproc);
6082 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
6085 * DROP must be fully qualified in case same name appears in
6088 appendPQExpBuffer(delq, "DROP CONVERSION %s",
6089 fmtId(convinfo->dobj.namespace->dobj.name));
6090 appendPQExpBuffer(delq, ".%s;\n",
6091 fmtId(convinfo->dobj.name));
6093 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
6094 (condefault) ? "DEFAULT " : "",
6095 fmtId(convinfo->dobj.name));
6096 appendStringLiteral(q, conforencoding, true);
6097 appendPQExpBuffer(q, " TO ");
6098 appendStringLiteral(q, contoencoding, true);
6099 /* regproc is automatically quoted in 7.3 and above */
6100 appendPQExpBuffer(q, " FROM %s;\n", conproc);
6102 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
6103 convinfo->dobj.name,
6104 convinfo->dobj.namespace->dobj.name, convinfo->usename,
6105 false, "CONVERSION", q->data, delq->data, NULL,
6106 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
6109 /* Dump Conversion Comments */
6110 resetPQExpBuffer(q);
6111 appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
6112 dumpComment(fout, q->data,
6113 convinfo->dobj.namespace->dobj.name, convinfo->usename,
6114 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
6118 destroyPQExpBuffer(query);
6119 destroyPQExpBuffer(q);
6120 destroyPQExpBuffer(delq);
6121 destroyPQExpBuffer(details);
6125 * format_aggregate_signature: generate aggregate name and argument list
6127 * The argument type names are qualified if needed. The aggregate name
6128 * is never qualified.
6131 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
6133 PQExpBufferData buf;
6135 initPQExpBuffer(&buf);
6137 appendPQExpBuffer(&buf, "%s",
6138 fmtId(agginfo->aggfn.dobj.name));
6140 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
6142 /* If using regtype or format_type, fmtbasetype is already quoted */
6143 if (fout->remoteVersion >= 70100)
6145 if (agginfo->anybasetype)
6146 appendPQExpBuffer(&buf, "(*)");
6148 appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
6152 if (agginfo->anybasetype)
6153 appendPQExpBuffer(&buf, "(*)");
6155 appendPQExpBuffer(&buf, "(%s)",
6156 fmtId(agginfo->fmtbasetype));
6164 * write out a single aggregate definition
6167 dumpAgg(Archive *fout, AggInfo *agginfo)
6172 PQExpBuffer details;
6184 const char *aggtransfn;
6185 const char *aggfinalfn;
6186 const char *aggtranstype;
6187 const char *agginitval;
6190 /* Dump only aggs in dumpable namespaces */
6191 if (!agginfo->aggfn.dobj.namespace->dump || dataOnly)
6194 query = createPQExpBuffer();
6195 q = createPQExpBuffer();
6196 delq = createPQExpBuffer();
6197 details = createPQExpBuffer();
6199 /* Make sure we are in proper schema */
6200 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
6202 /* Get aggregate-specific details */
6203 if (g_fout->remoteVersion >= 70300)
6205 appendPQExpBuffer(query, "SELECT aggtransfn, "
6206 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6208 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6209 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6210 "'t'::boolean as convertok "
6211 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6212 "where a.aggfnoid = p.oid "
6213 "and p.oid = '%u'::pg_catalog.oid",
6214 agginfo->aggfn.dobj.catId.oid);
6216 else if (g_fout->remoteVersion >= 70100)
6218 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
6219 "format_type(aggtranstype, NULL) as aggtranstype, "
6221 "aggbasetype = 0 as anybasetype, "
6222 "CASE WHEN aggbasetype = 0 THEN '-' "
6223 "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
6224 "'t'::boolean as convertok "
6225 "from pg_aggregate "
6226 "where oid = '%u'::oid",
6227 agginfo->aggfn.dobj.catId.oid);
6231 appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
6233 "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
6234 "agginitval1 as agginitval, "
6235 "aggbasetype = 0 as anybasetype, "
6236 "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
6237 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
6238 "from pg_aggregate "
6239 "where oid = '%u'::oid",
6240 agginfo->aggfn.dobj.catId.oid);
6243 res = PQexec(g_conn, query->data);
6244 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6246 /* Expecting a single result only */
6247 ntups = PQntuples(res);
6250 write_msg(NULL, "Got %d rows instead of one from: %s",
6251 ntups, query->data);
6255 i_aggtransfn = PQfnumber(res, "aggtransfn");
6256 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
6257 i_aggtranstype = PQfnumber(res, "aggtranstype");
6258 i_agginitval = PQfnumber(res, "agginitval");
6259 i_anybasetype = PQfnumber(res, "anybasetype");
6260 i_fmtbasetype = PQfnumber(res, "fmtbasetype");
6261 i_convertok = PQfnumber(res, "convertok");
6263 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
6264 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
6265 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
6266 agginitval = PQgetvalue(res, 0, i_agginitval);
6267 /* we save anybasetype for format_aggregate_signature */
6268 agginfo->anybasetype = (PQgetvalue(res, 0, i_anybasetype)[0] == 't');
6269 /* we save fmtbasetype for format_aggregate_signature */
6270 agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
6271 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
6273 aggsig = format_aggregate_signature(agginfo, fout, true);
6274 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
6278 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
6283 if (g_fout->remoteVersion >= 70300)
6285 /* If using 7.3's regproc or regtype, data is already quoted */
6286 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6287 agginfo->anybasetype ? "'any'" :
6288 agginfo->fmtbasetype,
6292 else if (g_fout->remoteVersion >= 70100)
6294 /* format_type quotes, regproc does not */
6295 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6296 agginfo->anybasetype ? "'any'" :
6297 agginfo->fmtbasetype,
6303 /* need quotes all around */
6304 appendPQExpBuffer(details, " BASETYPE = %s,\n",
6305 agginfo->anybasetype ? "'any'" :
6306 fmtId(agginfo->fmtbasetype));
6307 appendPQExpBuffer(details, " SFUNC = %s,\n",
6309 appendPQExpBuffer(details, " STYPE = %s",
6310 fmtId(aggtranstype));
6313 if (!PQgetisnull(res, 0, i_agginitval))
6315 appendPQExpBuffer(details, ",\n INITCOND = ");
6316 appendStringLiteral(details, agginitval, true);
6319 if (strcmp(aggfinalfn, "-") != 0)
6321 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
6326 * DROP must be fully qualified in case same name appears in
6329 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
6330 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
6333 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
6334 fmtId(agginfo->aggfn.dobj.name),
6337 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6339 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6340 false, "AGGREGATE", q->data, delq->data, NULL,
6341 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
6344 /* Dump Aggregate Comments */
6345 resetPQExpBuffer(q);
6346 appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
6347 dumpComment(fout, q->data,
6348 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6349 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
6352 * Since there is no GRANT ON AGGREGATE syntax, we have to make the
6353 * ACL command look like a function's GRANT; in particular this
6354 * affects the syntax for aggregates on ANY.
6359 aggsig = format_function_signature(&agginfo->aggfn, NULL, true);
6360 aggsig_tag = format_function_signature(&agginfo->aggfn, NULL, false);
6362 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6365 agginfo->aggfn.dobj.namespace->dobj.name,
6366 agginfo->aggfn.usename, agginfo->aggfn.proacl);
6373 destroyPQExpBuffer(query);
6374 destroyPQExpBuffer(q);
6375 destroyPQExpBuffer(delq);
6376 destroyPQExpBuffer(details);
6381 * Write out grant/revoke information
6383 * 'objCatId' is the catalog ID of the underlying object.
6384 * 'objDumpId' is the dump ID of the underlying object.
6385 * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA.
6386 * 'name' is the formatted name of the object. Must be quoted etc. already.
6387 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
6388 * 'nspname' is the namespace the object is in (NULL if none).
6389 * 'owner' is the owner, NULL if there is no owner (for languages).
6390 * 'acls' is the string read out of the fooacl system catalog field;
6391 * it will be parsed here.
6395 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
6396 const char *type, const char *name,
6397 const char *tag, const char *nspname, const char *owner,
6402 /* Do nothing if ACL dump is not enabled */
6403 if (dataOnly || aclsSkip)
6406 sql = createPQExpBuffer();
6408 if (!buildACLCommands(name, type, acls, owner, fout->remoteVersion, sql))
6410 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
6416 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6419 false, "ACL", sql->data, "", NULL,
6423 destroyPQExpBuffer(sql);
6428 * write out to fout the declarations (not data) of a user-defined table
6431 dumpTable(Archive *fout, TableInfo *tbinfo)
6437 if (tbinfo->relkind == RELKIND_SEQUENCE)
6438 dumpSequence(fout, tbinfo);
6440 dumpTableSchema(fout, tbinfo);
6442 /* Handle the ACL here */
6443 namecopy = strdup(fmtId(tbinfo->dobj.name));
6444 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
6445 namecopy, tbinfo->dobj.name,
6446 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6454 * write the declaration (not data) of one user-defined table or view
6457 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
6459 PQExpBuffer query = createPQExpBuffer();
6460 PQExpBuffer q = createPQExpBuffer();
6461 PQExpBuffer delq = createPQExpBuffer();
6464 TableInfo **parents;
6465 int actual_atts; /* number of attrs in this CREATE statment */
6471 /* Make sure we are in proper schema */
6472 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
6474 /* Is it a table or a view? */
6475 if (tbinfo->relkind == RELKIND_VIEW)
6479 reltypename = "VIEW";
6481 /* Fetch the view definition */
6482 if (g_fout->remoteVersion >= 70300)
6484 /* Beginning in 7.3, viewname is not unique; rely on OID */
6485 appendPQExpBuffer(query,
6486 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) as viewdef",
6487 tbinfo->dobj.catId.oid);
6491 appendPQExpBuffer(query, "SELECT definition as viewdef "
6492 " from pg_views where viewname = ");
6493 appendStringLiteral(query, tbinfo->dobj.name, true);
6494 appendPQExpBuffer(query, ";");
6497 res = PQexec(g_conn, query->data);
6498 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6500 if (PQntuples(res) != 1)
6502 if (PQntuples(res) < 1)
6503 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
6506 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
6511 viewdef = PQgetvalue(res, 0, 0);
6513 if (strlen(viewdef) == 0)
6515 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
6521 * DROP must be fully qualified in case same name appears in
6524 appendPQExpBuffer(delq, "DROP VIEW %s.",
6525 fmtId(tbinfo->dobj.namespace->dobj.name));
6526 appendPQExpBuffer(delq, "%s;\n",
6527 fmtId(tbinfo->dobj.name));
6529 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
6530 fmtId(tbinfo->dobj.name), viewdef);
6536 reltypename = "TABLE";
6537 numParents = tbinfo->numParents;
6538 parents = tbinfo->parents;
6541 * DROP must be fully qualified in case same name appears in
6544 appendPQExpBuffer(delq, "DROP TABLE %s.",
6545 fmtId(tbinfo->dobj.namespace->dobj.name));
6546 appendPQExpBuffer(delq, "%s;\n",
6547 fmtId(tbinfo->dobj.name));
6549 appendPQExpBuffer(q, "CREATE TABLE %s (",
6550 fmtId(tbinfo->dobj.name));
6552 for (j = 0; j < tbinfo->numatts; j++)
6554 /* Is this one of the table's own attrs, and not dropped ? */
6555 if (!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j])
6557 /* Format properly if not first attr */
6558 if (actual_atts > 0)
6559 appendPQExpBuffer(q, ",");
6560 appendPQExpBuffer(q, "\n ");
6562 /* Attribute name */
6563 appendPQExpBuffer(q, "%s ",
6564 fmtId(tbinfo->attnames[j]));
6566 /* Attribute type */
6567 if (g_fout->remoteVersion >= 70100)
6569 char *typname = tbinfo->atttypnames[j];
6571 if (tbinfo->attisserial[j])
6573 if (strcmp(typname, "integer") == 0)
6575 else if (strcmp(typname, "bigint") == 0)
6576 typname = "bigserial";
6578 appendPQExpBuffer(q, "%s", typname);
6582 /* If no format_type, fake it */
6583 appendPQExpBuffer(q, "%s",
6584 myFormatType(tbinfo->atttypnames[j],
6585 tbinfo->atttypmod[j]));
6589 * Default value --- suppress if inherited, serial, or to
6590 * be printed separately.
6592 if (tbinfo->attrdefs[j] != NULL &&
6593 !tbinfo->inhAttrDef[j] &&
6594 !tbinfo->attisserial[j] &&
6595 !tbinfo->attrdefs[j]->separate)
6596 appendPQExpBuffer(q, " DEFAULT %s",
6597 tbinfo->attrdefs[j]->adef_expr);
6600 * Not Null constraint --- suppress if inherited
6602 * Note: we could suppress this for serial columns since
6603 * SERIAL implies NOT NULL. We choose not to for forward
6604 * compatibility, since there has been some talk of making
6605 * SERIAL not imply NOT NULL, in which case the explicit
6606 * specification would be needed.
6608 if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
6609 appendPQExpBuffer(q, " NOT NULL");
6616 * Add non-inherited CHECK constraints, if any.
6618 for (j = 0; j < tbinfo->ncheck; j++)
6620 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
6622 if (constr->coninherited || constr->separate)
6625 if (actual_atts > 0)
6626 appendPQExpBuffer(q, ",\n ");
6628 appendPQExpBuffer(q, "CONSTRAINT %s ",
6629 fmtId(constr->dobj.name));
6630 appendPQExpBuffer(q, "%s", constr->condef);
6635 appendPQExpBuffer(q, "\n)");
6639 appendPQExpBuffer(q, "\nINHERITS (");
6640 for (k = 0; k < numParents; k++)
6642 TableInfo *parentRel = parents[k];
6645 appendPQExpBuffer(q, ", ");
6646 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
6647 appendPQExpBuffer(q, "%s.",
6648 fmtId(parentRel->dobj.namespace->dobj.name));
6649 appendPQExpBuffer(q, "%s",
6650 fmtId(parentRel->dobj.name));
6652 appendPQExpBuffer(q, ")");
6655 /* Output tablespace clause if necessary */
6656 if (strlen(tbinfo->reltablespace) != 0 &&
6657 strcmp(tbinfo->reltablespace,
6658 tbinfo->dobj.namespace->nsptablespace) != 0)
6660 appendPQExpBuffer(q, " TABLESPACE %s",
6661 fmtId(tbinfo->reltablespace));
6664 appendPQExpBuffer(q, ";\n");
6666 /* Loop dumping statistics and storage statements */
6667 for (j = 0; j < tbinfo->numatts; j++)
6670 * Dump per-column statistics information. We only issue an
6671 * ALTER TABLE statement if the attstattarget entry for this
6672 * column is non-negative (i.e. it's not the default value)
6674 if (tbinfo->attstattarget[j] >= 0 &&
6675 !tbinfo->attisdropped[j])
6677 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6678 fmtId(tbinfo->dobj.name));
6679 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6680 fmtId(tbinfo->attnames[j]));
6681 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
6682 tbinfo->attstattarget[j]);
6686 * Dump per-column storage information. The statement is only
6687 * dumped if the storage has been changed from the type's
6690 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
6692 switch (tbinfo->attstorage[j])
6698 storage = "EXTERNAL";
6704 storage = "EXTENDED";
6711 * Only dump the statement if it's a storage type we
6714 if (storage != NULL)
6716 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6717 fmtId(tbinfo->dobj.name));
6718 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6719 fmtId(tbinfo->attnames[j]));
6720 appendPQExpBuffer(q, "SET STORAGE %s;\n",
6727 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
6729 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6730 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
6731 reltypename, q->data, delq->data, NULL,
6732 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
6735 /* Dump Table Comments */
6736 dumpTableComment(fout, tbinfo, reltypename);
6738 destroyPQExpBuffer(query);
6739 destroyPQExpBuffer(q);
6740 destroyPQExpBuffer(delq);
6744 * dumpAttrDef --- dump an attribute's default-value declaration
6747 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
6749 TableInfo *tbinfo = adinfo->adtable;
6750 int adnum = adinfo->adnum;
6754 /* Only print it if "separate" mode is selected */
6755 if (!tbinfo->dump || !adinfo->separate || dataOnly)
6758 /* Don't print inherited or serial defaults, either */
6759 if (tbinfo->inhAttrDef[adnum - 1] || tbinfo->attisserial[adnum - 1])
6762 q = createPQExpBuffer();
6763 delq = createPQExpBuffer();
6765 appendPQExpBuffer(q, "ALTER TABLE %s ",
6766 fmtId(tbinfo->dobj.name));
6767 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
6768 fmtId(tbinfo->attnames[adnum - 1]),
6772 * DROP must be fully qualified in case same name appears in
6775 appendPQExpBuffer(delq, "ALTER TABLE %s.",
6776 fmtId(tbinfo->dobj.namespace->dobj.name));
6777 appendPQExpBuffer(delq, "%s ",
6778 fmtId(tbinfo->dobj.name));
6779 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
6780 fmtId(tbinfo->attnames[adnum - 1]));
6782 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
6783 tbinfo->attnames[adnum - 1],
6784 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6785 false, "DEFAULT", q->data, delq->data, NULL,
6786 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
6789 destroyPQExpBuffer(q);
6790 destroyPQExpBuffer(delq);
6794 * getAttrName: extract the correct name for an attribute
6796 * The array tblInfo->attnames[] only provides names of user attributes;
6797 * if a system attribute number is supplied, we have to fake it.
6798 * We also do a little bit of bounds checking for safety's sake.
6801 getAttrName(int attrnum, TableInfo *tblInfo)
6803 if (attrnum > 0 && attrnum <= tblInfo->numatts)
6804 return tblInfo->attnames[attrnum - 1];
6807 case SelfItemPointerAttributeNumber:
6809 case ObjectIdAttributeNumber:
6811 case MinTransactionIdAttributeNumber:
6813 case MinCommandIdAttributeNumber:
6815 case MaxTransactionIdAttributeNumber:
6817 case MaxCommandIdAttributeNumber:
6819 case TableOidAttributeNumber:
6822 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
6823 attrnum, tblInfo->dobj.name);
6825 return NULL; /* keep compiler quiet */
6830 * write out to fout a user-defined index
6833 dumpIndex(Archive *fout, IndxInfo *indxinfo)
6835 TableInfo *tbinfo = indxinfo->indextable;
6842 q = createPQExpBuffer();
6843 delq = createPQExpBuffer();
6846 * If there's an associated constraint, don't dump the index per se,
6847 * but do dump any comment for it.
6849 if (indxinfo->indexconstraint == 0)
6851 /* Plain secondary index */
6852 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
6854 /* If the index is clustered, we need to record that. */
6855 if (indxinfo->indisclustered)
6857 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6858 fmtId(tbinfo->dobj.name));
6859 appendPQExpBuffer(q, " ON %s;\n",
6860 fmtId(indxinfo->dobj.name));
6864 * DROP must be fully qualified in case same name appears in
6867 appendPQExpBuffer(delq, "DROP INDEX %s.",
6868 fmtId(tbinfo->dobj.namespace->dobj.name));
6869 appendPQExpBuffer(delq, "%s;\n",
6870 fmtId(indxinfo->dobj.name));
6872 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
6873 indxinfo->dobj.name,
6874 tbinfo->dobj.namespace->dobj.name,
6875 tbinfo->usename, false,
6876 "INDEX", q->data, delq->data, NULL,
6877 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
6881 /* Dump Index Comments */
6882 resetPQExpBuffer(q);
6883 appendPQExpBuffer(q, "INDEX %s",
6884 fmtId(indxinfo->dobj.name));
6885 dumpComment(fout, q->data,
6886 tbinfo->dobj.namespace->dobj.name,
6888 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
6890 destroyPQExpBuffer(q);
6891 destroyPQExpBuffer(delq);
6896 * write out to fout a user-defined constraint
6899 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
6901 TableInfo *tbinfo = coninfo->contable;
6907 if (tbinfo && !tbinfo->dump)
6910 q = createPQExpBuffer();
6911 delq = createPQExpBuffer();
6913 if (coninfo->contype == 'p' || coninfo->contype == 'u')
6915 /* Index-related constraint */
6919 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
6921 if (indxinfo == NULL)
6923 write_msg(NULL, "missing index for constraint %s\n",
6924 coninfo->dobj.name);
6928 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6929 fmtId(tbinfo->dobj.name));
6930 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s (",
6931 fmtId(coninfo->dobj.name),
6932 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
6934 for (k = 0; k < indxinfo->indnkeys; k++)
6936 int indkey = (int) indxinfo->indkeys[k];
6937 const char *attname;
6939 if (indkey == InvalidAttrNumber)
6941 attname = getAttrName(indkey, tbinfo);
6943 appendPQExpBuffer(q, "%s%s",
6944 (k == 0) ? "" : ", ",
6948 appendPQExpBuffer(q, ")");
6950 /* Output tablespace clause if necessary */
6951 if (strlen(indxinfo->tablespace) != 0 &&
6952 strcmp(indxinfo->tablespace,
6953 indxinfo->indextable->reltablespace) != 0)
6955 appendPQExpBuffer(q, " USING INDEX TABLESPACE %s",
6956 fmtId(indxinfo->tablespace));
6959 appendPQExpBuffer(q, ";\n");
6961 /* If the index is clustered, we need to record that. */
6962 if (indxinfo->indisclustered)
6964 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6965 fmtId(tbinfo->dobj.name));
6966 appendPQExpBuffer(q, " ON %s;\n",
6967 fmtId(indxinfo->dobj.name));
6971 * DROP must be fully qualified in case same name appears in
6974 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
6975 fmtId(tbinfo->dobj.namespace->dobj.name));
6976 appendPQExpBuffer(delq, "%s ",
6977 fmtId(tbinfo->dobj.name));
6978 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6979 fmtId(coninfo->dobj.name));
6981 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
6983 tbinfo->dobj.namespace->dobj.name,
6984 tbinfo->usename, false,
6985 "CONSTRAINT", q->data, delq->data, NULL,
6986 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
6989 else if (coninfo->contype == 'f')
6992 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that
6993 * the current table data is not processed
6995 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6996 fmtId(tbinfo->dobj.name));
6997 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
6998 fmtId(coninfo->dobj.name),
7002 * DROP must be fully qualified in case same name appears in
7005 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7006 fmtId(tbinfo->dobj.namespace->dobj.name));
7007 appendPQExpBuffer(delq, "%s ",
7008 fmtId(tbinfo->dobj.name));
7009 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7010 fmtId(coninfo->dobj.name));
7012 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7014 tbinfo->dobj.namespace->dobj.name,
7015 tbinfo->usename, false,
7016 "FK CONSTRAINT", q->data, delq->data, NULL,
7017 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7020 else if (coninfo->contype == 'c' && tbinfo)
7022 /* CHECK constraint on a table */
7024 /* Ignore if not to be dumped separately */
7025 if (coninfo->separate)
7027 /* not ONLY since we want it to propagate to children */
7028 appendPQExpBuffer(q, "ALTER TABLE %s\n",
7029 fmtId(tbinfo->dobj.name));
7030 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7031 fmtId(coninfo->dobj.name),
7035 * DROP must be fully qualified in case same name appears in
7038 appendPQExpBuffer(delq, "ALTER TABLE %s.",
7039 fmtId(tbinfo->dobj.namespace->dobj.name));
7040 appendPQExpBuffer(delq, "%s ",
7041 fmtId(tbinfo->dobj.name));
7042 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7043 fmtId(coninfo->dobj.name));
7045 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7047 tbinfo->dobj.namespace->dobj.name,
7048 tbinfo->usename, false,
7049 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7050 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7054 else if (coninfo->contype == 'c' && tbinfo == NULL)
7056 /* CHECK constraint on a domain */
7057 TypeInfo *tinfo = coninfo->condomain;
7059 /* Ignore if not to be dumped separately, or if not dumping domain */
7060 if (coninfo->separate && tinfo->dobj.namespace->dump)
7062 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
7063 fmtId(tinfo->dobj.name));
7064 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7065 fmtId(coninfo->dobj.name),
7069 * DROP must be fully qualified in case same name appears in
7072 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
7073 fmtId(tinfo->dobj.namespace->dobj.name));
7074 appendPQExpBuffer(delq, "%s ",
7075 fmtId(tinfo->dobj.name));
7076 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7077 fmtId(coninfo->dobj.name));
7079 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7081 tinfo->dobj.namespace->dobj.name,
7082 tinfo->usename, false,
7083 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7084 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7090 write_msg(NULL, "unexpected constraint type\n");
7094 /* Dump Constraint Comments --- only works for table constraints */
7097 resetPQExpBuffer(q);
7098 appendPQExpBuffer(q, "CONSTRAINT %s ",
7099 fmtId(coninfo->dobj.name));
7100 appendPQExpBuffer(q, "ON %s",
7101 fmtId(tbinfo->dobj.name));
7102 dumpComment(fout, q->data,
7103 tbinfo->dobj.namespace->dobj.name,
7105 coninfo->dobj.catId, 0, coninfo->dobj.dumpId);
7108 destroyPQExpBuffer(q);
7109 destroyPQExpBuffer(delq);
7114 * find the maximum oid and generate a COPY statement to set it
7118 setMaxOid(Archive *fout)
7124 do_sql_command(g_conn,
7125 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer)");
7126 res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
7127 check_sql_result(res, g_conn, "INSERT INTO pgdump_oid VALUES (0)",
7129 max_oid = PQoidValue(res);
7132 write_msg(NULL, "inserted invalid OID\n");
7136 do_sql_command(g_conn, "DROP TABLE pgdump_oid;");
7138 write_msg(NULL, "maximum system OID is %u\n", max_oid);
7139 snprintf(sql, sizeof(sql),
7140 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer);\n"
7141 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
7144 "DROP TABLE pgdump_oid;\n",
7147 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7148 "Max OID", NULL, "",
7149 false, "<Init>", sql, "", NULL,
7155 * findLastBuiltInOid -
7156 * find the last built in oid
7158 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
7159 * pg_database entry for the current database
7162 findLastBuiltinOid_V71(const char *dbname)
7167 PQExpBuffer query = createPQExpBuffer();
7169 resetPQExpBuffer(query);
7170 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
7171 appendStringLiteral(query, dbname, true);
7173 res = PQexec(g_conn, query->data);
7174 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7176 ntups = PQntuples(res);
7179 write_msg(NULL, "missing pg_database entry for this database\n");
7184 write_msg(NULL, "found more than one pg_database entry for this database\n");
7187 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
7189 destroyPQExpBuffer(query);
7194 * findLastBuiltInOid -
7195 * find the last built in oid
7197 * For 7.0, we do this by assuming that the last thing that initdb does is to
7198 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
7199 * initdb won't be changing anymore, it'll do.
7202 findLastBuiltinOid_V70(void)
7208 res = PQexec(g_conn,
7209 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
7210 check_sql_result(res, g_conn,
7211 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
7213 ntups = PQntuples(res);
7216 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
7221 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
7224 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
7230 dumpSequence(Archive *fout, TableInfo *tbinfo)
7242 PQExpBuffer query = createPQExpBuffer();
7243 PQExpBuffer delqry = createPQExpBuffer();
7245 /* Make sure we are in proper schema */
7246 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7248 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
7249 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
7251 appendPQExpBuffer(query,
7252 "SELECT sequence_name, last_value, increment_by, "
7253 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
7254 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
7256 "END AS max_value, "
7257 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
7258 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
7260 "END AS min_value, "
7261 "cache_value, is_cycled, is_called from %s",
7263 fmtId(tbinfo->dobj.name));
7265 res = PQexec(g_conn, query->data);
7266 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7268 if (PQntuples(res) != 1)
7270 write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
7271 tbinfo->dobj.name, PQntuples(res));
7275 /* Disable this check: it fails if sequence has been renamed */
7277 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
7279 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
7280 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
7285 last = PQgetvalue(res, 0, 1);
7286 incby = PQgetvalue(res, 0, 2);
7287 if (!PQgetisnull(res, 0, 3))
7288 maxv = PQgetvalue(res, 0, 3);
7289 if (!PQgetisnull(res, 0, 4))
7290 minv = PQgetvalue(res, 0, 4);
7291 cache = PQgetvalue(res, 0, 5);
7292 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
7293 called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
7296 * The logic we use for restoring sequences is as follows:
7298 * Add a basic CREATE SEQUENCE statement (use last_val for start if
7299 * called is false, else use min_val for start_val). Skip this if the
7300 * sequence came from a SERIAL column.
7302 * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
7303 * data. We do this for serial sequences too.
7306 if (!dataOnly && !OidIsValid(tbinfo->owning_tab))
7308 resetPQExpBuffer(delqry);
7311 * DROP must be fully qualified in case same name appears in
7314 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
7315 fmtId(tbinfo->dobj.namespace->dobj.name));
7316 appendPQExpBuffer(delqry, "%s;\n",
7317 fmtId(tbinfo->dobj.name));
7319 resetPQExpBuffer(query);
7320 appendPQExpBuffer(query,
7321 "CREATE SEQUENCE %s\n",
7322 fmtId(tbinfo->dobj.name));
7325 appendPQExpBuffer(query, " START WITH %s\n", last);
7327 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
7330 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
7332 appendPQExpBuffer(query, " NO MAXVALUE\n");
7335 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
7337 appendPQExpBuffer(query, " NO MINVALUE\n");
7339 appendPQExpBuffer(query,
7341 cache, (cycled ? "\n CYCLE" : ""));
7343 appendPQExpBuffer(query, ";\n");
7345 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7347 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7348 false, "SEQUENCE", query->data, delqry->data, NULL,
7349 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7355 TableInfo *owning_tab;
7357 resetPQExpBuffer(query);
7358 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
7361 * If this is a SERIAL sequence, then use the
7362 * pg_get_serial_sequence function to avoid hard-coding the
7363 * sequence name. Note that this implicitly assumes that the
7364 * sequence and its owning table are in the same schema, because
7365 * we don't schema-qualify the reference.
7367 if (OidIsValid(tbinfo->owning_tab) &&
7368 (owning_tab = findTableByOid(tbinfo->owning_tab)) != NULL)
7370 appendPQExpBuffer(query, "pg_catalog.pg_get_serial_sequence(");
7371 appendStringLiteral(query, fmtId(owning_tab->dobj.name), true);
7372 appendPQExpBuffer(query, ", ");
7373 appendStringLiteral(query, owning_tab->attnames[tbinfo->owning_col - 1], true);
7374 appendPQExpBuffer(query, ")");
7377 appendStringLiteral(query, fmtId(tbinfo->dobj.name), true);
7378 appendPQExpBuffer(query, ", %s, %s);\n",
7379 last, (called ? "true" : "false"));
7381 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7383 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7384 false, "SEQUENCE SET", query->data, "", NULL,
7385 &(tbinfo->dobj.dumpId), 1,
7391 /* Dump Sequence Comments */
7392 resetPQExpBuffer(query);
7393 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
7394 dumpComment(fout, query->data,
7395 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7396 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
7401 destroyPQExpBuffer(query);
7402 destroyPQExpBuffer(delqry);
7406 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
7408 TableInfo *tbinfo = tginfo->tgtable;
7417 query = createPQExpBuffer();
7418 delqry = createPQExpBuffer();
7421 * DROP must be fully qualified in case same name appears in
7424 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
7425 fmtId(tginfo->dobj.name));
7426 appendPQExpBuffer(delqry, "ON %s.",
7427 fmtId(tbinfo->dobj.namespace->dobj.name));
7428 appendPQExpBuffer(delqry, "%s;\n",
7429 fmtId(tbinfo->dobj.name));
7431 if (tginfo->tgisconstraint)
7433 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
7434 appendPQExpBuffer(query, fmtId(tginfo->tgconstrname));
7438 appendPQExpBuffer(query, "CREATE TRIGGER ");
7439 appendPQExpBuffer(query, fmtId(tginfo->dobj.name));
7441 appendPQExpBuffer(query, "\n ");
7445 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
7446 appendPQExpBuffer(query, "BEFORE");
7448 appendPQExpBuffer(query, "AFTER");
7449 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
7451 appendPQExpBuffer(query, " INSERT");
7454 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
7457 appendPQExpBuffer(query, " OR DELETE");
7459 appendPQExpBuffer(query, " DELETE");
7462 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
7465 appendPQExpBuffer(query, " OR UPDATE");
7467 appendPQExpBuffer(query, " UPDATE");
7469 appendPQExpBuffer(query, " ON %s\n",
7470 fmtId(tbinfo->dobj.name));
7472 if (tginfo->tgisconstraint)
7474 if (OidIsValid(tginfo->tgconstrrelid))
7476 /* If we are using regclass, name is already quoted */
7477 if (g_fout->remoteVersion >= 70300)
7478 appendPQExpBuffer(query, " FROM %s\n ",
7479 tginfo->tgconstrrelname);
7481 appendPQExpBuffer(query, " FROM %s\n ",
7482 fmtId(tginfo->tgconstrrelname));
7484 if (!tginfo->tgdeferrable)
7485 appendPQExpBuffer(query, "NOT ");
7486 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
7487 if (tginfo->tginitdeferred)
7488 appendPQExpBuffer(query, "DEFERRED\n");
7490 appendPQExpBuffer(query, "IMMEDIATE\n");
7493 if (TRIGGER_FOR_ROW(tginfo->tgtype))
7494 appendPQExpBuffer(query, " FOR EACH ROW\n ");
7496 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
7498 /* In 7.3, result of regproc is already quoted */
7499 if (g_fout->remoteVersion >= 70300)
7500 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7503 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7504 fmtId(tginfo->tgfname));
7507 for (findx = 0; findx < tginfo->tgnargs; findx++)
7513 p = strchr(p, '\\');
7516 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
7528 if (p[0] == '0' && p[1] == '0' && p[2] == '0')
7532 appendPQExpBufferChar(query, '\'');
7536 appendPQExpBufferChar(query, '\\');
7537 appendPQExpBufferChar(query, *s++);
7539 appendPQExpBufferChar(query, '\'');
7540 appendPQExpBuffer(query,
7541 (findx < tginfo->tgnargs - 1) ? ", " : "");
7544 appendPQExpBuffer(query, ");\n");
7546 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
7548 tbinfo->dobj.namespace->dobj.name,
7549 tbinfo->usename, false,
7550 "TRIGGER", query->data, delqry->data, NULL,
7551 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
7554 resetPQExpBuffer(query);
7555 appendPQExpBuffer(query, "TRIGGER %s ",
7556 fmtId(tginfo->dobj.name));
7557 appendPQExpBuffer(query, "ON %s",
7558 fmtId(tbinfo->dobj.name));
7560 dumpComment(fout, query->data,
7561 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7562 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
7564 destroyPQExpBuffer(query);
7565 destroyPQExpBuffer(delqry);
7573 dumpRule(Archive *fout, RuleInfo *rinfo)
7575 TableInfo *tbinfo = rinfo->ruletable;
7582 * Ignore rules for not-to-be-dumped tables
7584 if (tbinfo == NULL || !tbinfo->dump || dataOnly)
7588 * If it is an ON SELECT rule, we do not need to dump it because it
7589 * will be handled via CREATE VIEW for the table.
7591 if (rinfo->ev_type == '1' && rinfo->is_instead)
7595 * Make sure we are in proper schema.
7597 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7599 query = createPQExpBuffer();
7600 cmd = createPQExpBuffer();
7601 delcmd = createPQExpBuffer();
7603 if (g_fout->remoteVersion >= 70300)
7605 appendPQExpBuffer(query,
7606 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
7607 rinfo->dobj.catId.oid);
7611 /* Rule name was unique before 7.3 ... */
7612 appendPQExpBuffer(query,
7613 "SELECT pg_get_ruledef('%s') AS definition",
7617 res = PQexec(g_conn, query->data);
7618 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7620 if (PQntuples(res) != 1)
7622 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
7623 rinfo->dobj.name, tbinfo->dobj.name);
7627 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
7630 * DROP must be fully qualified in case same name appears in
7633 appendPQExpBuffer(delcmd, "DROP RULE %s ",
7634 fmtId(rinfo->dobj.name));
7635 appendPQExpBuffer(delcmd, "ON %s.",
7636 fmtId(tbinfo->dobj.namespace->dobj.name));
7637 appendPQExpBuffer(delcmd, "%s;\n",
7638 fmtId(tbinfo->dobj.name));
7640 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
7642 tbinfo->dobj.namespace->dobj.name,
7643 tbinfo->usename, false,
7644 "RULE", cmd->data, delcmd->data, NULL,
7645 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
7648 /* Dump rule comments */
7649 resetPQExpBuffer(query);
7650 appendPQExpBuffer(query, "RULE %s",
7651 fmtId(rinfo->dobj.name));
7652 appendPQExpBuffer(query, " ON %s",
7653 fmtId(tbinfo->dobj.name));
7654 dumpComment(fout, query->data,
7655 tbinfo->dobj.namespace->dobj.name,
7657 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
7661 destroyPQExpBuffer(query);
7662 destroyPQExpBuffer(cmd);
7663 destroyPQExpBuffer(delcmd);
7667 * getDependencies --- obtain available dependency data
7670 getDependencies(void)
7681 DumpableObject *dobj,
7684 /* No dependency info available before 7.3 */
7685 if (g_fout->remoteVersion < 70300)
7689 write_msg(NULL, "fetching dependency data\n");
7691 /* Make sure we are in proper schema */
7692 selectSourceSchema("pg_catalog");
7694 query = createPQExpBuffer();
7696 appendPQExpBuffer(query, "SELECT "
7697 "classid, objid, refclassid, refobjid, deptype "
7699 "WHERE deptype != 'p' "
7702 res = PQexec(g_conn, query->data);
7703 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7705 ntups = PQntuples(res);
7707 i_classid = PQfnumber(res, "classid");
7708 i_objid = PQfnumber(res, "objid");
7709 i_refclassid = PQfnumber(res, "refclassid");
7710 i_refobjid = PQfnumber(res, "refobjid");
7711 i_deptype = PQfnumber(res, "deptype");
7714 * Since we ordered the SELECT by referencing ID, we can expect that
7715 * multiple entries for the same object will appear together; this
7716 * saves on searches.
7720 for (i = 0; i < ntups; i++)
7726 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
7727 objId.oid = atooid(PQgetvalue(res, i, i_objid));
7728 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
7729 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
7730 deptype = *(PQgetvalue(res, i, i_deptype));
7733 dobj->catId.tableoid != objId.tableoid ||
7734 dobj->catId.oid != objId.oid)
7735 dobj = findObjectByCatalogId(objId);
7738 * Failure to find objects mentioned in pg_depend is not
7739 * unexpected, since for example we don't collect info about TOAST
7745 fprintf(stderr, "no referencing object %u %u\n",
7746 objId.tableoid, objId.oid);
7751 refdobj = findObjectByCatalogId(refobjId);
7753 if (refdobj == NULL)
7756 fprintf(stderr, "no referenced object %u %u\n",
7757 refobjId.tableoid, refobjId.oid);
7762 addObjectDependency(dobj, refdobj->dumpId);
7767 destroyPQExpBuffer(query);
7772 * selectSourceSchema - make the specified schema the active search path
7773 * in the source database.
7775 * NB: pg_catalog is explicitly searched after the specified schema;
7776 * so user names are only qualified if they are cross-schema references,
7777 * and system names are only qualified if they conflict with a user name
7778 * in the current schema.
7780 * Whenever the selected schema is not pg_catalog, be careful to qualify
7781 * references to system catalogs and types in our emitted commands!
7784 selectSourceSchema(const char *schemaName)
7786 static char *curSchemaName = NULL;
7789 /* Not relevant if fetching from pre-7.3 DB */
7790 if (g_fout->remoteVersion < 70300)
7792 /* Ignore null schema names */
7793 if (schemaName == NULL || *schemaName == '\0')
7795 /* Optimize away repeated selection of same schema */
7796 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
7799 query = createPQExpBuffer();
7800 appendPQExpBuffer(query, "SET search_path = %s",
7802 if (strcmp(schemaName, "pg_catalog") != 0)
7803 appendPQExpBuffer(query, ", pg_catalog");
7805 do_sql_command(g_conn, query->data);
7807 destroyPQExpBuffer(query);
7809 free(curSchemaName);
7810 curSchemaName = strdup(schemaName);
7814 * getFormattedTypeName - retrieve a nicely-formatted type name for the
7817 * NB: in 7.3 and up the result may depend on the currently-selected
7818 * schema; this is why we don't try to cache the names.
7821 getFormattedTypeName(Oid oid, OidOptions opts)
7830 if ((opts & zeroAsOpaque) != 0)
7831 return strdup(g_opaque_type);
7832 else if ((opts & zeroAsAny) != 0)
7833 return strdup("'any'");
7834 else if ((opts & zeroAsStar) != 0)
7836 else if ((opts & zeroAsNone) != 0)
7837 return strdup("NONE");
7840 query = createPQExpBuffer();
7841 if (g_fout->remoteVersion >= 70300)
7843 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
7846 else if (g_fout->remoteVersion >= 70100)
7848 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
7853 appendPQExpBuffer(query, "SELECT typname "
7855 "WHERE oid = '%u'::oid",
7859 res = PQexec(g_conn, query->data);
7860 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7862 /* Expecting a single result only */
7863 ntups = PQntuples(res);
7866 write_msg(NULL, "query yielded %d rows instead of one: %s\n",
7867 ntups, query->data);
7871 if (g_fout->remoteVersion >= 70100)
7873 /* already quoted */
7874 result = strdup(PQgetvalue(res, 0, 0));
7878 /* may need to quote it */
7879 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
7883 destroyPQExpBuffer(query);
7889 * myFormatType --- local implementation of format_type for use with 7.0.
7892 myFormatType(const char *typname, int32 typmod)
7895 bool isarray = false;
7896 PQExpBuffer buf = createPQExpBuffer();
7898 /* Handle array types */
7899 if (typname[0] == '_')
7905 /* Show lengths on bpchar and varchar */
7906 if (!strcmp(typname, "bpchar"))
7908 int len = (typmod - VARHDRSZ);
7910 appendPQExpBuffer(buf, "character");
7912 appendPQExpBuffer(buf, "(%d)",
7915 else if (!strcmp(typname, "varchar"))
7917 appendPQExpBuffer(buf, "character varying");
7919 appendPQExpBuffer(buf, "(%d)",
7922 else if (!strcmp(typname, "numeric"))
7924 appendPQExpBuffer(buf, "numeric");
7931 tmp_typmod = typmod - VARHDRSZ;
7932 precision = (tmp_typmod >> 16) & 0xffff;
7933 scale = tmp_typmod & 0xffff;
7934 appendPQExpBuffer(buf, "(%d,%d)",
7940 * char is an internal single-byte data type; Let's make sure we force
7941 * it through with quotes. - thomas 1998-12-13
7943 else if (strcmp(typname, "char") == 0)
7944 appendPQExpBuffer(buf, "\"char\"");
7946 appendPQExpBuffer(buf, "%s", fmtId(typname));
7948 /* Append array qualifier for array types */
7950 appendPQExpBuffer(buf, "[]");
7952 result = strdup(buf->data);
7953 destroyPQExpBuffer(buf);
7959 * fmtQualifiedId - convert a qualified name to the proper format for
7960 * the source database.
7962 * Like fmtId, use the result before calling again.
7965 fmtQualifiedId(const char *schema, const char *id)
7967 static PQExpBuffer id_return = NULL;
7969 if (id_return) /* first time through? */
7970 resetPQExpBuffer(id_return);
7972 id_return = createPQExpBuffer();
7974 /* Suppress schema name if fetching from pre-7.3 DB */
7975 if (g_fout->remoteVersion >= 70300 && schema && *schema)
7977 appendPQExpBuffer(id_return, "%s.",
7980 appendPQExpBuffer(id_return, "%s",
7983 return id_return->data;
7987 * Return a column list clause for the given relation.
7989 * Special case: if there are no undropped columns in the relation, return
7990 * "", not an invalid "()" column list.
7993 fmtCopyColumnList(const TableInfo *ti)
7995 static PQExpBuffer q = NULL;
7996 int numatts = ti->numatts;
7997 char **attnames = ti->attnames;
7998 bool *attisdropped = ti->attisdropped;
8002 if (q) /* first time through? */
8003 resetPQExpBuffer(q);
8005 q = createPQExpBuffer();
8007 appendPQExpBuffer(q, "(");
8009 for (i = 0; i < numatts; i++)
8011 if (attisdropped[i])
8014 appendPQExpBuffer(q, ", ");
8015 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
8020 return ""; /* no undropped columns */
8022 appendPQExpBuffer(q, ")");
8027 * Convenience subroutine to execute a SQL command and check for
8028 * COMMAND_OK status.
8031 do_sql_command(PGconn *conn, const char *query)
8035 res = PQexec(conn, query);
8036 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
8041 * Convenience subroutine to verify a SQL command succeeded,
8042 * and exit with a useful error message if not.
8045 check_sql_result(PGresult *res, PGconn *conn, const char *query,
8046 ExecStatusType expected)
8050 if (res && PQresultStatus(res) == expected)
8053 write_msg(NULL, "SQL command failed\n");
8055 err = PQresultErrorMessage(res);
8057 err = PQerrorMessage(conn);
8058 write_msg(NULL, "Error message from server: %s", err);
8059 write_msg(NULL, "The command was: %s\n", query);