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.396 2004/12/14 22:16:32 tgl 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"
43 #ifndef HAVE_INT_OPTRESET
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);
145 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
147 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
148 const char *type, const char *name,
149 const char *tag, const char *nspname, const char *owner,
152 static void getDependencies(void);
153 static void getDomainConstraints(TypeInfo *tinfo);
154 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
155 static char *format_function_signature(FuncInfo *finfo, char **argnames,
157 static const char *convertRegProcReference(const char *proc);
158 static const char *convertOperatorReference(const char *opr);
159 static Oid findLastBuiltinOid_V71(const char *);
160 static Oid findLastBuiltinOid_V70(void);
161 static void setMaxOid(Archive *fout);
162 static void selectSourceSchema(const char *schemaName);
163 static char *getFormattedTypeName(Oid oid, OidOptions opts);
164 static char *myFormatType(const char *typname, int32 typmod);
165 static const char *fmtQualifiedId(const char *schema, const char *id);
166 static int dumpBlobs(Archive *AH, void *arg);
167 static void dumpDatabase(Archive *AH);
168 static void dumpTimestamp(Archive *AH, char *msg);
169 static void dumpEncoding(Archive *AH);
170 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
171 static const char *fmtCopyColumnList(const TableInfo *ti);
172 static void do_sql_command(PGconn *conn, const char *query);
173 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
174 ExecStatusType expected);
178 main(int argc, char **argv)
181 const char *filename = NULL;
182 const char *format = "p";
183 const char *dbname = NULL;
184 const char *pghost = NULL;
185 const char *pgport = NULL;
186 const char *username = NULL;
190 DumpableObject **dobjs;
193 bool force_password = false;
194 int compressLevel = -1;
195 bool ignore_version = false;
198 int outputCreate = 0;
200 int outputNoOwner = 0;
201 static int use_setsessauth = 0;
202 static int disable_triggers = 0;
203 char *outputSuperuser = NULL;
205 RestoreOptions *ropt;
207 static struct option long_options[] = {
208 {"data-only", no_argument, NULL, 'a'},
209 {"blobs", no_argument, NULL, 'b'},
210 {"clean", no_argument, NULL, 'c'},
211 {"create", no_argument, NULL, 'C'},
212 {"file", required_argument, NULL, 'f'},
213 {"format", required_argument, NULL, 'F'},
214 {"inserts", no_argument, NULL, 'd'},
215 {"attribute-inserts", no_argument, NULL, 'D'},
216 {"column-inserts", no_argument, NULL, 'D'},
217 {"host", required_argument, NULL, 'h'},
218 {"ignore-version", no_argument, NULL, 'i'},
219 {"no-reconnect", no_argument, NULL, 'R'},
220 {"oids", no_argument, NULL, 'o'},
221 {"no-owner", no_argument, NULL, 'O'},
222 {"port", required_argument, NULL, 'p'},
223 {"schema", required_argument, NULL, 'n'},
224 {"schema-only", no_argument, NULL, 's'},
225 {"superuser", required_argument, NULL, 'S'},
226 {"table", required_argument, NULL, 't'},
227 {"password", no_argument, NULL, 'W'},
228 {"username", required_argument, NULL, 'U'},
229 {"verbose", no_argument, NULL, 'v'},
230 {"no-privileges", no_argument, NULL, 'x'},
231 {"no-acl", no_argument, NULL, 'x'},
232 {"compress", required_argument, NULL, 'Z'},
233 {"help", no_argument, NULL, '?'},
234 {"version", no_argument, NULL, 'V'},
237 * the following options don't have an equivalent short option
238 * letter, but are available as '-X long-name'
240 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
241 {"disable-triggers", no_argument, &disable_triggers, 1},
242 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
248 set_pglocale_pgservice(argv[0], "pg_dump");
252 strcpy(g_comment_start, "-- ");
253 g_comment_end[0] = '\0';
254 strcpy(g_opaque_type, "opaque");
256 dataOnly = schemaOnly = dumpInserts = attrNames = false;
258 progname = get_progname(argv[0]);
260 /* Set default options based on progname */
261 if (strcmp(progname, "pg_backup") == 0)
269 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
274 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
276 puts("pg_dump (PostgreSQL) " PG_VERSION);
281 while ((c = getopt_long(argc, argv, "abcCdDf:F:h:in:oOp:RsS:t:uU:vWxX:Z:",
282 long_options, &optindex)) != -1)
286 case 'a': /* Dump data only */
290 case 'b': /* Dump blobs */
294 case 'c': /* clean (i.e., drop) schema prior to
299 case 'C': /* Create DB */
303 case 'd': /* dump data as proper insert strings */
307 case 'D': /* dump data as proper insert strings with
321 case 'h': /* server host */
325 case 'i': /* ignore database version mismatch */
326 ignore_version = true;
329 case 'n': /* Dump data for this schema only */
330 selectSchemaName = strdup(optarg);
333 case 'o': /* Dump oids */
337 case 'O': /* Don't reconnect to match owner */
341 case 'p': /* server port */
346 /* no-op, still accepted for backwards compatibility */
349 case 's': /* dump schema only */
353 case 'S': /* Username for superuser in plain text
355 outputSuperuser = strdup(optarg);
358 case 't': /* Dump data for this table only */
359 selectTableName = strdup(optarg);
363 force_password = true;
364 username = simple_prompt("User name: ", 100, true);
371 case 'v': /* verbose */
376 force_password = true;
379 case 'x': /* skip ACL dump */
384 * Option letters were getting scarce, so I invented this
385 * new scheme: '-X feature' turns on some feature. Compare
386 * to the -f option in GCC. You should also add an
387 * equivalent GNU-style option --feature. Features that
388 * require arguments should use '-X feature=foo'.
391 if (strcmp(optarg, "disable-dollar-quoting") == 0)
392 disable_dollar_quoting = 1;
393 else if (strcmp(optarg, "disable-triggers") == 0)
394 disable_triggers = 1;
395 else if (strcmp(optarg, "use-set-session-authorization") == 0)
400 _("%s: invalid -X option -- %s\n"),
402 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
407 case 'Z': /* Compression Level */
408 compressLevel = atoi(optarg);
410 /* This covers the long options equivalent to -X xxx. */
416 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
421 if (optind < (argc - 1))
423 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
424 progname, argv[optind + 1]);
425 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
430 /* Get database name from command line */
432 dbname = argv[optind];
434 if (dataOnly && schemaOnly)
436 write_msg(NULL, "options \"schema only\" (-s) and \"data only\" (-a) cannot be used together\n");
440 if (dataOnly && outputClean)
442 write_msg(NULL, "options \"clean\" (-c) and \"data only\" (-a) cannot be used together\n");
446 if (outputBlobs && selectTableName != NULL)
448 write_msg(NULL, "large-object output not supported for a single table\n");
449 write_msg(NULL, "use a full dump instead\n");
453 if (outputBlobs && selectSchemaName != NULL)
455 write_msg(NULL, "large-object output not supported for a single schema\n");
456 write_msg(NULL, "use a full dump instead\n");
460 if (dumpInserts == true && oids == true)
462 write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together\n");
463 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
467 if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
469 write_msg(NULL, "large-object output is not supported for plain-text dump files\n");
470 write_msg(NULL, "(Use a different output format.)\n");
474 /* open the output file */
479 g_fout = CreateArchive(filename, archCustom, compressLevel);
484 g_fout = CreateArchive(filename, archFiles, compressLevel);
490 g_fout = CreateArchive(filename, archNull, 0);
495 g_fout = CreateArchive(filename, archTar, compressLevel);
499 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
505 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
509 /* Let the archiver know how noisy to be */
510 g_fout->verbose = g_verbose;
512 g_fout->minRemoteVersion = 70000; /* we can handle back to 7.0 */
513 g_fout->maxRemoteVersion = parse_version(PG_VERSION);
514 if (g_fout->maxRemoteVersion < 0)
516 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
521 * Open the database using the Archiver, so it knows about it. Errors
524 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
525 username, force_password, ignore_version);
528 * Start serializable transaction to dump consistent data.
530 do_sql_command(g_conn, "BEGIN");
532 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
534 /* Set the datestyle to ISO to ensure the dump's portability */
535 do_sql_command(g_conn, "SET DATESTYLE = ISO");
538 * If supported, set extra_float_digits so that we can dump float data
539 * exactly (given correctly implemented float I/O code, anyway)
541 if (g_fout->remoteVersion >= 70400)
542 do_sql_command(g_conn, "SET extra_float_digits TO 2");
544 /* Find the last built-in OID, if needed */
545 if (g_fout->remoteVersion < 70300)
547 if (g_fout->remoteVersion >= 70100)
548 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
550 g_last_builtin_oid = findLastBuiltinOid_V70();
552 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
556 * Now scan the database and create DumpableObject structs for all the
557 * objects we intend to dump.
559 tblinfo = getSchemaData(&numTables, schemaOnly, dataOnly);
562 getTableData(tblinfo, numTables, oids);
566 /* This is just a placeholder to allow correct sorting of blobs */
567 DumpableObject *blobobj;
569 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
570 blobobj->objType = DO_BLOBS;
571 blobobj->catId = nilCatalogId;
572 AssignDumpId(blobobj);
573 blobobj->name = strdup("BLOBS");
577 * Collect dependency data to assist in ordering the objects.
582 * Sort the objects into a safe dump order (no forward references).
584 * In 7.3 or later, we can rely on dependency information to help us
585 * determine a safe order, so the initial sort is mostly for cosmetic
586 * purposes: we sort by name to ensure that logically identical
587 * schemas will dump identically. Before 7.3 we don't have
588 * dependencies and we use OID ordering as an (unreliable) guide to
591 getDumpableObjects(&dobjs, &numObjs);
593 if (g_fout->remoteVersion >= 70300)
594 sortDumpableObjectsByTypeName(dobjs, numObjs);
596 sortDumpableObjectsByTypeOid(dobjs, numObjs);
598 sortDumpableObjects(dobjs, numObjs);
601 * Create archive TOC entries for all the objects to be dumped, in a
606 dumpTimestamp(g_fout, "Started on");
608 /* First the special encoding entry. */
609 dumpEncoding(g_fout);
611 /* The database item is always second. */
613 dumpDatabase(g_fout);
615 /* Max OID is next. */
619 /* Now the rearrangeable objects. */
620 for (i = 0; i < numObjs; i++)
621 dumpDumpableObject(g_fout, dobjs[i]);
624 dumpTimestamp(g_fout, "Completed on");
627 * And finally we can do the actual output.
631 ropt = NewRestoreOptions();
632 ropt->filename = (char *) filename;
633 ropt->dropSchema = outputClean;
634 ropt->aclsSkip = aclsSkip;
635 ropt->superuser = outputSuperuser;
636 ropt->create = outputCreate;
637 ropt->noOwner = outputNoOwner;
638 ropt->disable_triggers = disable_triggers;
639 ropt->use_setsessauth = use_setsessauth;
641 if (compressLevel == -1)
642 ropt->compression = 0;
644 ropt->compression = compressLevel;
646 ropt->suppressDumpWarnings = true; /* We've already shown
649 RestoreArchive(g_fout, ropt);
652 CloseArchive(g_fout);
661 help(const char *progname)
663 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
664 printf(_("Usage:\n"));
665 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
667 printf(_("\nGeneral options:\n"));
668 printf(_(" -f, --file=FILENAME output file name\n"));
669 printf(_(" -F, --format=c|t|p output file format (custom, tar, plain text)\n"));
670 printf(_(" -i, --ignore-version proceed even when server version mismatches\n"
671 " pg_dump version\n"));
672 printf(_(" -v, --verbose verbose mode\n"));
673 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
674 printf(_(" --help show this help, then exit\n"));
675 printf(_(" --version output version information, then exit\n"));
677 printf(_("\nOptions controlling the output content:\n"));
678 printf(_(" -a, --data-only dump only the data, not the schema\n"));
679 printf(_(" -b, --blobs include large objects in dump\n"));
680 printf(_(" -c, --clean clean (drop) schema prior to create\n"));
681 printf(_(" -C, --create include commands to create database in dump\n"));
682 printf(_(" -d, --inserts dump data as INSERT, rather than COPY, commands\n"));
683 printf(_(" -D, --column-inserts dump data as INSERT commands with column names\n"));
684 printf(_(" -n, --schema=SCHEMA dump the named schema only\n"));
685 printf(_(" -o, --oids include OIDs in dump\n"));
686 printf(_(" -O, --no-owner skip restoration of object ownership\n"
687 " in plain text format\n"));
688 printf(_(" -s, --schema-only dump only the schema, no data\n"));
689 printf(_(" -S, --superuser=NAME specify the superuser user name to use in\n"
690 " plain text format\n"));
691 printf(_(" -t, --table=TABLE dump the named table only\n"));
692 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
693 printf(_(" -X disable-dollar-quoting, --disable-dollar-quoting\n"
694 " disable dollar quoting, use SQL standard quoting\n"));
695 printf(_(" -X disable-triggers, --disable-triggers\n"
696 " disable triggers during data-only restore\n"));
697 printf(_(" -X use-set-session-authorization, --use-set-session-authorization\n"
698 " use SESSION AUTHORIZATION commands instead of\n"
699 " OWNER TO commands\n"));
701 printf(_("\nConnection options:\n"));
702 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
703 printf(_(" -p, --port=PORT database server port number\n"));
704 printf(_(" -U, --username=NAME connect as specified database user\n"));
705 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
707 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
708 "variable value is used.\n\n"));
709 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
717 write_msg(NULL, "*** aborted because of error\n");
722 * selectDumpableNamespace: policy-setting subroutine
723 * Mark a namespace as to be dumped or not
726 selectDumpableNamespace(NamespaceInfo *nsinfo)
729 * If a specific table is being dumped, do not dump any complete
730 * namespaces. If a specific namespace is being dumped, dump just
731 * that namespace. Otherwise, dump all non-system namespaces.
733 if (selectTableName != NULL)
734 nsinfo->dump = false;
735 else if (selectSchemaName != NULL)
737 if (strcmp(nsinfo->dobj.name, selectSchemaName) == 0)
740 nsinfo->dump = false;
742 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
743 strcmp(nsinfo->dobj.name, "information_schema") == 0)
744 nsinfo->dump = false;
750 * selectDumpableTable: policy-setting subroutine
751 * Mark a table as to be dumped or not
754 selectDumpableTable(TableInfo *tbinfo)
757 * Always dump if dumping parent namespace; else, if a particular
758 * tablename has been specified, dump matching table name; else, do
761 tbinfo->dump = false;
762 if (tbinfo->dobj.namespace->dump)
764 else if (selectTableName != NULL &&
765 strcmp(tbinfo->dobj.name, selectTableName) == 0)
767 /* If both -s and -t specified, must match both to dump */
768 if (selectSchemaName == NULL)
770 else if (strcmp(tbinfo->dobj.namespace->dobj.name, selectSchemaName) == 0)
776 * Dump a table's contents for loading using the COPY command
777 * - this routine is called by the Archiver when it wants the table
781 #define COPYBUFSIZ 8192
784 dumpTableData_copy(Archive *fout, void *dcontext)
786 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
787 TableInfo *tbinfo = tdinfo->tdtable;
788 const char *classname = tbinfo->dobj.name;
789 const bool hasoids = tbinfo->hasoids;
790 const bool oids = tdinfo->oids;
791 PQExpBuffer q = createPQExpBuffer();
795 char copybuf[COPYBUFSIZ];
796 const char *column_list;
799 write_msg(NULL, "dumping contents of table %s\n", classname);
802 * Make sure we are in proper schema. We will qualify the table name
803 * below anyway (in case its name conflicts with a pg_catalog table);
804 * but this ensures reproducible results in case the table contains
805 * regproc, regclass, etc columns.
807 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
810 * If possible, specify the column list explicitly so that we have no
811 * possibility of retrieving data in the wrong column order. (The
812 * default column ordering of COPY will not be what we want in certain
813 * corner cases involving ADD COLUMN and inheritance.)
815 if (g_fout->remoteVersion >= 70300)
816 column_list = fmtCopyColumnList(tbinfo);
818 column_list = ""; /* can't select columns in COPY */
822 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
823 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
829 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
830 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
834 res = PQexec(g_conn, q->data);
835 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
841 ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
843 if (copybuf[0] == '\\' &&
847 copydone = true; /* don't print this... */
851 archputs(copybuf, fout);
858 archputs("\n", fout);
868 * There was considerable discussion in late July, 2000 regarding
869 * slowing down pg_dump when backing up large tables. Users with
870 * both slow & fast (muti-processor) machines experienced
871 * performance degradation when doing a backup.
873 * Initial attempts based on sleeping for a number of ms for each ms
874 * of work were deemed too complex, then a simple 'sleep in each
875 * loop' implementation was suggested. The latter failed because
876 * the loop was too tight. Finally, the following was implemented:
878 * If throttle is non-zero, then See how long since the last sleep.
879 * Work out how long to sleep (based on ratio). If sleep is more
880 * than 100ms, then sleep reset timer EndIf EndIf
882 * where the throttle value was the number of ms to sleep per ms of
883 * work. The calculation was done in each loop.
885 * Most of the hard work is done in the backend, and this solution
886 * still did not work particularly well: on slow machines, the
887 * ratio was 50:1, and on medium paced machines, 1:1, and on fast
888 * multi-processor machines, it had little or no effect, for
889 * reasons that were unclear.
891 * Further discussion ensued, and the proposal was dropped.
893 * For those people who want this feature, it can be implemented
894 * using gettimeofday in each loop, calculating the time since
895 * last sleep, multiplying that by the sleep ratio, then if the
896 * result is more than a preset 'minimum sleep time' (say 100ms),
897 * call the 'select' function to sleep for a subsecond period ie.
899 * select(0, NULL, NULL, NULL, &tvi);
901 * This will return after the interval specified in the structure
902 * tvi. Finally, call gettimeofday again to save the 'last sleep
906 archprintf(fout, "\\.\n\n\n");
908 ret = PQendcopy(g_conn);
911 write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
912 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
913 write_msg(NULL, "The command was: %s\n", q->data);
918 destroyPQExpBuffer(q);
923 dumpTableData_insert(Archive *fout, void *dcontext)
925 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
926 TableInfo *tbinfo = tdinfo->tdtable;
927 const char *classname = tbinfo->dobj.name;
928 PQExpBuffer q = createPQExpBuffer();
935 * Make sure we are in proper schema. We will qualify the table name
936 * below anyway (in case its name conflicts with a pg_catalog table);
937 * but this ensures reproducible results in case the table contains
938 * regproc, regclass, etc columns.
940 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
942 if (fout->remoteVersion >= 70100)
944 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
945 "SELECT * FROM ONLY %s",
946 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
951 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
953 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
957 res = PQexec(g_conn, q->data);
958 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
964 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
965 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
967 nfields = PQnfields(res);
968 for (tuple = 0; tuple < PQntuples(res); tuple++)
970 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
973 /* corner case for zero-column table */
974 archprintf(fout, "DEFAULT VALUES;\n");
977 if (attrNames == true)
980 appendPQExpBuffer(q, "(");
981 for (field = 0; field < nfields; field++)
984 appendPQExpBuffer(q, ", ");
985 appendPQExpBuffer(q, fmtId(PQfname(res, field)));
987 appendPQExpBuffer(q, ") ");
988 archprintf(fout, "%s", q->data);
990 archprintf(fout, "VALUES (");
991 for (field = 0; field < nfields; field++)
994 archprintf(fout, ", ");
995 if (PQgetisnull(res, tuple, field))
997 archprintf(fout, "NULL");
1001 /* XXX This code is partially duplicated in ruleutils.c */
1002 switch (PQftype(res, field))
1013 * These types are printed without quotes
1014 * unless they contain values that aren't
1015 * accepted by the scanner unquoted (e.g.,
1016 * 'NaN'). Note that strtod() and friends
1017 * might accept NaN, so we can't use that to
1020 * In reality we only need to defend against
1021 * infinity and NaN, so we need not get too
1022 * crazy about pattern matching here.
1024 const char *s = PQgetvalue(res, tuple, field);
1026 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1027 archprintf(fout, "%s", s);
1029 archprintf(fout, "'%s'", s);
1035 archprintf(fout, "B'%s'",
1036 PQgetvalue(res, tuple, field));
1040 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1041 archprintf(fout, "true");
1043 archprintf(fout, "false");
1047 /* All other types are printed as string literals. */
1048 resetPQExpBuffer(q);
1049 appendStringLiteral(q, PQgetvalue(res, tuple, field), false);
1050 archprintf(fout, "%s", q->data);
1054 archprintf(fout, ");\n");
1056 } while (PQntuples(res) > 0);
1060 archprintf(fout, "\n\n");
1062 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1064 destroyPQExpBuffer(q);
1071 * dump the contents of a single table
1073 * Actually, this just makes an ArchiveEntry for the table contents.
1076 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1078 TableInfo *tbinfo = tdinfo->tdtable;
1079 PQExpBuffer copyBuf = createPQExpBuffer();
1080 DataDumperPtr dumpFn;
1085 /* Dump/restore using COPY */
1086 dumpFn = dumpTableData_copy;
1087 /* must use 2 steps here 'cause fmtId is nonreentrant */
1088 appendPQExpBuffer(copyBuf, "COPY %s ",
1089 fmtId(tbinfo->dobj.name));
1090 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1091 fmtCopyColumnList(tbinfo),
1092 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1093 copyStmt = copyBuf->data;
1097 /* Restore using INSERT */
1098 dumpFn = dumpTableData_insert;
1102 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1104 tbinfo->dobj.namespace->dobj.name,
1106 tbinfo->usename, false,
1107 "TABLE DATA", "", "", copyStmt,
1108 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1111 destroyPQExpBuffer(copyBuf);
1116 * set up dumpable objects representing the contents of tables
1119 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1123 for (i = 0; i < numTables; i++)
1125 /* Skip VIEWs (no data to dump) */
1126 if (tblinfo[i].relkind == RELKIND_VIEW)
1128 /* Skip SEQUENCEs (handled elsewhere) */
1129 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1132 if (tblinfo[i].dump)
1134 TableDataInfo *tdinfo;
1136 tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1138 tdinfo->dobj.objType = DO_TABLE_DATA;
1141 * Note: use tableoid 0 so that this object won't be mistaken
1142 * for something that pg_depend entries apply to.
1144 tdinfo->dobj.catId.tableoid = 0;
1145 tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1146 AssignDumpId(&tdinfo->dobj);
1147 tdinfo->dobj.name = tblinfo[i].dobj.name;
1148 tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1149 tdinfo->tdtable = &(tblinfo[i]);
1150 tdinfo->oids = oids;
1151 addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1159 * dump the database definition
1162 dumpDatabase(Archive *AH)
1164 PQExpBuffer dbQry = createPQExpBuffer();
1165 PQExpBuffer delQry = createPQExpBuffer();
1166 PQExpBuffer creaQry = createPQExpBuffer();
1176 const char *datname,
1181 datname = PQdb(g_conn);
1184 write_msg(NULL, "saving database definition\n");
1186 /* Make sure we are in proper schema */
1187 selectSourceSchema("pg_catalog");
1189 /* Get the database owner and parameters from pg_database */
1190 if (g_fout->remoteVersion >= 80000)
1192 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1193 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1194 "pg_encoding_to_char(encoding) as encoding, "
1195 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) as tablespace "
1197 "WHERE datname = ");
1198 appendStringLiteral(dbQry, datname, true);
1200 else if (g_fout->remoteVersion >= 70100)
1202 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1203 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1204 "pg_encoding_to_char(encoding) as encoding, "
1205 "NULL as tablespace "
1207 "WHERE datname = ");
1208 appendStringLiteral(dbQry, datname, true);
1212 appendPQExpBuffer(dbQry, "SELECT "
1213 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1215 "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1216 "pg_encoding_to_char(encoding) as encoding, "
1217 "NULL as tablespace "
1219 "WHERE datname = ");
1220 appendStringLiteral(dbQry, datname, true);
1223 res = PQexec(g_conn, dbQry->data);
1224 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1226 ntups = PQntuples(res);
1230 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1237 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1242 i_tableoid = PQfnumber(res, "tableoid");
1243 i_oid = PQfnumber(res, "oid");
1244 i_dba = PQfnumber(res, "dba");
1245 i_encoding = PQfnumber(res, "encoding");
1246 i_tablespace = PQfnumber(res, "tablespace");
1248 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1249 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1250 dba = PQgetvalue(res, 0, i_dba);
1251 encoding = PQgetvalue(res, 0, i_encoding);
1252 tablespace = PQgetvalue(res, 0, i_tablespace);
1254 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1256 if (strlen(encoding) > 0)
1258 appendPQExpBuffer(creaQry, " ENCODING = ");
1259 appendStringLiteral(creaQry, encoding, true);
1261 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1262 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1264 appendPQExpBuffer(creaQry, ";\n");
1266 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1269 dbDumpId = createDumpId();
1272 dbCatId, /* catalog ID */
1273 dbDumpId, /* dump ID */
1275 NULL, /* Namespace */
1276 NULL, /* Tablespace */
1278 false, /* with oids */
1279 "DATABASE", /* Desc */
1280 creaQry->data, /* Create */
1281 delQry->data, /* Del */
1286 NULL); /* Dumper Arg */
1288 /* Dump DB comment if any */
1289 resetPQExpBuffer(dbQry);
1290 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1291 dumpComment(AH, dbQry->data, NULL, "",
1292 dbCatId, 0, dbDumpId);
1296 destroyPQExpBuffer(dbQry);
1297 destroyPQExpBuffer(delQry);
1298 destroyPQExpBuffer(creaQry);
1306 dumpTimestamp(Archive *AH, char *msg)
1309 time_t now = time(NULL);
1311 if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&now)) != 0)
1313 PQExpBuffer qry = createPQExpBuffer();
1315 appendPQExpBuffer(qry, "-- ");
1316 appendPQExpBuffer(qry, msg);
1317 appendPQExpBuffer(qry, " ");
1318 appendPQExpBuffer(qry, buf);
1319 appendPQExpBuffer(qry, "\n");
1321 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1322 "DUMP TIMESTAMP", NULL, NULL, "",
1323 false, "DUMP TIMESTAMP", qry->data, "", NULL,
1326 destroyPQExpBuffer(qry);
1332 * dumpEncoding: put the correct encoding into the archive
1335 dumpEncoding(Archive *AH)
1340 /* Can't read the encoding from pre-7.3 servers (SHOW isn't a query) */
1341 if (AH->remoteVersion < 70300)
1345 write_msg(NULL, "saving encoding\n");
1347 qry = createPQExpBuffer();
1349 appendPQExpBuffer(qry, "SHOW client_encoding");
1351 res = PQexec(g_conn, qry->data);
1353 check_sql_result(res, g_conn, qry->data, PGRES_TUPLES_OK);
1355 resetPQExpBuffer(qry);
1357 appendPQExpBuffer(qry, "SET client_encoding = ");
1358 appendStringLiteral(qry, PQgetvalue(res, 0, 0), true);
1359 appendPQExpBuffer(qry, ";\n");
1361 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1362 "ENCODING", NULL, NULL, "",
1363 false, "ENCODING", qry->data, "", NULL,
1369 destroyPQExpBuffer(qry);
1379 #define loBufSize 16384
1380 #define loFetchSize 1000
1383 dumpBlobs(Archive *AH, void *arg)
1385 PQExpBuffer oidQry = createPQExpBuffer();
1386 PQExpBuffer oidFetchQry = createPQExpBuffer();
1390 char buf[loBufSize];
1395 write_msg(NULL, "saving large objects\n");
1397 /* Make sure we are in proper schema */
1398 selectSourceSchema("pg_catalog");
1400 /* Cursor to get all BLOB tables */
1401 if (AH->remoteVersion >= 70100)
1402 appendPQExpBuffer(oidQry, "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject");
1404 appendPQExpBuffer(oidQry, "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'");
1406 res = PQexec(g_conn, oidQry->data);
1407 check_sql_result(res, g_conn, oidQry->data, PGRES_COMMAND_OK);
1409 /* Fetch for cursor */
1410 appendPQExpBuffer(oidFetchQry, "FETCH %d IN bloboid", loFetchSize);
1417 res = PQexec(g_conn, oidFetchQry->data);
1418 check_sql_result(res, g_conn, oidFetchQry->data, PGRES_TUPLES_OK);
1420 /* Process the tuples, if any */
1421 for (i = 0; i < PQntuples(res); i++)
1423 blobOid = atooid(PQgetvalue(res, i, 0));
1425 loFd = lo_open(g_conn, blobOid, INV_READ);
1428 write_msg(NULL, "dumpBlobs(): could not open large object: %s",
1429 PQerrorMessage(g_conn));
1433 StartBlob(AH, blobOid);
1435 /* Now read it in chunks, sending data to archive */
1438 cnt = lo_read(g_conn, loFd, buf, loBufSize);
1441 write_msg(NULL, "dumpBlobs(): error reading large object: %s",
1442 PQerrorMessage(g_conn));
1446 WriteData(AH, buf, cnt);
1450 lo_close(g_conn, loFd);
1452 EndBlob(AH, blobOid);
1455 } while (PQntuples(res) > 0);
1457 destroyPQExpBuffer(oidQry);
1458 destroyPQExpBuffer(oidFetchQry);
1465 * read all namespaces in the system catalogs and return them in the
1466 * NamespaceInfo* structure
1468 * numNamespaces is set to the number of namespaces read in
1471 getNamespaces(int *numNamespaces)
1477 NamespaceInfo *nsinfo;
1485 * Before 7.3, there are no real namespaces; create two dummy entries,
1486 * one for user stuff and one for system stuff.
1488 if (g_fout->remoteVersion < 70300)
1490 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
1492 nsinfo[0].dobj.objType = DO_NAMESPACE;
1493 nsinfo[0].dobj.catId.tableoid = 0;
1494 nsinfo[0].dobj.catId.oid = 0;
1495 AssignDumpId(&nsinfo[0].dobj);
1496 nsinfo[0].dobj.name = strdup("public");
1497 nsinfo[0].usename = strdup("");
1498 nsinfo[0].nspacl = strdup("");
1500 selectDumpableNamespace(&nsinfo[0]);
1502 nsinfo[1].dobj.objType = DO_NAMESPACE;
1503 nsinfo[1].dobj.catId.tableoid = 0;
1504 nsinfo[1].dobj.catId.oid = 1;
1505 AssignDumpId(&nsinfo[1].dobj);
1506 nsinfo[1].dobj.name = strdup("pg_catalog");
1507 nsinfo[1].usename = strdup("");
1508 nsinfo[1].nspacl = strdup("");
1510 selectDumpableNamespace(&nsinfo[1]);
1512 g_namespaces = nsinfo;
1513 g_numNamespaces = *numNamespaces = 2;
1518 query = createPQExpBuffer();
1520 /* Make sure we are in proper schema */
1521 selectSourceSchema("pg_catalog");
1524 * we fetch all namespaces including system ones, so that every object
1525 * we read in can be linked to a containing namespace.
1527 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1528 "(select usename from pg_user where nspowner = usesysid) as usename, "
1529 "nspacl FROM pg_namespace");
1531 res = PQexec(g_conn, query->data);
1532 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1534 ntups = PQntuples(res);
1536 nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1538 i_tableoid = PQfnumber(res, "tableoid");
1539 i_oid = PQfnumber(res, "oid");
1540 i_nspname = PQfnumber(res, "nspname");
1541 i_usename = PQfnumber(res, "usename");
1542 i_nspacl = PQfnumber(res, "nspacl");
1544 for (i = 0; i < ntups; i++)
1546 nsinfo[i].dobj.objType = DO_NAMESPACE;
1547 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1548 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1549 AssignDumpId(&nsinfo[i].dobj);
1550 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
1551 nsinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1552 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1554 /* Decide whether to dump this namespace */
1555 selectDumpableNamespace(&nsinfo[i]);
1557 if (strlen(nsinfo[i].usename) == 0)
1558 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
1559 nsinfo[i].dobj.name);
1563 * If the user attempted to dump a specific namespace, check to ensure
1564 * that the specified namespace actually exists.
1566 if (selectSchemaName)
1568 for (i = 0; i < ntups; i++)
1569 if (strcmp(nsinfo[i].dobj.name, selectSchemaName) == 0)
1572 /* Didn't find a match */
1575 write_msg(NULL, "specified schema \"%s\" does not exist\n",
1582 destroyPQExpBuffer(query);
1584 g_namespaces = nsinfo;
1585 g_numNamespaces = *numNamespaces = ntups;
1592 * given a namespace OID and an object OID, look up the info read by
1595 * NB: for pre-7.3 source database, we use object OID to guess whether it's
1596 * a system object or not. In 7.3 and later there is no guessing.
1598 static NamespaceInfo *
1599 findNamespace(Oid nsoid, Oid objoid)
1603 if (g_fout->remoteVersion >= 70300)
1605 for (i = 0; i < g_numNamespaces; i++)
1607 NamespaceInfo *nsinfo = &g_namespaces[i];
1609 if (nsoid == nsinfo->dobj.catId.oid)
1612 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
1617 /* This code depends on the layout set up by getNamespaces. */
1618 if (objoid > g_last_builtin_oid)
1619 i = 0; /* user object */
1621 i = 1; /* system object */
1622 return &g_namespaces[i];
1625 return NULL; /* keep compiler quiet */
1630 * read all types in the system catalogs and return them in the
1631 * TypeInfo* structure
1633 * numTypes is set to the number of types read in
1635 * NB: this must run after getFuncs() because we assume we can do
1639 getTypes(int *numTypes)
1644 PQExpBuffer query = createPQExpBuffer();
1660 * we include even the built-in types because those may be used as
1661 * array elements by user-defined types
1663 * we filter out the built-in types when we dump out the types
1665 * same approach for undefined (shell) types
1668 /* Make sure we are in proper schema */
1669 selectSourceSchema("pg_catalog");
1671 if (g_fout->remoteVersion >= 70300)
1673 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1675 "(select usename from pg_user where typowner = usesysid) as usename, "
1676 "typinput::oid as typinput, "
1677 "typoutput::oid as typoutput, typelem, typrelid, "
1678 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1679 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1680 "typtype, typisdefined "
1683 else if (g_fout->remoteVersion >= 70100)
1685 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1686 "0::oid as typnamespace, "
1687 "(select usename from pg_user where typowner = usesysid) as usename, "
1688 "typinput::oid as typinput, "
1689 "typoutput::oid as typoutput, typelem, typrelid, "
1690 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1691 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1692 "typtype, typisdefined "
1697 appendPQExpBuffer(query, "SELECT "
1698 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
1700 "0::oid as typnamespace, "
1701 "(select usename from pg_user where typowner = usesysid) as usename, "
1702 "typinput::oid as typinput, "
1703 "typoutput::oid as typoutput, typelem, typrelid, "
1704 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1705 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1706 "typtype, typisdefined "
1710 res = PQexec(g_conn, query->data);
1711 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1713 ntups = PQntuples(res);
1715 tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1717 i_tableoid = PQfnumber(res, "tableoid");
1718 i_oid = PQfnumber(res, "oid");
1719 i_typname = PQfnumber(res, "typname");
1720 i_typnamespace = PQfnumber(res, "typnamespace");
1721 i_usename = PQfnumber(res, "usename");
1722 i_typinput = PQfnumber(res, "typinput");
1723 i_typoutput = PQfnumber(res, "typoutput");
1724 i_typelem = PQfnumber(res, "typelem");
1725 i_typrelid = PQfnumber(res, "typrelid");
1726 i_typrelkind = PQfnumber(res, "typrelkind");
1727 i_typtype = PQfnumber(res, "typtype");
1728 i_typisdefined = PQfnumber(res, "typisdefined");
1730 for (i = 0; i < ntups; i++)
1735 tinfo[i].dobj.objType = DO_TYPE;
1736 tinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1737 tinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1738 AssignDumpId(&tinfo[i].dobj);
1739 tinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
1740 tinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
1741 tinfo[i].dobj.catId.oid);
1742 tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1743 tinfo[i].typinput = atooid(PQgetvalue(res, i, i_typinput));
1744 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
1745 tinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
1746 tinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
1747 tinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
1748 tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
1751 * If it's a table's rowtype, use special type code to facilitate
1752 * sorting into the desired order. (We don't want to consider it
1753 * an ordinary type because that would bring the table up into the
1754 * datatype part of the dump order.)
1756 if (OidIsValid(tinfo[i].typrelid) && tinfo[i].typrelkind != 'c')
1757 tinfo[i].dobj.objType = DO_TABLE_TYPE;
1760 * check for user-defined array types, omit system generated ones
1762 if (OidIsValid(tinfo[i].typelem) &&
1763 tinfo[i].dobj.name[0] != '_')
1764 tinfo[i].isArray = true;
1766 tinfo[i].isArray = false;
1768 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
1769 tinfo[i].isDefined = true;
1771 tinfo[i].isDefined = false;
1774 * If it's a domain, fetch info about its constraints, if any
1776 tinfo[i].nDomChecks = 0;
1777 tinfo[i].domChecks = NULL;
1778 if (tinfo[i].typtype == 'd')
1779 getDomainConstraints(&(tinfo[i]));
1782 * Make sure there are dependencies from the type to its input and
1783 * output functions. (We don't worry about typsend, typreceive,
1784 * or typanalyze since those are only valid in 7.4 and later,
1785 * wherein the standard dependency mechanism will pick them up.)
1787 funcInfo = findFuncByOid(tinfo[i].typinput);
1789 addObjectDependency(&tinfo[i].dobj,
1790 funcInfo->dobj.dumpId);
1791 funcInfo = findFuncByOid(typoutput);
1793 addObjectDependency(&tinfo[i].dobj,
1794 funcInfo->dobj.dumpId);
1796 if (strlen(tinfo[i].usename) == 0 && tinfo[i].isDefined)
1797 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
1798 tinfo[i].dobj.name);
1805 destroyPQExpBuffer(query);
1812 * read all operators in the system catalogs and return them in the
1813 * OprInfo* structure
1815 * numOprs is set to the number of operators read in
1818 getOperators(int *numOprs)
1823 PQExpBuffer query = createPQExpBuffer();
1833 * find all operators, including builtin operators; we filter out
1834 * system-defined operators at dump-out time.
1837 /* Make sure we are in proper schema */
1838 selectSourceSchema("pg_catalog");
1840 if (g_fout->remoteVersion >= 70300)
1842 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1844 "(select usename from pg_user where oprowner = usesysid) as usename, "
1845 "oprcode::oid as oprcode "
1846 "FROM pg_operator");
1848 else if (g_fout->remoteVersion >= 70100)
1850 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1851 "0::oid as oprnamespace, "
1852 "(select usename from pg_user where oprowner = usesysid) as usename, "
1853 "oprcode::oid as oprcode "
1854 "FROM pg_operator");
1858 appendPQExpBuffer(query, "SELECT "
1859 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
1861 "0::oid as oprnamespace, "
1862 "(select usename from pg_user where oprowner = usesysid) as usename, "
1863 "oprcode::oid as oprcode "
1864 "FROM pg_operator");
1867 res = PQexec(g_conn, query->data);
1868 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1870 ntups = PQntuples(res);
1873 oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
1875 i_tableoid = PQfnumber(res, "tableoid");
1876 i_oid = PQfnumber(res, "oid");
1877 i_oprname = PQfnumber(res, "oprname");
1878 i_oprnamespace = PQfnumber(res, "oprnamespace");
1879 i_usename = PQfnumber(res, "usename");
1880 i_oprcode = PQfnumber(res, "oprcode");
1882 for (i = 0; i < ntups; i++)
1884 oprinfo[i].dobj.objType = DO_OPERATOR;
1885 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1886 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1887 AssignDumpId(&oprinfo[i].dobj);
1888 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
1889 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
1890 oprinfo[i].dobj.catId.oid);
1891 oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1892 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
1894 if (strlen(oprinfo[i].usename) == 0)
1895 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
1896 oprinfo[i].dobj.name);
1901 destroyPQExpBuffer(query);
1908 * read all conversions in the system catalogs and return them in the
1909 * ConvInfo* structure
1911 * numConversions is set to the number of conversions read in
1914 getConversions(int *numConversions)
1919 PQExpBuffer query = createPQExpBuffer();
1927 /* Conversions didn't exist pre-7.3 */
1928 if (g_fout->remoteVersion < 70300)
1930 *numConversions = 0;
1935 * find all conversions, including builtin conversions; we filter out
1936 * system-defined conversions at dump-out time.
1939 /* Make sure we are in proper schema */
1940 selectSourceSchema("pg_catalog");
1942 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
1944 "(select usename from pg_user where conowner = usesysid) as usename "
1945 "FROM pg_conversion");
1947 res = PQexec(g_conn, query->data);
1948 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1950 ntups = PQntuples(res);
1951 *numConversions = ntups;
1953 convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
1955 i_tableoid = PQfnumber(res, "tableoid");
1956 i_oid = PQfnumber(res, "oid");
1957 i_conname = PQfnumber(res, "conname");
1958 i_connamespace = PQfnumber(res, "connamespace");
1959 i_usename = PQfnumber(res, "usename");
1961 for (i = 0; i < ntups; i++)
1963 convinfo[i].dobj.objType = DO_CONVERSION;
1964 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1965 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1966 AssignDumpId(&convinfo[i].dobj);
1967 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
1968 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
1969 convinfo[i].dobj.catId.oid);
1970 convinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1975 destroyPQExpBuffer(query);
1982 * read all opclasses in the system catalogs and return them in the
1983 * OpclassInfo* structure
1985 * numOpclasses is set to the number of opclasses read in
1988 getOpclasses(int *numOpclasses)
1993 PQExpBuffer query = createPQExpBuffer();
1994 OpclassInfo *opcinfo;
2002 * find all opclasses, including builtin opclasses; we filter out
2003 * system-defined opclasses at dump-out time.
2006 /* Make sure we are in proper schema */
2007 selectSourceSchema("pg_catalog");
2009 if (g_fout->remoteVersion >= 70300)
2011 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2013 "(select usename from pg_user where opcowner = usesysid) as usename "
2016 else if (g_fout->remoteVersion >= 70100)
2018 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2019 "0::oid as opcnamespace, "
2020 "''::name as usename "
2025 appendPQExpBuffer(query, "SELECT "
2026 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2028 "0::oid as opcnamespace, "
2029 "''::name as usename "
2033 res = PQexec(g_conn, query->data);
2034 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2036 ntups = PQntuples(res);
2037 *numOpclasses = ntups;
2039 opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2041 i_tableoid = PQfnumber(res, "tableoid");
2042 i_oid = PQfnumber(res, "oid");
2043 i_opcname = PQfnumber(res, "opcname");
2044 i_opcnamespace = PQfnumber(res, "opcnamespace");
2045 i_usename = PQfnumber(res, "usename");
2047 for (i = 0; i < ntups; i++)
2049 opcinfo[i].dobj.objType = DO_OPCLASS;
2050 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2051 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2052 AssignDumpId(&opcinfo[i].dobj);
2053 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
2054 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
2055 opcinfo[i].dobj.catId.oid);
2056 opcinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2058 if (g_fout->remoteVersion >= 70300)
2060 if (strlen(opcinfo[i].usename) == 0)
2061 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
2062 opcinfo[i].dobj.name);
2068 destroyPQExpBuffer(query);
2075 * read all the user-defined aggregates in the system catalogs and
2076 * return them in the AggInfo* structure
2078 * numAggs is set to the number of aggregates read in
2081 getAggregates(int *numAggs)
2086 PQExpBuffer query = createPQExpBuffer();
2096 /* Make sure we are in proper schema */
2097 selectSourceSchema("pg_catalog");
2099 /* find all user-defined aggregates */
2101 if (g_fout->remoteVersion >= 70300)
2103 appendPQExpBuffer(query, "SELECT tableoid, oid, proname as aggname, "
2104 "pronamespace as aggnamespace, "
2105 "proargtypes[0] as aggbasetype, "
2106 "(select usename from pg_user where proowner = usesysid) as usename, "
2110 "AND pronamespace != "
2111 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2113 else if (g_fout->remoteVersion >= 70100)
2115 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
2116 "0::oid as aggnamespace, "
2118 "(select usename from pg_user where aggowner = usesysid) as usename, "
2120 "FROM pg_aggregate "
2121 "where oid > '%u'::oid",
2122 g_last_builtin_oid);
2126 appendPQExpBuffer(query, "SELECT "
2127 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
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);
2138 res = PQexec(g_conn, query->data);
2139 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2141 ntups = PQntuples(res);
2144 agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
2146 i_tableoid = PQfnumber(res, "tableoid");
2147 i_oid = PQfnumber(res, "oid");
2148 i_aggname = PQfnumber(res, "aggname");
2149 i_aggnamespace = PQfnumber(res, "aggnamespace");
2150 i_aggbasetype = PQfnumber(res, "aggbasetype");
2151 i_usename = PQfnumber(res, "usename");
2152 i_aggacl = PQfnumber(res, "aggacl");
2154 for (i = 0; i < ntups; i++)
2156 agginfo[i].aggfn.dobj.objType = DO_AGG;
2157 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2158 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2159 AssignDumpId(&agginfo[i].aggfn.dobj);
2160 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
2161 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
2162 agginfo[i].aggfn.dobj.catId.oid);
2163 agginfo[i].aggfn.usename = strdup(PQgetvalue(res, i, i_usename));
2164 if (strlen(agginfo[i].aggfn.usename) == 0)
2165 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
2166 agginfo[i].aggfn.dobj.name);
2167 agginfo[i].aggfn.lang = InvalidOid; /* not currently
2169 agginfo[i].aggfn.nargs = 1;
2170 agginfo[i].aggfn.argtypes = (Oid *) malloc(sizeof(Oid));
2171 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_aggbasetype));
2172 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
2173 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
2174 agginfo[i].anybasetype = false; /* computed when it's dumped */
2175 agginfo[i].fmtbasetype = NULL; /* computed when it's dumped */
2180 destroyPQExpBuffer(query);
2187 * read all the user-defined functions in the system catalogs and
2188 * return them in the FuncInfo* structure
2190 * numFuncs is set to the number of functions read in
2193 getFuncs(int *numFuncs)
2198 PQExpBuffer query = createPQExpBuffer();
2211 /* Make sure we are in proper schema */
2212 selectSourceSchema("pg_catalog");
2214 /* find all user-defined funcs */
2216 if (g_fout->remoteVersion >= 70300)
2218 appendPQExpBuffer(query,
2219 "SELECT tableoid, oid, proname, prolang, "
2220 "pronargs, proargtypes, prorettype, proacl, "
2222 "(select usename from pg_user where proowner = usesysid) as usename "
2224 "WHERE NOT proisagg "
2225 "AND pronamespace != "
2226 "(select oid from pg_namespace where nspname = 'pg_catalog')");
2228 else if (g_fout->remoteVersion >= 70100)
2230 appendPQExpBuffer(query,
2231 "SELECT tableoid, oid, proname, prolang, "
2232 "pronargs, proargtypes, prorettype, "
2233 "'{=X}' as proacl, "
2234 "0::oid as pronamespace, "
2235 "(select usename from pg_user where proowner = usesysid) as usename "
2237 "where pg_proc.oid > '%u'::oid",
2238 g_last_builtin_oid);
2242 appendPQExpBuffer(query,
2244 "(SELECT oid FROM pg_class WHERE relname = 'pg_proc') AS tableoid, "
2245 "oid, proname, prolang, "
2246 "pronargs, proargtypes, prorettype, "
2247 "'{=X}' as proacl, "
2248 "0::oid as pronamespace, "
2249 "(select usename from pg_user where proowner = usesysid) as usename "
2251 "where pg_proc.oid > '%u'::oid",
2252 g_last_builtin_oid);
2255 res = PQexec(g_conn, query->data);
2256 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2258 ntups = PQntuples(res);
2262 finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
2264 i_tableoid = PQfnumber(res, "tableoid");
2265 i_oid = PQfnumber(res, "oid");
2266 i_proname = PQfnumber(res, "proname");
2267 i_pronamespace = PQfnumber(res, "pronamespace");
2268 i_usename = PQfnumber(res, "usename");
2269 i_prolang = PQfnumber(res, "prolang");
2270 i_pronargs = PQfnumber(res, "pronargs");
2271 i_proargtypes = PQfnumber(res, "proargtypes");
2272 i_prorettype = PQfnumber(res, "prorettype");
2273 i_proacl = PQfnumber(res, "proacl");
2275 for (i = 0; i < ntups; i++)
2277 finfo[i].dobj.objType = DO_FUNC;
2278 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2279 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2280 AssignDumpId(&finfo[i].dobj);
2281 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
2282 finfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
2283 finfo[i].dobj.catId.oid);
2284 finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2285 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2286 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
2287 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
2288 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
2289 if (finfo[i].nargs == 0)
2290 finfo[i].argtypes = NULL;
2293 finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
2294 parseOidArray(PQgetvalue(res, i, i_proargtypes),
2295 finfo[i].argtypes, finfo[i].nargs);
2298 if (strlen(finfo[i].usename) == 0)
2299 write_msg(NULL, "WARNING: owner of function \"%s\" appears to be invalid\n",
2300 finfo[i].dobj.name);
2305 destroyPQExpBuffer(query);
2312 * read all the user-defined tables (no indexes, no catalogs)
2313 * in the system catalogs return them in the TableInfo* structure
2315 * numTables is set to the number of tables read in
2318 getTables(int *numTables)
2323 PQExpBuffer query = createPQExpBuffer();
2324 PQExpBuffer delqry = createPQExpBuffer();
2325 PQExpBuffer lockquery = createPQExpBuffer();
2341 int i_reltablespace;
2343 /* Make sure we are in proper schema */
2344 selectSourceSchema("pg_catalog");
2347 * Find all the tables (including views and sequences).
2349 * We include system catalogs, so that we can work if a user table is
2350 * defined to inherit from a system catalog (pretty weird, but...)
2352 * We ignore tables that are not type 'r' (ordinary relation) or 'S'
2353 * (sequence) or 'v' (view).
2355 * Note: in this phase we should collect only a minimal amount of
2356 * information about each table, basically just enough to decide if it
2357 * is interesting. We must fetch all tables in this phase because
2358 * otherwise we cannot correctly identify inherited columns, serial
2362 if (g_fout->remoteVersion >= 80000)
2365 * Left join to pick up dependency info linking sequences to their
2366 * serial column, if any
2368 appendPQExpBuffer(query,
2369 "SELECT c.tableoid, c.oid, relname, "
2370 "relacl, relkind, relnamespace, "
2371 "(select usename from pg_user where relowner = usesysid) as usename, "
2372 "relchecks, reltriggers, "
2373 "relhasindex, relhasrules, relhasoids, "
2374 "d.refobjid as owning_tab, "
2375 "d.refobjsubid as owning_col, "
2376 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace "
2378 "left join pg_depend d on "
2379 "(c.relkind = '%c' and "
2380 "d.classid = c.tableoid and d.objid = c.oid and "
2381 "d.objsubid = 0 and "
2382 "d.refclassid = c.tableoid and d.deptype = 'i') "
2383 "where relkind in ('%c', '%c', '%c') "
2386 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2388 else if (g_fout->remoteVersion >= 70300)
2391 * Left join to pick up dependency info linking sequences to their
2392 * serial column, if any
2394 appendPQExpBuffer(query,
2395 "SELECT c.tableoid, c.oid, relname, "
2396 "relacl, relkind, relnamespace, "
2397 "(select usename from pg_user where relowner = usesysid) as usename, "
2398 "relchecks, reltriggers, "
2399 "relhasindex, relhasrules, relhasoids, "
2400 "d.refobjid as owning_tab, "
2401 "d.refobjsubid as owning_col, "
2402 "NULL as reltablespace "
2404 "left join pg_depend d on "
2405 "(c.relkind = '%c' and "
2406 "d.classid = c.tableoid and d.objid = c.oid and "
2407 "d.objsubid = 0 and "
2408 "d.refclassid = c.tableoid and d.deptype = 'i') "
2409 "where relkind in ('%c', '%c', '%c') "
2412 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2414 else if (g_fout->remoteVersion >= 70200)
2416 appendPQExpBuffer(query,
2417 "SELECT tableoid, oid, relname, relacl, relkind, "
2418 "0::oid as relnamespace, "
2419 "(select usename from pg_user where relowner = usesysid) as usename, "
2420 "relchecks, reltriggers, "
2421 "relhasindex, relhasrules, relhasoids, "
2422 "NULL::oid as owning_tab, "
2423 "NULL::int4 as owning_col, "
2424 "NULL as reltablespace "
2426 "where relkind in ('%c', '%c', '%c') "
2428 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2430 else if (g_fout->remoteVersion >= 70100)
2432 /* all tables have oids in 7.1 */
2433 appendPQExpBuffer(query,
2434 "SELECT tableoid, oid, relname, relacl, relkind, "
2435 "0::oid as relnamespace, "
2436 "(select usename from pg_user where relowner = usesysid) as usename, "
2437 "relchecks, reltriggers, "
2438 "relhasindex, relhasrules, "
2439 "'t'::bool as relhasoids, "
2440 "NULL::oid as owning_tab, "
2441 "NULL::int4 as owning_col, "
2442 "NULL as reltablespace "
2444 "where relkind in ('%c', '%c', '%c') "
2446 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2451 * Before 7.1, view relkind was not set to 'v', so we must check
2452 * if we have a view by looking for a rule in pg_rewrite.
2454 appendPQExpBuffer(query,
2456 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2457 "oid, relname, relacl, "
2458 "CASE WHEN relhasrules and relkind = 'r' "
2459 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
2460 " r.ev_class = c.oid AND r.ev_type = '1') "
2461 "THEN '%c'::\"char\" "
2462 "ELSE relkind END AS relkind,"
2463 "0::oid as relnamespace, "
2464 "(select usename from pg_user where relowner = usesysid) as usename, "
2465 "relchecks, reltriggers, "
2466 "relhasindex, relhasrules, "
2467 "'t'::bool as relhasoids, "
2468 "NULL::oid as owning_tab, "
2469 "NULL::int4 as owning_col, "
2470 "NULL as reltablespace "
2472 "where relkind in ('%c', '%c') "
2475 RELKIND_RELATION, RELKIND_SEQUENCE);
2478 res = PQexec(g_conn, query->data);
2479 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2481 ntups = PQntuples(res);
2486 * Extract data from result and lock dumpable tables. We do the
2487 * locking before anything else, to minimize the window wherein a
2488 * table could disappear under us.
2490 * Note that we have to save info about all tables here, even when
2491 * dumping only one, because we don't yet know which tables might be
2492 * inheritance ancestors of the target table.
2494 tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
2496 i_reltableoid = PQfnumber(res, "tableoid");
2497 i_reloid = PQfnumber(res, "oid");
2498 i_relname = PQfnumber(res, "relname");
2499 i_relnamespace = PQfnumber(res, "relnamespace");
2500 i_relacl = PQfnumber(res, "relacl");
2501 i_relkind = PQfnumber(res, "relkind");
2502 i_usename = PQfnumber(res, "usename");
2503 i_relchecks = PQfnumber(res, "relchecks");
2504 i_reltriggers = PQfnumber(res, "reltriggers");
2505 i_relhasindex = PQfnumber(res, "relhasindex");
2506 i_relhasrules = PQfnumber(res, "relhasrules");
2507 i_relhasoids = PQfnumber(res, "relhasoids");
2508 i_owning_tab = PQfnumber(res, "owning_tab");
2509 i_owning_col = PQfnumber(res, "owning_col");
2510 i_reltablespace = PQfnumber(res, "reltablespace");
2512 for (i = 0; i < ntups; i++)
2514 tblinfo[i].dobj.objType = DO_TABLE;
2515 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
2516 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
2517 AssignDumpId(&tblinfo[i].dobj);
2518 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
2519 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
2520 tblinfo[i].dobj.catId.oid);
2521 tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2522 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
2523 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
2524 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
2525 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
2526 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
2527 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
2528 tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2529 if (PQgetisnull(res, i, i_owning_tab))
2531 tblinfo[i].owning_tab = InvalidOid;
2532 tblinfo[i].owning_col = 0;
2536 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
2537 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
2539 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
2541 /* other fields were zeroed above */
2544 * Decide whether we want to dump this table. Sequences owned by
2545 * serial columns are never dumpable on their own; we will
2546 * transpose their owning table's dump flag to them below.
2548 if (OidIsValid(tblinfo[i].owning_tab))
2549 tblinfo[i].dump = false;
2551 selectDumpableTable(&tblinfo[i]);
2552 tblinfo[i].interesting = tblinfo[i].dump;
2555 * Read-lock target tables to make sure they aren't DROPPED or
2556 * altered in schema before we get around to dumping them.
2558 * Note that we don't explicitly lock parents of the target tables;
2559 * we assume our lock on the child is enough to prevent schema
2560 * alterations to parent tables.
2562 * NOTE: it'd be kinda nice to lock views and sequences too, not only
2563 * plain tables, but the backend doesn't presently allow that.
2565 if (tblinfo[i].dump && tblinfo[i].relkind == RELKIND_RELATION)
2567 resetPQExpBuffer(lockquery);
2568 appendPQExpBuffer(lockquery,
2569 "LOCK TABLE %s IN ACCESS SHARE MODE",
2570 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
2571 tblinfo[i].dobj.name));
2572 do_sql_command(g_conn, lockquery->data);
2575 /* Emit notice if join for owner failed */
2576 if (strlen(tblinfo[i].usename) == 0)
2577 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
2578 tblinfo[i].dobj.name);
2582 * If the user is attempting to dump a specific table, check to ensure
2583 * that the specified table actually exists. (This is a bit
2584 * simplistic since we don't fully check the combination of -n and -t
2587 if (selectTableName)
2589 for (i = 0; i < ntups; i++)
2590 if (strcmp(tblinfo[i].dobj.name, selectTableName) == 0)
2593 /* Didn't find a match */
2596 write_msg(NULL, "specified table \"%s\" does not exist\n",
2603 destroyPQExpBuffer(query);
2604 destroyPQExpBuffer(delqry);
2605 destroyPQExpBuffer(lockquery);
2612 * read all the inheritance information
2613 * from the system catalogs return them in the InhInfo* structure
2615 * numInherits is set to the number of pairs read in
2618 getInherits(int *numInherits)
2623 PQExpBuffer query = createPQExpBuffer();
2629 /* Make sure we are in proper schema */
2630 selectSourceSchema("pg_catalog");
2632 /* find all the inheritance information */
2634 appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2636 res = PQexec(g_conn, query->data);
2637 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2639 ntups = PQntuples(res);
2641 *numInherits = ntups;
2643 inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
2645 i_inhrelid = PQfnumber(res, "inhrelid");
2646 i_inhparent = PQfnumber(res, "inhparent");
2648 for (i = 0; i < ntups; i++)
2650 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
2651 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
2656 destroyPQExpBuffer(query);
2663 * get information about every index on a dumpable table
2665 * Note: index data is not returned directly to the caller, but it
2666 * does get entered into the DumpableObject tables.
2669 getIndexes(TableInfo tblinfo[], int numTables)
2673 PQExpBuffer query = createPQExpBuffer();
2676 ConstraintInfo *constrinfo;
2691 for (i = 0; i < numTables; i++)
2693 TableInfo *tbinfo = &tblinfo[i];
2695 /* Only plain tables have indexes */
2696 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
2703 write_msg(NULL, "reading indexes for table \"%s\"\n",
2706 /* Make sure we are in proper schema so indexdef is right */
2707 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2710 * The point of the messy-looking outer join is to find a
2711 * constraint that is related by an internal dependency link to
2712 * the index. If we find one, create a CONSTRAINT entry linked to
2713 * the INDEX entry. We assume an index won't have more than one
2714 * internal dependency.
2716 resetPQExpBuffer(query);
2717 if (g_fout->remoteVersion >= 80000)
2719 appendPQExpBuffer(query,
2720 "SELECT t.tableoid, t.oid, "
2721 "t.relname as indexname, "
2722 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2723 "t.relnatts as indnkeys, "
2724 "i.indkey, i.indisclustered, "
2725 "c.contype, c.conname, "
2726 "c.tableoid as contableoid, "
2728 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) as tablespace "
2729 "FROM pg_catalog.pg_index i "
2730 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2731 "LEFT JOIN pg_catalog.pg_depend d "
2732 "ON (d.classid = t.tableoid "
2733 "AND d.objid = t.oid "
2734 "AND d.deptype = 'i') "
2735 "LEFT JOIN pg_catalog.pg_constraint c "
2736 "ON (d.refclassid = c.tableoid "
2737 "AND d.refobjid = c.oid) "
2738 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2739 "ORDER BY indexname",
2740 tbinfo->dobj.catId.oid);
2742 else if (g_fout->remoteVersion >= 70300)
2744 appendPQExpBuffer(query,
2745 "SELECT t.tableoid, t.oid, "
2746 "t.relname as indexname, "
2747 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2748 "t.relnatts as indnkeys, "
2749 "i.indkey, i.indisclustered, "
2750 "c.contype, c.conname, "
2751 "c.tableoid as contableoid, "
2753 "NULL as tablespace "
2754 "FROM pg_catalog.pg_index i "
2755 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2756 "LEFT JOIN pg_catalog.pg_depend d "
2757 "ON (d.classid = t.tableoid "
2758 "AND d.objid = t.oid "
2759 "AND d.deptype = 'i') "
2760 "LEFT JOIN pg_catalog.pg_constraint c "
2761 "ON (d.refclassid = c.tableoid "
2762 "AND d.refobjid = c.oid) "
2763 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2764 "ORDER BY indexname",
2765 tbinfo->dobj.catId.oid);
2767 else if (g_fout->remoteVersion >= 70100)
2769 appendPQExpBuffer(query,
2770 "SELECT t.tableoid, t.oid, "
2771 "t.relname as indexname, "
2772 "pg_get_indexdef(i.indexrelid) as indexdef, "
2773 "t.relnatts as indnkeys, "
2774 "i.indkey, false as indisclustered, "
2775 "CASE WHEN i.indisprimary THEN 'p'::char "
2776 "ELSE '0'::char END as contype, "
2777 "t.relname as conname, "
2778 "0::oid as contableoid, "
2780 "NULL as tablespace "
2781 "FROM pg_index i, pg_class t "
2782 "WHERE t.oid = i.indexrelid "
2783 "AND i.indrelid = '%u'::oid "
2784 "ORDER BY indexname",
2785 tbinfo->dobj.catId.oid);
2789 appendPQExpBuffer(query,
2791 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2793 "t.relname as indexname, "
2794 "pg_get_indexdef(i.indexrelid) as indexdef, "
2795 "t.relnatts as indnkeys, "
2796 "i.indkey, false as indisclustered, "
2797 "CASE WHEN i.indisprimary THEN 'p'::char "
2798 "ELSE '0'::char END as contype, "
2799 "t.relname as conname, "
2800 "0::oid as contableoid, "
2802 "NULL as tablespace "
2803 "FROM pg_index i, pg_class t "
2804 "WHERE t.oid = i.indexrelid "
2805 "AND i.indrelid = '%u'::oid "
2806 "ORDER BY indexname",
2807 tbinfo->dobj.catId.oid);
2810 res = PQexec(g_conn, query->data);
2811 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2813 ntups = PQntuples(res);
2815 i_tableoid = PQfnumber(res, "tableoid");
2816 i_oid = PQfnumber(res, "oid");
2817 i_indexname = PQfnumber(res, "indexname");
2818 i_indexdef = PQfnumber(res, "indexdef");
2819 i_indnkeys = PQfnumber(res, "indnkeys");
2820 i_indkey = PQfnumber(res, "indkey");
2821 i_indisclustered = PQfnumber(res, "indisclustered");
2822 i_contype = PQfnumber(res, "contype");
2823 i_conname = PQfnumber(res, "conname");
2824 i_contableoid = PQfnumber(res, "contableoid");
2825 i_conoid = PQfnumber(res, "conoid");
2826 i_tablespace = PQfnumber(res, "tablespace");
2828 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
2829 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2831 for (j = 0; j < ntups; j++)
2835 indxinfo[j].dobj.objType = DO_INDEX;
2836 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
2837 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
2838 AssignDumpId(&indxinfo[j].dobj);
2839 indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
2840 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2841 indxinfo[j].indextable = tbinfo;
2842 indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
2843 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
2844 indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
2847 * In pre-7.4 releases, indkeys may contain more entries than
2848 * indnkeys says (since indnkeys will be 1 for a functional
2849 * index). We don't actually care about this case since we
2850 * don't examine indkeys except for indexes associated with
2851 * PRIMARY and UNIQUE constraints, which are never functional
2852 * indexes. But we have to allocate enough space to keep
2853 * parseOidArray from complaining.
2855 indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
2856 parseOidArray(PQgetvalue(res, j, i_indkey),
2857 indxinfo[j].indkeys, INDEX_MAX_KEYS);
2858 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
2859 contype = *(PQgetvalue(res, j, i_contype));
2861 if (contype == 'p' || contype == 'u')
2864 * If we found a constraint matching the index, create an
2867 * In a pre-7.3 database, we take this path iff the index was
2868 * marked indisprimary.
2870 constrinfo[j].dobj.objType = DO_CONSTRAINT;
2871 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2872 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2873 AssignDumpId(&constrinfo[j].dobj);
2874 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2875 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2876 constrinfo[j].contable = tbinfo;
2877 constrinfo[j].condomain = NULL;
2878 constrinfo[j].contype = contype;
2879 constrinfo[j].condef = NULL;
2880 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
2881 constrinfo[j].coninherited = false;
2882 constrinfo[j].separate = true;
2884 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
2886 /* If pre-7.3 DB, better make sure table comes first */
2887 addObjectDependency(&constrinfo[j].dobj,
2888 tbinfo->dobj.dumpId);
2892 /* Plain secondary index */
2893 indxinfo[j].indexconstraint = 0;
2900 destroyPQExpBuffer(query);
2906 * Get info about constraints on dumpable tables.
2908 * Currently handles foreign keys only.
2909 * Unique and primary key constraints are handled with indexes,
2910 * while check constraints are processed in getTableAttrs().
2913 getConstraints(TableInfo tblinfo[], int numTables)
2917 ConstraintInfo *constrinfo;
2926 /* pg_constraint was created in 7.3, so nothing to do if older */
2927 if (g_fout->remoteVersion < 70300)
2930 query = createPQExpBuffer();
2932 for (i = 0; i < numTables; i++)
2934 TableInfo *tbinfo = &tblinfo[i];
2936 if (tbinfo->ntrig == 0 || !tbinfo->dump)
2940 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
2944 * select table schema to ensure constraint expr is qualified if
2947 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2949 resetPQExpBuffer(query);
2950 appendPQExpBuffer(query,
2951 "SELECT tableoid, oid, conname, "
2952 "pg_catalog.pg_get_constraintdef(oid) as condef "
2953 "FROM pg_catalog.pg_constraint "
2954 "WHERE conrelid = '%u'::pg_catalog.oid "
2955 "AND contype = 'f'",
2956 tbinfo->dobj.catId.oid);
2957 res = PQexec(g_conn, query->data);
2958 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2960 ntups = PQntuples(res);
2962 i_contableoid = PQfnumber(res, "tableoid");
2963 i_conoid = PQfnumber(res, "oid");
2964 i_conname = PQfnumber(res, "conname");
2965 i_condef = PQfnumber(res, "condef");
2967 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2969 for (j = 0; j < ntups; j++)
2971 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
2972 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2973 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2974 AssignDumpId(&constrinfo[j].dobj);
2975 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2976 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2977 constrinfo[j].contable = tbinfo;
2978 constrinfo[j].condomain = NULL;
2979 constrinfo[j].contype = 'f';
2980 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
2981 constrinfo[j].conindex = 0;
2982 constrinfo[j].coninherited = false;
2983 constrinfo[j].separate = true;
2989 destroyPQExpBuffer(query);
2993 * getDomainConstraints
2995 * Get info about constraints on a domain.
2998 getDomainConstraints(TypeInfo *tinfo)
3001 ConstraintInfo *constrinfo;
3010 /* pg_constraint was created in 7.3, so nothing to do if older */
3011 if (g_fout->remoteVersion < 70300)
3015 * select appropriate schema to ensure names in constraint are
3016 * properly qualified
3018 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
3020 query = createPQExpBuffer();
3022 if (g_fout->remoteVersion >= 70400)
3023 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3024 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3025 "FROM pg_catalog.pg_constraint "
3026 "WHERE contypid = '%u'::pg_catalog.oid "
3028 tinfo->dobj.catId.oid);
3030 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3031 "'CHECK (' || consrc || ')' AS consrc "
3032 "FROM pg_catalog.pg_constraint "
3033 "WHERE contypid = '%u'::pg_catalog.oid "
3035 tinfo->dobj.catId.oid);
3037 res = PQexec(g_conn, query->data);
3038 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3040 ntups = PQntuples(res);
3042 i_tableoid = PQfnumber(res, "tableoid");
3043 i_oid = PQfnumber(res, "oid");
3044 i_conname = PQfnumber(res, "conname");
3045 i_consrc = PQfnumber(res, "consrc");
3047 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3049 tinfo->nDomChecks = ntups;
3050 tinfo->domChecks = constrinfo;
3052 for (i = 0; i < ntups; i++)
3054 constrinfo[i].dobj.objType = DO_CONSTRAINT;
3055 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3056 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3057 AssignDumpId(&constrinfo[i].dobj);
3058 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
3059 constrinfo[i].dobj.namespace = tinfo->dobj.namespace;
3060 constrinfo[i].contable = NULL;
3061 constrinfo[i].condomain = tinfo;
3062 constrinfo[i].contype = 'c';
3063 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
3064 constrinfo[i].conindex = 0;
3065 constrinfo[i].coninherited = false;
3066 constrinfo[i].separate = false;
3069 * Make the domain depend on the constraint, ensuring it won't be
3070 * output till any constraint dependencies are OK.
3072 addObjectDependency(&tinfo->dobj,
3073 constrinfo[i].dobj.dumpId);
3078 destroyPQExpBuffer(query);
3083 * get basic information about every rule in the system
3085 * numRules is set to the number of rules read in
3088 getRules(int *numRules)
3093 PQExpBuffer query = createPQExpBuffer();
3102 /* Make sure we are in proper schema */
3103 selectSourceSchema("pg_catalog");
3105 if (g_fout->remoteVersion >= 70100)
3107 appendPQExpBuffer(query, "SELECT "
3108 "tableoid, oid, rulename, "
3109 "ev_class as ruletable, ev_type, is_instead "
3115 appendPQExpBuffer(query, "SELECT "
3116 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
3118 "ev_class as ruletable, ev_type, is_instead "
3123 res = PQexec(g_conn, query->data);
3124 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3126 ntups = PQntuples(res);
3130 ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
3132 i_tableoid = PQfnumber(res, "tableoid");
3133 i_oid = PQfnumber(res, "oid");
3134 i_rulename = PQfnumber(res, "rulename");
3135 i_ruletable = PQfnumber(res, "ruletable");
3136 i_ev_type = PQfnumber(res, "ev_type");
3137 i_is_instead = PQfnumber(res, "is_instead");
3139 for (i = 0; i < ntups; i++)
3143 ruleinfo[i].dobj.objType = DO_RULE;
3144 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3145 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3146 AssignDumpId(&ruleinfo[i].dobj);
3147 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
3148 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
3149 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
3150 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
3151 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
3152 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
3153 if (ruleinfo[i].ruletable)
3156 * If the table is a view, force its ON SELECT rule to be
3157 * sorted before the view itself --- this ensures that any
3158 * dependencies for the rule affect the table's positioning.
3159 * Other rules are forced to appear after their table.
3161 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
3162 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
3164 addObjectDependency(&ruleinfo[i].ruletable->dobj,
3165 ruleinfo[i].dobj.dumpId);
3166 /* We'll merge the rule into CREATE VIEW, if possible */
3167 ruleinfo[i].separate = false;
3171 addObjectDependency(&ruleinfo[i].dobj,
3172 ruleinfo[i].ruletable->dobj.dumpId);
3173 ruleinfo[i].separate = true;
3177 ruleinfo[i].separate = true;
3182 destroyPQExpBuffer(query);
3189 * get information about every trigger on a dumpable table
3191 * Note: trigger data is not returned directly to the caller, but it
3192 * does get entered into the DumpableObject tables.
3195 getTriggers(TableInfo tblinfo[], int numTables)
3199 PQExpBuffer query = createPQExpBuffer();
3201 TriggerInfo *tginfo;
3217 for (i = 0; i < numTables; i++)
3219 TableInfo *tbinfo = &tblinfo[i];
3221 if (tbinfo->ntrig == 0 || !tbinfo->dump)
3225 write_msg(NULL, "reading triggers for table \"%s\"\n",
3229 * select table schema to ensure regproc name is qualified if
3232 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3234 resetPQExpBuffer(query);
3235 if (g_fout->remoteVersion >= 70300)
3238 * We ignore triggers that are tied to a foreign-key
3241 appendPQExpBuffer(query,
3243 "tgfoid::pg_catalog.regproc as tgfname, "
3244 "tgtype, tgnargs, tgargs, "
3245 "tgisconstraint, tgconstrname, tgdeferrable, "
3246 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3247 "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
3248 "from pg_catalog.pg_trigger t "
3249 "where tgrelid = '%u'::pg_catalog.oid "
3250 "and (not tgisconstraint "
3252 " (SELECT 1 FROM pg_catalog.pg_depend d "
3253 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
3254 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
3255 tbinfo->dobj.catId.oid);
3257 else if (g_fout->remoteVersion >= 70100)
3259 appendPQExpBuffer(query,
3260 "SELECT tgname, tgfoid::regproc as tgfname, "
3261 "tgtype, tgnargs, tgargs, "
3262 "tgisconstraint, tgconstrname, tgdeferrable, "
3263 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3264 "(select relname from pg_class where oid = tgconstrrelid) "
3265 " as tgconstrrelname "
3267 "where tgrelid = '%u'::oid",
3268 tbinfo->dobj.catId.oid);
3272 appendPQExpBuffer(query,
3273 "SELECT tgname, tgfoid::regproc as tgfname, "
3274 "tgtype, tgnargs, tgargs, "
3275 "tgisconstraint, tgconstrname, tgdeferrable, "
3276 "tgconstrrelid, tginitdeferred, "
3277 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
3280 "(select relname from pg_class where oid = tgconstrrelid) "
3281 " as tgconstrrelname "
3283 "where tgrelid = '%u'::oid",
3284 tbinfo->dobj.catId.oid);
3286 res = PQexec(g_conn, query->data);
3287 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3289 ntups = PQntuples(res);
3292 * We may have less triggers than recorded due to having ignored
3293 * foreign-key triggers
3295 if (ntups > tbinfo->ntrig)
3297 write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
3298 tbinfo->ntrig, tbinfo->dobj.name, ntups);
3301 i_tableoid = PQfnumber(res, "tableoid");
3302 i_oid = PQfnumber(res, "oid");
3303 i_tgname = PQfnumber(res, "tgname");
3304 i_tgfname = PQfnumber(res, "tgfname");
3305 i_tgtype = PQfnumber(res, "tgtype");
3306 i_tgnargs = PQfnumber(res, "tgnargs");
3307 i_tgargs = PQfnumber(res, "tgargs");
3308 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
3309 i_tgconstrname = PQfnumber(res, "tgconstrname");
3310 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
3311 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
3312 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
3313 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
3315 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
3317 for (j = 0; j < ntups; j++)
3319 tginfo[j].dobj.objType = DO_TRIGGER;
3320 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3321 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3322 AssignDumpId(&tginfo[j].dobj);
3323 tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
3324 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
3325 tginfo[j].tgtable = tbinfo;
3326 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
3327 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
3328 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
3329 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
3330 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
3331 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
3332 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
3334 if (tginfo[j].tgisconstraint)
3336 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
3337 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
3338 if (OidIsValid(tginfo[j].tgconstrrelid))
3340 if (PQgetisnull(res, j, i_tgconstrrelname))
3342 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
3343 tginfo[j].dobj.name, tbinfo->dobj.name,
3344 tginfo[j].tgconstrrelid);
3347 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
3350 tginfo[j].tgconstrrelname = NULL;
3354 tginfo[j].tgconstrname = NULL;
3355 tginfo[j].tgconstrrelid = InvalidOid;
3356 tginfo[j].tgconstrrelname = NULL;
3363 destroyPQExpBuffer(query);
3368 * get basic information about every procedural language in the system
3370 * numProcLangs is set to the number of langs read in
3372 * NB: this must run after getFuncs() because we assume we can do
3376 getProcLangs(int *numProcLangs)
3381 PQExpBuffer query = createPQExpBuffer();
3382 ProcLangInfo *planginfo;
3387 int i_lanplcallfoid;
3388 int i_lanvalidator = -1;
3391 /* Make sure we are in proper schema */
3392 selectSourceSchema("pg_catalog");
3394 if (g_fout->remoteVersion >= 70100)
3396 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
3402 appendPQExpBuffer(query, "SELECT "
3403 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
3404 "oid, * FROM pg_language "
3409 res = PQexec(g_conn, query->data);
3410 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3412 ntups = PQntuples(res);
3414 *numProcLangs = ntups;
3416 planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
3418 i_tableoid = PQfnumber(res, "tableoid");
3419 i_oid = PQfnumber(res, "oid");
3420 i_lanname = PQfnumber(res, "lanname");
3421 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
3422 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
3423 if (g_fout->remoteVersion >= 70300)
3425 i_lanvalidator = PQfnumber(res, "lanvalidator");
3426 i_lanacl = PQfnumber(res, "lanacl");
3429 for (i = 0; i < ntups; i++)
3431 planginfo[i].dobj.objType = DO_PROCLANG;
3432 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3433 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3434 AssignDumpId(&planginfo[i].dobj);
3436 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
3437 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
3438 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
3439 if (g_fout->remoteVersion >= 70300)
3441 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
3442 planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
3448 planginfo[i].lanvalidator = InvalidOid;
3449 planginfo[i].lanacl = strdup("{=U}");
3452 * We need to make a dependency to ensure the function will be
3453 * dumped first. (In 7.3 and later the regular dependency
3454 * mechanism will handle this for us.)
3456 funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
3458 addObjectDependency(&planginfo[i].dobj,
3459 funcInfo->dobj.dumpId);
3465 destroyPQExpBuffer(query);
3472 * get basic information about every cast in the system
3474 * numCasts is set to the number of casts read in
3477 getCasts(int *numCasts)
3482 PQExpBuffer query = createPQExpBuffer();
3491 /* Make sure we are in proper schema */
3492 selectSourceSchema("pg_catalog");
3494 if (g_fout->remoteVersion >= 70300)
3496 appendPQExpBuffer(query, "SELECT tableoid, oid, "
3497 "castsource, casttarget, castfunc, castcontext "
3498 "FROM pg_cast ORDER BY 3,4");
3502 appendPQExpBuffer(query, "SELECT 0 as tableoid, p.oid, "
3503 "t1.oid as castsource, t2.oid as casttarget, "
3504 "p.oid as castfunc, 'e' as castcontext "
3505 "FROM pg_type t1, pg_type t2, pg_proc p "
3506 "WHERE p.pronargs = 1 AND "
3507 "p.proargtypes[0] = t1.oid AND "
3508 "p.prorettype = t2.oid AND p.proname = t2.typname "
3512 res = PQexec(g_conn, query->data);
3513 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3515 ntups = PQntuples(res);
3519 castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
3521 i_tableoid = PQfnumber(res, "tableoid");
3522 i_oid = PQfnumber(res, "oid");
3523 i_castsource = PQfnumber(res, "castsource");
3524 i_casttarget = PQfnumber(res, "casttarget");
3525 i_castfunc = PQfnumber(res, "castfunc");
3526 i_castcontext = PQfnumber(res, "castcontext");
3528 for (i = 0; i < ntups; i++)
3530 PQExpBufferData namebuf;
3531 TypeInfo *sTypeInfo;
3532 TypeInfo *tTypeInfo;
3534 castinfo[i].dobj.objType = DO_CAST;
3535 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3536 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3537 AssignDumpId(&castinfo[i].dobj);
3538 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
3539 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
3540 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
3541 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
3544 * Try to name cast as concatenation of typnames. This is only
3545 * used for purposes of sorting. If we fail to find either type,
3546 * the name will be an empty string.
3548 initPQExpBuffer(&namebuf);
3549 sTypeInfo = findTypeByOid(castinfo[i].castsource);
3550 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
3551 if (sTypeInfo && tTypeInfo)
3552 appendPQExpBuffer(&namebuf, "%s %s",
3553 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
3554 castinfo[i].dobj.name = namebuf.data;
3556 if (OidIsValid(castinfo[i].castfunc))
3559 * We need to make a dependency to ensure the function will be
3560 * dumped first. (In 7.3 and later the regular dependency
3561 * mechanism will handle this for us.)
3565 funcInfo = findFuncByOid(castinfo[i].castfunc);
3567 addObjectDependency(&castinfo[i].dobj,
3568 funcInfo->dobj.dumpId);
3574 destroyPQExpBuffer(query);
3581 * for each interesting table, read info about its attributes
3582 * (names, types, default values, CHECK constraints, etc)
3584 * This is implemented in a very inefficient way right now, looping
3585 * through the tblinfo and doing a join per table to find the attrs and their
3586 * types. However, because we want type names and so forth to be named
3587 * relative to the schema of each table, we couldn't do it in just one
3588 * query. (Maybe one query per schema?)
3593 getTableAttrs(TableInfo *tblinfo, int numTables)
3598 PQExpBuffer q = createPQExpBuffer();
3603 int i_attstattarget;
3614 for (i = 0; i < numTables; i++)
3616 TableInfo *tbinfo = &tblinfo[i];
3618 /* Don't bother to collect info for sequences */
3619 if (tbinfo->relkind == RELKIND_SEQUENCE)
3622 /* Don't bother with uninteresting tables, either */
3623 if (!tbinfo->interesting)
3627 * Make sure we are in proper schema for this table; this allows
3628 * correct retrieval of formatted type names and default exprs
3630 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3632 /* find all the user attributes and their types */
3635 * we must read the attribute names in attribute number order!
3636 * because we will use the attnum to index into the attnames array
3637 * later. We actually ask to order by "attrelid, attnum" because
3638 * (at least up to 7.3) the planner is not smart enough to realize
3639 * it needn't re-sort the output of an indexscan on
3640 * pg_attribute_relid_attnum_index.
3643 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
3646 resetPQExpBuffer(q);
3648 if (g_fout->remoteVersion >= 70300)
3650 /* need left join here to not fail on dropped columns ... */
3651 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, "
3652 "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, "
3653 "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname "
3654 "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t "
3655 "on a.atttypid = t.oid "
3656 "where a.attrelid = '%u'::pg_catalog.oid "
3657 "and a.attnum > 0::pg_catalog.int2 "
3658 "order by a.attrelid, a.attnum",
3659 tbinfo->dobj.catId.oid);
3661 else if (g_fout->remoteVersion >= 70100)
3664 * attstattarget doesn't exist in 7.1. It does exist in 7.2,
3665 * but we don't dump it because we can't tell whether it's
3666 * been explicitly set or was just a default.
3668 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, "
3669 "a.attnotnull, a.atthasdef, false as attisdropped, false as attislocal, "
3670 "format_type(t.oid,a.atttypmod) as atttypname "
3671 "from pg_attribute a left join pg_type t "
3672 "on a.atttypid = t.oid "
3673 "where a.attrelid = '%u'::oid "
3674 "and a.attnum > 0::int2 "
3675 "order by a.attrelid, a.attnum",
3676 tbinfo->dobj.catId.oid);
3680 /* format_type not available before 7.1 */
3681 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, "
3682 "attnotnull, atthasdef, false as attisdropped, false as attislocal, "
3683 "(select typname from pg_type where oid = atttypid) as atttypname "
3684 "from pg_attribute a "
3685 "where attrelid = '%u'::oid "
3686 "and attnum > 0::int2 "
3687 "order by attrelid, attnum",
3688 tbinfo->dobj.catId.oid);
3691 res = PQexec(g_conn, q->data);
3692 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3694 ntups = PQntuples(res);
3696 i_attnum = PQfnumber(res, "attnum");
3697 i_attname = PQfnumber(res, "attname");
3698 i_atttypname = PQfnumber(res, "atttypname");
3699 i_atttypmod = PQfnumber(res, "atttypmod");
3700 i_attstattarget = PQfnumber(res, "attstattarget");
3701 i_attstorage = PQfnumber(res, "attstorage");
3702 i_typstorage = PQfnumber(res, "typstorage");
3703 i_attnotnull = PQfnumber(res, "attnotnull");
3704 i_atthasdef = PQfnumber(res, "atthasdef");
3705 i_attisdropped = PQfnumber(res, "attisdropped");
3706 i_attislocal = PQfnumber(res, "attislocal");
3708 tbinfo->numatts = ntups;
3709 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
3710 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
3711 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
3712 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
3713 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
3714 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
3715 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
3716 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
3717 tbinfo->attisserial = (bool *) malloc(ntups * sizeof(bool));
3718 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
3719 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
3720 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
3721 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
3722 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
3723 hasdefaults = false;
3725 for (j = 0; j < ntups; j++)
3727 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
3729 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
3733 tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
3734 tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
3735 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
3736 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
3737 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
3738 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
3739 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
3740 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
3741 tbinfo->attisserial[j] = false; /* fix below */
3742 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
3743 tbinfo->attrdefs[j] = NULL; /* fix below */
3744 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
3746 /* these flags will be set in flagInhAttrs() */
3747 tbinfo->inhAttrs[j] = false;
3748 tbinfo->inhAttrDef[j] = false;
3749 tbinfo->inhNotNull[j] = false;
3755 * Get info about column defaults
3759 AttrDefInfo *attrdefs;
3763 write_msg(NULL, "finding default expressions of table \"%s\"\n",
3766 resetPQExpBuffer(q);
3767 if (g_fout->remoteVersion >= 70300)
3769 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
3770 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
3771 "FROM pg_catalog.pg_attrdef "
3772 "WHERE adrelid = '%u'::pg_catalog.oid",
3773 tbinfo->dobj.catId.oid);
3775 else if (g_fout->remoteVersion >= 70200)
3777 /* 7.2 did not have OIDs in pg_attrdef */
3778 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, adnum, "
3779 "pg_get_expr(adbin, adrelid) AS adsrc "
3781 "WHERE adrelid = '%u'::oid",
3782 tbinfo->dobj.catId.oid);
3784 else if (g_fout->remoteVersion >= 70100)
3786 /* no pg_get_expr, so must rely on adsrc */
3787 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
3789 "WHERE adrelid = '%u'::oid",
3790 tbinfo->dobj.catId.oid);
3794 /* no pg_get_expr, no tableoid either */
3795 appendPQExpBuffer(q, "SELECT "
3796 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
3797 "oid, adnum, adsrc "
3799 "WHERE adrelid = '%u'::oid",
3800 tbinfo->dobj.catId.oid);
3802 res = PQexec(g_conn, q->data);
3803 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3805 numDefaults = PQntuples(res);
3806 attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
3808 for (j = 0; j < numDefaults; j++)
3812 attrdefs[j].dobj.objType = DO_ATTRDEF;
3813 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3814 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3815 AssignDumpId(&attrdefs[j].dobj);
3816 attrdefs[j].adtable = tbinfo;
3817 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
3818 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
3820 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
3821 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
3824 * Defaults on a VIEW must always be dumped as separate
3825 * ALTER TABLE commands. Defaults on regular tables are
3826 * dumped as part of the CREATE TABLE if possible. To
3827 * check if it's safe, we mark the default as needing to
3828 * appear before the CREATE.
3830 if (tbinfo->relkind == RELKIND_VIEW)
3832 attrdefs[j].separate = true;
3833 /* needed in case pre-7.3 DB: */
3834 addObjectDependency(&attrdefs[j].dobj,
3835 tbinfo->dobj.dumpId);
3839 attrdefs[j].separate = false;
3840 addObjectDependency(&tbinfo->dobj,
3841 attrdefs[j].dobj.dumpId);
3844 if (adnum <= 0 || adnum > ntups)
3846 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
3847 adnum, tbinfo->dobj.name);
3850 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
3856 * Get info about table CHECK constraints
3858 if (tbinfo->ncheck > 0)
3860 ConstraintInfo *constrs;
3864 write_msg(NULL, "finding check constraints for table \"%s\"\n",
3867 resetPQExpBuffer(q);
3868 if (g_fout->remoteVersion >= 70400)
3870 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3871 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3872 "FROM pg_catalog.pg_constraint "
3873 "WHERE conrelid = '%u'::pg_catalog.oid "
3874 " AND contype = 'c' "
3876 tbinfo->dobj.catId.oid);
3878 else if (g_fout->remoteVersion >= 70300)
3880 /* no pg_get_constraintdef, must use consrc */
3881 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3882 "'CHECK (' || consrc || ')' AS consrc "
3883 "FROM pg_catalog.pg_constraint "
3884 "WHERE conrelid = '%u'::pg_catalog.oid "
3885 " AND contype = 'c' "
3887 tbinfo->dobj.catId.oid);
3889 else if (g_fout->remoteVersion >= 70200)
3891 /* 7.2 did not have OIDs in pg_relcheck */
3892 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, "
3893 "rcname AS conname, "
3894 "'CHECK (' || rcsrc || ')' AS consrc "
3896 "WHERE rcrelid = '%u'::oid "
3898 tbinfo->dobj.catId.oid);
3900 else if (g_fout->remoteVersion >= 70100)
3902 appendPQExpBuffer(q, "SELECT tableoid, oid, "
3903 "rcname AS conname, "
3904 "'CHECK (' || rcsrc || ')' AS consrc "
3906 "WHERE rcrelid = '%u'::oid "
3908 tbinfo->dobj.catId.oid);
3912 /* no tableoid in 7.0 */
3913 appendPQExpBuffer(q, "SELECT "
3914 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
3915 "oid, rcname AS conname, "
3916 "'CHECK (' || rcsrc || ')' AS consrc "
3918 "WHERE rcrelid = '%u'::oid "
3920 tbinfo->dobj.catId.oid);
3922 res = PQexec(g_conn, q->data);
3923 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3925 numConstrs = PQntuples(res);
3926 if (numConstrs != tbinfo->ncheck)
3928 write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
3929 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
3930 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
3934 constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
3935 tbinfo->checkexprs = constrs;
3937 for (j = 0; j < numConstrs; j++)
3939 constrs[j].dobj.objType = DO_CONSTRAINT;
3940 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3941 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3942 AssignDumpId(&constrs[j].dobj);
3943 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
3944 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
3945 constrs[j].contable = tbinfo;
3946 constrs[j].condomain = NULL;
3947 constrs[j].contype = 'c';
3948 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
3949 constrs[j].conindex = 0;
3950 constrs[j].coninherited = false;
3951 constrs[j].separate = false;
3953 * Mark the constraint as needing to appear before the
3954 * table --- this is so that any other dependencies of
3955 * the constraint will be emitted before we try to create
3958 addObjectDependency(&tbinfo->dobj,
3959 constrs[j].dobj.dumpId);
3962 * If the constraint is inherited, this will be detected
3963 * later. We also detect later if the constraint must be
3964 * split out from the table definition.
3971 * Check to see if any columns are serial columns. Our first
3972 * quick filter is that it must be integer or bigint with a
3973 * default. If so, we scan to see if we found a sequence linked
3974 * to this column. If we did, mark the column and sequence
3977 for (j = 0; j < ntups; j++)
3980 * Note assumption that format_type will show these types as
3981 * exactly "integer" and "bigint" regardless of schema path.
3982 * This is correct in 7.3 but needs to be watched.
3984 if (strcmp(tbinfo->atttypnames[j], "integer") != 0 &&
3985 strcmp(tbinfo->atttypnames[j], "bigint") != 0)
3987 if (tbinfo->attrdefs[j] == NULL)
3989 for (k = 0; k < numTables; k++)
3991 TableInfo *seqinfo = &tblinfo[k];
3993 if (OidIsValid(seqinfo->owning_tab) &&
3994 seqinfo->owning_tab == tbinfo->dobj.catId.oid &&
3995 seqinfo->owning_col == j + 1)
3998 * Found a match. Copy the table's interesting and
3999 * dumpable flags to the sequence.
4001 tbinfo->attisserial[j] = true;
4002 seqinfo->interesting = tbinfo->interesting;
4003 seqinfo->dump = tbinfo->dump;
4010 destroyPQExpBuffer(q);
4017 * This routine is used to dump any comments associated with the
4018 * object handed to this routine. The routine takes a constant character
4019 * string for the target part of the comment-creation command, plus
4020 * the namespace and owner of the object (for labeling the ArchiveEntry),
4021 * plus catalog ID and subid which are the lookup key for pg_description,
4022 * plus the dump ID for the object (for setting a dependency).
4023 * If a matching pg_description entry is found, it is dumped.
4025 * Note: although this routine takes a dumpId for dependency purposes,
4026 * that purpose is just to mark the dependency in the emitted dump file
4027 * for possible future use by pg_restore. We do NOT use it for determining
4028 * ordering of the comment in the dump file, because this routine is called
4029 * after dependency sorting occurs. This routine should be called just after
4030 * calling ArchiveEntry() for the specified object.
4033 dumpComment(Archive *fout, const char *target,
4034 const char *namespace, const char *owner,
4035 CatalogId catalogId, int subid, DumpId dumpId)
4037 CommentItem *comments;
4040 /* Comments are SCHEMA not data */
4044 /* Search for comments associated with catalogId, using table */
4045 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
4048 /* Is there one matching the subid? */
4049 while (ncomments > 0)
4051 if (comments->objsubid == subid)
4057 /* If a comment exists, build COMMENT ON statement */
4060 PQExpBuffer query = createPQExpBuffer();
4062 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
4063 appendStringLiteral(query, comments->descr, false);
4064 appendPQExpBuffer(query, ";\n");
4066 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4067 target, namespace, NULL, owner, false,
4068 "COMMENT", query->data, "", NULL,
4072 destroyPQExpBuffer(query);
4077 * dumpTableComment --
4079 * As above, but dump comments for both the specified table (or view)
4083 dumpTableComment(Archive *fout, TableInfo *tbinfo,
4084 const char *reltypename)
4086 CommentItem *comments;
4091 /* Comments are SCHEMA not data */
4095 /* Search for comments associated with relation, using table */
4096 ncomments = findComments(fout,
4097 tbinfo->dobj.catId.tableoid,
4098 tbinfo->dobj.catId.oid,
4101 /* If comments exist, build COMMENT ON statements */
4105 query = createPQExpBuffer();
4106 target = createPQExpBuffer();
4108 while (ncomments > 0)
4110 const char *descr = comments->descr;
4111 int objsubid = comments->objsubid;
4115 resetPQExpBuffer(target);
4116 appendPQExpBuffer(target, "%s %s", reltypename,
4117 fmtId(tbinfo->dobj.name));
4119 resetPQExpBuffer(query);
4120 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4121 appendStringLiteral(query, descr, false);
4122 appendPQExpBuffer(query, ";\n");
4124 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4126 tbinfo->dobj.namespace->dobj.name,
4129 false, "COMMENT", query->data, "", NULL,
4130 &(tbinfo->dobj.dumpId), 1,
4133 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
4135 resetPQExpBuffer(target);
4136 appendPQExpBuffer(target, "COLUMN %s.",
4137 fmtId(tbinfo->dobj.name));
4138 appendPQExpBuffer(target, "%s",
4139 fmtId(tbinfo->attnames[objsubid - 1]));
4141 resetPQExpBuffer(query);
4142 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4143 appendStringLiteral(query, descr, false);
4144 appendPQExpBuffer(query, ";\n");
4146 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4148 tbinfo->dobj.namespace->dobj.name,
4151 false, "COMMENT", query->data, "", NULL,
4152 &(tbinfo->dobj.dumpId), 1,
4160 destroyPQExpBuffer(query);
4161 destroyPQExpBuffer(target);
4167 * Find the comment(s), if any, associated with the given object. All the
4168 * objsubid values associated with the given classoid/objoid are found with
4172 findComments(Archive *fout, Oid classoid, Oid objoid,
4173 CommentItem **items)
4175 /* static storage for table of comments */
4176 static CommentItem *comments = NULL;
4177 static int ncomments = -1;
4179 CommentItem *middle = NULL;
4184 /* Get comments if we didn't already */
4186 ncomments = collectComments(fout, &comments);
4189 * Pre-7.2, pg_description does not contain classoid, so
4190 * collectComments just stores a zero. If there's a collision on
4191 * object OID, well, you get duplicate comments.
4193 if (fout->remoteVersion < 70200)
4197 * Do binary search to find some item matching the object.
4200 high = &comments[ncomments - 1];
4203 middle = low + (high - low) / 2;
4205 if (classoid < middle->classoid)
4207 else if (classoid > middle->classoid)
4209 else if (objoid < middle->objoid)
4211 else if (objoid > middle->objoid)
4214 break; /* found a match */
4217 if (low > high) /* no matches */
4224 * Now determine how many items match the object. The search loop
4225 * invariant still holds: only items between low and high inclusive
4229 while (middle > low)
4231 if (classoid != middle[-1].classoid ||
4232 objoid != middle[-1].objoid)
4241 while (middle <= high)
4243 if (classoid != middle->classoid ||
4244 objoid != middle->objoid)
4254 * collectComments --
4256 * Construct a table of all comments available for database objects.
4257 * We used to do per-object queries for the comments, but it's much faster
4258 * to pull them all over at once, and on most databases the memory cost
4261 * The table is sorted by classoid/objid/objsubid for speed in lookup.
4264 collectComments(Archive *fout, CommentItem **items)
4274 CommentItem *comments;
4277 * Note we do NOT change source schema here; preserve the caller's
4281 query = createPQExpBuffer();
4283 if (fout->remoteVersion >= 70300)
4285 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4286 "FROM pg_catalog.pg_description "
4287 "ORDER BY classoid, objoid, objsubid");
4289 else if (fout->remoteVersion >= 70200)
4291 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4292 "FROM pg_description "
4293 "ORDER BY classoid, objoid, objsubid");
4297 /* Note: this will fail to find attribute comments in pre-7.2... */
4298 appendPQExpBuffer(query, "SELECT description, 0 as classoid, objoid, 0 as objsubid "
4299 "FROM pg_description "
4303 res = PQexec(g_conn, query->data);
4304 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4306 /* Construct lookup table containing OIDs in numeric form */
4308 i_description = PQfnumber(res, "description");
4309 i_classoid = PQfnumber(res, "classoid");
4310 i_objoid = PQfnumber(res, "objoid");
4311 i_objsubid = PQfnumber(res, "objsubid");
4313 ntups = PQntuples(res);
4315 comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
4317 for (i = 0; i < ntups; i++)
4319 comments[i].descr = PQgetvalue(res, i, i_description);
4320 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
4321 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
4322 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
4325 /* Do NOT free the PGresult since we are keeping pointers into it */
4326 destroyPQExpBuffer(query);
4333 * dumpDumpableObject
4335 * This routine and its subsidiaries are responsible for creating
4336 * ArchiveEntries (TOC objects) for each object to be dumped.
4339 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
4341 switch (dobj->objType)
4344 dumpNamespace(fout, (NamespaceInfo *) dobj);
4347 dumpType(fout, (TypeInfo *) dobj);
4350 dumpFunc(fout, (FuncInfo *) dobj);
4353 dumpAgg(fout, (AggInfo *) dobj);
4356 dumpOpr(fout, (OprInfo *) dobj);
4359 dumpOpclass(fout, (OpclassInfo *) dobj);
4362 dumpConversion(fout, (ConvInfo *) dobj);
4365 dumpTable(fout, (TableInfo *) dobj);
4368 dumpAttrDef(fout, (AttrDefInfo *) dobj);
4371 dumpIndex(fout, (IndxInfo *) dobj);
4374 dumpRule(fout, (RuleInfo *) dobj);
4377 dumpTrigger(fout, (TriggerInfo *) dobj);
4380 dumpConstraint(fout, (ConstraintInfo *) dobj);
4382 case DO_FK_CONSTRAINT:
4383 dumpConstraint(fout, (ConstraintInfo *) dobj);
4386 dumpProcLang(fout, (ProcLangInfo *) dobj);
4389 dumpCast(fout, (CastInfo *) dobj);
4392 dumpTableData(fout, (TableDataInfo *) dobj);
4395 /* table rowtypes are never dumped separately */
4398 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4399 dobj->name, NULL, NULL, "",
4400 false, "BLOBS", "", "", NULL,
4409 * writes out to fout the queries to recreate a user-defined namespace
4412 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
4418 /* skip if not to be dumped */
4419 if (!nspinfo->dump || dataOnly)
4422 /* don't dump dummy namespace from pre-7.3 source */
4423 if (strlen(nspinfo->dobj.name) == 0)
4426 q = createPQExpBuffer();
4427 delq = createPQExpBuffer();
4429 qnspname = strdup(fmtId(nspinfo->dobj.name));
4432 * Note that ownership is shown in the AUTHORIZATION clause, while the
4433 * archive entry is listed with empty owner (causing it to be emitted
4434 * with SET SESSION AUTHORIZATION DEFAULT). This seems the best way of
4435 * dealing with schemas owned by users without CREATE SCHEMA
4436 * privilege. Further hacking has to be applied for --no-owner mode,
4439 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
4441 appendPQExpBuffer(q, "CREATE SCHEMA %s AUTHORIZATION %s;\n",
4442 qnspname, fmtId(nspinfo->usename));
4444 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
4447 strcmp(nspinfo->dobj.name, "public") == 0 ? nspinfo->usename : "",
4448 false, "SCHEMA", q->data, delq->data, NULL,
4449 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
4452 /* Dump Schema Comments */
4453 resetPQExpBuffer(q);
4454 appendPQExpBuffer(q, "SCHEMA %s", qnspname);
4455 dumpComment(fout, q->data,
4456 NULL, nspinfo->usename,
4457 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
4459 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
4460 qnspname, nspinfo->dobj.name, NULL,
4461 nspinfo->usename, nspinfo->nspacl);
4465 destroyPQExpBuffer(q);
4466 destroyPQExpBuffer(delq);
4471 * writes out to fout the queries to recreate a user-defined type
4474 dumpType(Archive *fout, TypeInfo *tinfo)
4476 /* Dump only types in dumpable namespaces */
4477 if (!tinfo->dobj.namespace->dump || dataOnly)
4480 /* skip complex types, except for standalone composite types */
4481 /* (note: this test should now be unnecessary) */
4482 if (OidIsValid(tinfo->typrelid) && tinfo->typrelkind != 'c')
4485 /* skip undefined placeholder types */
4486 if (!tinfo->isDefined)
4489 /* skip all array types that start w/ underscore */
4490 if ((tinfo->dobj.name[0] == '_') &&
4491 OidIsValid(tinfo->typelem))
4494 /* Dump out in proper style */
4495 if (tinfo->typtype == 'b')
4496 dumpBaseType(fout, tinfo);
4497 else if (tinfo->typtype == 'd')
4498 dumpDomain(fout, tinfo);
4499 else if (tinfo->typtype == 'c')
4500 dumpCompositeType(fout, tinfo);
4505 * writes out to fout the queries to recreate a user-defined base type
4508 dumpBaseType(Archive *fout, TypeInfo *tinfo)
4510 PQExpBuffer q = createPQExpBuffer();
4511 PQExpBuffer delq = createPQExpBuffer();
4512 PQExpBuffer query = createPQExpBuffer();
4532 /* Set proper schema search path so regproc references list correctly */
4533 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4535 /* Fetch type-specific details */
4536 if (fout->remoteVersion >= 80000)
4538 appendPQExpBuffer(query, "SELECT typlen, "
4539 "typinput, typoutput, typreceive, typsend, "
4541 "typinput::pg_catalog.oid as typinputoid, "
4542 "typoutput::pg_catalog.oid as typoutputoid, "
4543 "typreceive::pg_catalog.oid as typreceiveoid, "
4544 "typsend::pg_catalog.oid as typsendoid, "
4545 "typanalyze::pg_catalog.oid as typanalyzeoid, "
4546 "typdelim, typdefault, typbyval, typalign, "
4548 "FROM pg_catalog.pg_type "
4549 "WHERE oid = '%u'::pg_catalog.oid",
4550 tinfo->dobj.catId.oid);
4552 else if (fout->remoteVersion >= 70400)
4554 appendPQExpBuffer(query, "SELECT typlen, "
4555 "typinput, typoutput, typreceive, typsend, "
4556 "'-' as typanalyze, "
4557 "typinput::pg_catalog.oid as typinputoid, "
4558 "typoutput::pg_catalog.oid as typoutputoid, "
4559 "typreceive::pg_catalog.oid as typreceiveoid, "
4560 "typsend::pg_catalog.oid as typsendoid, "
4561 "0 as typanalyzeoid, "
4562 "typdelim, typdefault, typbyval, typalign, "
4564 "FROM pg_catalog.pg_type "
4565 "WHERE oid = '%u'::pg_catalog.oid",
4566 tinfo->dobj.catId.oid);
4568 else if (fout->remoteVersion >= 70300)
4570 appendPQExpBuffer(query, "SELECT typlen, "
4571 "typinput, typoutput, "
4572 "'-' as typreceive, '-' as typsend, "
4573 "'-' as typanalyze, "
4574 "typinput::pg_catalog.oid as typinputoid, "
4575 "typoutput::pg_catalog.oid as typoutputoid, "
4576 "0 as typreceiveoid, 0 as typsendoid, "
4577 "0 as typanalyzeoid, "
4578 "typdelim, typdefault, typbyval, typalign, "
4580 "FROM pg_catalog.pg_type "
4581 "WHERE oid = '%u'::pg_catalog.oid",
4582 tinfo->dobj.catId.oid);
4584 else if (fout->remoteVersion >= 70100)
4587 * Note: although pre-7.3 catalogs contain typreceive and typsend,
4588 * ignore them because they are not right.
4590 appendPQExpBuffer(query, "SELECT typlen, "
4591 "typinput, typoutput, "
4592 "'-' as typreceive, '-' as typsend, "
4593 "'-' as typanalyze, "
4594 "typinput::oid as typinputoid, "
4595 "typoutput::oid as typoutputoid, "
4596 "0 as typreceiveoid, 0 as typsendoid, "
4597 "0 as typanalyzeoid, "
4598 "typdelim, typdefault, typbyval, typalign, "
4601 "WHERE oid = '%u'::oid",
4602 tinfo->dobj.catId.oid);
4606 appendPQExpBuffer(query, "SELECT typlen, "
4607 "typinput, typoutput, "
4608 "'-' as typreceive, '-' as typsend, "
4609 "'-' as typanalyze, "
4610 "typinput::oid as typinputoid, "
4611 "typoutput::oid as typoutputoid, "
4612 "0 as typreceiveoid, 0 as typsendoid, "
4613 "0 as typanalyzeoid, "
4614 "typdelim, typdefault, typbyval, typalign, "
4615 "'p'::char as typstorage "
4617 "WHERE oid = '%u'::oid",
4618 tinfo->dobj.catId.oid);
4621 res = PQexec(g_conn, query->data);
4622 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4624 /* Expecting a single result only */
4625 ntups = PQntuples(res);
4628 write_msg(NULL, "Got %d rows instead of one from: %s",
4629 ntups, query->data);
4633 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
4634 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
4635 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
4636 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
4637 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
4638 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
4639 typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
4640 typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
4641 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
4642 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
4643 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
4644 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
4645 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4648 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4649 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
4650 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
4651 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
4654 * DROP must be fully qualified in case same name appears in
4657 appendPQExpBuffer(delq, "DROP TYPE %s.",
4658 fmtId(tinfo->dobj.namespace->dobj.name));
4659 appendPQExpBuffer(delq, "%s CASCADE;\n",
4660 fmtId(tinfo->dobj.name));
4662 appendPQExpBuffer(q,
4663 "CREATE TYPE %s (\n"
4664 " INTERNALLENGTH = %s",
4665 fmtId(tinfo->dobj.name),
4666 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
4668 if (fout->remoteVersion >= 70300)
4670 /* regproc result is correctly quoted as of 7.3 */
4671 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
4672 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
4673 if (OidIsValid(typreceiveoid))
4674 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
4675 if (OidIsValid(typsendoid))
4676 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
4677 if (OidIsValid(typanalyzeoid))
4678 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
4682 /* regproc delivers an unquoted name before 7.3 */
4683 /* cannot combine these because fmtId uses static result area */
4684 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
4685 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
4686 /* no chance that receive/send/analyze need be printed */
4689 if (typdefault != NULL)
4691 appendPQExpBuffer(q, ",\n DEFAULT = ");
4692 appendStringLiteral(q, typdefault, true);
4699 /* reselect schema in case changed by function dump */
4700 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4701 elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
4702 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
4706 if (typdelim && strcmp(typdelim, ",") != 0)
4708 appendPQExpBuffer(q, ",\n DELIMITER = ");
4709 appendStringLiteral(q, typdelim, true);
4712 if (strcmp(typalign, "c") == 0)
4713 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
4714 else if (strcmp(typalign, "s") == 0)
4715 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
4716 else if (strcmp(typalign, "i") == 0)
4717 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
4718 else if (strcmp(typalign, "d") == 0)
4719 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
4721 if (strcmp(typstorage, "p") == 0)
4722 appendPQExpBuffer(q, ",\n STORAGE = plain");
4723 else if (strcmp(typstorage, "e") == 0)
4724 appendPQExpBuffer(q, ",\n STORAGE = external");
4725 else if (strcmp(typstorage, "x") == 0)
4726 appendPQExpBuffer(q, ",\n STORAGE = extended");
4727 else if (strcmp(typstorage, "m") == 0)
4728 appendPQExpBuffer(q, ",\n STORAGE = main");
4730 if (strcmp(typbyval, "t") == 0)
4731 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
4733 appendPQExpBuffer(q, "\n);\n");
4735 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4737 tinfo->dobj.namespace->dobj.name,
4739 tinfo->usename, false,
4740 "TYPE", q->data, delq->data, NULL,
4741 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4744 /* Dump Type Comments */
4745 resetPQExpBuffer(q);
4747 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4748 dumpComment(fout, q->data,
4749 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4750 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4753 destroyPQExpBuffer(q);
4754 destroyPQExpBuffer(delq);
4755 destroyPQExpBuffer(query);
4760 * writes out to fout the queries to recreate a user-defined domain
4763 dumpDomain(Archive *fout, TypeInfo *tinfo)
4765 PQExpBuffer q = createPQExpBuffer();
4766 PQExpBuffer delq = createPQExpBuffer();
4767 PQExpBuffer query = createPQExpBuffer();
4775 /* Set proper schema search path so type references list correctly */
4776 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4778 /* Fetch domain specific details */
4779 /* We assume here that remoteVersion must be at least 70300 */
4780 appendPQExpBuffer(query, "SELECT typnotnull, "
4781 "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
4783 "FROM pg_catalog.pg_type "
4784 "WHERE oid = '%u'::pg_catalog.oid",
4785 tinfo->dobj.catId.oid);
4787 res = PQexec(g_conn, query->data);
4788 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4790 /* Expecting a single result only */
4791 ntups = PQntuples(res);
4794 write_msg(NULL, "Got %d rows instead of one from: %s",
4795 ntups, query->data);
4799 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
4800 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
4801 if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4804 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4806 appendPQExpBuffer(q,
4807 "CREATE DOMAIN %s AS %s",
4808 fmtId(tinfo->dobj.name),
4811 if (typnotnull[0] == 't')
4812 appendPQExpBuffer(q, " NOT NULL");
4815 appendPQExpBuffer(q, " DEFAULT %s", typdefault);
4820 * Add any CHECK constraints for the domain
4822 for (i = 0; i < tinfo->nDomChecks; i++)
4824 ConstraintInfo *domcheck = &(tinfo->domChecks[i]);
4826 if (!domcheck->separate)
4827 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
4828 fmtId(domcheck->dobj.name), domcheck->condef);
4831 appendPQExpBuffer(q, ";\n");
4834 * DROP must be fully qualified in case same name appears in
4837 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
4838 fmtId(tinfo->dobj.namespace->dobj.name));
4839 appendPQExpBuffer(delq, "%s;\n",
4840 fmtId(tinfo->dobj.name));
4842 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4844 tinfo->dobj.namespace->dobj.name,
4846 tinfo->usename, false,
4847 "DOMAIN", q->data, delq->data, NULL,
4848 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4851 /* Dump Domain Comments */
4852 resetPQExpBuffer(q);
4854 appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->dobj.name));
4855 dumpComment(fout, q->data,
4856 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4857 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4859 destroyPQExpBuffer(q);
4860 destroyPQExpBuffer(delq);
4861 destroyPQExpBuffer(query);
4866 * writes out to fout the queries to recreate a user-defined stand-alone
4870 dumpCompositeType(Archive *fout, TypeInfo *tinfo)
4872 PQExpBuffer q = createPQExpBuffer();
4873 PQExpBuffer delq = createPQExpBuffer();
4874 PQExpBuffer query = createPQExpBuffer();
4881 /* Set proper schema search path so type references list correctly */
4882 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4884 /* Fetch type specific details */
4885 /* We assume here that remoteVersion must be at least 70300 */
4887 appendPQExpBuffer(query, "SELECT a.attname, "
4888 "pg_catalog.format_type(a.atttypid, a.atttypmod) as atttypdefn "
4889 "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
4890 "WHERE t.oid = '%u'::pg_catalog.oid "
4891 "AND a.attrelid = t.typrelid "
4892 "AND NOT a.attisdropped "
4893 "ORDER BY a.attnum ",
4894 tinfo->dobj.catId.oid);
4896 res = PQexec(g_conn, query->data);
4897 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4899 /* Expecting at least a single result */
4900 ntups = PQntuples(res);
4903 write_msg(NULL, "query yielded no rows: %s\n", query->data);
4907 i_attname = PQfnumber(res, "attname");
4908 i_atttypdefn = PQfnumber(res, "atttypdefn");
4910 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
4911 fmtId(tinfo->dobj.name));
4913 for (i = 0; i < ntups; i++)
4918 attname = PQgetvalue(res, i, i_attname);
4919 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
4921 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
4923 appendPQExpBuffer(q, ",");
4925 appendPQExpBuffer(q, "\n);\n");
4928 * DROP must be fully qualified in case same name appears in
4931 appendPQExpBuffer(delq, "DROP TYPE %s.",
4932 fmtId(tinfo->dobj.namespace->dobj.name));
4933 appendPQExpBuffer(delq, "%s;\n",
4934 fmtId(tinfo->dobj.name));
4936 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4938 tinfo->dobj.namespace->dobj.name,
4940 tinfo->usename, false,
4941 "TYPE", q->data, delq->data, NULL,
4942 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4946 /* Dump Type Comments */
4947 resetPQExpBuffer(q);
4949 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4950 dumpComment(fout, q->data,
4951 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4952 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4955 destroyPQExpBuffer(q);
4956 destroyPQExpBuffer(delq);
4957 destroyPQExpBuffer(query);
4962 * writes out to fout the queries to recreate a user-defined
4963 * procedural language
4966 dumpProcLang(Archive *fout, ProcLangInfo *plang)
4972 FuncInfo *validatorInfo = NULL;
4978 * Current theory is to dump PLs iff their underlying functions will
4979 * be dumped (are in a dumpable namespace, or have a non-system OID in
4980 * pre-7.3 databases). Actually, we treat the PL itself as being in
4981 * the underlying function's namespace, though it isn't really. This
4982 * avoids searchpath problems for the HANDLER clause.
4984 * If the underlying function is in the pg_catalog namespace, we won't
4985 * have loaded it into finfo[] at all; therefore, treat failure to
4986 * find it in finfo[] as indicating we shouldn't dump it, not as an
4987 * error condition. Ditto for the validator.
4990 funcInfo = findFuncByOid(plang->lanplcallfoid);
4991 if (funcInfo == NULL)
4994 if (!funcInfo->dobj.namespace->dump)
4997 if (OidIsValid(plang->lanvalidator))
4999 validatorInfo = findFuncByOid(plang->lanvalidator);
5000 if (validatorInfo == NULL)
5004 defqry = createPQExpBuffer();
5005 delqry = createPQExpBuffer();
5007 qlanname = strdup(fmtId(plang->dobj.name));
5009 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
5012 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
5013 plang->lanpltrusted ? "TRUSTED " : "",
5015 appendPQExpBuffer(defqry, " HANDLER %s",
5016 fmtId(funcInfo->dobj.name));
5017 if (OidIsValid(plang->lanvalidator))
5019 appendPQExpBuffer(defqry, " VALIDATOR ");
5020 /* Cope with possibility that validator is in different schema */
5021 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
5022 appendPQExpBuffer(defqry, "%s.",
5023 fmtId(validatorInfo->dobj.namespace->dobj.name));
5024 appendPQExpBuffer(defqry, "%s",
5025 fmtId(validatorInfo->dobj.name));
5027 appendPQExpBuffer(defqry, ";\n");
5029 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
5031 funcInfo->dobj.namespace->dobj.name, NULL, "",
5032 false, "PROCEDURAL LANGUAGE",
5033 defqry->data, delqry->data, NULL,
5034 plang->dobj.dependencies, plang->dobj.nDeps,
5037 /* Dump Proc Lang Comments */
5038 resetPQExpBuffer(defqry);
5040 appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
5041 dumpComment(fout, defqry->data,
5043 plang->dobj.catId, 0, plang->dobj.dumpId);
5045 if (plang->lanpltrusted)
5046 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
5047 qlanname, plang->dobj.name,
5048 funcInfo->dobj.namespace->dobj.name,
5049 NULL, plang->lanacl);
5053 destroyPQExpBuffer(defqry);
5054 destroyPQExpBuffer(delqry);
5058 * format_function_signature: generate function name and argument list
5060 * The argument type names are qualified if needed. The function name
5061 * is never qualified.
5063 * argnames may be NULL if no names are available.
5066 format_function_signature(FuncInfo *finfo, char **argnames,
5072 initPQExpBuffer(&fn);
5074 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5076 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
5077 for (j = 0; j < finfo->nargs; j++)
5082 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
5084 argname = argnames ? argnames[j] : (char *) NULL;
5085 if (argname && argname[0] == '\0')
5088 appendPQExpBuffer(&fn, "%s%s%s%s",
5089 (j > 0) ? ", " : "",
5090 argname ? fmtId(argname) : "",
5095 appendPQExpBuffer(&fn, ")");
5102 * dump out one function
5105 dumpFunc(Archive *fout, FuncInfo *finfo)
5124 char **argnamearray = NULL;
5126 /* Dump only funcs in dumpable namespaces */
5127 if (!finfo->dobj.namespace->dump || dataOnly)
5130 query = createPQExpBuffer();
5131 q = createPQExpBuffer();
5132 delqry = createPQExpBuffer();
5133 asPart = createPQExpBuffer();
5135 /* Set proper schema search path so type references list correctly */
5136 selectSourceSchema(finfo->dobj.namespace->dobj.name);
5138 /* Fetch function-specific details */
5139 if (g_fout->remoteVersion >= 80000)
5141 appendPQExpBuffer(query,
5142 "SELECT proretset, prosrc, probin, "
5144 "provolatile, proisstrict, prosecdef, "
5145 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5146 "FROM pg_catalog.pg_proc "
5147 "WHERE oid = '%u'::pg_catalog.oid",
5148 finfo->dobj.catId.oid);
5150 else if (g_fout->remoteVersion >= 70300)
5152 appendPQExpBuffer(query,
5153 "SELECT proretset, prosrc, probin, "
5154 "null::text as proargnames, "
5155 "provolatile, proisstrict, prosecdef, "
5156 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5157 "FROM pg_catalog.pg_proc "
5158 "WHERE oid = '%u'::pg_catalog.oid",
5159 finfo->dobj.catId.oid);
5161 else if (g_fout->remoteVersion >= 70100)
5163 appendPQExpBuffer(query,
5164 "SELECT proretset, prosrc, probin, "
5165 "null::text as proargnames, "
5166 "case when proiscachable then 'i' else 'v' end as provolatile, "
5168 "'f'::boolean as prosecdef, "
5169 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5171 "WHERE oid = '%u'::oid",
5172 finfo->dobj.catId.oid);
5176 appendPQExpBuffer(query,
5177 "SELECT proretset, prosrc, probin, "
5178 "null::text as proargnames, "
5179 "case when proiscachable then 'i' else 'v' end as provolatile, "
5180 "'f'::boolean as proisstrict, "
5181 "'f'::boolean as prosecdef, "
5182 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5184 "WHERE oid = '%u'::oid",
5185 finfo->dobj.catId.oid);
5188 res = PQexec(g_conn, query->data);
5189 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5191 /* Expecting a single result only */
5192 ntups = PQntuples(res);
5195 write_msg(NULL, "Got %d rows instead of one from: %s",
5196 ntups, query->data);
5200 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
5201 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
5202 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
5203 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
5204 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
5205 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
5206 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
5207 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
5210 * See backend/commands/define.c for details of how the 'AS' clause is
5213 if (strcmp(probin, "-") != 0)
5215 appendPQExpBuffer(asPart, "AS ");
5216 appendStringLiteral(asPart, probin, true);
5217 if (strcmp(prosrc, "-") != 0)
5219 appendPQExpBuffer(asPart, ", ");
5222 * where we have bin, use dollar quoting if allowed and src
5223 * contains quote or backslash; else use regular quoting.
5225 if (disable_dollar_quoting)
5226 appendStringLiteral(asPart, prosrc, false);
5228 appendStringLiteralDQOpt(asPart, prosrc, false, NULL);
5233 if (strcmp(prosrc, "-") != 0)
5235 appendPQExpBuffer(asPart, "AS ");
5236 /* with no bin, dollar quote src unconditionally if allowed */
5237 if (disable_dollar_quoting)
5238 appendStringLiteral(asPart, prosrc, false);
5240 appendStringLiteralDQ(asPart, prosrc, NULL);
5244 if (proargnames && *proargnames)
5248 if (!parsePGArray(proargnames, &argnamearray, &nitems) ||
5249 nitems != finfo->nargs)
5251 write_msg(NULL, "WARNING: could not parse proargnames array\n");
5254 argnamearray = NULL;
5258 funcsig = format_function_signature(finfo, argnamearray, true);
5259 funcsig_tag = format_function_signature(finfo, NULL, false);
5262 * DROP must be fully qualified in case same name appears in
5265 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
5266 fmtId(finfo->dobj.namespace->dobj.name),
5269 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
5271 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
5272 appendPQExpBuffer(q, "RETURNS %s%s\n %s\n LANGUAGE %s",
5273 (proretset[0] == 't') ? "SETOF " : "",
5280 if (provolatile[0] != PROVOLATILE_VOLATILE)
5282 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
5283 appendPQExpBuffer(q, " IMMUTABLE");
5284 else if (provolatile[0] == PROVOLATILE_STABLE)
5285 appendPQExpBuffer(q, " STABLE");
5286 else if (provolatile[0] != PROVOLATILE_VOLATILE)
5288 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
5294 if (proisstrict[0] == 't')
5295 appendPQExpBuffer(q, " STRICT");
5297 if (prosecdef[0] == 't')
5298 appendPQExpBuffer(q, " SECURITY DEFINER");
5300 appendPQExpBuffer(q, ";\n");
5302 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
5304 finfo->dobj.namespace->dobj.name,
5306 finfo->usename, false,
5307 "FUNCTION", q->data, delqry->data, NULL,
5308 finfo->dobj.dependencies, finfo->dobj.nDeps,
5311 /* Dump Function Comments */
5312 resetPQExpBuffer(q);
5313 appendPQExpBuffer(q, "FUNCTION %s", funcsig);
5314 dumpComment(fout, q->data,
5315 finfo->dobj.namespace->dobj.name, finfo->usename,
5316 finfo->dobj.catId, 0, finfo->dobj.dumpId);
5318 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
5319 funcsig, funcsig_tag,
5320 finfo->dobj.namespace->dobj.name,
5321 finfo->usename, finfo->proacl);
5325 destroyPQExpBuffer(query);
5326 destroyPQExpBuffer(q);
5327 destroyPQExpBuffer(delqry);
5328 destroyPQExpBuffer(asPart);
5337 * Dump a user-defined cast
5340 dumpCast(Archive *fout, CastInfo *cast)
5344 PQExpBuffer castsig;
5345 FuncInfo *funcInfo = NULL;
5346 TypeInfo *sourceInfo;
5347 TypeInfo *targetInfo;
5352 if (OidIsValid(cast->castfunc))
5354 funcInfo = findFuncByOid(cast->castfunc);
5355 if (funcInfo == NULL)
5360 * As per discussion we dump casts if one or more of the underlying
5361 * objects (the conversion function and the two data types) are not
5362 * builtin AND if all of the non-builtin objects namespaces are
5363 * included in the dump. Builtin meaning, the namespace name does not
5366 sourceInfo = findTypeByOid(cast->castsource);
5367 targetInfo = findTypeByOid(cast->casttarget);
5369 if (sourceInfo == NULL || targetInfo == NULL)
5373 * Skip this cast if all objects are from pg_
5375 if ((funcInfo == NULL ||
5376 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
5377 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
5378 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
5382 * Skip cast if function isn't from pg_ and that namespace is not
5386 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5387 !funcInfo->dobj.namespace->dump)
5391 * Same for the Source type
5393 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5394 !sourceInfo->dobj.namespace->dump)
5398 * and the target type.
5400 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5401 !targetInfo->dobj.namespace->dump)
5404 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
5405 selectSourceSchema("pg_catalog");
5407 defqry = createPQExpBuffer();
5408 delqry = createPQExpBuffer();
5409 castsig = createPQExpBuffer();
5411 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
5412 getFormattedTypeName(cast->castsource, zeroAsNone),
5413 getFormattedTypeName(cast->casttarget, zeroAsNone));
5415 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
5416 getFormattedTypeName(cast->castsource, zeroAsNone),
5417 getFormattedTypeName(cast->casttarget, zeroAsNone));
5419 if (!OidIsValid(cast->castfunc))
5420 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
5424 * Always qualify the function name, in case it is not in
5425 * pg_catalog schema (format_function_signature won't qualify it).
5427 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
5428 fmtId(funcInfo->dobj.namespace->dobj.name));
5429 appendPQExpBuffer(defqry, "%s",
5430 format_function_signature(funcInfo, NULL, true));
5433 if (cast->castcontext == 'a')
5434 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
5435 else if (cast->castcontext == 'i')
5436 appendPQExpBuffer(defqry, " AS IMPLICIT");
5437 appendPQExpBuffer(defqry, ";\n");
5439 appendPQExpBuffer(castsig, "CAST (%s AS %s)",
5440 getFormattedTypeName(cast->castsource, zeroAsNone),
5441 getFormattedTypeName(cast->casttarget, zeroAsNone));
5443 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
5445 "pg_catalog", NULL, "",
5446 false, "CAST", defqry->data, delqry->data, NULL,
5447 cast->dobj.dependencies, cast->dobj.nDeps,
5450 /* Dump Cast Comments */
5451 resetPQExpBuffer(defqry);
5452 appendPQExpBuffer(defqry, "CAST (%s AS %s)",
5453 getFormattedTypeName(cast->castsource, zeroAsNone),
5454 getFormattedTypeName(cast->casttarget, zeroAsNone));
5455 dumpComment(fout, defqry->data,
5457 cast->dobj.catId, 0, cast->dobj.dumpId);
5459 destroyPQExpBuffer(defqry);
5460 destroyPQExpBuffer(delqry);
5461 destroyPQExpBuffer(castsig);
5466 * write out a single operator definition
5469 dumpOpr(Archive *fout, OprInfo *oprinfo)
5475 PQExpBuffer details;
5506 /* Dump only operators in dumpable namespaces */
5507 if (!oprinfo->dobj.namespace->dump || dataOnly)
5511 * some operators are invalid because they were the result of user
5512 * defining operators before commutators exist
5514 if (!OidIsValid(oprinfo->oprcode))
5517 query = createPQExpBuffer();
5518 q = createPQExpBuffer();
5519 delq = createPQExpBuffer();
5520 oprid = createPQExpBuffer();
5521 details = createPQExpBuffer();
5523 /* Make sure we are in proper schema so regoperator works correctly */
5524 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
5526 if (g_fout->remoteVersion >= 70300)
5528 appendPQExpBuffer(query, "SELECT oprkind, "
5529 "oprcode::pg_catalog.regprocedure, "
5530 "oprleft::pg_catalog.regtype, "
5531 "oprright::pg_catalog.regtype, "
5532 "oprcom::pg_catalog.regoperator, "
5533 "oprnegate::pg_catalog.regoperator, "
5534 "oprrest::pg_catalog.regprocedure, "
5535 "oprjoin::pg_catalog.regprocedure, "
5537 "oprlsortop::pg_catalog.regoperator, "
5538 "oprrsortop::pg_catalog.regoperator, "
5539 "oprltcmpop::pg_catalog.regoperator, "
5540 "oprgtcmpop::pg_catalog.regoperator "
5541 "from pg_catalog.pg_operator "
5542 "where oid = '%u'::pg_catalog.oid",
5543 oprinfo->dobj.catId.oid);
5545 else if (g_fout->remoteVersion >= 70100)
5547 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5548 "CASE WHEN oprleft = 0 THEN '-' "
5549 "ELSE format_type(oprleft, NULL) END as oprleft, "
5550 "CASE WHEN oprright = 0 THEN '-' "
5551 "ELSE format_type(oprright, NULL) END as oprright, "
5552 "oprcom, oprnegate, oprrest, oprjoin, "
5553 "oprcanhash, oprlsortop, oprrsortop, "
5554 "0 as oprltcmpop, 0 as oprgtcmpop "
5556 "where oid = '%u'::oid",
5557 oprinfo->dobj.catId.oid);
5561 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5562 "CASE WHEN oprleft = 0 THEN '-'::name "
5563 "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
5564 "CASE WHEN oprright = 0 THEN '-'::name "
5565 "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
5566 "oprcom, oprnegate, oprrest, oprjoin, "
5567 "oprcanhash, oprlsortop, oprrsortop, "
5568 "0 as oprltcmpop, 0 as oprgtcmpop "
5570 "where oid = '%u'::oid",
5571 oprinfo->dobj.catId.oid);
5574 res = PQexec(g_conn, query->data);
5575 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5577 /* Expecting a single result only */
5578 ntups = PQntuples(res);
5581 write_msg(NULL, "Got %d rows instead of one from: %s",
5582 ntups, query->data);
5586 i_oprkind = PQfnumber(res, "oprkind");
5587 i_oprcode = PQfnumber(res, "oprcode");
5588 i_oprleft = PQfnumber(res, "oprleft");
5589 i_oprright = PQfnumber(res, "oprright");
5590 i_oprcom = PQfnumber(res, "oprcom");
5591 i_oprnegate = PQfnumber(res, "oprnegate");
5592 i_oprrest = PQfnumber(res, "oprrest");
5593 i_oprjoin = PQfnumber(res, "oprjoin");
5594 i_oprcanhash = PQfnumber(res, "oprcanhash");
5595 i_oprlsortop = PQfnumber(res, "oprlsortop");
5596 i_oprrsortop = PQfnumber(res, "oprrsortop");
5597 i_oprltcmpop = PQfnumber(res, "oprltcmpop");
5598 i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");
5600 oprkind = PQgetvalue(res, 0, i_oprkind);
5601 oprcode = PQgetvalue(res, 0, i_oprcode);
5602 oprleft = PQgetvalue(res, 0, i_oprleft);
5603 oprright = PQgetvalue(res, 0, i_oprright);
5604 oprcom = PQgetvalue(res, 0, i_oprcom);
5605 oprnegate = PQgetvalue(res, 0, i_oprnegate);
5606 oprrest = PQgetvalue(res, 0, i_oprrest);
5607 oprjoin = PQgetvalue(res, 0, i_oprjoin);
5608 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
5609 oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
5610 oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
5611 oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
5612 oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);
5614 appendPQExpBuffer(details, " PROCEDURE = %s",
5615 convertRegProcReference(oprcode));
5617 appendPQExpBuffer(oprid, "%s (",
5618 oprinfo->dobj.name);
5621 * right unary means there's a left arg and left unary means there's a
5624 if (strcmp(oprkind, "r") == 0 ||
5625 strcmp(oprkind, "b") == 0)
5627 if (g_fout->remoteVersion >= 70100)
5630 name = fmtId(oprleft);
5631 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
5632 appendPQExpBuffer(oprid, "%s", name);
5635 appendPQExpBuffer(oprid, "NONE");
5637 if (strcmp(oprkind, "l") == 0 ||
5638 strcmp(oprkind, "b") == 0)
5640 if (g_fout->remoteVersion >= 70100)
5643 name = fmtId(oprright);
5644 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
5645 appendPQExpBuffer(oprid, ", %s)", name);
5648 appendPQExpBuffer(oprid, ", NONE)");
5650 name = convertOperatorReference(oprcom);
5652 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
5654 name = convertOperatorReference(oprnegate);
5656 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
5658 if (strcmp(oprcanhash, "t") == 0)
5659 appendPQExpBuffer(details, ",\n HASHES");
5661 name = convertRegProcReference(oprrest);
5663 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
5665 name = convertRegProcReference(oprjoin);
5667 appendPQExpBuffer(details, ",\n JOIN = %s", name);
5669 name = convertOperatorReference(oprlsortop);
5671 appendPQExpBuffer(details, ",\n SORT1 = %s", name);
5673 name = convertOperatorReference(oprrsortop);
5675 appendPQExpBuffer(details, ",\n SORT2 = %s", name);
5677 name = convertOperatorReference(oprltcmpop);
5679 appendPQExpBuffer(details, ",\n LTCMP = %s", name);
5681 name = convertOperatorReference(oprgtcmpop);
5683 appendPQExpBuffer(details, ",\n GTCMP = %s", name);
5686 * DROP must be fully qualified in case same name appears in
5689 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
5690 fmtId(oprinfo->dobj.namespace->dobj.name),
5693 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
5694 oprinfo->dobj.name, details->data);
5696 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
5698 oprinfo->dobj.namespace->dobj.name,
5701 false, "OPERATOR", q->data, delq->data, NULL,
5702 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
5705 /* Dump Operator Comments */
5706 resetPQExpBuffer(q);
5707 appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
5708 dumpComment(fout, q->data,
5709 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5710 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
5714 destroyPQExpBuffer(query);
5715 destroyPQExpBuffer(q);
5716 destroyPQExpBuffer(delq);
5717 destroyPQExpBuffer(oprid);
5718 destroyPQExpBuffer(details);
5722 * Convert a function reference obtained from pg_operator
5724 * Returns what to print, or NULL if function references is InvalidOid
5726 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
5727 * argument-types part. In prior versions, the input is a REGPROC display.
5730 convertRegProcReference(const char *proc)
5732 /* In all cases "-" means a null reference */
5733 if (strcmp(proc, "-") == 0)
5736 if (g_fout->remoteVersion >= 70300)
5742 name = strdup(proc);
5743 /* find non-double-quoted left paren */
5745 for (paren = name; *paren; paren++)
5747 if (*paren == '(' && !inquote)
5758 /* REGPROC before 7.3 does not quote its result */
5763 * Convert an operator cross-reference obtained from pg_operator
5765 * Returns what to print, or NULL to print nothing
5767 * In 7.3 the input is a REGOPERATOR display; we have to strip the
5768 * argument-types part. In prior versions, the input is just a
5769 * numeric OID, which we search our operator list for.
5772 convertOperatorReference(const char *opr)
5776 /* In all cases "0" means a null reference */
5777 if (strcmp(opr, "0") == 0)
5780 if (g_fout->remoteVersion >= 70300)
5787 /* find non-double-quoted left paren */
5789 for (paren = name; *paren; paren++)
5791 if (*paren == '(' && !inquote)
5802 oprInfo = findOprByOid(atooid(opr));
5803 if (oprInfo == NULL)
5805 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
5809 return oprInfo->dobj.name;
5814 * write out a single operator class definition
5817 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
5845 /* Dump only opclasses in dumpable namespaces */
5846 if (!opcinfo->dobj.namespace->dump || dataOnly)
5850 * XXX currently we do not implement dumping of operator classes from
5851 * pre-7.3 databases. This could be done but it seems not worth the
5854 if (g_fout->remoteVersion < 70300)
5857 query = createPQExpBuffer();
5858 q = createPQExpBuffer();
5859 delq = createPQExpBuffer();
5861 /* Make sure we are in proper schema so regoperator works correctly */
5862 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
5864 /* Get additional fields from the pg_opclass row */
5865 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
5866 "opckeytype::pg_catalog.regtype, "
5868 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
5869 "FROM pg_catalog.pg_opclass "
5870 "WHERE oid = '%u'::pg_catalog.oid",
5871 opcinfo->dobj.catId.oid);
5873 res = PQexec(g_conn, query->data);
5874 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5876 /* Expecting a single result only */
5877 ntups = PQntuples(res);
5880 write_msg(NULL, "Got %d rows instead of one from: %s",
5881 ntups, query->data);
5885 i_opcintype = PQfnumber(res, "opcintype");
5886 i_opckeytype = PQfnumber(res, "opckeytype");
5887 i_opcdefault = PQfnumber(res, "opcdefault");
5888 i_amname = PQfnumber(res, "amname");
5890 opcintype = PQgetvalue(res, 0, i_opcintype);
5891 opckeytype = PQgetvalue(res, 0, i_opckeytype);
5892 opcdefault = PQgetvalue(res, 0, i_opcdefault);
5893 /* amname will still be needed after we PQclear res */
5894 amname = strdup(PQgetvalue(res, 0, i_amname));
5897 * DROP must be fully qualified in case same name appears in
5900 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
5901 fmtId(opcinfo->dobj.namespace->dobj.name));
5902 appendPQExpBuffer(delq, ".%s",
5903 fmtId(opcinfo->dobj.name));
5904 appendPQExpBuffer(delq, " USING %s;\n",
5907 /* Build the fixed portion of the CREATE command */
5908 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
5909 fmtId(opcinfo->dobj.name));
5910 if (strcmp(opcdefault, "t") == 0)
5911 appendPQExpBuffer(q, "DEFAULT ");
5912 appendPQExpBuffer(q, "FOR TYPE %s USING %s AS\n ",
5918 if (strcmp(opckeytype, "-") != 0)
5920 appendPQExpBuffer(q, "STORAGE %s",
5928 * Now fetch and print the OPERATOR entries (pg_amop rows).
5930 resetPQExpBuffer(query);
5932 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
5933 "amopopr::pg_catalog.regoperator "
5934 "FROM pg_catalog.pg_amop "
5935 "WHERE amopclaid = '%u'::pg_catalog.oid "
5936 "ORDER BY amopstrategy",
5937 opcinfo->dobj.catId.oid);
5939 res = PQexec(g_conn, query->data);
5940 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5942 ntups = PQntuples(res);
5944 i_amopstrategy = PQfnumber(res, "amopstrategy");
5945 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
5946 i_amopopr = PQfnumber(res, "amopopr");
5948 for (i = 0; i < ntups; i++)
5950 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
5951 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
5952 amopopr = PQgetvalue(res, i, i_amopopr);
5955 appendPQExpBuffer(q, " ,\n ");
5957 appendPQExpBuffer(q, "OPERATOR %s %s",
5958 amopstrategy, amopopr);
5959 if (strcmp(amopreqcheck, "t") == 0)
5960 appendPQExpBuffer(q, " RECHECK");
5968 * Now fetch and print the FUNCTION entries (pg_amproc rows).
5970 resetPQExpBuffer(query);
5972 appendPQExpBuffer(query, "SELECT amprocnum, "
5973 "amproc::pg_catalog.regprocedure "
5974 "FROM pg_catalog.pg_amproc "
5975 "WHERE amopclaid = '%u'::pg_catalog.oid "
5976 "ORDER BY amprocnum",
5977 opcinfo->dobj.catId.oid);
5979 res = PQexec(g_conn, query->data);
5980 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5982 ntups = PQntuples(res);
5984 i_amprocnum = PQfnumber(res, "amprocnum");
5985 i_amproc = PQfnumber(res, "amproc");
5987 for (i = 0; i < ntups; i++)
5989 amprocnum = PQgetvalue(res, i, i_amprocnum);
5990 amproc = PQgetvalue(res, i, i_amproc);
5993 appendPQExpBuffer(q, " ,\n ");
5995 appendPQExpBuffer(q, "FUNCTION %s %s",
6003 appendPQExpBuffer(q, ";\n");
6005 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
6007 opcinfo->dobj.namespace->dobj.name,
6010 false, "OPERATOR CLASS", q->data, delq->data, NULL,
6011 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
6014 /* Dump Operator Class Comments */
6015 resetPQExpBuffer(q);
6016 appendPQExpBuffer(q, "OPERATOR CLASS %s",
6017 fmtId(opcinfo->dobj.name));
6018 appendPQExpBuffer(q, " USING %s",
6020 dumpComment(fout, q->data,
6021 NULL, opcinfo->usename,
6022 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
6025 destroyPQExpBuffer(query);
6026 destroyPQExpBuffer(q);
6027 destroyPQExpBuffer(delq);
6032 * write out a single conversion definition
6035 dumpConversion(Archive *fout, ConvInfo *convinfo)
6040 PQExpBuffer details;
6044 int i_conforencoding;
6045 int i_contoencoding;
6048 const char *conname;
6049 const char *conforencoding;
6050 const char *contoencoding;
6051 const char *conproc;
6054 /* Dump only conversions in dumpable namespaces */
6055 if (!convinfo->dobj.namespace->dump || dataOnly)
6058 query = createPQExpBuffer();
6059 q = createPQExpBuffer();
6060 delq = createPQExpBuffer();
6061 details = createPQExpBuffer();
6063 /* Make sure we are in proper schema */
6064 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
6066 /* Get conversion-specific details */
6067 appendPQExpBuffer(query, "SELECT conname, "
6068 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
6069 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
6070 "conproc, condefault "
6071 "FROM pg_catalog.pg_conversion c "
6072 "WHERE c.oid = '%u'::pg_catalog.oid",
6073 convinfo->dobj.catId.oid);
6075 res = PQexec(g_conn, query->data);
6076 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6078 /* Expecting a single result only */
6079 ntups = PQntuples(res);
6082 write_msg(NULL, "Got %d rows instead of one from: %s",
6083 ntups, query->data);
6087 i_conname = PQfnumber(res, "conname");
6088 i_conforencoding = PQfnumber(res, "conforencoding");
6089 i_contoencoding = PQfnumber(res, "contoencoding");
6090 i_conproc = PQfnumber(res, "conproc");
6091 i_condefault = PQfnumber(res, "condefault");
6093 conname = PQgetvalue(res, 0, i_conname);
6094 conforencoding = PQgetvalue(res, 0, i_conforencoding);
6095 contoencoding = PQgetvalue(res, 0, i_contoencoding);
6096 conproc = PQgetvalue(res, 0, i_conproc);
6097 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
6100 * DROP must be fully qualified in case same name appears in
6103 appendPQExpBuffer(delq, "DROP CONVERSION %s",
6104 fmtId(convinfo->dobj.namespace->dobj.name));
6105 appendPQExpBuffer(delq, ".%s;\n",
6106 fmtId(convinfo->dobj.name));
6108 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
6109 (condefault) ? "DEFAULT " : "",
6110 fmtId(convinfo->dobj.name));
6111 appendStringLiteral(q, conforencoding, true);
6112 appendPQExpBuffer(q, " TO ");
6113 appendStringLiteral(q, contoencoding, true);
6114 /* regproc is automatically quoted in 7.3 and above */
6115 appendPQExpBuffer(q, " FROM %s;\n", conproc);
6117 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
6118 convinfo->dobj.name,
6119 convinfo->dobj.namespace->dobj.name,
6122 false, "CONVERSION", q->data, delq->data, NULL,
6123 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
6126 /* Dump Conversion Comments */
6127 resetPQExpBuffer(q);
6128 appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
6129 dumpComment(fout, q->data,
6130 convinfo->dobj.namespace->dobj.name, convinfo->usename,
6131 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
6135 destroyPQExpBuffer(query);
6136 destroyPQExpBuffer(q);
6137 destroyPQExpBuffer(delq);
6138 destroyPQExpBuffer(details);
6142 * format_aggregate_signature: generate aggregate name and argument list
6144 * The argument type names are qualified if needed. The aggregate name
6145 * is never qualified.
6148 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
6150 PQExpBufferData buf;
6152 initPQExpBuffer(&buf);
6154 appendPQExpBuffer(&buf, "%s",
6155 fmtId(agginfo->aggfn.dobj.name));
6157 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
6159 /* If using regtype or format_type, fmtbasetype is already quoted */
6160 if (fout->remoteVersion >= 70100)
6162 if (agginfo->anybasetype)
6163 appendPQExpBuffer(&buf, "(*)");
6165 appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
6169 if (agginfo->anybasetype)
6170 appendPQExpBuffer(&buf, "(*)");
6172 appendPQExpBuffer(&buf, "(%s)",
6173 fmtId(agginfo->fmtbasetype));
6181 * write out a single aggregate definition
6184 dumpAgg(Archive *fout, AggInfo *agginfo)
6189 PQExpBuffer details;
6201 const char *aggtransfn;
6202 const char *aggfinalfn;
6203 const char *aggtranstype;
6204 const char *agginitval;
6207 /* Dump only aggs in dumpable namespaces */
6208 if (!agginfo->aggfn.dobj.namespace->dump || dataOnly)
6211 query = createPQExpBuffer();
6212 q = createPQExpBuffer();
6213 delq = createPQExpBuffer();
6214 details = createPQExpBuffer();
6216 /* Make sure we are in proper schema */
6217 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
6219 /* Get aggregate-specific details */
6220 if (g_fout->remoteVersion >= 70300)
6222 appendPQExpBuffer(query, "SELECT aggtransfn, "
6223 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6225 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6226 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6227 "'t'::boolean as convertok "
6228 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6229 "where a.aggfnoid = p.oid "
6230 "and p.oid = '%u'::pg_catalog.oid",
6231 agginfo->aggfn.dobj.catId.oid);
6233 else if (g_fout->remoteVersion >= 70100)
6235 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
6236 "format_type(aggtranstype, NULL) as aggtranstype, "
6238 "aggbasetype = 0 as anybasetype, "
6239 "CASE WHEN aggbasetype = 0 THEN '-' "
6240 "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
6241 "'t'::boolean as convertok "
6242 "from pg_aggregate "
6243 "where oid = '%u'::oid",
6244 agginfo->aggfn.dobj.catId.oid);
6248 appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
6250 "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
6251 "agginitval1 as agginitval, "
6252 "aggbasetype = 0 as anybasetype, "
6253 "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
6254 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
6255 "from pg_aggregate "
6256 "where oid = '%u'::oid",
6257 agginfo->aggfn.dobj.catId.oid);
6260 res = PQexec(g_conn, query->data);
6261 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6263 /* Expecting a single result only */
6264 ntups = PQntuples(res);
6267 write_msg(NULL, "Got %d rows instead of one from: %s",
6268 ntups, query->data);
6272 i_aggtransfn = PQfnumber(res, "aggtransfn");
6273 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
6274 i_aggtranstype = PQfnumber(res, "aggtranstype");
6275 i_agginitval = PQfnumber(res, "agginitval");
6276 i_anybasetype = PQfnumber(res, "anybasetype");
6277 i_fmtbasetype = PQfnumber(res, "fmtbasetype");
6278 i_convertok = PQfnumber(res, "convertok");
6280 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
6281 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
6282 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
6283 agginitval = PQgetvalue(res, 0, i_agginitval);
6284 /* we save anybasetype for format_aggregate_signature */
6285 agginfo->anybasetype = (PQgetvalue(res, 0, i_anybasetype)[0] == 't');
6286 /* we save fmtbasetype for format_aggregate_signature */
6287 agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
6288 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
6290 aggsig = format_aggregate_signature(agginfo, fout, true);
6291 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
6295 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
6300 if (g_fout->remoteVersion >= 70300)
6302 /* If using 7.3's regproc or regtype, data is already quoted */
6303 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6304 agginfo->anybasetype ? "'any'" :
6305 agginfo->fmtbasetype,
6309 else if (g_fout->remoteVersion >= 70100)
6311 /* format_type quotes, regproc does not */
6312 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6313 agginfo->anybasetype ? "'any'" :
6314 agginfo->fmtbasetype,
6320 /* need quotes all around */
6321 appendPQExpBuffer(details, " BASETYPE = %s,\n",
6322 agginfo->anybasetype ? "'any'" :
6323 fmtId(agginfo->fmtbasetype));
6324 appendPQExpBuffer(details, " SFUNC = %s,\n",
6326 appendPQExpBuffer(details, " STYPE = %s",
6327 fmtId(aggtranstype));
6330 if (!PQgetisnull(res, 0, i_agginitval))
6332 appendPQExpBuffer(details, ",\n INITCOND = ");
6333 appendStringLiteral(details, agginitval, true);
6336 if (strcmp(aggfinalfn, "-") != 0)
6338 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
6343 * DROP must be fully qualified in case same name appears in
6346 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
6347 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
6350 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
6351 fmtId(agginfo->aggfn.dobj.name),
6354 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6356 agginfo->aggfn.dobj.namespace->dobj.name,
6358 agginfo->aggfn.usename,
6359 false, "AGGREGATE", q->data, delq->data, NULL,
6360 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
6363 /* Dump Aggregate Comments */
6364 resetPQExpBuffer(q);
6365 appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
6366 dumpComment(fout, q->data,
6367 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6368 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
6371 * Since there is no GRANT ON AGGREGATE syntax, we have to make the
6372 * ACL command look like a function's GRANT; in particular this
6373 * affects the syntax for aggregates on ANY.
6378 aggsig = format_function_signature(&agginfo->aggfn, NULL, true);
6379 aggsig_tag = format_function_signature(&agginfo->aggfn, NULL, false);
6381 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6384 agginfo->aggfn.dobj.namespace->dobj.name,
6385 agginfo->aggfn.usename, agginfo->aggfn.proacl);
6392 destroyPQExpBuffer(query);
6393 destroyPQExpBuffer(q);
6394 destroyPQExpBuffer(delq);
6395 destroyPQExpBuffer(details);
6400 * Write out grant/revoke information
6402 * 'objCatId' is the catalog ID of the underlying object.
6403 * 'objDumpId' is the dump ID of the underlying object.
6404 * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA.
6405 * 'name' is the formatted name of the object. Must be quoted etc. already.
6406 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
6407 * 'nspname' is the namespace the object is in (NULL if none).
6408 * 'owner' is the owner, NULL if there is no owner (for languages).
6409 * 'acls' is the string read out of the fooacl system catalog field;
6410 * it will be parsed here.
6414 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
6415 const char *type, const char *name,
6416 const char *tag, const char *nspname, const char *owner,
6421 /* Do nothing if ACL dump is not enabled */
6422 if (dataOnly || aclsSkip)
6425 sql = createPQExpBuffer();
6427 if (!buildACLCommands(name, type, acls, owner, fout->remoteVersion, sql))
6429 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
6435 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6439 false, "ACL", sql->data, "", NULL,
6443 destroyPQExpBuffer(sql);
6448 * write out to fout the declarations (not data) of a user-defined table
6451 dumpTable(Archive *fout, TableInfo *tbinfo)
6457 if (tbinfo->relkind == RELKIND_SEQUENCE)
6458 dumpSequence(fout, tbinfo);
6460 dumpTableSchema(fout, tbinfo);
6462 /* Handle the ACL here */
6463 namecopy = strdup(fmtId(tbinfo->dobj.name));
6464 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
6465 namecopy, tbinfo->dobj.name,
6466 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6474 * write the declaration (not data) of one user-defined table or view
6477 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
6479 PQExpBuffer query = createPQExpBuffer();
6480 PQExpBuffer q = createPQExpBuffer();
6481 PQExpBuffer delq = createPQExpBuffer();
6484 TableInfo **parents;
6485 int actual_atts; /* number of attrs in this CREATE statment */
6491 /* Make sure we are in proper schema */
6492 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
6494 /* Is it a table or a view? */
6495 if (tbinfo->relkind == RELKIND_VIEW)
6499 reltypename = "VIEW";
6501 /* Fetch the view definition */
6502 if (g_fout->remoteVersion >= 70300)
6504 /* Beginning in 7.3, viewname is not unique; rely on OID */
6505 appendPQExpBuffer(query,
6506 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) as viewdef",
6507 tbinfo->dobj.catId.oid);
6511 appendPQExpBuffer(query, "SELECT definition as viewdef "
6512 " from pg_views where viewname = ");
6513 appendStringLiteral(query, tbinfo->dobj.name, true);
6514 appendPQExpBuffer(query, ";");
6517 res = PQexec(g_conn, query->data);
6518 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6520 if (PQntuples(res) != 1)
6522 if (PQntuples(res) < 1)
6523 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
6526 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
6531 viewdef = PQgetvalue(res, 0, 0);
6533 if (strlen(viewdef) == 0)
6535 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
6541 * DROP must be fully qualified in case same name appears in
6544 appendPQExpBuffer(delq, "DROP VIEW %s.",
6545 fmtId(tbinfo->dobj.namespace->dobj.name));
6546 appendPQExpBuffer(delq, "%s;\n",
6547 fmtId(tbinfo->dobj.name));
6549 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
6550 fmtId(tbinfo->dobj.name), viewdef);
6556 reltypename = "TABLE";
6557 numParents = tbinfo->numParents;
6558 parents = tbinfo->parents;
6561 * DROP must be fully qualified in case same name appears in
6564 appendPQExpBuffer(delq, "DROP TABLE %s.",
6565 fmtId(tbinfo->dobj.namespace->dobj.name));
6566 appendPQExpBuffer(delq, "%s;\n",
6567 fmtId(tbinfo->dobj.name));
6569 appendPQExpBuffer(q, "CREATE TABLE %s (",
6570 fmtId(tbinfo->dobj.name));
6572 for (j = 0; j < tbinfo->numatts; j++)
6574 /* Is this one of the table's own attrs, and not dropped ? */
6575 if (!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j])
6577 /* Format properly if not first attr */
6578 if (actual_atts > 0)
6579 appendPQExpBuffer(q, ",");
6580 appendPQExpBuffer(q, "\n ");
6582 /* Attribute name */
6583 appendPQExpBuffer(q, "%s ",
6584 fmtId(tbinfo->attnames[j]));
6586 /* Attribute type */
6587 if (g_fout->remoteVersion >= 70100)
6589 char *typname = tbinfo->atttypnames[j];
6591 if (tbinfo->attisserial[j])
6593 if (strcmp(typname, "integer") == 0)
6595 else if (strcmp(typname, "bigint") == 0)
6596 typname = "bigserial";
6598 appendPQExpBuffer(q, "%s", typname);
6602 /* If no format_type, fake it */
6603 appendPQExpBuffer(q, "%s",
6604 myFormatType(tbinfo->atttypnames[j],
6605 tbinfo->atttypmod[j]));
6609 * Default value --- suppress if inherited, serial, or to
6610 * be printed separately.
6612 if (tbinfo->attrdefs[j] != NULL &&
6613 !tbinfo->inhAttrDef[j] &&
6614 !tbinfo->attisserial[j] &&
6615 !tbinfo->attrdefs[j]->separate)
6616 appendPQExpBuffer(q, " DEFAULT %s",
6617 tbinfo->attrdefs[j]->adef_expr);
6620 * Not Null constraint --- suppress if inherited
6622 * Note: we could suppress this for serial columns since
6623 * SERIAL implies NOT NULL. We choose not to for forward
6624 * compatibility, since there has been some talk of making
6625 * SERIAL not imply NOT NULL, in which case the explicit
6626 * specification would be needed.
6628 if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
6629 appendPQExpBuffer(q, " NOT NULL");
6636 * Add non-inherited CHECK constraints, if any.
6638 for (j = 0; j < tbinfo->ncheck; j++)
6640 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
6642 if (constr->coninherited || constr->separate)
6645 if (actual_atts > 0)
6646 appendPQExpBuffer(q, ",\n ");
6648 appendPQExpBuffer(q, "CONSTRAINT %s ",
6649 fmtId(constr->dobj.name));
6650 appendPQExpBuffer(q, "%s", constr->condef);
6655 appendPQExpBuffer(q, "\n)");
6659 appendPQExpBuffer(q, "\nINHERITS (");
6660 for (k = 0; k < numParents; k++)
6662 TableInfo *parentRel = parents[k];
6665 appendPQExpBuffer(q, ", ");
6666 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
6667 appendPQExpBuffer(q, "%s.",
6668 fmtId(parentRel->dobj.namespace->dobj.name));
6669 appendPQExpBuffer(q, "%s",
6670 fmtId(parentRel->dobj.name));
6672 appendPQExpBuffer(q, ")");
6675 appendPQExpBuffer(q, ";\n");
6677 /* Loop dumping statistics and storage statements */
6678 for (j = 0; j < tbinfo->numatts; j++)
6681 * Dump per-column statistics information. We only issue an
6682 * ALTER TABLE statement if the attstattarget entry for this
6683 * column is non-negative (i.e. it's not the default value)
6685 if (tbinfo->attstattarget[j] >= 0 &&
6686 !tbinfo->attisdropped[j])
6688 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6689 fmtId(tbinfo->dobj.name));
6690 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6691 fmtId(tbinfo->attnames[j]));
6692 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
6693 tbinfo->attstattarget[j]);
6697 * Dump per-column storage information. The statement is only
6698 * dumped if the storage has been changed from the type's
6701 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
6703 switch (tbinfo->attstorage[j])
6709 storage = "EXTERNAL";
6715 storage = "EXTENDED";
6722 * Only dump the statement if it's a storage type we
6725 if (storage != NULL)
6727 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6728 fmtId(tbinfo->dobj.name));
6729 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6730 fmtId(tbinfo->attnames[j]));
6731 appendPQExpBuffer(q, "SET STORAGE %s;\n",
6738 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
6740 tbinfo->dobj.namespace->dobj.name,
6741 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
6743 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
6744 reltypename, q->data, delq->data, NULL,
6745 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
6748 /* Dump Table Comments */
6749 dumpTableComment(fout, tbinfo, reltypename);
6751 /* Dump comments on inlined table constraints */
6752 for (j = 0; j < tbinfo->ncheck; j++)
6754 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
6756 if (constr->coninherited || constr->separate)
6759 dumpTableConstraintComment(fout, constr);
6762 destroyPQExpBuffer(query);
6763 destroyPQExpBuffer(q);
6764 destroyPQExpBuffer(delq);
6768 * dumpAttrDef --- dump an attribute's default-value declaration
6771 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
6773 TableInfo *tbinfo = adinfo->adtable;
6774 int adnum = adinfo->adnum;
6778 /* Only print it if "separate" mode is selected */
6779 if (!tbinfo->dump || !adinfo->separate || dataOnly)
6782 /* Don't print inherited or serial defaults, either */
6783 if (tbinfo->inhAttrDef[adnum - 1] || tbinfo->attisserial[adnum - 1])
6786 q = createPQExpBuffer();
6787 delq = createPQExpBuffer();
6789 appendPQExpBuffer(q, "ALTER TABLE %s ",
6790 fmtId(tbinfo->dobj.name));
6791 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
6792 fmtId(tbinfo->attnames[adnum - 1]),
6796 * DROP must be fully qualified in case same name appears in
6799 appendPQExpBuffer(delq, "ALTER TABLE %s.",
6800 fmtId(tbinfo->dobj.namespace->dobj.name));
6801 appendPQExpBuffer(delq, "%s ",
6802 fmtId(tbinfo->dobj.name));
6803 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
6804 fmtId(tbinfo->attnames[adnum - 1]));
6806 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
6807 tbinfo->attnames[adnum - 1],
6808 tbinfo->dobj.namespace->dobj.name,
6811 false, "DEFAULT", q->data, delq->data, NULL,
6812 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
6815 destroyPQExpBuffer(q);
6816 destroyPQExpBuffer(delq);
6820 * getAttrName: extract the correct name for an attribute
6822 * The array tblInfo->attnames[] only provides names of user attributes;
6823 * if a system attribute number is supplied, we have to fake it.
6824 * We also do a little bit of bounds checking for safety's sake.
6827 getAttrName(int attrnum, TableInfo *tblInfo)
6829 if (attrnum > 0 && attrnum <= tblInfo->numatts)
6830 return tblInfo->attnames[attrnum - 1];
6833 case SelfItemPointerAttributeNumber:
6835 case ObjectIdAttributeNumber:
6837 case MinTransactionIdAttributeNumber:
6839 case MinCommandIdAttributeNumber:
6841 case MaxTransactionIdAttributeNumber:
6843 case MaxCommandIdAttributeNumber:
6845 case TableOidAttributeNumber:
6848 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
6849 attrnum, tblInfo->dobj.name);
6851 return NULL; /* keep compiler quiet */
6856 * write out to fout a user-defined index
6859 dumpIndex(Archive *fout, IndxInfo *indxinfo)
6861 TableInfo *tbinfo = indxinfo->indextable;
6868 q = createPQExpBuffer();
6869 delq = createPQExpBuffer();
6872 * If there's an associated constraint, don't dump the index per se,
6873 * but do dump any comment for it. (This is safe because dependency
6874 * ordering will have ensured the constraint is emitted first.)
6876 if (indxinfo->indexconstraint == 0)
6878 /* Plain secondary index */
6879 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
6881 /* If the index is clustered, we need to record that. */
6882 if (indxinfo->indisclustered)
6884 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6885 fmtId(tbinfo->dobj.name));
6886 appendPQExpBuffer(q, " ON %s;\n",
6887 fmtId(indxinfo->dobj.name));
6891 * DROP must be fully qualified in case same name appears in
6894 appendPQExpBuffer(delq, "DROP INDEX %s.",
6895 fmtId(tbinfo->dobj.namespace->dobj.name));
6896 appendPQExpBuffer(delq, "%s;\n",
6897 fmtId(indxinfo->dobj.name));
6899 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
6900 indxinfo->dobj.name,
6901 tbinfo->dobj.namespace->dobj.name,
6902 tbinfo->reltablespace,
6903 tbinfo->usename, false,
6904 "INDEX", q->data, delq->data, NULL,
6905 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
6909 /* Dump Index Comments */
6910 resetPQExpBuffer(q);
6911 appendPQExpBuffer(q, "INDEX %s",
6912 fmtId(indxinfo->dobj.name));
6913 dumpComment(fout, q->data,
6914 tbinfo->dobj.namespace->dobj.name,
6916 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
6918 destroyPQExpBuffer(q);
6919 destroyPQExpBuffer(delq);
6924 * write out to fout a user-defined constraint
6927 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
6929 TableInfo *tbinfo = coninfo->contable;
6935 if (tbinfo && !tbinfo->dump)
6938 q = createPQExpBuffer();
6939 delq = createPQExpBuffer();
6941 if (coninfo->contype == 'p' || coninfo->contype == 'u')
6943 /* Index-related constraint */
6947 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
6949 if (indxinfo == NULL)
6951 write_msg(NULL, "missing index for constraint \"%s\"\n",
6952 coninfo->dobj.name);
6956 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6957 fmtId(tbinfo->dobj.name));
6958 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s (",
6959 fmtId(coninfo->dobj.name),
6960 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
6962 for (k = 0; k < indxinfo->indnkeys; k++)
6964 int indkey = (int) indxinfo->indkeys[k];
6965 const char *attname;
6967 if (indkey == InvalidAttrNumber)
6969 attname = getAttrName(indkey, tbinfo);
6971 appendPQExpBuffer(q, "%s%s",
6972 (k == 0) ? "" : ", ",
6976 appendPQExpBuffer(q, ");\n");
6978 /* If the index is clustered, we need to record that. */
6979 if (indxinfo->indisclustered)
6981 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6982 fmtId(tbinfo->dobj.name));
6983 appendPQExpBuffer(q, " ON %s;\n",
6984 fmtId(indxinfo->dobj.name));
6988 * DROP must be fully qualified in case same name appears in
6991 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
6992 fmtId(tbinfo->dobj.namespace->dobj.name));
6993 appendPQExpBuffer(delq, "%s ",
6994 fmtId(tbinfo->dobj.name));
6995 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6996 fmtId(coninfo->dobj.name));
6998 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7000 tbinfo->dobj.namespace->dobj.name,
7001 indxinfo->tablespace,
7002 tbinfo->usename, false,
7003 "CONSTRAINT", q->data, delq->data, NULL,
7004 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7007 else if (coninfo->contype == 'f')
7010 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that
7011 * the current table data is not processed
7013 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
7014 fmtId(tbinfo->dobj.name));
7015 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7016 fmtId(coninfo->dobj.name),
7020 * DROP must be fully qualified in case same name appears in
7023 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7024 fmtId(tbinfo->dobj.namespace->dobj.name));
7025 appendPQExpBuffer(delq, "%s ",
7026 fmtId(tbinfo->dobj.name));
7027 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7028 fmtId(coninfo->dobj.name));
7030 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7032 tbinfo->dobj.namespace->dobj.name,
7034 tbinfo->usename, false,
7035 "FK CONSTRAINT", q->data, delq->data, NULL,
7036 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7039 else if (coninfo->contype == 'c' && tbinfo)
7041 /* CHECK constraint on a table */
7043 /* Ignore if not to be dumped separately */
7044 if (coninfo->separate)
7046 /* not ONLY since we want it to propagate to children */
7047 appendPQExpBuffer(q, "ALTER TABLE %s\n",
7048 fmtId(tbinfo->dobj.name));
7049 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7050 fmtId(coninfo->dobj.name),
7054 * DROP must be fully qualified in case same name appears in
7057 appendPQExpBuffer(delq, "ALTER TABLE %s.",
7058 fmtId(tbinfo->dobj.namespace->dobj.name));
7059 appendPQExpBuffer(delq, "%s ",
7060 fmtId(tbinfo->dobj.name));
7061 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7062 fmtId(coninfo->dobj.name));
7064 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7066 tbinfo->dobj.namespace->dobj.name,
7068 tbinfo->usename, false,
7069 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7070 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7074 else if (coninfo->contype == 'c' && tbinfo == NULL)
7076 /* CHECK constraint on a domain */
7077 TypeInfo *tinfo = coninfo->condomain;
7079 /* Ignore if not to be dumped separately, or if not dumping domain */
7080 if (coninfo->separate && tinfo->dobj.namespace->dump)
7082 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
7083 fmtId(tinfo->dobj.name));
7084 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7085 fmtId(coninfo->dobj.name),
7089 * DROP must be fully qualified in case same name appears in
7092 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
7093 fmtId(tinfo->dobj.namespace->dobj.name));
7094 appendPQExpBuffer(delq, "%s ",
7095 fmtId(tinfo->dobj.name));
7096 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7097 fmtId(coninfo->dobj.name));
7099 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7101 tinfo->dobj.namespace->dobj.name,
7103 tinfo->usename, false,
7104 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7105 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7111 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
7115 /* Dump Constraint Comments --- only works for table constraints */
7116 if (tbinfo && coninfo->separate)
7117 dumpTableConstraintComment(fout, coninfo);
7119 destroyPQExpBuffer(q);
7120 destroyPQExpBuffer(delq);
7124 * dumpTableConstraintComment --- dump a constraint's comment if any
7126 * This is split out because we need the function in two different places
7127 * depending on whether the constraint is dumped as part of CREATE TABLE
7128 * or as a separate ALTER command.
7131 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
7133 TableInfo *tbinfo = coninfo->contable;
7134 PQExpBuffer q = createPQExpBuffer();
7136 appendPQExpBuffer(q, "CONSTRAINT %s ",
7137 fmtId(coninfo->dobj.name));
7138 appendPQExpBuffer(q, "ON %s",
7139 fmtId(tbinfo->dobj.name));
7140 dumpComment(fout, q->data,
7141 tbinfo->dobj.namespace->dobj.name,
7143 coninfo->dobj.catId, 0,
7144 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
7146 destroyPQExpBuffer(q);
7151 * find the maximum oid and generate a COPY statement to set it
7154 setMaxOid(Archive *fout)
7160 do_sql_command(g_conn,
7161 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer)");
7162 res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
7163 check_sql_result(res, g_conn, "INSERT INTO pgdump_oid VALUES (0)",
7165 max_oid = PQoidValue(res);
7168 write_msg(NULL, "inserted invalid OID\n");
7172 do_sql_command(g_conn, "DROP TABLE pgdump_oid;");
7174 write_msg(NULL, "maximum system OID is %u\n", max_oid);
7175 snprintf(sql, sizeof(sql),
7176 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer);\n"
7177 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
7180 "DROP TABLE pgdump_oid;\n",
7183 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7184 "Max OID", NULL, NULL, "",
7185 false, "<Init>", sql, "", NULL,
7191 * findLastBuiltInOid -
7192 * find the last built in oid
7194 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
7195 * pg_database entry for the current database
7198 findLastBuiltinOid_V71(const char *dbname)
7203 PQExpBuffer query = createPQExpBuffer();
7205 resetPQExpBuffer(query);
7206 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
7207 appendStringLiteral(query, dbname, true);
7209 res = PQexec(g_conn, query->data);
7210 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7212 ntups = PQntuples(res);
7215 write_msg(NULL, "missing pg_database entry for this database\n");
7220 write_msg(NULL, "found more than one pg_database entry for this database\n");
7223 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
7225 destroyPQExpBuffer(query);
7230 * findLastBuiltInOid -
7231 * find the last built in oid
7233 * For 7.0, we do this by assuming that the last thing that initdb does is to
7234 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
7235 * initdb won't be changing anymore, it'll do.
7238 findLastBuiltinOid_V70(void)
7244 res = PQexec(g_conn,
7245 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
7246 check_sql_result(res, g_conn,
7247 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
7249 ntups = PQntuples(res);
7252 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
7257 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
7260 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
7266 dumpSequence(Archive *fout, TableInfo *tbinfo)
7278 PQExpBuffer query = createPQExpBuffer();
7279 PQExpBuffer delqry = createPQExpBuffer();
7281 /* Make sure we are in proper schema */
7282 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7284 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
7285 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
7287 appendPQExpBuffer(query,
7288 "SELECT sequence_name, last_value, increment_by, "
7289 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
7290 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
7292 "END AS max_value, "
7293 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
7294 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
7296 "END AS min_value, "
7297 "cache_value, is_cycled, is_called from %s",
7299 fmtId(tbinfo->dobj.name));
7301 res = PQexec(g_conn, query->data);
7302 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7304 if (PQntuples(res) != 1)
7306 write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
7307 tbinfo->dobj.name, PQntuples(res));
7311 /* Disable this check: it fails if sequence has been renamed */
7313 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
7315 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
7316 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
7321 last = PQgetvalue(res, 0, 1);
7322 incby = PQgetvalue(res, 0, 2);
7323 if (!PQgetisnull(res, 0, 3))
7324 maxv = PQgetvalue(res, 0, 3);
7325 if (!PQgetisnull(res, 0, 4))
7326 minv = PQgetvalue(res, 0, 4);
7327 cache = PQgetvalue(res, 0, 5);
7328 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
7329 called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
7332 * The logic we use for restoring sequences is as follows:
7334 * Add a basic CREATE SEQUENCE statement (use last_val for start if
7335 * called is false, else use min_val for start_val). Skip this if the
7336 * sequence came from a SERIAL column.
7338 * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
7339 * data. We do this for serial sequences too.
7342 if (!dataOnly && !OidIsValid(tbinfo->owning_tab))
7344 resetPQExpBuffer(delqry);
7347 * DROP must be fully qualified in case same name appears in
7350 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
7351 fmtId(tbinfo->dobj.namespace->dobj.name));
7352 appendPQExpBuffer(delqry, "%s;\n",
7353 fmtId(tbinfo->dobj.name));
7355 resetPQExpBuffer(query);
7356 appendPQExpBuffer(query,
7357 "CREATE SEQUENCE %s\n",
7358 fmtId(tbinfo->dobj.name));
7361 appendPQExpBuffer(query, " START WITH %s\n", last);
7363 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
7366 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
7368 appendPQExpBuffer(query, " NO MAXVALUE\n");
7371 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
7373 appendPQExpBuffer(query, " NO MINVALUE\n");
7375 appendPQExpBuffer(query,
7377 cache, (cycled ? "\n CYCLE" : ""));
7379 appendPQExpBuffer(query, ";\n");
7381 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7383 tbinfo->dobj.namespace->dobj.name,
7386 false, "SEQUENCE", query->data, delqry->data, NULL,
7387 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7393 TableInfo *owning_tab;
7395 resetPQExpBuffer(query);
7396 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
7399 * If this is a SERIAL sequence, then use the
7400 * pg_get_serial_sequence function to avoid hard-coding the
7401 * sequence name. Note that this implicitly assumes that the
7402 * sequence and its owning table are in the same schema, because
7403 * we don't schema-qualify the reference.
7405 if (OidIsValid(tbinfo->owning_tab) &&
7406 (owning_tab = findTableByOid(tbinfo->owning_tab)) != NULL)
7408 appendPQExpBuffer(query, "pg_catalog.pg_get_serial_sequence(");
7409 appendStringLiteral(query, fmtId(owning_tab->dobj.name), true);
7410 appendPQExpBuffer(query, ", ");
7411 appendStringLiteral(query, owning_tab->attnames[tbinfo->owning_col - 1], true);
7412 appendPQExpBuffer(query, ")");
7415 appendStringLiteral(query, fmtId(tbinfo->dobj.name), true);
7416 appendPQExpBuffer(query, ", %s, %s);\n",
7417 last, (called ? "true" : "false"));
7419 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7421 tbinfo->dobj.namespace->dobj.name,
7424 false, "SEQUENCE SET", query->data, "", NULL,
7425 &(tbinfo->dobj.dumpId), 1,
7431 /* Dump Sequence Comments */
7432 resetPQExpBuffer(query);
7433 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
7434 dumpComment(fout, query->data,
7435 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7436 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
7441 destroyPQExpBuffer(query);
7442 destroyPQExpBuffer(delqry);
7446 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
7448 TableInfo *tbinfo = tginfo->tgtable;
7457 query = createPQExpBuffer();
7458 delqry = createPQExpBuffer();
7461 * DROP must be fully qualified in case same name appears in
7464 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
7465 fmtId(tginfo->dobj.name));
7466 appendPQExpBuffer(delqry, "ON %s.",
7467 fmtId(tbinfo->dobj.namespace->dobj.name));
7468 appendPQExpBuffer(delqry, "%s;\n",
7469 fmtId(tbinfo->dobj.name));
7471 if (tginfo->tgisconstraint)
7473 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
7474 appendPQExpBuffer(query, fmtId(tginfo->tgconstrname));
7478 appendPQExpBuffer(query, "CREATE TRIGGER ");
7479 appendPQExpBuffer(query, fmtId(tginfo->dobj.name));
7481 appendPQExpBuffer(query, "\n ");
7485 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
7486 appendPQExpBuffer(query, "BEFORE");
7488 appendPQExpBuffer(query, "AFTER");
7489 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
7491 appendPQExpBuffer(query, " INSERT");
7494 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
7497 appendPQExpBuffer(query, " OR DELETE");
7499 appendPQExpBuffer(query, " DELETE");
7502 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
7505 appendPQExpBuffer(query, " OR UPDATE");
7507 appendPQExpBuffer(query, " UPDATE");
7509 appendPQExpBuffer(query, " ON %s\n",
7510 fmtId(tbinfo->dobj.name));
7512 if (tginfo->tgisconstraint)
7514 if (OidIsValid(tginfo->tgconstrrelid))
7516 /* If we are using regclass, name is already quoted */
7517 if (g_fout->remoteVersion >= 70300)
7518 appendPQExpBuffer(query, " FROM %s\n ",
7519 tginfo->tgconstrrelname);
7521 appendPQExpBuffer(query, " FROM %s\n ",
7522 fmtId(tginfo->tgconstrrelname));
7524 if (!tginfo->tgdeferrable)
7525 appendPQExpBuffer(query, "NOT ");
7526 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
7527 if (tginfo->tginitdeferred)
7528 appendPQExpBuffer(query, "DEFERRED\n");
7530 appendPQExpBuffer(query, "IMMEDIATE\n");
7533 if (TRIGGER_FOR_ROW(tginfo->tgtype))
7534 appendPQExpBuffer(query, " FOR EACH ROW\n ");
7536 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
7538 /* In 7.3, result of regproc is already quoted */
7539 if (g_fout->remoteVersion >= 70300)
7540 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7543 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7544 fmtId(tginfo->tgfname));
7547 for (findx = 0; findx < tginfo->tgnargs; findx++)
7553 p = strchr(p, '\\');
7556 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
7568 if (p[0] == '0' && p[1] == '0' && p[2] == '0')
7572 appendPQExpBufferChar(query, '\'');
7576 appendPQExpBufferChar(query, '\\');
7577 appendPQExpBufferChar(query, *s++);
7579 appendPQExpBufferChar(query, '\'');
7580 appendPQExpBuffer(query,
7581 (findx < tginfo->tgnargs - 1) ? ", " : "");
7584 appendPQExpBuffer(query, ");\n");
7586 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
7588 tbinfo->dobj.namespace->dobj.name,
7590 tbinfo->usename, false,
7591 "TRIGGER", query->data, delqry->data, NULL,
7592 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
7595 resetPQExpBuffer(query);
7596 appendPQExpBuffer(query, "TRIGGER %s ",
7597 fmtId(tginfo->dobj.name));
7598 appendPQExpBuffer(query, "ON %s",
7599 fmtId(tbinfo->dobj.name));
7601 dumpComment(fout, query->data,
7602 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7603 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
7605 destroyPQExpBuffer(query);
7606 destroyPQExpBuffer(delqry);
7614 dumpRule(Archive *fout, RuleInfo *rinfo)
7616 TableInfo *tbinfo = rinfo->ruletable;
7623 * Ignore rules for not-to-be-dumped tables
7625 if (tbinfo == NULL || !tbinfo->dump || dataOnly)
7629 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
7630 * we do not want to dump it as a separate object.
7632 if (!rinfo->separate)
7636 * Make sure we are in proper schema.
7638 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7640 query = createPQExpBuffer();
7641 cmd = createPQExpBuffer();
7642 delcmd = createPQExpBuffer();
7644 if (g_fout->remoteVersion >= 70300)
7646 appendPQExpBuffer(query,
7647 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
7648 rinfo->dobj.catId.oid);
7652 /* Rule name was unique before 7.3 ... */
7653 appendPQExpBuffer(query,
7654 "SELECT pg_get_ruledef('%s') AS definition",
7658 res = PQexec(g_conn, query->data);
7659 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7661 if (PQntuples(res) != 1)
7663 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
7664 rinfo->dobj.name, tbinfo->dobj.name);
7668 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
7671 * DROP must be fully qualified in case same name appears in
7674 appendPQExpBuffer(delcmd, "DROP RULE %s ",
7675 fmtId(rinfo->dobj.name));
7676 appendPQExpBuffer(delcmd, "ON %s.",
7677 fmtId(tbinfo->dobj.namespace->dobj.name));
7678 appendPQExpBuffer(delcmd, "%s;\n",
7679 fmtId(tbinfo->dobj.name));
7681 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
7683 tbinfo->dobj.namespace->dobj.name,
7685 tbinfo->usename, false,
7686 "RULE", cmd->data, delcmd->data, NULL,
7687 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
7690 /* Dump rule comments */
7691 resetPQExpBuffer(query);
7692 appendPQExpBuffer(query, "RULE %s",
7693 fmtId(rinfo->dobj.name));
7694 appendPQExpBuffer(query, " ON %s",
7695 fmtId(tbinfo->dobj.name));
7696 dumpComment(fout, query->data,
7697 tbinfo->dobj.namespace->dobj.name,
7699 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
7703 destroyPQExpBuffer(query);
7704 destroyPQExpBuffer(cmd);
7705 destroyPQExpBuffer(delcmd);
7709 * getDependencies --- obtain available dependency data
7712 getDependencies(void)
7723 DumpableObject *dobj,
7726 /* No dependency info available before 7.3 */
7727 if (g_fout->remoteVersion < 70300)
7731 write_msg(NULL, "reading dependency data\n");
7733 /* Make sure we are in proper schema */
7734 selectSourceSchema("pg_catalog");
7736 query = createPQExpBuffer();
7738 appendPQExpBuffer(query, "SELECT "
7739 "classid, objid, refclassid, refobjid, deptype "
7741 "WHERE deptype != 'p' "
7744 res = PQexec(g_conn, query->data);
7745 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7747 ntups = PQntuples(res);
7749 i_classid = PQfnumber(res, "classid");
7750 i_objid = PQfnumber(res, "objid");
7751 i_refclassid = PQfnumber(res, "refclassid");
7752 i_refobjid = PQfnumber(res, "refobjid");
7753 i_deptype = PQfnumber(res, "deptype");
7756 * Since we ordered the SELECT by referencing ID, we can expect that
7757 * multiple entries for the same object will appear together; this
7758 * saves on searches.
7762 for (i = 0; i < ntups; i++)
7768 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
7769 objId.oid = atooid(PQgetvalue(res, i, i_objid));
7770 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
7771 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
7772 deptype = *(PQgetvalue(res, i, i_deptype));
7775 dobj->catId.tableoid != objId.tableoid ||
7776 dobj->catId.oid != objId.oid)
7777 dobj = findObjectByCatalogId(objId);
7780 * Failure to find objects mentioned in pg_depend is not
7781 * unexpected, since for example we don't collect info about TOAST
7787 fprintf(stderr, "no referencing object %u %u\n",
7788 objId.tableoid, objId.oid);
7793 refdobj = findObjectByCatalogId(refobjId);
7795 if (refdobj == NULL)
7798 fprintf(stderr, "no referenced object %u %u\n",
7799 refobjId.tableoid, refobjId.oid);
7804 addObjectDependency(dobj, refdobj->dumpId);
7809 destroyPQExpBuffer(query);
7814 * selectSourceSchema - make the specified schema the active search path
7815 * in the source database.
7817 * NB: pg_catalog is explicitly searched after the specified schema;
7818 * so user names are only qualified if they are cross-schema references,
7819 * and system names are only qualified if they conflict with a user name
7820 * in the current schema.
7822 * Whenever the selected schema is not pg_catalog, be careful to qualify
7823 * references to system catalogs and types in our emitted commands!
7826 selectSourceSchema(const char *schemaName)
7828 static char *curSchemaName = NULL;
7831 /* Not relevant if fetching from pre-7.3 DB */
7832 if (g_fout->remoteVersion < 70300)
7834 /* Ignore null schema names */
7835 if (schemaName == NULL || *schemaName == '\0')
7837 /* Optimize away repeated selection of same schema */
7838 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
7841 query = createPQExpBuffer();
7842 appendPQExpBuffer(query, "SET search_path = %s",
7844 if (strcmp(schemaName, "pg_catalog") != 0)
7845 appendPQExpBuffer(query, ", pg_catalog");
7847 do_sql_command(g_conn, query->data);
7849 destroyPQExpBuffer(query);
7851 free(curSchemaName);
7852 curSchemaName = strdup(schemaName);
7856 * getFormattedTypeName - retrieve a nicely-formatted type name for the
7859 * NB: in 7.3 and up the result may depend on the currently-selected
7860 * schema; this is why we don't try to cache the names.
7863 getFormattedTypeName(Oid oid, OidOptions opts)
7872 if ((opts & zeroAsOpaque) != 0)
7873 return strdup(g_opaque_type);
7874 else if ((opts & zeroAsAny) != 0)
7875 return strdup("'any'");
7876 else if ((opts & zeroAsStar) != 0)
7878 else if ((opts & zeroAsNone) != 0)
7879 return strdup("NONE");
7882 query = createPQExpBuffer();
7883 if (g_fout->remoteVersion >= 70300)
7885 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
7888 else if (g_fout->remoteVersion >= 70100)
7890 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
7895 appendPQExpBuffer(query, "SELECT typname "
7897 "WHERE oid = '%u'::oid",
7901 res = PQexec(g_conn, query->data);
7902 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7904 /* Expecting a single result only */
7905 ntups = PQntuples(res);
7908 write_msg(NULL, "query yielded %d rows instead of one: %s\n",
7909 ntups, query->data);
7913 if (g_fout->remoteVersion >= 70100)
7915 /* already quoted */
7916 result = strdup(PQgetvalue(res, 0, 0));
7920 /* may need to quote it */
7921 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
7925 destroyPQExpBuffer(query);
7931 * myFormatType --- local implementation of format_type for use with 7.0.
7934 myFormatType(const char *typname, int32 typmod)
7937 bool isarray = false;
7938 PQExpBuffer buf = createPQExpBuffer();
7940 /* Handle array types */
7941 if (typname[0] == '_')
7947 /* Show lengths on bpchar and varchar */
7948 if (!strcmp(typname, "bpchar"))
7950 int len = (typmod - VARHDRSZ);
7952 appendPQExpBuffer(buf, "character");
7954 appendPQExpBuffer(buf, "(%d)",
7957 else if (!strcmp(typname, "varchar"))
7959 appendPQExpBuffer(buf, "character varying");
7961 appendPQExpBuffer(buf, "(%d)",
7964 else if (!strcmp(typname, "numeric"))
7966 appendPQExpBuffer(buf, "numeric");
7973 tmp_typmod = typmod - VARHDRSZ;
7974 precision = (tmp_typmod >> 16) & 0xffff;
7975 scale = tmp_typmod & 0xffff;
7976 appendPQExpBuffer(buf, "(%d,%d)",
7982 * char is an internal single-byte data type; Let's make sure we force
7983 * it through with quotes. - thomas 1998-12-13
7985 else if (strcmp(typname, "char") == 0)
7986 appendPQExpBuffer(buf, "\"char\"");
7988 appendPQExpBuffer(buf, "%s", fmtId(typname));
7990 /* Append array qualifier for array types */
7992 appendPQExpBuffer(buf, "[]");
7994 result = strdup(buf->data);
7995 destroyPQExpBuffer(buf);
8001 * fmtQualifiedId - convert a qualified name to the proper format for
8002 * the source database.
8004 * Like fmtId, use the result before calling again.
8007 fmtQualifiedId(const char *schema, const char *id)
8009 static PQExpBuffer id_return = NULL;
8011 if (id_return) /* first time through? */
8012 resetPQExpBuffer(id_return);
8014 id_return = createPQExpBuffer();
8016 /* Suppress schema name if fetching from pre-7.3 DB */
8017 if (g_fout->remoteVersion >= 70300 && schema && *schema)
8019 appendPQExpBuffer(id_return, "%s.",
8022 appendPQExpBuffer(id_return, "%s",
8025 return id_return->data;
8029 * Return a column list clause for the given relation.
8031 * Special case: if there are no undropped columns in the relation, return
8032 * "", not an invalid "()" column list.
8035 fmtCopyColumnList(const TableInfo *ti)
8037 static PQExpBuffer q = NULL;
8038 int numatts = ti->numatts;
8039 char **attnames = ti->attnames;
8040 bool *attisdropped = ti->attisdropped;
8044 if (q) /* first time through? */
8045 resetPQExpBuffer(q);
8047 q = createPQExpBuffer();
8049 appendPQExpBuffer(q, "(");
8051 for (i = 0; i < numatts; i++)
8053 if (attisdropped[i])
8056 appendPQExpBuffer(q, ", ");
8057 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
8062 return ""; /* no undropped columns */
8064 appendPQExpBuffer(q, ")");
8069 * Convenience subroutine to execute a SQL command and check for
8070 * COMMAND_OK status.
8073 do_sql_command(PGconn *conn, const char *query)
8077 res = PQexec(conn, query);
8078 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
8083 * Convenience subroutine to verify a SQL command succeeded,
8084 * and exit with a useful error message if not.
8087 check_sql_result(PGresult *res, PGconn *conn, const char *query,
8088 ExecStatusType expected)
8092 if (res && PQresultStatus(res) == expected)
8095 write_msg(NULL, "SQL command failed\n");
8097 err = PQresultErrorMessage(res);
8099 err = PQerrorMessage(conn);
8100 write_msg(NULL, "Error message from server: %s", err);
8101 write_msg(NULL, "The command was: %s\n", query);