1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
15 * $PostgreSQL: pgsql/src/bin/pg_dump/pg_dump.c,v 1.431 2006/03/02 01:18:25 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 ...
27 #ifndef WIN32_CLIENT_ONLY
43 #include "getopt_long.h"
45 #ifndef HAVE_INT_OPTRESET
49 #include "access/attnum.h"
50 #include "access/htup.h"
51 #include "catalog/pg_class.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_trigger.h"
54 #include "catalog/pg_type.h"
56 #include "commands/sequence.h"
59 #include "libpq/libpq-fs.h"
62 #include "pg_backup.h"
63 #include "pg_backup_archiver.h"
64 #include "dumputils.h"
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 /* subquery used to convert user ID (eg, datdba) to user name */
94 static const char *username_subquery;
96 /* obsolete as of 7.3: */
97 static Oid g_last_builtin_oid; /* value of the last builtin oid */
99 static char *selectTableName = NULL; /* name of a single table to dump */
100 static char *selectSchemaName = NULL; /* name of a single schema to dump */
102 char g_opaque_type[10]; /* name for the opaque type */
104 /* placeholders for the delimiters for comments */
105 char g_comment_start[10];
106 char g_comment_end[10];
108 static const CatalogId nilCatalogId = {0, 0};
110 /* these are to avoid passing around info for findNamespace() */
111 static NamespaceInfo *g_namespaces;
112 static int g_numNamespaces;
114 /* flag to turn on/off dollar quoting */
115 static int disable_dollar_quoting = 0;
118 static void help(const char *progname);
119 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
120 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
121 static void dumpComment(Archive *fout, const char *target,
122 const char *namespace, const char *owner,
123 CatalogId catalogId, int subid, DumpId dumpId);
124 static int findComments(Archive *fout, Oid classoid, Oid objoid,
125 CommentItem **items);
126 static int collectComments(Archive *fout, CommentItem **items);
127 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
128 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
129 static void dumpType(Archive *fout, TypeInfo *tinfo);
130 static void dumpBaseType(Archive *fout, TypeInfo *tinfo);
131 static void dumpDomain(Archive *fout, TypeInfo *tinfo);
132 static void dumpCompositeType(Archive *fout, TypeInfo *tinfo);
133 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
134 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
135 static void dumpFunc(Archive *fout, FuncInfo *finfo);
136 static void dumpCast(Archive *fout, CastInfo *cast);
137 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
138 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
139 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
140 static void dumpRule(Archive *fout, RuleInfo *rinfo);
141 static void dumpAgg(Archive *fout, AggInfo *agginfo);
142 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
143 static void dumpTable(Archive *fout, TableInfo *tbinfo);
144 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
145 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
146 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
147 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
148 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
149 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
151 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
152 const char *type, const char *name,
153 const char *tag, const char *nspname, const char *owner,
156 static void getDependencies(void);
157 static void getDomainConstraints(TypeInfo *tinfo);
158 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
159 static char *format_function_arguments(FuncInfo *finfo, int nallargs,
163 static char *format_function_signature(FuncInfo *finfo, bool honor_quotes);
164 static const char *convertRegProcReference(const char *proc);
165 static const char *convertOperatorReference(const char *opr);
166 static Oid findLastBuiltinOid_V71(const char *);
167 static Oid findLastBuiltinOid_V70(void);
168 static void selectSourceSchema(const char *schemaName);
169 static char *getFormattedTypeName(Oid oid, OidOptions opts);
170 static char *myFormatType(const char *typname, int32 typmod);
171 static const char *fmtQualifiedId(const char *schema, const char *id);
172 static bool hasBlobs(Archive *AH);
173 static int dumpBlobs(Archive *AH, void *arg);
174 static int dumpBlobComments(Archive *AH, void *arg);
175 static void dumpDatabase(Archive *AH);
176 static void dumpEncoding(Archive *AH);
177 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
178 static const char *fmtCopyColumnList(const TableInfo *ti);
179 static void do_sql_command(PGconn *conn, const char *query);
180 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
181 ExecStatusType expected);
185 main(int argc, char **argv)
188 const char *filename = NULL;
189 const char *format = "p";
190 const char *dbname = NULL;
191 const char *pghost = NULL;
192 const char *pgport = NULL;
193 const char *username = NULL;
194 const char *dumpencoding = NULL;
198 DumpableObject **dobjs;
201 bool force_password = false;
202 int compressLevel = -1;
203 bool ignore_version = false;
206 int outputCreate = 0;
207 bool outputBlobs = true;
208 int outputNoOwner = 0;
209 static int use_setsessauth = 0;
210 static int disable_triggers = 0;
211 char *outputSuperuser = NULL;
213 RestoreOptions *ropt;
215 static struct option long_options[] = {
216 {"data-only", no_argument, NULL, 'a'},
217 {"blobs", no_argument, NULL, 'b'},
218 {"clean", no_argument, NULL, 'c'},
219 {"create", no_argument, NULL, 'C'},
220 {"file", required_argument, NULL, 'f'},
221 {"format", required_argument, NULL, 'F'},
222 {"inserts", no_argument, NULL, 'd'},
223 {"attribute-inserts", no_argument, NULL, 'D'},
224 {"column-inserts", no_argument, NULL, 'D'},
225 {"host", required_argument, NULL, 'h'},
226 {"ignore-version", no_argument, NULL, 'i'},
227 {"no-reconnect", no_argument, NULL, 'R'},
228 {"oids", no_argument, NULL, 'o'},
229 {"no-owner", no_argument, NULL, 'O'},
230 {"port", required_argument, NULL, 'p'},
231 {"schema", required_argument, NULL, 'n'},
232 {"schema-only", no_argument, NULL, 's'},
233 {"superuser", required_argument, NULL, 'S'},
234 {"table", required_argument, NULL, 't'},
235 {"password", no_argument, NULL, 'W'},
236 {"username", required_argument, NULL, 'U'},
237 {"verbose", no_argument, NULL, 'v'},
238 {"no-privileges", no_argument, NULL, 'x'},
239 {"no-acl", no_argument, NULL, 'x'},
240 {"compress", required_argument, NULL, 'Z'},
241 {"encoding", required_argument, NULL, 'E'},
242 {"help", no_argument, NULL, '?'},
243 {"version", no_argument, NULL, 'V'},
246 * the following options don't have an equivalent short option letter,
247 * but are available as '-X long-name'
249 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
250 {"disable-triggers", no_argument, &disable_triggers, 1},
251 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
257 set_pglocale_pgservice(argv[0], "pg_dump");
261 strcpy(g_comment_start, "-- ");
262 g_comment_end[0] = '\0';
263 strcpy(g_opaque_type, "opaque");
265 dataOnly = schemaOnly = dumpInserts = attrNames = false;
267 progname = get_progname(argv[0]);
269 /* Set default options based on progname */
270 if (strcmp(progname, "pg_backup") == 0)
275 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
280 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
282 puts("pg_dump (PostgreSQL) " PG_VERSION);
287 while ((c = getopt_long(argc, argv, "abcCdDE:f:F:h:in:oOp:RsS:t:uU:vWxX:Z:",
288 long_options, &optindex)) != -1)
292 case 'a': /* Dump data only */
296 case 'b': /* Dump blobs */
297 /* this is now default, so just ignore the switch */
300 case 'c': /* clean (i.e., drop) schema prior to create */
304 case 'C': /* Create DB */
308 case 'd': /* dump data as proper insert strings */
312 case 'D': /* dump data as proper insert strings with
318 case 'E': /* Dump encoding */
319 dumpencoding = optarg;
330 case 'h': /* server host */
334 case 'i': /* ignore database version mismatch */
335 ignore_version = true;
338 case 'n': /* Dump data for this schema only */
339 selectSchemaName = strdup(optarg);
342 case 'o': /* Dump oids */
346 case 'O': /* Don't reconnect to match owner */
350 case 'p': /* server port */
355 /* no-op, still accepted for backwards compatibility */
358 case 's': /* dump schema only */
363 case 'S': /* Username for superuser in plain text output */
364 outputSuperuser = strdup(optarg);
367 case 't': /* Dump data for this table only */
368 selectTableName = strdup(optarg);
372 force_password = true;
373 username = simple_prompt("User name: ", 100, true);
380 case 'v': /* verbose */
385 force_password = true;
388 case 'x': /* skip ACL dump */
393 * Option letters were getting scarce, so I invented this new
394 * scheme: '-X feature' turns on some feature. Compare to the
395 * -f option in GCC. You should also add an equivalent
396 * GNU-style option --feature. Features that require
397 * arguments should use '-X feature=foo'.
400 if (strcmp(optarg, "disable-dollar-quoting") == 0)
401 disable_dollar_quoting = 1;
402 else if (strcmp(optarg, "disable-triggers") == 0)
403 disable_triggers = 1;
404 else if (strcmp(optarg, "use-set-session-authorization") == 0)
409 _("%s: invalid -X option -- %s\n"),
411 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
416 case 'Z': /* Compression Level */
417 compressLevel = atoi(optarg);
419 /* This covers the long options equivalent to -X xxx. */
425 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
430 if (optind < (argc - 1))
432 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
433 progname, argv[optind + 1]);
434 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
439 /* Get database name from command line */
441 dbname = argv[optind];
443 if (dataOnly && schemaOnly)
445 write_msg(NULL, "options \"schema only\" (-s) and \"data only\" (-a) cannot be used together\n");
449 if (dataOnly && outputClean)
451 write_msg(NULL, "options \"clean\" (-c) and \"data only\" (-a) cannot be used together\n");
455 if (selectTableName != NULL || selectSchemaName != NULL)
458 if (dumpInserts == true && oids == true)
460 write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together\n");
461 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
465 /* open the output file */
470 g_fout = CreateArchive(filename, archCustom, compressLevel);
475 g_fout = CreateArchive(filename, archFiles, compressLevel);
481 g_fout = CreateArchive(filename, archNull, 0);
486 g_fout = CreateArchive(filename, archTar, compressLevel);
490 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
496 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
500 /* Let the archiver know how noisy to be */
501 g_fout->verbose = g_verbose;
503 g_fout->minRemoteVersion = 70000; /* we can handle back to 7.0 */
504 g_fout->maxRemoteVersion = parse_version(PG_VERSION);
505 if (g_fout->maxRemoteVersion < 0)
507 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
512 * Open the database using the Archiver, so it knows about it. Errors mean
515 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
516 username, force_password, ignore_version);
519 * Start serializable transaction to dump consistent data.
521 do_sql_command(g_conn, "BEGIN");
523 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
525 /* Set the datestyle to ISO to ensure the dump's portability */
526 do_sql_command(g_conn, "SET DATESTYLE = ISO");
528 /* Set the client encoding */
531 char *cmd = malloc(strlen(dumpencoding) + 32);
533 sprintf(cmd, "SET client_encoding='%s'", dumpencoding);
534 do_sql_command(g_conn, cmd);
538 /* Select the appropriate subquery to convert user IDs to names */
539 if (g_fout->remoteVersion >= 80100)
540 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
541 else if (g_fout->remoteVersion >= 70300)
542 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
544 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
547 * If supported, set extra_float_digits so that we can dump float data
548 * exactly (given correctly implemented float I/O code, anyway)
550 if (g_fout->remoteVersion >= 70400)
551 do_sql_command(g_conn, "SET extra_float_digits TO 2");
553 /* Find the last built-in OID, if needed */
554 if (g_fout->remoteVersion < 70300)
556 if (g_fout->remoteVersion >= 70100)
557 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
559 g_last_builtin_oid = findLastBuiltinOid_V70();
561 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
565 * Now scan the database and create DumpableObject structs for all the
566 * objects we intend to dump.
568 tblinfo = getSchemaData(&numTables, schemaOnly, dataOnly);
571 getTableData(tblinfo, numTables, oids);
573 if (outputBlobs && hasBlobs(g_fout))
575 /* Add placeholders to allow correct sorting of blobs */
576 DumpableObject *blobobj;
578 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
579 blobobj->objType = DO_BLOBS;
580 blobobj->catId = nilCatalogId;
581 AssignDumpId(blobobj);
582 blobobj->name = strdup("BLOBS");
584 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
585 blobobj->objType = DO_BLOB_COMMENTS;
586 blobobj->catId = nilCatalogId;
587 AssignDumpId(blobobj);
588 blobobj->name = strdup("BLOB COMMENTS");
592 * Collect dependency data to assist in ordering the objects.
597 * Sort the objects into a safe dump order (no forward references).
599 * In 7.3 or later, we can rely on dependency information to help us
600 * determine a safe order, so the initial sort is mostly for cosmetic
601 * purposes: we sort by name to ensure that logically identical schemas
602 * will dump identically. Before 7.3 we don't have dependencies and we
603 * use OID ordering as an (unreliable) guide to creation order.
605 getDumpableObjects(&dobjs, &numObjs);
607 if (g_fout->remoteVersion >= 70300)
608 sortDumpableObjectsByTypeName(dobjs, numObjs);
610 sortDumpableObjectsByTypeOid(dobjs, numObjs);
612 sortDumpableObjects(dobjs, numObjs);
615 * Create archive TOC entries for all the objects to be dumped, in a safe
619 /* First the special encoding entry. */
620 dumpEncoding(g_fout);
622 /* The database item is always second, unless we don't want it at all */
623 if (!dataOnly && selectTableName == NULL && selectSchemaName == NULL)
624 dumpDatabase(g_fout);
626 /* Now the rearrangeable objects. */
627 for (i = 0; i < numObjs; i++)
628 dumpDumpableObject(g_fout, dobjs[i]);
631 * And finally we can do the actual output.
635 ropt = NewRestoreOptions();
636 ropt->filename = (char *) filename;
637 ropt->dropSchema = outputClean;
638 ropt->aclsSkip = aclsSkip;
639 ropt->superuser = outputSuperuser;
640 ropt->create = outputCreate;
641 ropt->noOwner = outputNoOwner;
642 ropt->disable_triggers = disable_triggers;
643 ropt->use_setsessauth = use_setsessauth;
644 ropt->dataOnly = dataOnly;
646 if (compressLevel == -1)
647 ropt->compression = 0;
649 ropt->compression = compressLevel;
651 ropt->suppressDumpWarnings = true; /* We've already shown them */
653 RestoreArchive(g_fout, ropt);
656 CloseArchive(g_fout);
665 help(const char *progname)
667 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
668 printf(_("Usage:\n"));
669 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
671 printf(_("\nGeneral options:\n"));
672 printf(_(" -f, --file=FILENAME output file name\n"));
673 printf(_(" -F, --format=c|t|p output file format (custom, tar, plain text)\n"));
674 printf(_(" -i, --ignore-version proceed even when server version mismatches\n"
675 " pg_dump version\n"));
676 printf(_(" -v, --verbose verbose mode\n"));
677 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
678 printf(_(" --help show this help, then exit\n"));
679 printf(_(" --version output version information, then exit\n"));
681 printf(_("\nOptions controlling the output content:\n"));
682 printf(_(" -a, --data-only dump only the data, not the schema\n"));
683 printf(_(" -c, --clean clean (drop) schema prior to create\n"));
684 printf(_(" -C, --create include commands to create database in dump\n"));
685 printf(_(" -d, --inserts dump data as INSERT, rather than COPY, commands\n"));
686 printf(_(" -D, --column-inserts dump data as INSERT commands with column names\n"));
687 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
688 printf(_(" -n, --schema=SCHEMA dump the named schema only\n"));
689 printf(_(" -o, --oids include OIDs in dump\n"));
690 printf(_(" -O, --no-owner skip restoration of object ownership\n"
691 " in plain text format\n"));
692 printf(_(" -s, --schema-only dump only the schema, no data\n"));
693 printf(_(" -S, --superuser=NAME specify the superuser user name to use in\n"
694 " plain text format\n"));
695 printf(_(" -t, --table=TABLE dump the named table only\n"));
696 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
697 printf(_(" -X disable-dollar-quoting, --disable-dollar-quoting\n"
698 " disable dollar quoting, use SQL standard quoting\n"));
699 printf(_(" -X disable-triggers, --disable-triggers\n"
700 " disable triggers during data-only restore\n"));
701 printf(_(" -X use-set-session-authorization, --use-set-session-authorization\n"
702 " use SESSION AUTHORIZATION commands instead of\n"
703 " OWNER TO commands\n"));
705 printf(_("\nConnection options:\n"));
706 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
707 printf(_(" -p, --port=PORT database server port number\n"));
708 printf(_(" -U, --username=NAME connect as specified database user\n"));
709 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
711 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
712 "variable value is used.\n\n"));
713 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
721 write_msg(NULL, "*** aborted because of error\n");
726 * selectDumpableNamespace: policy-setting subroutine
727 * Mark a namespace as to be dumped or not
730 selectDumpableNamespace(NamespaceInfo *nsinfo)
733 * If a specific table is being dumped, do not dump any complete
734 * namespaces. If a specific namespace is being dumped, dump just that
735 * namespace. Otherwise, dump all non-system namespaces.
737 if (selectTableName != NULL)
738 nsinfo->dobj.dump = false;
739 else if (selectSchemaName != NULL)
741 if (strcmp(nsinfo->dobj.name, selectSchemaName) == 0)
742 nsinfo->dobj.dump = true;
744 nsinfo->dobj.dump = false;
746 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
747 strcmp(nsinfo->dobj.name, "information_schema") == 0)
748 nsinfo->dobj.dump = false;
750 nsinfo->dobj.dump = true;
754 * selectDumpableTable: policy-setting subroutine
755 * Mark a table as to be dumped or not
758 selectDumpableTable(TableInfo *tbinfo)
761 * Always dump if dumping parent namespace; else, if a particular
762 * tablename has been specified, dump matching table name; else, do not
765 tbinfo->dobj.dump = false;
766 if (tbinfo->dobj.namespace->dobj.dump)
767 tbinfo->dobj.dump = true;
768 else if (selectTableName != NULL &&
769 strcmp(tbinfo->dobj.name, selectTableName) == 0)
771 /* If both -s and -t specified, must match both to dump */
772 if (selectSchemaName == NULL)
773 tbinfo->dobj.dump = true;
774 else if (strcmp(tbinfo->dobj.namespace->dobj.name, selectSchemaName) == 0)
775 tbinfo->dobj.dump = true;
780 * selectDumpableType: policy-setting subroutine
781 * Mark a type as to be dumped or not
784 selectDumpableType(TypeInfo *tinfo)
786 /* Dump only types in dumpable namespaces */
787 if (!tinfo->dobj.namespace->dobj.dump)
788 tinfo->dobj.dump = false;
790 /* skip complex types, except for standalone composite types */
791 /* (note: this test should now be unnecessary) */
792 else if (OidIsValid(tinfo->typrelid) &&
793 tinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
794 tinfo->dobj.dump = false;
796 /* skip undefined placeholder types */
797 else if (!tinfo->isDefined)
798 tinfo->dobj.dump = false;
800 /* skip all array types that start w/ underscore */
801 else if ((tinfo->dobj.name[0] == '_') &&
802 OidIsValid(tinfo->typelem))
803 tinfo->dobj.dump = false;
806 tinfo->dobj.dump = true;
810 * selectDumpableObject: policy-setting subroutine
811 * Mark a generic dumpable object as to be dumped or not
813 * Use this only for object types without a special-case routine above.
816 selectDumpableObject(DumpableObject *dobj)
819 * Default policy is to dump if parent namespace is dumpable,
820 * or always for non-namespace-associated items.
823 dobj->dump = dobj->namespace->dobj.dump;
829 * Dump a table's contents for loading using the COPY command
830 * - this routine is called by the Archiver when it wants the table
834 #define COPYBUFSIZ 8192
837 dumpTableData_copy(Archive *fout, void *dcontext)
839 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
840 TableInfo *tbinfo = tdinfo->tdtable;
841 const char *classname = tbinfo->dobj.name;
842 const bool hasoids = tbinfo->hasoids;
843 const bool oids = tdinfo->oids;
844 PQExpBuffer q = createPQExpBuffer();
848 char copybuf[COPYBUFSIZ];
849 const char *column_list;
852 write_msg(NULL, "dumping contents of table %s\n", classname);
855 * Make sure we are in proper schema. We will qualify the table name
856 * below anyway (in case its name conflicts with a pg_catalog table); but
857 * this ensures reproducible results in case the table contains regproc,
858 * regclass, etc columns.
860 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
863 * If possible, specify the column list explicitly so that we have no
864 * possibility of retrieving data in the wrong column order. (The default
865 * column ordering of COPY will not be what we want in certain corner
866 * cases involving ADD COLUMN and inheritance.)
868 if (g_fout->remoteVersion >= 70300)
869 column_list = fmtCopyColumnList(tbinfo);
871 column_list = ""; /* can't select columns in COPY */
875 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
876 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
882 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
883 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
887 res = PQexec(g_conn, q->data);
888 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
894 ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
896 if (copybuf[0] == '\\' &&
900 copydone = true; /* don't print this... */
904 archputs(copybuf, fout);
911 archputs("\n", fout);
921 * There was considerable discussion in late July, 2000 regarding
922 * slowing down pg_dump when backing up large tables. Users with both
923 * slow & fast (muti-processor) machines experienced performance
924 * degradation when doing a backup.
926 * Initial attempts based on sleeping for a number of ms for each ms
927 * of work were deemed too complex, then a simple 'sleep in each loop'
928 * implementation was suggested. The latter failed because the loop
929 * was too tight. Finally, the following was implemented:
931 * If throttle is non-zero, then See how long since the last sleep.
932 * Work out how long to sleep (based on ratio). If sleep is more than
933 * 100ms, then sleep reset timer EndIf EndIf
935 * where the throttle value was the number of ms to sleep per ms of
936 * work. The calculation was done in each loop.
938 * Most of the hard work is done in the backend, and this solution
939 * still did not work particularly well: on slow machines, the ratio
940 * was 50:1, and on medium paced machines, 1:1, and on fast
941 * multi-processor machines, it had little or no effect, for reasons
944 * Further discussion ensued, and the proposal was dropped.
946 * For those people who want this feature, it can be implemented using
947 * gettimeofday in each loop, calculating the time since last sleep,
948 * multiplying that by the sleep ratio, then if the result is more
949 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
950 * function to sleep for a subsecond period ie.
952 * select(0, NULL, NULL, NULL, &tvi);
954 * This will return after the interval specified in the structure tvi.
955 * Finally, call gettimeofday again to save the 'last sleep time'.
958 archprintf(fout, "\\.\n\n\n");
960 ret = PQendcopy(g_conn);
963 write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
964 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
965 write_msg(NULL, "The command was: %s\n", q->data);
970 destroyPQExpBuffer(q);
975 dumpTableData_insert(Archive *fout, void *dcontext)
977 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
978 TableInfo *tbinfo = tdinfo->tdtable;
979 const char *classname = tbinfo->dobj.name;
980 PQExpBuffer q = createPQExpBuffer();
987 * Make sure we are in proper schema. We will qualify the table name
988 * below anyway (in case its name conflicts with a pg_catalog table); but
989 * this ensures reproducible results in case the table contains regproc,
990 * regclass, etc columns.
992 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
994 if (fout->remoteVersion >= 70100)
996 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
997 "SELECT * FROM ONLY %s",
998 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1003 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1005 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1009 res = PQexec(g_conn, q->data);
1010 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1016 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
1017 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
1019 nfields = PQnfields(res);
1020 for (tuple = 0; tuple < PQntuples(res); tuple++)
1022 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1025 /* corner case for zero-column table */
1026 archprintf(fout, "DEFAULT VALUES;\n");
1029 if (attrNames == true)
1031 resetPQExpBuffer(q);
1032 appendPQExpBuffer(q, "(");
1033 for (field = 0; field < nfields; field++)
1036 appendPQExpBuffer(q, ", ");
1037 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1039 appendPQExpBuffer(q, ") ");
1040 archputs(q->data, fout);
1042 archprintf(fout, "VALUES (");
1043 for (field = 0; field < nfields; field++)
1046 archprintf(fout, ", ");
1047 if (PQgetisnull(res, tuple, field))
1049 archprintf(fout, "NULL");
1053 /* XXX This code is partially duplicated in ruleutils.c */
1054 switch (PQftype(res, field))
1065 * These types are printed without quotes unless
1066 * they contain values that aren't accepted by the
1067 * scanner unquoted (e.g., 'NaN'). Note that
1068 * strtod() and friends might accept NaN, so we
1069 * can't use that to test.
1071 * In reality we only need to defend against
1072 * infinity and NaN, so we need not get too crazy
1073 * about pattern matching here.
1075 const char *s = PQgetvalue(res, tuple, field);
1077 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1078 archprintf(fout, "%s", s);
1080 archprintf(fout, "'%s'", s);
1086 archprintf(fout, "B'%s'",
1087 PQgetvalue(res, tuple, field));
1091 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1092 archprintf(fout, "true");
1094 archprintf(fout, "false");
1098 /* All other types are printed as string literals. */
1099 resetPQExpBuffer(q);
1100 appendStringLiteral(q, PQgetvalue(res, tuple, field), false);
1101 archputs(q->data, fout);
1105 archprintf(fout, ");\n");
1107 } while (PQntuples(res) > 0);
1111 archprintf(fout, "\n\n");
1113 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1115 destroyPQExpBuffer(q);
1122 * dump the contents of a single table
1124 * Actually, this just makes an ArchiveEntry for the table contents.
1127 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1129 TableInfo *tbinfo = tdinfo->tdtable;
1130 PQExpBuffer copyBuf = createPQExpBuffer();
1131 DataDumperPtr dumpFn;
1136 /* Dump/restore using COPY */
1137 dumpFn = dumpTableData_copy;
1138 /* must use 2 steps here 'cause fmtId is nonreentrant */
1139 appendPQExpBuffer(copyBuf, "COPY %s ",
1140 fmtId(tbinfo->dobj.name));
1141 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1142 fmtCopyColumnList(tbinfo),
1143 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1144 copyStmt = copyBuf->data;
1148 /* Restore using INSERT */
1149 dumpFn = dumpTableData_insert;
1153 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1155 tbinfo->dobj.namespace->dobj.name,
1157 tbinfo->rolname, false,
1158 "TABLE DATA", "", "", copyStmt,
1159 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1162 destroyPQExpBuffer(copyBuf);
1167 * set up dumpable objects representing the contents of tables
1170 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1174 for (i = 0; i < numTables; i++)
1176 /* Skip VIEWs (no data to dump) */
1177 if (tblinfo[i].relkind == RELKIND_VIEW)
1179 /* Skip SEQUENCEs (handled elsewhere) */
1180 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1183 if (tblinfo[i].dobj.dump)
1185 TableDataInfo *tdinfo;
1187 tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1189 tdinfo->dobj.objType = DO_TABLE_DATA;
1192 * Note: use tableoid 0 so that this object won't be mistaken for
1193 * something that pg_depend entries apply to.
1195 tdinfo->dobj.catId.tableoid = 0;
1196 tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1197 AssignDumpId(&tdinfo->dobj);
1198 tdinfo->dobj.name = tblinfo[i].dobj.name;
1199 tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1200 tdinfo->tdtable = &(tblinfo[i]);
1201 tdinfo->oids = oids;
1202 addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1210 * dump the database definition
1213 dumpDatabase(Archive *AH)
1215 PQExpBuffer dbQry = createPQExpBuffer();
1216 PQExpBuffer delQry = createPQExpBuffer();
1217 PQExpBuffer creaQry = createPQExpBuffer();
1227 const char *datname,
1232 datname = PQdb(g_conn);
1235 write_msg(NULL, "saving database definition\n");
1237 /* Make sure we are in proper schema */
1238 selectSourceSchema("pg_catalog");
1240 /* Get the database owner and parameters from pg_database */
1241 if (g_fout->remoteVersion >= 80200)
1243 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1244 "(%s datdba) as dba, "
1245 "pg_encoding_to_char(encoding) as encoding, "
1246 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) as tablespace, "
1247 "shobj_description(oid, 'pg_database') as description "
1252 appendStringLiteral(dbQry, datname, true);
1254 else if (g_fout->remoteVersion >= 80000)
1256 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1257 "(%s datdba) as dba, "
1258 "pg_encoding_to_char(encoding) as encoding, "
1259 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) as tablespace "
1263 appendStringLiteral(dbQry, datname, true);
1265 else if (g_fout->remoteVersion >= 70100)
1267 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1268 "(%s datdba) as dba, "
1269 "pg_encoding_to_char(encoding) as encoding, "
1270 "NULL as tablespace "
1274 appendStringLiteral(dbQry, datname, true);
1278 appendPQExpBuffer(dbQry, "SELECT "
1279 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1281 "(%s datdba) as dba, "
1282 "pg_encoding_to_char(encoding) as encoding, "
1283 "NULL as tablespace "
1287 appendStringLiteral(dbQry, datname, true);
1290 res = PQexec(g_conn, dbQry->data);
1291 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1293 ntups = PQntuples(res);
1297 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1304 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1309 i_tableoid = PQfnumber(res, "tableoid");
1310 i_oid = PQfnumber(res, "oid");
1311 i_dba = PQfnumber(res, "dba");
1312 i_encoding = PQfnumber(res, "encoding");
1313 i_tablespace = PQfnumber(res, "tablespace");
1315 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1316 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1317 dba = PQgetvalue(res, 0, i_dba);
1318 encoding = PQgetvalue(res, 0, i_encoding);
1319 tablespace = PQgetvalue(res, 0, i_tablespace);
1321 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1323 if (strlen(encoding) > 0)
1325 appendPQExpBuffer(creaQry, " ENCODING = ");
1326 appendStringLiteral(creaQry, encoding, true);
1328 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1329 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1331 appendPQExpBuffer(creaQry, ";\n");
1333 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1336 dbDumpId = createDumpId();
1339 dbCatId, /* catalog ID */
1340 dbDumpId, /* dump ID */
1342 NULL, /* Namespace */
1343 NULL, /* Tablespace */
1345 false, /* with oids */
1346 "DATABASE", /* Desc */
1347 creaQry->data, /* Create */
1348 delQry->data, /* Del */
1353 NULL); /* Dumper Arg */
1355 /* Dump DB comment if any */
1356 if (g_fout->remoteVersion >= 80200)
1358 /* 8.2 keeps comments on shared objects in a shared table, so
1359 * we cannot use the dumpComment used for other database objects.
1361 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
1362 if (comment && strlen(comment)) {
1363 resetPQExpBuffer(dbQry);
1364 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
1365 appendStringLiteral(dbQry, comment, false);
1366 appendPQExpBuffer(dbQry, ";\n");
1368 ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
1369 dba, false, "COMMENT", dbQry->data, "", NULL,
1370 &dbDumpId, 1, NULL, NULL);
1373 resetPQExpBuffer(dbQry);
1374 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1375 dumpComment(AH, dbQry->data, NULL, "",
1376 dbCatId, 0, dbDumpId);
1381 destroyPQExpBuffer(dbQry);
1382 destroyPQExpBuffer(delQry);
1383 destroyPQExpBuffer(creaQry);
1388 * dumpEncoding: put the correct encoding into the archive
1391 dumpEncoding(Archive *AH)
1396 /* Can't read the encoding from pre-7.3 servers (SHOW isn't a query) */
1397 if (AH->remoteVersion < 70300)
1401 write_msg(NULL, "saving encoding\n");
1403 qry = createPQExpBuffer();
1405 appendPQExpBuffer(qry, "SHOW client_encoding");
1407 res = PQexec(g_conn, qry->data);
1409 check_sql_result(res, g_conn, qry->data, PGRES_TUPLES_OK);
1411 resetPQExpBuffer(qry);
1413 appendPQExpBuffer(qry, "SET client_encoding = ");
1414 appendStringLiteral(qry, PQgetvalue(res, 0, 0), true);
1415 appendPQExpBuffer(qry, ";\n");
1417 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1418 "ENCODING", NULL, NULL, "",
1419 false, "ENCODING", qry->data, "", NULL,
1425 destroyPQExpBuffer(qry);
1431 * Test whether database contains any large objects
1434 hasBlobs(Archive *AH)
1437 const char *blobQry;
1440 /* Make sure we are in proper schema */
1441 selectSourceSchema("pg_catalog");
1443 /* Check for BLOB OIDs */
1444 if (AH->remoteVersion >= 70100)
1445 blobQry = "SELECT loid FROM pg_largeobject LIMIT 1";
1447 blobQry = "SELECT oid FROM pg_class WHERE relkind = 'l' LIMIT 1";
1449 res = PQexec(g_conn, blobQry);
1450 check_sql_result(res, g_conn, blobQry, PGRES_TUPLES_OK);
1452 result = PQntuples(res) > 0;
1464 dumpBlobs(Archive *AH, void *arg)
1466 const char *blobQry;
1467 const char *blobFetchQry;
1469 char buf[LOBBUFSIZE];
1474 write_msg(NULL, "saving large objects\n");
1476 /* Make sure we are in proper schema */
1477 selectSourceSchema("pg_catalog");
1479 /* Cursor to get all BLOB OIDs */
1480 if (AH->remoteVersion >= 70100)
1481 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
1483 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
1485 res = PQexec(g_conn, blobQry);
1486 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
1488 /* Command to fetch from cursor */
1489 blobFetchQry = "FETCH 1000 IN bloboid";
1496 res = PQexec(g_conn, blobFetchQry);
1497 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
1499 /* Process the tuples, if any */
1500 for (i = 0; i < PQntuples(res); i++)
1505 blobOid = atooid(PQgetvalue(res, i, 0));
1507 loFd = lo_open(g_conn, blobOid, INV_READ);
1510 write_msg(NULL, "dumpBlobs(): could not open large object: %s",
1511 PQerrorMessage(g_conn));
1515 StartBlob(AH, blobOid);
1517 /* Now read it in chunks, sending data to archive */
1520 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
1523 write_msg(NULL, "dumpBlobs(): error reading large object: %s",
1524 PQerrorMessage(g_conn));
1528 WriteData(AH, buf, cnt);
1531 lo_close(g_conn, loFd);
1533 EndBlob(AH, blobOid);
1535 } while (PQntuples(res) > 0);
1544 * dump all blob comments
1546 * Since we don't provide any way to be selective about dumping blobs,
1547 * there's no need to be selective about their comments either. We put
1548 * all the comments into one big TOC entry.
1551 dumpBlobComments(Archive *AH, void *arg)
1553 const char *blobQry;
1554 const char *blobFetchQry;
1555 PQExpBuffer commentcmd = createPQExpBuffer();
1560 write_msg(NULL, "saving large object comments\n");
1562 /* Make sure we are in proper schema */
1563 selectSourceSchema("pg_catalog");
1565 /* Cursor to get all BLOB comments */
1566 if (AH->remoteVersion >= 70200)
1567 blobQry = "DECLARE blobcmt CURSOR FOR SELECT DISTINCT loid, obj_description(loid, 'pg_largeobject') FROM pg_largeobject";
1568 else if (AH->remoteVersion >= 70100)
1569 blobQry = "DECLARE blobcmt CURSOR FOR SELECT DISTINCT loid, obj_description(loid) FROM pg_largeobject";
1571 blobQry = "DECLARE blobcmt CURSOR FOR SELECT oid, (SELECT description FROM pg_description pd WHERE pd.objoid=pc.oid) FROM pg_class pc WHERE relkind = 'l'";
1573 res = PQexec(g_conn, blobQry);
1574 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
1576 /* Command to fetch from cursor */
1577 blobFetchQry = "FETCH 100 IN blobcmt";
1584 res = PQexec(g_conn, blobFetchQry);
1585 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
1587 /* Process the tuples, if any */
1588 for (i = 0; i < PQntuples(res); i++)
1593 /* ignore blobs without comments */
1594 if (PQgetisnull(res, i, 1))
1597 blobOid = atooid(PQgetvalue(res, i, 0));
1598 comment = PQgetvalue(res, i, 1);
1600 printfPQExpBuffer(commentcmd, "COMMENT ON LARGE OBJECT %u IS ",
1602 appendStringLiteral(commentcmd, comment, false);
1603 appendPQExpBuffer(commentcmd, ";\n");
1605 archputs(commentcmd->data, AH);
1607 } while (PQntuples(res) > 0);
1613 destroyPQExpBuffer(commentcmd);
1620 * read all namespaces in the system catalogs and return them in the
1621 * NamespaceInfo* structure
1623 * numNamespaces is set to the number of namespaces read in
1626 getNamespaces(int *numNamespaces)
1632 NamespaceInfo *nsinfo;
1640 * Before 7.3, there are no real namespaces; create two dummy entries, one
1641 * for user stuff and one for system stuff.
1643 if (g_fout->remoteVersion < 70300)
1645 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
1647 nsinfo[0].dobj.objType = DO_NAMESPACE;
1648 nsinfo[0].dobj.catId.tableoid = 0;
1649 nsinfo[0].dobj.catId.oid = 0;
1650 AssignDumpId(&nsinfo[0].dobj);
1651 nsinfo[0].dobj.name = strdup("public");
1652 nsinfo[0].rolname = strdup("");
1653 nsinfo[0].nspacl = strdup("");
1655 selectDumpableNamespace(&nsinfo[0]);
1657 nsinfo[1].dobj.objType = DO_NAMESPACE;
1658 nsinfo[1].dobj.catId.tableoid = 0;
1659 nsinfo[1].dobj.catId.oid = 1;
1660 AssignDumpId(&nsinfo[1].dobj);
1661 nsinfo[1].dobj.name = strdup("pg_catalog");
1662 nsinfo[1].rolname = strdup("");
1663 nsinfo[1].nspacl = strdup("");
1665 selectDumpableNamespace(&nsinfo[1]);
1667 g_namespaces = nsinfo;
1668 g_numNamespaces = *numNamespaces = 2;
1673 query = createPQExpBuffer();
1675 /* Make sure we are in proper schema */
1676 selectSourceSchema("pg_catalog");
1679 * we fetch all namespaces including system ones, so that every object we
1680 * read in can be linked to a containing namespace.
1682 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1683 "(%s nspowner) as rolname, "
1684 "nspacl FROM pg_namespace",
1687 res = PQexec(g_conn, query->data);
1688 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1690 ntups = PQntuples(res);
1692 nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1694 i_tableoid = PQfnumber(res, "tableoid");
1695 i_oid = PQfnumber(res, "oid");
1696 i_nspname = PQfnumber(res, "nspname");
1697 i_rolname = PQfnumber(res, "rolname");
1698 i_nspacl = PQfnumber(res, "nspacl");
1700 for (i = 0; i < ntups; i++)
1702 nsinfo[i].dobj.objType = DO_NAMESPACE;
1703 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1704 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1705 AssignDumpId(&nsinfo[i].dobj);
1706 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
1707 nsinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
1708 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1710 /* Decide whether to dump this namespace */
1711 selectDumpableNamespace(&nsinfo[i]);
1713 if (strlen(nsinfo[i].rolname) == 0)
1714 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
1715 nsinfo[i].dobj.name);
1719 * If the user attempted to dump a specific namespace, check to ensure
1720 * that the specified namespace actually exists.
1722 if (selectSchemaName)
1724 for (i = 0; i < ntups; i++)
1725 if (strcmp(nsinfo[i].dobj.name, selectSchemaName) == 0)
1728 /* Didn't find a match */
1731 write_msg(NULL, "specified schema \"%s\" does not exist\n",
1738 destroyPQExpBuffer(query);
1740 g_namespaces = nsinfo;
1741 g_numNamespaces = *numNamespaces = ntups;
1748 * given a namespace OID and an object OID, look up the info read by
1751 * NB: for pre-7.3 source database, we use object OID to guess whether it's
1752 * a system object or not. In 7.3 and later there is no guessing.
1754 static NamespaceInfo *
1755 findNamespace(Oid nsoid, Oid objoid)
1759 if (g_fout->remoteVersion >= 70300)
1761 for (i = 0; i < g_numNamespaces; i++)
1763 NamespaceInfo *nsinfo = &g_namespaces[i];
1765 if (nsoid == nsinfo->dobj.catId.oid)
1768 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
1773 /* This code depends on the layout set up by getNamespaces. */
1774 if (objoid > g_last_builtin_oid)
1775 i = 0; /* user object */
1777 i = 1; /* system object */
1778 return &g_namespaces[i];
1781 return NULL; /* keep compiler quiet */
1786 * read all types in the system catalogs and return them in the
1787 * TypeInfo* structure
1789 * numTypes is set to the number of types read in
1791 * NB: this must run after getFuncs() because we assume we can do
1795 getTypes(int *numTypes)
1800 PQExpBuffer query = createPQExpBuffer();
1802 ShellTypeInfo *stinfo;
1817 * we include even the built-in types because those may be used as array
1818 * elements by user-defined types
1820 * we filter out the built-in types when we dump out the types
1822 * same approach for undefined (shell) types
1825 /* Make sure we are in proper schema */
1826 selectSourceSchema("pg_catalog");
1828 if (g_fout->remoteVersion >= 70300)
1830 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1832 "(%s typowner) as rolname, "
1833 "typinput::oid as typinput, "
1834 "typoutput::oid as typoutput, typelem, typrelid, "
1835 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1836 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1837 "typtype, typisdefined "
1841 else if (g_fout->remoteVersion >= 70100)
1843 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1844 "0::oid as typnamespace, "
1845 "(%s typowner) as rolname, "
1846 "typinput::oid as typinput, "
1847 "typoutput::oid as typoutput, typelem, typrelid, "
1848 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1849 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1850 "typtype, typisdefined "
1856 appendPQExpBuffer(query, "SELECT "
1857 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
1859 "0::oid as typnamespace, "
1860 "(%s typowner) as rolname, "
1861 "typinput::oid as typinput, "
1862 "typoutput::oid as typoutput, typelem, typrelid, "
1863 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1864 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1865 "typtype, typisdefined "
1870 res = PQexec(g_conn, query->data);
1871 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1873 ntups = PQntuples(res);
1875 tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1877 i_tableoid = PQfnumber(res, "tableoid");
1878 i_oid = PQfnumber(res, "oid");
1879 i_typname = PQfnumber(res, "typname");
1880 i_typnamespace = PQfnumber(res, "typnamespace");
1881 i_rolname = PQfnumber(res, "rolname");
1882 i_typinput = PQfnumber(res, "typinput");
1883 i_typoutput = PQfnumber(res, "typoutput");
1884 i_typelem = PQfnumber(res, "typelem");
1885 i_typrelid = PQfnumber(res, "typrelid");
1886 i_typrelkind = PQfnumber(res, "typrelkind");
1887 i_typtype = PQfnumber(res, "typtype");
1888 i_typisdefined = PQfnumber(res, "typisdefined");
1890 for (i = 0; i < ntups; i++)
1892 tinfo[i].dobj.objType = DO_TYPE;
1893 tinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1894 tinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1895 AssignDumpId(&tinfo[i].dobj);
1896 tinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
1897 tinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
1898 tinfo[i].dobj.catId.oid);
1899 tinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
1900 tinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
1901 tinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
1902 tinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
1903 tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
1904 tinfo[i].shellType = NULL;
1907 * If it's a table's rowtype, use special type code to facilitate
1908 * sorting into the desired order. (We don't want to consider it an
1909 * ordinary type because that would bring the table up into the
1910 * datatype part of the dump order.)
1912 if (OidIsValid(tinfo[i].typrelid) &&
1913 tinfo[i].typrelkind != RELKIND_COMPOSITE_TYPE)
1914 tinfo[i].dobj.objType = DO_TABLE_TYPE;
1917 * check for user-defined array types, omit system generated ones
1919 if (OidIsValid(tinfo[i].typelem) &&
1920 tinfo[i].dobj.name[0] != '_')
1921 tinfo[i].isArray = true;
1923 tinfo[i].isArray = false;
1925 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
1926 tinfo[i].isDefined = true;
1928 tinfo[i].isDefined = false;
1930 /* Decide whether we want to dump it */
1931 selectDumpableType(&tinfo[i]);
1934 * If it's a domain, fetch info about its constraints, if any
1936 tinfo[i].nDomChecks = 0;
1937 tinfo[i].domChecks = NULL;
1938 if (tinfo[i].dobj.dump && tinfo[i].typtype == 'd')
1939 getDomainConstraints(&(tinfo[i]));
1942 * If it's a base type, make a DumpableObject representing a shell
1943 * definition of the type. We will need to dump that ahead of the
1944 * I/O functions for the type.
1946 * Note: the shell type doesn't have a catId. You might think it
1947 * should copy the base type's catId, but then it might capture
1948 * the pg_depend entries for the type, which we don't want.
1950 if (tinfo[i].dobj.dump && tinfo[i].typtype == 'b')
1952 stinfo = (ShellTypeInfo *) malloc(sizeof(ShellTypeInfo));
1953 stinfo->dobj.objType = DO_SHELL_TYPE;
1954 stinfo->dobj.catId = nilCatalogId;
1955 AssignDumpId(&stinfo->dobj);
1956 stinfo->dobj.name = strdup(tinfo[i].dobj.name);
1957 stinfo->dobj.namespace = tinfo[i].dobj.namespace;
1958 stinfo->baseType = &(tinfo[i]);
1959 tinfo[i].shellType = stinfo;
1962 * Initially mark the shell type as not to be dumped. We'll
1963 * only dump it if the I/O functions need to be dumped; this
1964 * is taken care of while sorting dependencies.
1966 stinfo->dobj.dump = false;
1969 * However, if dumping from pre-7.3, there will be no dependency
1970 * info so we have to fake it here. We only need to worry about
1971 * typinput and typoutput since the other functions only exist
1974 if (g_fout->remoteVersion < 70300)
1980 typinput = atooid(PQgetvalue(res, i, i_typinput));
1981 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
1983 funcInfo = findFuncByOid(typinput);
1984 if (funcInfo && funcInfo->dobj.dump)
1986 /* base type depends on function */
1987 addObjectDependency(&tinfo[i].dobj,
1988 funcInfo->dobj.dumpId);
1989 /* function depends on shell type */
1990 addObjectDependency(&funcInfo->dobj,
1991 stinfo->dobj.dumpId);
1992 /* mark shell type as to be dumped */
1993 stinfo->dobj.dump = true;
1996 funcInfo = findFuncByOid(typoutput);
1997 if (funcInfo && funcInfo->dobj.dump)
1999 /* base type depends on function */
2000 addObjectDependency(&tinfo[i].dobj,
2001 funcInfo->dobj.dumpId);
2002 /* function depends on shell type */
2003 addObjectDependency(&funcInfo->dobj,
2004 stinfo->dobj.dumpId);
2005 /* mark shell type as to be dumped */
2006 stinfo->dobj.dump = true;
2011 if (strlen(tinfo[i].rolname) == 0 && tinfo[i].isDefined)
2012 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
2013 tinfo[i].dobj.name);
2020 destroyPQExpBuffer(query);
2027 * read all operators in the system catalogs and return them in the
2028 * OprInfo* structure
2030 * numOprs is set to the number of operators read in
2033 getOperators(int *numOprs)
2038 PQExpBuffer query = createPQExpBuffer();
2048 * find all operators, including builtin operators; we filter out
2049 * system-defined operators at dump-out time.
2052 /* Make sure we are in proper schema */
2053 selectSourceSchema("pg_catalog");
2055 if (g_fout->remoteVersion >= 70300)
2057 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
2059 "(%s oprowner) as rolname, "
2060 "oprcode::oid as oprcode "
2064 else if (g_fout->remoteVersion >= 70100)
2066 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
2067 "0::oid as oprnamespace, "
2068 "(%s oprowner) as rolname, "
2069 "oprcode::oid as oprcode "
2075 appendPQExpBuffer(query, "SELECT "
2076 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
2078 "0::oid as oprnamespace, "
2079 "(%s oprowner) as rolname, "
2080 "oprcode::oid as oprcode "
2085 res = PQexec(g_conn, query->data);
2086 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2088 ntups = PQntuples(res);
2091 oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
2093 i_tableoid = PQfnumber(res, "tableoid");
2094 i_oid = PQfnumber(res, "oid");
2095 i_oprname = PQfnumber(res, "oprname");
2096 i_oprnamespace = PQfnumber(res, "oprnamespace");
2097 i_rolname = PQfnumber(res, "rolname");
2098 i_oprcode = PQfnumber(res, "oprcode");
2100 for (i = 0; i < ntups; i++)
2102 oprinfo[i].dobj.objType = DO_OPERATOR;
2103 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2104 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2105 AssignDumpId(&oprinfo[i].dobj);
2106 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
2107 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
2108 oprinfo[i].dobj.catId.oid);
2109 oprinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2110 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
2112 /* Decide whether we want to dump it */
2113 selectDumpableObject(&(oprinfo[i].dobj));
2115 if (strlen(oprinfo[i].rolname) == 0)
2116 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
2117 oprinfo[i].dobj.name);
2122 destroyPQExpBuffer(query);
2129 * read all conversions in the system catalogs and return them in the
2130 * ConvInfo* structure
2132 * numConversions is set to the number of conversions read in
2135 getConversions(int *numConversions)
2140 PQExpBuffer query = createPQExpBuffer();
2148 /* Conversions didn't exist pre-7.3 */
2149 if (g_fout->remoteVersion < 70300)
2151 *numConversions = 0;
2156 * find all conversions, including builtin conversions; we filter out
2157 * system-defined conversions at dump-out time.
2160 /* Make sure we are in proper schema */
2161 selectSourceSchema("pg_catalog");
2163 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
2165 "(%s conowner) as rolname "
2166 "FROM pg_conversion",
2169 res = PQexec(g_conn, query->data);
2170 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2172 ntups = PQntuples(res);
2173 *numConversions = ntups;
2175 convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
2177 i_tableoid = PQfnumber(res, "tableoid");
2178 i_oid = PQfnumber(res, "oid");
2179 i_conname = PQfnumber(res, "conname");
2180 i_connamespace = PQfnumber(res, "connamespace");
2181 i_rolname = PQfnumber(res, "rolname");
2183 for (i = 0; i < ntups; i++)
2185 convinfo[i].dobj.objType = DO_CONVERSION;
2186 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2187 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2188 AssignDumpId(&convinfo[i].dobj);
2189 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
2190 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
2191 convinfo[i].dobj.catId.oid);
2192 convinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2194 /* Decide whether we want to dump it */
2195 selectDumpableObject(&(convinfo[i].dobj));
2200 destroyPQExpBuffer(query);
2207 * read all opclasses in the system catalogs and return them in the
2208 * OpclassInfo* structure
2210 * numOpclasses is set to the number of opclasses read in
2213 getOpclasses(int *numOpclasses)
2218 PQExpBuffer query = createPQExpBuffer();
2219 OpclassInfo *opcinfo;
2227 * find all opclasses, including builtin opclasses; we filter out
2228 * system-defined opclasses at dump-out time.
2231 /* Make sure we are in proper schema */
2232 selectSourceSchema("pg_catalog");
2234 if (g_fout->remoteVersion >= 70300)
2236 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2238 "(%s opcowner) as rolname "
2242 else if (g_fout->remoteVersion >= 70100)
2244 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2245 "0::oid as opcnamespace, "
2246 "''::name as rolname "
2251 appendPQExpBuffer(query, "SELECT "
2252 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2254 "0::oid as opcnamespace, "
2255 "''::name as rolname "
2259 res = PQexec(g_conn, query->data);
2260 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2262 ntups = PQntuples(res);
2263 *numOpclasses = ntups;
2265 opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2267 i_tableoid = PQfnumber(res, "tableoid");
2268 i_oid = PQfnumber(res, "oid");
2269 i_opcname = PQfnumber(res, "opcname");
2270 i_opcnamespace = PQfnumber(res, "opcnamespace");
2271 i_rolname = PQfnumber(res, "rolname");
2273 for (i = 0; i < ntups; i++)
2275 opcinfo[i].dobj.objType = DO_OPCLASS;
2276 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2277 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2278 AssignDumpId(&opcinfo[i].dobj);
2279 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
2280 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
2281 opcinfo[i].dobj.catId.oid);
2282 opcinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2284 /* Decide whether we want to dump it */
2285 selectDumpableObject(&(opcinfo[i].dobj));
2287 if (g_fout->remoteVersion >= 70300)
2289 if (strlen(opcinfo[i].rolname) == 0)
2290 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
2291 opcinfo[i].dobj.name);
2297 destroyPQExpBuffer(query);
2304 * read all the user-defined aggregates in the system catalogs and
2305 * return them in the AggInfo* structure
2307 * numAggs is set to the number of aggregates read in
2310 getAggregates(int *numAggs)
2315 PQExpBuffer query = createPQExpBuffer();
2325 /* Make sure we are in proper schema */
2326 selectSourceSchema("pg_catalog");
2328 /* find all user-defined aggregates */
2330 if (g_fout->remoteVersion >= 70300)
2332 appendPQExpBuffer(query, "SELECT tableoid, oid, proname as aggname, "
2333 "pronamespace as aggnamespace, "
2334 "proargtypes[0] as aggbasetype, "
2335 "(%s proowner) as rolname, "
2339 "AND pronamespace != "
2340 "(select oid from pg_namespace where nspname = 'pg_catalog')",
2343 else if (g_fout->remoteVersion >= 70100)
2345 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
2346 "0::oid as aggnamespace, "
2348 "(%s aggowner) as rolname, "
2350 "FROM pg_aggregate "
2351 "where oid > '%u'::oid",
2353 g_last_builtin_oid);
2357 appendPQExpBuffer(query, "SELECT "
2358 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
2360 "0::oid as aggnamespace, "
2362 "(%s aggowner) as rolname, "
2364 "FROM pg_aggregate "
2365 "where oid > '%u'::oid",
2367 g_last_builtin_oid);
2370 res = PQexec(g_conn, query->data);
2371 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2373 ntups = PQntuples(res);
2376 agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
2378 i_tableoid = PQfnumber(res, "tableoid");
2379 i_oid = PQfnumber(res, "oid");
2380 i_aggname = PQfnumber(res, "aggname");
2381 i_aggnamespace = PQfnumber(res, "aggnamespace");
2382 i_aggbasetype = PQfnumber(res, "aggbasetype");
2383 i_rolname = PQfnumber(res, "rolname");
2384 i_aggacl = PQfnumber(res, "aggacl");
2386 for (i = 0; i < ntups; i++)
2388 agginfo[i].aggfn.dobj.objType = DO_AGG;
2389 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2390 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2391 AssignDumpId(&agginfo[i].aggfn.dobj);
2392 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
2393 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
2394 agginfo[i].aggfn.dobj.catId.oid);
2395 agginfo[i].aggfn.rolname = strdup(PQgetvalue(res, i, i_rolname));
2396 if (strlen(agginfo[i].aggfn.rolname) == 0)
2397 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
2398 agginfo[i].aggfn.dobj.name);
2399 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
2400 agginfo[i].aggfn.nargs = 1;
2401 agginfo[i].aggfn.argtypes = (Oid *) malloc(sizeof(Oid));
2402 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_aggbasetype));
2403 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
2404 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
2405 agginfo[i].anybasetype = false; /* computed when it's dumped */
2406 agginfo[i].fmtbasetype = NULL; /* computed when it's dumped */
2408 /* Decide whether we want to dump it */
2409 selectDumpableObject(&(agginfo[i].aggfn.dobj));
2414 destroyPQExpBuffer(query);
2421 * read all the user-defined functions in the system catalogs and
2422 * return them in the FuncInfo* structure
2424 * numFuncs is set to the number of functions read in
2427 getFuncs(int *numFuncs)
2432 PQExpBuffer query = createPQExpBuffer();
2445 /* Make sure we are in proper schema */
2446 selectSourceSchema("pg_catalog");
2448 /* find all user-defined funcs */
2450 if (g_fout->remoteVersion >= 70300)
2452 appendPQExpBuffer(query,
2453 "SELECT tableoid, oid, proname, prolang, "
2454 "pronargs, proargtypes, prorettype, proacl, "
2456 "(%s proowner) as rolname "
2458 "WHERE NOT proisagg "
2459 "AND pronamespace != "
2460 "(select oid from pg_namespace"
2461 " where nspname = 'pg_catalog')",
2464 else if (g_fout->remoteVersion >= 70100)
2466 appendPQExpBuffer(query,
2467 "SELECT tableoid, oid, proname, prolang, "
2468 "pronargs, proargtypes, prorettype, "
2469 "'{=X}' as proacl, "
2470 "0::oid as pronamespace, "
2471 "(%s proowner) as rolname "
2473 "where pg_proc.oid > '%u'::oid",
2475 g_last_builtin_oid);
2479 appendPQExpBuffer(query,
2481 "(SELECT oid FROM pg_class "
2482 " WHERE relname = 'pg_proc') AS tableoid, "
2483 "oid, proname, prolang, "
2484 "pronargs, proargtypes, prorettype, "
2485 "'{=X}' as proacl, "
2486 "0::oid as pronamespace, "
2487 "(%s proowner) as rolname "
2489 "where pg_proc.oid > '%u'::oid",
2491 g_last_builtin_oid);
2494 res = PQexec(g_conn, query->data);
2495 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2497 ntups = PQntuples(res);
2501 finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
2503 i_tableoid = PQfnumber(res, "tableoid");
2504 i_oid = PQfnumber(res, "oid");
2505 i_proname = PQfnumber(res, "proname");
2506 i_pronamespace = PQfnumber(res, "pronamespace");
2507 i_rolname = PQfnumber(res, "rolname");
2508 i_prolang = PQfnumber(res, "prolang");
2509 i_pronargs = PQfnumber(res, "pronargs");
2510 i_proargtypes = PQfnumber(res, "proargtypes");
2511 i_prorettype = PQfnumber(res, "prorettype");
2512 i_proacl = PQfnumber(res, "proacl");
2514 for (i = 0; i < ntups; i++)
2516 finfo[i].dobj.objType = DO_FUNC;
2517 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2518 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2519 AssignDumpId(&finfo[i].dobj);
2520 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
2521 finfo[i].dobj.namespace =
2522 findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
2523 finfo[i].dobj.catId.oid);
2524 finfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2525 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2526 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
2527 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
2528 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
2529 if (finfo[i].nargs == 0)
2530 finfo[i].argtypes = NULL;
2533 finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
2534 parseOidArray(PQgetvalue(res, i, i_proargtypes),
2535 finfo[i].argtypes, finfo[i].nargs);
2538 /* Decide whether we want to dump it */
2539 selectDumpableObject(&(finfo[i].dobj));
2541 if (strlen(finfo[i].rolname) == 0)
2543 "WARNING: owner of function \"%s\" appears to be invalid\n",
2544 finfo[i].dobj.name);
2549 destroyPQExpBuffer(query);
2556 * read all the user-defined tables (no indexes, no catalogs)
2557 * in the system catalogs return them in the TableInfo* structure
2559 * numTables is set to the number of tables read in
2562 getTables(int *numTables)
2567 PQExpBuffer query = createPQExpBuffer();
2568 PQExpBuffer delqry = createPQExpBuffer();
2569 PQExpBuffer lockquery = createPQExpBuffer();
2585 int i_reltablespace;
2587 /* Make sure we are in proper schema */
2588 selectSourceSchema("pg_catalog");
2591 * Find all the tables (including views and sequences).
2593 * We include system catalogs, so that we can work if a user table is
2594 * defined to inherit from a system catalog (pretty weird, but...)
2596 * We ignore tables that are not type 'r' (ordinary relation), 'S'
2597 * (sequence), 'v' (view), or 'c' (composite type).
2599 * Composite-type table entries won't be dumped as such, but we have to
2600 * make a DumpableObject for them so that we can track dependencies of the
2601 * composite type (pg_depend entries for columns of the composite type
2602 * link to the pg_class entry not the pg_type entry).
2604 * Note: in this phase we should collect only a minimal amount of
2605 * information about each table, basically just enough to decide if it is
2606 * interesting. We must fetch all tables in this phase because otherwise
2607 * we cannot correctly identify inherited columns, serial columns, etc.
2610 if (g_fout->remoteVersion >= 80000)
2613 * Left join to pick up dependency info linking sequences to their
2614 * serial column, if any
2616 appendPQExpBuffer(query,
2617 "SELECT c.tableoid, c.oid, relname, "
2618 "relacl, relkind, relnamespace, "
2619 "(%s relowner) as rolname, "
2620 "relchecks, reltriggers, "
2621 "relhasindex, relhasrules, relhasoids, "
2622 "d.refobjid as owning_tab, "
2623 "d.refobjsubid as owning_col, "
2624 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace "
2626 "left join pg_depend d on "
2627 "(c.relkind = '%c' and "
2628 "d.classid = c.tableoid and d.objid = c.oid and "
2629 "d.objsubid = 0 and "
2630 "d.refclassid = c.tableoid and d.deptype = 'i') "
2631 "where relkind in ('%c', '%c', '%c', '%c') "
2635 RELKIND_RELATION, RELKIND_SEQUENCE,
2636 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
2638 else if (g_fout->remoteVersion >= 70300)
2641 * Left join to pick up dependency info linking sequences to their
2642 * serial column, if any
2644 appendPQExpBuffer(query,
2645 "SELECT c.tableoid, c.oid, relname, "
2646 "relacl, relkind, relnamespace, "
2647 "(%s relowner) as rolname, "
2648 "relchecks, reltriggers, "
2649 "relhasindex, relhasrules, relhasoids, "
2650 "d.refobjid as owning_tab, "
2651 "d.refobjsubid as owning_col, "
2652 "NULL as reltablespace "
2654 "left join pg_depend d on "
2655 "(c.relkind = '%c' and "
2656 "d.classid = c.tableoid and d.objid = c.oid and "
2657 "d.objsubid = 0 and "
2658 "d.refclassid = c.tableoid and d.deptype = 'i') "
2659 "where relkind in ('%c', '%c', '%c', '%c') "
2663 RELKIND_RELATION, RELKIND_SEQUENCE,
2664 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
2666 else if (g_fout->remoteVersion >= 70200)
2668 appendPQExpBuffer(query,
2669 "SELECT tableoid, oid, relname, relacl, relkind, "
2670 "0::oid as relnamespace, "
2671 "(%s relowner) as rolname, "
2672 "relchecks, reltriggers, "
2673 "relhasindex, relhasrules, relhasoids, "
2674 "NULL::oid as owning_tab, "
2675 "NULL::int4 as owning_col, "
2676 "NULL as reltablespace "
2678 "where relkind in ('%c', '%c', '%c') "
2681 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2683 else if (g_fout->remoteVersion >= 70100)
2685 /* all tables have oids in 7.1 */
2686 appendPQExpBuffer(query,
2687 "SELECT tableoid, oid, relname, relacl, relkind, "
2688 "0::oid as relnamespace, "
2689 "(%s relowner) as rolname, "
2690 "relchecks, reltriggers, "
2691 "relhasindex, relhasrules, "
2692 "'t'::bool as relhasoids, "
2693 "NULL::oid as owning_tab, "
2694 "NULL::int4 as owning_col, "
2695 "NULL as reltablespace "
2697 "where relkind in ('%c', '%c', '%c') "
2700 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2705 * Before 7.1, view relkind was not set to 'v', so we must check if we
2706 * have a view by looking for a rule in pg_rewrite.
2708 appendPQExpBuffer(query,
2710 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2711 "oid, relname, relacl, "
2712 "CASE WHEN relhasrules and relkind = 'r' "
2713 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
2714 " r.ev_class = c.oid AND r.ev_type = '1') "
2715 "THEN '%c'::\"char\" "
2716 "ELSE relkind END AS relkind,"
2717 "0::oid as relnamespace, "
2718 "(%s relowner) as rolname, "
2719 "relchecks, reltriggers, "
2720 "relhasindex, relhasrules, "
2721 "'t'::bool as relhasoids, "
2722 "NULL::oid as owning_tab, "
2723 "NULL::int4 as owning_col, "
2724 "NULL as reltablespace "
2726 "where relkind in ('%c', '%c') "
2730 RELKIND_RELATION, RELKIND_SEQUENCE);
2733 res = PQexec(g_conn, query->data);
2734 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2736 ntups = PQntuples(res);
2741 * Extract data from result and lock dumpable tables. We do the locking
2742 * before anything else, to minimize the window wherein a table could
2743 * disappear under us.
2745 * Note that we have to save info about all tables here, even when dumping
2746 * only one, because we don't yet know which tables might be inheritance
2747 * ancestors of the target table.
2749 tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
2751 i_reltableoid = PQfnumber(res, "tableoid");
2752 i_reloid = PQfnumber(res, "oid");
2753 i_relname = PQfnumber(res, "relname");
2754 i_relnamespace = PQfnumber(res, "relnamespace");
2755 i_relacl = PQfnumber(res, "relacl");
2756 i_relkind = PQfnumber(res, "relkind");
2757 i_rolname = PQfnumber(res, "rolname");
2758 i_relchecks = PQfnumber(res, "relchecks");
2759 i_reltriggers = PQfnumber(res, "reltriggers");
2760 i_relhasindex = PQfnumber(res, "relhasindex");
2761 i_relhasrules = PQfnumber(res, "relhasrules");
2762 i_relhasoids = PQfnumber(res, "relhasoids");
2763 i_owning_tab = PQfnumber(res, "owning_tab");
2764 i_owning_col = PQfnumber(res, "owning_col");
2765 i_reltablespace = PQfnumber(res, "reltablespace");
2767 for (i = 0; i < ntups; i++)
2769 tblinfo[i].dobj.objType = DO_TABLE;
2770 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
2771 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
2772 AssignDumpId(&tblinfo[i].dobj);
2773 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
2774 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
2775 tblinfo[i].dobj.catId.oid);
2776 tblinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2777 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
2778 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
2779 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
2780 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
2781 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
2782 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
2783 tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2784 if (PQgetisnull(res, i, i_owning_tab))
2786 tblinfo[i].owning_tab = InvalidOid;
2787 tblinfo[i].owning_col = 0;
2791 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
2792 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
2794 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
2796 /* other fields were zeroed above */
2799 * Decide whether we want to dump this table. Sequences owned by
2800 * serial columns are never dumpable on their own; we will transpose
2801 * their owning table's dump flag to them below.
2803 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
2804 tblinfo[i].dobj.dump = false;
2805 else if (OidIsValid(tblinfo[i].owning_tab))
2806 tblinfo[i].dobj.dump = false;
2808 selectDumpableTable(&tblinfo[i]);
2809 tblinfo[i].interesting = tblinfo[i].dobj.dump;
2812 * Read-lock target tables to make sure they aren't DROPPED or altered
2813 * in schema before we get around to dumping them.
2815 * Note that we don't explicitly lock parents of the target tables; we
2816 * assume our lock on the child is enough to prevent schema
2817 * alterations to parent tables.
2819 * NOTE: it'd be kinda nice to lock views and sequences too, not only
2820 * plain tables, but the backend doesn't presently allow that.
2822 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
2824 resetPQExpBuffer(lockquery);
2825 appendPQExpBuffer(lockquery,
2826 "LOCK TABLE %s IN ACCESS SHARE MODE",
2827 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
2828 tblinfo[i].dobj.name));
2829 do_sql_command(g_conn, lockquery->data);
2832 /* Emit notice if join for owner failed */
2833 if (strlen(tblinfo[i].rolname) == 0)
2834 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
2835 tblinfo[i].dobj.name);
2839 * If the user is attempting to dump a specific table, check to ensure
2840 * that the specified table actually exists. (This is a bit simplistic
2841 * since we don't fully check the combination of -n and -t switches.)
2843 if (selectTableName)
2845 for (i = 0; i < ntups; i++)
2846 if (strcmp(tblinfo[i].dobj.name, selectTableName) == 0)
2849 /* Didn't find a match */
2852 write_msg(NULL, "specified table \"%s\" does not exist\n",
2859 destroyPQExpBuffer(query);
2860 destroyPQExpBuffer(delqry);
2861 destroyPQExpBuffer(lockquery);
2868 * read all the inheritance information
2869 * from the system catalogs return them in the InhInfo* structure
2871 * numInherits is set to the number of pairs read in
2874 getInherits(int *numInherits)
2879 PQExpBuffer query = createPQExpBuffer();
2885 /* Make sure we are in proper schema */
2886 selectSourceSchema("pg_catalog");
2888 /* find all the inheritance information */
2890 appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2892 res = PQexec(g_conn, query->data);
2893 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2895 ntups = PQntuples(res);
2897 *numInherits = ntups;
2899 inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
2901 i_inhrelid = PQfnumber(res, "inhrelid");
2902 i_inhparent = PQfnumber(res, "inhparent");
2904 for (i = 0; i < ntups; i++)
2906 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
2907 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
2912 destroyPQExpBuffer(query);
2919 * get information about every index on a dumpable table
2921 * Note: index data is not returned directly to the caller, but it
2922 * does get entered into the DumpableObject tables.
2925 getIndexes(TableInfo tblinfo[], int numTables)
2929 PQExpBuffer query = createPQExpBuffer();
2932 ConstraintInfo *constrinfo;
2947 for (i = 0; i < numTables; i++)
2949 TableInfo *tbinfo = &tblinfo[i];
2951 /* Only plain tables have indexes */
2952 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
2955 /* Ignore indexes of tables not to be dumped */
2956 if (!tbinfo->dobj.dump)
2960 write_msg(NULL, "reading indexes for table \"%s\"\n",
2963 /* Make sure we are in proper schema so indexdef is right */
2964 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2967 * The point of the messy-looking outer join is to find a constraint
2968 * that is related by an internal dependency link to the index. If we
2969 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
2970 * assume an index won't have more than one internal dependency.
2972 resetPQExpBuffer(query);
2973 if (g_fout->remoteVersion >= 80000)
2975 appendPQExpBuffer(query,
2976 "SELECT t.tableoid, t.oid, "
2977 "t.relname as indexname, "
2978 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2979 "t.relnatts as indnkeys, "
2980 "i.indkey, i.indisclustered, "
2981 "c.contype, c.conname, "
2982 "c.tableoid as contableoid, "
2984 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) as tablespace "
2985 "FROM pg_catalog.pg_index i "
2986 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2987 "LEFT JOIN pg_catalog.pg_depend d "
2988 "ON (d.classid = t.tableoid "
2989 "AND d.objid = t.oid "
2990 "AND d.deptype = 'i') "
2991 "LEFT JOIN pg_catalog.pg_constraint c "
2992 "ON (d.refclassid = c.tableoid "
2993 "AND d.refobjid = c.oid) "
2994 "WHERE i.indrelid = '%u'::pg_catalog.oid "
2995 "ORDER BY indexname",
2996 tbinfo->dobj.catId.oid);
2998 else if (g_fout->remoteVersion >= 70300)
3000 appendPQExpBuffer(query,
3001 "SELECT t.tableoid, t.oid, "
3002 "t.relname as indexname, "
3003 "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
3004 "t.relnatts as indnkeys, "
3005 "i.indkey, i.indisclustered, "
3006 "c.contype, c.conname, "
3007 "c.tableoid as contableoid, "
3009 "NULL as tablespace "
3010 "FROM pg_catalog.pg_index i "
3011 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
3012 "LEFT JOIN pg_catalog.pg_depend d "
3013 "ON (d.classid = t.tableoid "
3014 "AND d.objid = t.oid "
3015 "AND d.deptype = 'i') "
3016 "LEFT JOIN pg_catalog.pg_constraint c "
3017 "ON (d.refclassid = c.tableoid "
3018 "AND d.refobjid = c.oid) "
3019 "WHERE i.indrelid = '%u'::pg_catalog.oid "
3020 "ORDER BY indexname",
3021 tbinfo->dobj.catId.oid);
3023 else if (g_fout->remoteVersion >= 70100)
3025 appendPQExpBuffer(query,
3026 "SELECT t.tableoid, t.oid, "
3027 "t.relname as indexname, "
3028 "pg_get_indexdef(i.indexrelid) as indexdef, "
3029 "t.relnatts as indnkeys, "
3030 "i.indkey, false as indisclustered, "
3031 "CASE WHEN i.indisprimary THEN 'p'::char "
3032 "ELSE '0'::char END as contype, "
3033 "t.relname as conname, "
3034 "0::oid as contableoid, "
3036 "NULL as tablespace "
3037 "FROM pg_index i, pg_class t "
3038 "WHERE t.oid = i.indexrelid "
3039 "AND i.indrelid = '%u'::oid "
3040 "ORDER BY indexname",
3041 tbinfo->dobj.catId.oid);
3045 appendPQExpBuffer(query,
3047 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
3049 "t.relname as indexname, "
3050 "pg_get_indexdef(i.indexrelid) as indexdef, "
3051 "t.relnatts as indnkeys, "
3052 "i.indkey, false as indisclustered, "
3053 "CASE WHEN i.indisprimary THEN 'p'::char "
3054 "ELSE '0'::char END as contype, "
3055 "t.relname as conname, "
3056 "0::oid as contableoid, "
3058 "NULL as tablespace "
3059 "FROM pg_index i, pg_class t "
3060 "WHERE t.oid = i.indexrelid "
3061 "AND i.indrelid = '%u'::oid "
3062 "ORDER BY indexname",
3063 tbinfo->dobj.catId.oid);
3066 res = PQexec(g_conn, query->data);
3067 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3069 ntups = PQntuples(res);
3071 i_tableoid = PQfnumber(res, "tableoid");
3072 i_oid = PQfnumber(res, "oid");
3073 i_indexname = PQfnumber(res, "indexname");
3074 i_indexdef = PQfnumber(res, "indexdef");
3075 i_indnkeys = PQfnumber(res, "indnkeys");
3076 i_indkey = PQfnumber(res, "indkey");
3077 i_indisclustered = PQfnumber(res, "indisclustered");
3078 i_contype = PQfnumber(res, "contype");
3079 i_conname = PQfnumber(res, "conname");
3080 i_contableoid = PQfnumber(res, "contableoid");
3081 i_conoid = PQfnumber(res, "conoid");
3082 i_tablespace = PQfnumber(res, "tablespace");
3084 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
3085 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3087 for (j = 0; j < ntups; j++)
3091 indxinfo[j].dobj.objType = DO_INDEX;
3092 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3093 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3094 AssignDumpId(&indxinfo[j].dobj);
3095 indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
3096 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3097 indxinfo[j].indextable = tbinfo;
3098 indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
3099 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
3100 indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
3103 * In pre-7.4 releases, indkeys may contain more entries than
3104 * indnkeys says (since indnkeys will be 1 for a functional
3105 * index). We don't actually care about this case since we don't
3106 * examine indkeys except for indexes associated with PRIMARY and
3107 * UNIQUE constraints, which are never functional indexes. But we
3108 * have to allocate enough space to keep parseOidArray from
3111 indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
3112 parseOidArray(PQgetvalue(res, j, i_indkey),
3113 indxinfo[j].indkeys, INDEX_MAX_KEYS);
3114 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
3115 contype = *(PQgetvalue(res, j, i_contype));
3117 if (contype == 'p' || contype == 'u')
3120 * If we found a constraint matching the index, create an
3123 * In a pre-7.3 database, we take this path iff the index was
3124 * marked indisprimary.
3126 constrinfo[j].dobj.objType = DO_CONSTRAINT;
3127 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
3128 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
3129 AssignDumpId(&constrinfo[j].dobj);
3130 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
3131 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3132 constrinfo[j].contable = tbinfo;
3133 constrinfo[j].condomain = NULL;
3134 constrinfo[j].contype = contype;
3135 constrinfo[j].condef = NULL;
3136 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
3137 constrinfo[j].coninherited = false;
3138 constrinfo[j].separate = true;
3140 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
3142 /* If pre-7.3 DB, better make sure table comes first */
3143 addObjectDependency(&constrinfo[j].dobj,
3144 tbinfo->dobj.dumpId);
3148 /* Plain secondary index */
3149 indxinfo[j].indexconstraint = 0;
3156 destroyPQExpBuffer(query);
3162 * Get info about constraints on dumpable tables.
3164 * Currently handles foreign keys only.
3165 * Unique and primary key constraints are handled with indexes,
3166 * while check constraints are processed in getTableAttrs().
3169 getConstraints(TableInfo tblinfo[], int numTables)
3173 ConstraintInfo *constrinfo;
3182 /* pg_constraint was created in 7.3, so nothing to do if older */
3183 if (g_fout->remoteVersion < 70300)
3186 query = createPQExpBuffer();
3188 for (i = 0; i < numTables; i++)
3190 TableInfo *tbinfo = &tblinfo[i];
3192 if (tbinfo->ntrig == 0 || !tbinfo->dobj.dump)
3196 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
3200 * select table schema to ensure constraint expr is qualified if
3203 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3205 resetPQExpBuffer(query);
3206 appendPQExpBuffer(query,
3207 "SELECT tableoid, oid, conname, "
3208 "pg_catalog.pg_get_constraintdef(oid) as condef "
3209 "FROM pg_catalog.pg_constraint "
3210 "WHERE conrelid = '%u'::pg_catalog.oid "
3211 "AND contype = 'f'",
3212 tbinfo->dobj.catId.oid);
3213 res = PQexec(g_conn, query->data);
3214 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3216 ntups = PQntuples(res);
3218 i_contableoid = PQfnumber(res, "tableoid");
3219 i_conoid = PQfnumber(res, "oid");
3220 i_conname = PQfnumber(res, "conname");
3221 i_condef = PQfnumber(res, "condef");
3223 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3225 for (j = 0; j < ntups; j++)
3227 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
3228 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
3229 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
3230 AssignDumpId(&constrinfo[j].dobj);
3231 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
3232 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3233 constrinfo[j].contable = tbinfo;
3234 constrinfo[j].condomain = NULL;
3235 constrinfo[j].contype = 'f';
3236 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
3237 constrinfo[j].conindex = 0;
3238 constrinfo[j].coninherited = false;
3239 constrinfo[j].separate = true;
3245 destroyPQExpBuffer(query);
3249 * getDomainConstraints
3251 * Get info about constraints on a domain.
3254 getDomainConstraints(TypeInfo *tinfo)
3257 ConstraintInfo *constrinfo;
3266 /* pg_constraint was created in 7.3, so nothing to do if older */
3267 if (g_fout->remoteVersion < 70300)
3271 * select appropriate schema to ensure names in constraint are properly
3274 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
3276 query = createPQExpBuffer();
3278 if (g_fout->remoteVersion >= 70400)
3279 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3280 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3281 "FROM pg_catalog.pg_constraint "
3282 "WHERE contypid = '%u'::pg_catalog.oid "
3284 tinfo->dobj.catId.oid);
3286 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3287 "'CHECK (' || consrc || ')' AS consrc "
3288 "FROM pg_catalog.pg_constraint "
3289 "WHERE contypid = '%u'::pg_catalog.oid "
3291 tinfo->dobj.catId.oid);
3293 res = PQexec(g_conn, query->data);
3294 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3296 ntups = PQntuples(res);
3298 i_tableoid = PQfnumber(res, "tableoid");
3299 i_oid = PQfnumber(res, "oid");
3300 i_conname = PQfnumber(res, "conname");
3301 i_consrc = PQfnumber(res, "consrc");
3303 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3305 tinfo->nDomChecks = ntups;
3306 tinfo->domChecks = constrinfo;
3308 for (i = 0; i < ntups; i++)
3310 constrinfo[i].dobj.objType = DO_CONSTRAINT;
3311 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3312 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3313 AssignDumpId(&constrinfo[i].dobj);
3314 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
3315 constrinfo[i].dobj.namespace = tinfo->dobj.namespace;
3316 constrinfo[i].contable = NULL;
3317 constrinfo[i].condomain = tinfo;
3318 constrinfo[i].contype = 'c';
3319 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
3320 constrinfo[i].conindex = 0;
3321 constrinfo[i].coninherited = false;
3322 constrinfo[i].separate = false;
3325 * Make the domain depend on the constraint, ensuring it won't be
3326 * output till any constraint dependencies are OK.
3328 addObjectDependency(&tinfo->dobj,
3329 constrinfo[i].dobj.dumpId);
3334 destroyPQExpBuffer(query);
3339 * get basic information about every rule in the system
3341 * numRules is set to the number of rules read in
3344 getRules(int *numRules)
3349 PQExpBuffer query = createPQExpBuffer();
3358 /* Make sure we are in proper schema */
3359 selectSourceSchema("pg_catalog");
3361 if (g_fout->remoteVersion >= 70100)
3363 appendPQExpBuffer(query, "SELECT "
3364 "tableoid, oid, rulename, "
3365 "ev_class as ruletable, ev_type, is_instead "
3371 appendPQExpBuffer(query, "SELECT "
3372 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
3374 "ev_class as ruletable, ev_type, is_instead "
3379 res = PQexec(g_conn, query->data);
3380 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3382 ntups = PQntuples(res);
3386 ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
3388 i_tableoid = PQfnumber(res, "tableoid");
3389 i_oid = PQfnumber(res, "oid");
3390 i_rulename = PQfnumber(res, "rulename");
3391 i_ruletable = PQfnumber(res, "ruletable");
3392 i_ev_type = PQfnumber(res, "ev_type");
3393 i_is_instead = PQfnumber(res, "is_instead");
3395 for (i = 0; i < ntups; i++)
3399 ruleinfo[i].dobj.objType = DO_RULE;
3400 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3401 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3402 AssignDumpId(&ruleinfo[i].dobj);
3403 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
3404 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
3405 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
3406 if (ruleinfo[i].ruletable == NULL)
3408 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
3410 ruleinfo[i].dobj.catId.oid);
3413 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
3414 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
3415 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
3416 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
3417 if (ruleinfo[i].ruletable)
3420 * If the table is a view, force its ON SELECT rule to be sorted
3421 * before the view itself --- this ensures that any dependencies
3422 * for the rule affect the table's positioning. Other rules are
3423 * forced to appear after their table.
3425 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
3426 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
3428 addObjectDependency(&ruleinfo[i].ruletable->dobj,
3429 ruleinfo[i].dobj.dumpId);
3430 /* We'll merge the rule into CREATE VIEW, if possible */
3431 ruleinfo[i].separate = false;
3435 addObjectDependency(&ruleinfo[i].dobj,
3436 ruleinfo[i].ruletable->dobj.dumpId);
3437 ruleinfo[i].separate = true;
3441 ruleinfo[i].separate = true;
3446 destroyPQExpBuffer(query);
3453 * get information about every trigger on a dumpable table
3455 * Note: trigger data is not returned directly to the caller, but it
3456 * does get entered into the DumpableObject tables.
3459 getTriggers(TableInfo tblinfo[], int numTables)
3463 PQExpBuffer query = createPQExpBuffer();
3465 TriggerInfo *tginfo;
3482 for (i = 0; i < numTables; i++)
3484 TableInfo *tbinfo = &tblinfo[i];
3486 if (tbinfo->ntrig == 0 || !tbinfo->dobj.dump)
3490 write_msg(NULL, "reading triggers for table \"%s\"\n",
3494 * select table schema to ensure regproc name is qualified if needed
3496 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3498 resetPQExpBuffer(query);
3499 if (g_fout->remoteVersion >= 70300)
3502 * We ignore triggers that are tied to a foreign-key constraint
3504 appendPQExpBuffer(query,
3506 "tgfoid::pg_catalog.regproc as tgfname, "
3507 "tgtype, tgnargs, tgargs, tgenabled, "
3508 "tgisconstraint, tgconstrname, tgdeferrable, "
3509 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3510 "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
3511 "from pg_catalog.pg_trigger t "
3512 "where tgrelid = '%u'::pg_catalog.oid "
3513 "and (not tgisconstraint "
3515 " (SELECT 1 FROM pg_catalog.pg_depend d "
3516 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
3517 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
3518 tbinfo->dobj.catId.oid);
3520 else if (g_fout->remoteVersion >= 70100)
3522 appendPQExpBuffer(query,
3523 "SELECT tgname, tgfoid::regproc as tgfname, "
3524 "tgtype, tgnargs, tgargs, tgenabled, "
3525 "tgisconstraint, tgconstrname, tgdeferrable, "
3526 "tgconstrrelid, tginitdeferred, tableoid, oid, "
3527 "(select relname from pg_class where oid = tgconstrrelid) "
3528 " as tgconstrrelname "
3530 "where tgrelid = '%u'::oid",
3531 tbinfo->dobj.catId.oid);
3535 appendPQExpBuffer(query,
3536 "SELECT tgname, tgfoid::regproc as tgfname, "
3537 "tgtype, tgnargs, tgargs, tgenabled, "
3538 "tgisconstraint, tgconstrname, tgdeferrable, "
3539 "tgconstrrelid, tginitdeferred, "
3540 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
3543 "(select relname from pg_class where oid = tgconstrrelid) "
3544 " as tgconstrrelname "
3546 "where tgrelid = '%u'::oid",
3547 tbinfo->dobj.catId.oid);
3549 res = PQexec(g_conn, query->data);
3550 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3552 ntups = PQntuples(res);
3555 * We may have less triggers than recorded due to having ignored
3556 * foreign-key triggers
3558 if (ntups > tbinfo->ntrig)
3560 write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
3561 tbinfo->ntrig, tbinfo->dobj.name, ntups);
3564 i_tableoid = PQfnumber(res, "tableoid");
3565 i_oid = PQfnumber(res, "oid");
3566 i_tgname = PQfnumber(res, "tgname");
3567 i_tgfname = PQfnumber(res, "tgfname");
3568 i_tgtype = PQfnumber(res, "tgtype");
3569 i_tgnargs = PQfnumber(res, "tgnargs");
3570 i_tgargs = PQfnumber(res, "tgargs");
3571 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
3572 i_tgconstrname = PQfnumber(res, "tgconstrname");
3573 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
3574 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
3575 i_tgenabled = PQfnumber(res, "tgenabled");
3576 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
3577 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
3579 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
3581 for (j = 0; j < ntups; j++)
3583 tginfo[j].dobj.objType = DO_TRIGGER;
3584 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3585 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3586 AssignDumpId(&tginfo[j].dobj);
3587 tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
3588 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
3589 tginfo[j].tgtable = tbinfo;
3590 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
3591 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
3592 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
3593 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
3594 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
3595 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled)) == 't';
3596 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
3597 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
3599 if (tginfo[j].tgisconstraint)
3601 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
3602 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
3603 if (OidIsValid(tginfo[j].tgconstrrelid))
3605 if (PQgetisnull(res, j, i_tgconstrrelname))
3607 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
3608 tginfo[j].dobj.name, tbinfo->dobj.name,
3609 tginfo[j].tgconstrrelid);
3612 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
3615 tginfo[j].tgconstrrelname = NULL;
3619 tginfo[j].tgconstrname = NULL;
3620 tginfo[j].tgconstrrelid = InvalidOid;
3621 tginfo[j].tgconstrrelname = NULL;
3628 destroyPQExpBuffer(query);
3633 * get basic information about every procedural language in the system
3635 * numProcLangs is set to the number of langs read in
3637 * NB: this must run after getFuncs() because we assume we can do
3641 getProcLangs(int *numProcLangs)
3646 PQExpBuffer query = createPQExpBuffer();
3647 ProcLangInfo *planginfo;
3652 int i_lanplcallfoid;
3657 /* Make sure we are in proper schema */
3658 selectSourceSchema("pg_catalog");
3660 if (g_fout->remoteVersion >= 80100)
3662 /* Languages are owned by the bootstrap superuser, OID 10 */
3663 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
3664 "(%s '10') as lanowner "
3670 else if (g_fout->remoteVersion >= 70400)
3672 /* Languages are owned by the bootstrap superuser, sysid 1 */
3673 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
3674 "(%s '1') as lanowner "
3680 else if (g_fout->remoteVersion >= 70100)
3682 /* No clear notion of an owner at all before 7.4 ... */
3683 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
3689 appendPQExpBuffer(query, "SELECT "
3690 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
3691 "oid, * FROM pg_language "
3696 res = PQexec(g_conn, query->data);
3697 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3699 ntups = PQntuples(res);
3701 *numProcLangs = ntups;
3703 planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
3705 i_tableoid = PQfnumber(res, "tableoid");
3706 i_oid = PQfnumber(res, "oid");
3707 i_lanname = PQfnumber(res, "lanname");
3708 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
3709 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
3710 /* these may fail and return -1: */
3711 i_lanvalidator = PQfnumber(res, "lanvalidator");
3712 i_lanacl = PQfnumber(res, "lanacl");
3713 i_lanowner = PQfnumber(res, "lanowner");
3715 for (i = 0; i < ntups; i++)
3717 planginfo[i].dobj.objType = DO_PROCLANG;
3718 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3719 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3720 AssignDumpId(&planginfo[i].dobj);
3722 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
3723 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
3724 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
3725 if (i_lanvalidator >= 0)
3726 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
3728 planginfo[i].lanvalidator = InvalidOid;
3730 planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
3732 planginfo[i].lanacl = strdup("{=U}");
3733 if (i_lanowner >= 0)
3734 planginfo[i].lanowner = strdup(PQgetvalue(res, i, i_lanowner));
3736 planginfo[i].lanowner = strdup("");
3738 if (g_fout->remoteVersion < 70300)
3741 * We need to make a dependency to ensure the function will be
3742 * dumped first. (In 7.3 and later the regular dependency
3743 * mechanism will handle this for us.)
3745 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
3748 addObjectDependency(&planginfo[i].dobj,
3749 funcInfo->dobj.dumpId);
3755 destroyPQExpBuffer(query);
3762 * get basic information about every cast in the system
3764 * numCasts is set to the number of casts read in
3767 getCasts(int *numCasts)
3772 PQExpBuffer query = createPQExpBuffer();
3781 /* Make sure we are in proper schema */
3782 selectSourceSchema("pg_catalog");
3784 if (g_fout->remoteVersion >= 70300)
3786 appendPQExpBuffer(query, "SELECT tableoid, oid, "
3787 "castsource, casttarget, castfunc, castcontext "
3788 "FROM pg_cast ORDER BY 3,4");
3792 appendPQExpBuffer(query, "SELECT 0 as tableoid, p.oid, "
3793 "t1.oid as castsource, t2.oid as casttarget, "
3794 "p.oid as castfunc, 'e' as castcontext "
3795 "FROM pg_type t1, pg_type t2, pg_proc p "
3796 "WHERE p.pronargs = 1 AND "
3797 "p.proargtypes[0] = t1.oid AND "
3798 "p.prorettype = t2.oid AND p.proname = t2.typname "
3802 res = PQexec(g_conn, query->data);
3803 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3805 ntups = PQntuples(res);
3809 castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
3811 i_tableoid = PQfnumber(res, "tableoid");
3812 i_oid = PQfnumber(res, "oid");
3813 i_castsource = PQfnumber(res, "castsource");
3814 i_casttarget = PQfnumber(res, "casttarget");
3815 i_castfunc = PQfnumber(res, "castfunc");
3816 i_castcontext = PQfnumber(res, "castcontext");
3818 for (i = 0; i < ntups; i++)
3820 PQExpBufferData namebuf;
3821 TypeInfo *sTypeInfo;
3822 TypeInfo *tTypeInfo;
3824 castinfo[i].dobj.objType = DO_CAST;
3825 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3826 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3827 AssignDumpId(&castinfo[i].dobj);
3828 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
3829 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
3830 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
3831 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
3834 * Try to name cast as concatenation of typnames. This is only used
3835 * for purposes of sorting. If we fail to find either type, the name
3836 * will be an empty string.
3838 initPQExpBuffer(&namebuf);
3839 sTypeInfo = findTypeByOid(castinfo[i].castsource);
3840 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
3841 if (sTypeInfo && tTypeInfo)
3842 appendPQExpBuffer(&namebuf, "%s %s",
3843 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
3844 castinfo[i].dobj.name = namebuf.data;
3846 if (OidIsValid(castinfo[i].castfunc))
3849 * We need to make a dependency to ensure the function will be
3850 * dumped first. (In 7.3 and later the regular dependency
3851 * mechanism will handle this for us.)
3855 funcInfo = findFuncByOid(castinfo[i].castfunc);
3857 addObjectDependency(&castinfo[i].dobj,
3858 funcInfo->dobj.dumpId);
3864 destroyPQExpBuffer(query);
3871 * for each interesting table, read info about its attributes
3872 * (names, types, default values, CHECK constraints, etc)
3874 * This is implemented in a very inefficient way right now, looping
3875 * through the tblinfo and doing a join per table to find the attrs and their
3876 * types. However, because we want type names and so forth to be named
3877 * relative to the schema of each table, we couldn't do it in just one
3878 * query. (Maybe one query per schema?)
3883 getTableAttrs(TableInfo *tblinfo, int numTables)
3888 PQExpBuffer q = createPQExpBuffer();
3893 int i_attstattarget;
3904 for (i = 0; i < numTables; i++)
3906 TableInfo *tbinfo = &tblinfo[i];
3908 /* Don't bother to collect info for sequences */
3909 if (tbinfo->relkind == RELKIND_SEQUENCE)
3912 /* Don't bother with uninteresting tables, either */
3913 if (!tbinfo->interesting)
3917 * Make sure we are in proper schema for this table; this allows
3918 * correct retrieval of formatted type names and default exprs
3920 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3922 /* find all the user attributes and their types */
3925 * we must read the attribute names in attribute number order! because
3926 * we will use the attnum to index into the attnames array later. We
3927 * actually ask to order by "attrelid, attnum" because (at least up to
3928 * 7.3) the planner is not smart enough to realize it needn't re-sort
3929 * the output of an indexscan on pg_attribute_relid_attnum_index.
3932 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
3935 resetPQExpBuffer(q);
3937 if (g_fout->remoteVersion >= 70300)
3939 /* need left join here to not fail on dropped columns ... */
3940 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, "
3941 "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, "
3942 "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname "
3943 "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t "
3944 "on a.atttypid = t.oid "
3945 "where a.attrelid = '%u'::pg_catalog.oid "
3946 "and a.attnum > 0::pg_catalog.int2 "
3947 "order by a.attrelid, a.attnum",
3948 tbinfo->dobj.catId.oid);
3950 else if (g_fout->remoteVersion >= 70100)
3953 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
3954 * we don't dump it because we can't tell whether it's been
3955 * explicitly set or was just a default.
3957 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, "
3958 "a.attnotnull, a.atthasdef, false as attisdropped, false as attislocal, "
3959 "format_type(t.oid,a.atttypmod) as atttypname "
3960 "from pg_attribute a left join pg_type t "
3961 "on a.atttypid = t.oid "
3962 "where a.attrelid = '%u'::oid "
3963 "and a.attnum > 0::int2 "
3964 "order by a.attrelid, a.attnum",
3965 tbinfo->dobj.catId.oid);
3969 /* format_type not available before 7.1 */
3970 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, "
3971 "attnotnull, atthasdef, false as attisdropped, false as attislocal, "
3972 "(select typname from pg_type where oid = atttypid) as atttypname "
3973 "from pg_attribute a "
3974 "where attrelid = '%u'::oid "
3975 "and attnum > 0::int2 "
3976 "order by attrelid, attnum",
3977 tbinfo->dobj.catId.oid);
3980 res = PQexec(g_conn, q->data);
3981 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3983 ntups = PQntuples(res);
3985 i_attnum = PQfnumber(res, "attnum");
3986 i_attname = PQfnumber(res, "attname");
3987 i_atttypname = PQfnumber(res, "atttypname");
3988 i_atttypmod = PQfnumber(res, "atttypmod");
3989 i_attstattarget = PQfnumber(res, "attstattarget");
3990 i_attstorage = PQfnumber(res, "attstorage");
3991 i_typstorage = PQfnumber(res, "typstorage");
3992 i_attnotnull = PQfnumber(res, "attnotnull");
3993 i_atthasdef = PQfnumber(res, "atthasdef");
3994 i_attisdropped = PQfnumber(res, "attisdropped");
3995 i_attislocal = PQfnumber(res, "attislocal");
3997 tbinfo->numatts = ntups;
3998 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
3999 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
4000 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
4001 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
4002 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
4003 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
4004 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
4005 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
4006 tbinfo->attisserial = (bool *) malloc(ntups * sizeof(bool));
4007 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
4008 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
4009 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
4010 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
4011 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
4012 hasdefaults = false;
4014 for (j = 0; j < ntups; j++)
4016 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
4018 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
4022 tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
4023 tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
4024 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
4025 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
4026 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
4027 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
4028 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
4029 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
4030 tbinfo->attisserial[j] = false; /* fix below */
4031 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
4032 tbinfo->attrdefs[j] = NULL; /* fix below */
4033 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
4035 /* these flags will be set in flagInhAttrs() */
4036 tbinfo->inhAttrs[j] = false;
4037 tbinfo->inhAttrDef[j] = false;
4038 tbinfo->inhNotNull[j] = false;
4044 * Get info about column defaults
4048 AttrDefInfo *attrdefs;
4052 write_msg(NULL, "finding default expressions of table \"%s\"\n",
4055 resetPQExpBuffer(q);
4056 if (g_fout->remoteVersion >= 70300)
4058 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
4059 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
4060 "FROM pg_catalog.pg_attrdef "
4061 "WHERE adrelid = '%u'::pg_catalog.oid",
4062 tbinfo->dobj.catId.oid);
4064 else if (g_fout->remoteVersion >= 70200)
4066 /* 7.2 did not have OIDs in pg_attrdef */
4067 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, adnum, "
4068 "pg_get_expr(adbin, adrelid) AS adsrc "
4070 "WHERE adrelid = '%u'::oid",
4071 tbinfo->dobj.catId.oid);
4073 else if (g_fout->remoteVersion >= 70100)
4075 /* no pg_get_expr, so must rely on adsrc */
4076 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
4078 "WHERE adrelid = '%u'::oid",
4079 tbinfo->dobj.catId.oid);
4083 /* no pg_get_expr, no tableoid either */
4084 appendPQExpBuffer(q, "SELECT "
4085 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
4086 "oid, adnum, adsrc "
4088 "WHERE adrelid = '%u'::oid",
4089 tbinfo->dobj.catId.oid);
4091 res = PQexec(g_conn, q->data);
4092 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
4094 numDefaults = PQntuples(res);
4095 attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
4097 for (j = 0; j < numDefaults; j++)
4101 attrdefs[j].dobj.objType = DO_ATTRDEF;
4102 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
4103 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
4104 AssignDumpId(&attrdefs[j].dobj);
4105 attrdefs[j].adtable = tbinfo;
4106 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
4107 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
4109 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
4110 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
4112 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
4115 * Defaults on a VIEW must always be dumped as separate ALTER
4116 * TABLE commands. Defaults on regular tables are dumped as
4117 * part of the CREATE TABLE if possible. To check if it's
4118 * safe, we mark the default as needing to appear before the
4121 if (tbinfo->relkind == RELKIND_VIEW)
4123 attrdefs[j].separate = true;
4124 /* needed in case pre-7.3 DB: */
4125 addObjectDependency(&attrdefs[j].dobj,
4126 tbinfo->dobj.dumpId);
4130 attrdefs[j].separate = false;
4131 addObjectDependency(&tbinfo->dobj,
4132 attrdefs[j].dobj.dumpId);
4135 if (adnum <= 0 || adnum > ntups)
4137 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
4138 adnum, tbinfo->dobj.name);
4141 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
4147 * Get info about table CHECK constraints
4149 if (tbinfo->ncheck > 0)
4151 ConstraintInfo *constrs;
4155 write_msg(NULL, "finding check constraints for table \"%s\"\n",
4158 resetPQExpBuffer(q);
4159 if (g_fout->remoteVersion >= 70400)
4161 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
4162 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
4163 "FROM pg_catalog.pg_constraint "
4164 "WHERE conrelid = '%u'::pg_catalog.oid "
4165 " AND contype = 'c' "
4167 tbinfo->dobj.catId.oid);
4169 else if (g_fout->remoteVersion >= 70300)
4171 /* no pg_get_constraintdef, must use consrc */
4172 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
4173 "'CHECK (' || consrc || ')' AS consrc "
4174 "FROM pg_catalog.pg_constraint "
4175 "WHERE conrelid = '%u'::pg_catalog.oid "
4176 " AND contype = 'c' "
4178 tbinfo->dobj.catId.oid);
4180 else if (g_fout->remoteVersion >= 70200)
4182 /* 7.2 did not have OIDs in pg_relcheck */
4183 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, "
4184 "rcname AS conname, "
4185 "'CHECK (' || rcsrc || ')' AS consrc "
4187 "WHERE rcrelid = '%u'::oid "
4189 tbinfo->dobj.catId.oid);
4191 else if (g_fout->remoteVersion >= 70100)
4193 appendPQExpBuffer(q, "SELECT tableoid, oid, "
4194 "rcname AS conname, "
4195 "'CHECK (' || rcsrc || ')' AS consrc "
4197 "WHERE rcrelid = '%u'::oid "
4199 tbinfo->dobj.catId.oid);
4203 /* no tableoid in 7.0 */
4204 appendPQExpBuffer(q, "SELECT "
4205 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
4206 "oid, rcname AS conname, "
4207 "'CHECK (' || rcsrc || ')' AS consrc "
4209 "WHERE rcrelid = '%u'::oid "
4211 tbinfo->dobj.catId.oid);
4213 res = PQexec(g_conn, q->data);
4214 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
4216 numConstrs = PQntuples(res);
4217 if (numConstrs != tbinfo->ncheck)
4219 write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
4220 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
4221 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
4225 constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
4226 tbinfo->checkexprs = constrs;
4228 for (j = 0; j < numConstrs; j++)
4230 constrs[j].dobj.objType = DO_CONSTRAINT;
4231 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
4232 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
4233 AssignDumpId(&constrs[j].dobj);
4234 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
4235 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
4236 constrs[j].contable = tbinfo;
4237 constrs[j].condomain = NULL;
4238 constrs[j].contype = 'c';
4239 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
4240 constrs[j].conindex = 0;
4241 constrs[j].coninherited = false;
4242 constrs[j].separate = false;
4244 constrs[j].dobj.dump = tbinfo->dobj.dump;
4247 * Mark the constraint as needing to appear before the table
4248 * --- this is so that any other dependencies of the
4249 * constraint will be emitted before we try to create the
4252 addObjectDependency(&tbinfo->dobj,
4253 constrs[j].dobj.dumpId);
4256 * If the constraint is inherited, this will be detected
4257 * later. We also detect later if the constraint must be
4258 * split out from the table definition.
4265 * Check to see if any columns are serial columns. Our first quick
4266 * filter is that it must be integer or bigint with a default. If so,
4267 * we scan to see if we found a sequence linked to this column. If we
4268 * did, mark the column and sequence appropriately.
4270 for (j = 0; j < ntups; j++)
4273 * Note assumption that format_type will show these types as
4274 * exactly "integer" and "bigint" regardless of schema path. This
4275 * is correct in 7.3 but needs to be watched.
4277 if (strcmp(tbinfo->atttypnames[j], "integer") != 0 &&
4278 strcmp(tbinfo->atttypnames[j], "bigint") != 0)
4280 if (tbinfo->attrdefs[j] == NULL)
4282 for (k = 0; k < numTables; k++)
4284 TableInfo *seqinfo = &tblinfo[k];
4286 if (OidIsValid(seqinfo->owning_tab) &&
4287 seqinfo->owning_tab == tbinfo->dobj.catId.oid &&
4288 seqinfo->owning_col == j + 1)
4291 * Found a match. Copy the table's interesting and
4292 * dumpable flags to the sequence.
4294 tbinfo->attisserial[j] = true;
4295 seqinfo->interesting = tbinfo->interesting;
4296 seqinfo->dobj.dump = tbinfo->dobj.dump;
4303 destroyPQExpBuffer(q);
4310 * This routine is used to dump any comments associated with the
4311 * object handed to this routine. The routine takes a constant character
4312 * string for the target part of the comment-creation command, plus
4313 * the namespace and owner of the object (for labeling the ArchiveEntry),
4314 * plus catalog ID and subid which are the lookup key for pg_description,
4315 * plus the dump ID for the object (for setting a dependency).
4316 * If a matching pg_description entry is found, it is dumped.
4318 * Note: although this routine takes a dumpId for dependency purposes,
4319 * that purpose is just to mark the dependency in the emitted dump file
4320 * for possible future use by pg_restore. We do NOT use it for determining
4321 * ordering of the comment in the dump file, because this routine is called
4322 * after dependency sorting occurs. This routine should be called just after
4323 * calling ArchiveEntry() for the specified object.
4326 dumpComment(Archive *fout, const char *target,
4327 const char *namespace, const char *owner,
4328 CatalogId catalogId, int subid, DumpId dumpId)
4330 CommentItem *comments;
4333 /* Comments are SCHEMA not data */
4337 /* Search for comments associated with catalogId, using table */
4338 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
4341 /* Is there one matching the subid? */
4342 while (ncomments > 0)
4344 if (comments->objsubid == subid)
4350 /* If a comment exists, build COMMENT ON statement */
4353 PQExpBuffer query = createPQExpBuffer();
4355 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
4356 appendStringLiteral(query, comments->descr, false);
4357 appendPQExpBuffer(query, ";\n");
4359 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4360 target, namespace, NULL, owner, false,
4361 "COMMENT", query->data, "", NULL,
4365 destroyPQExpBuffer(query);
4370 * dumpTableComment --
4372 * As above, but dump comments for both the specified table (or view)
4376 dumpTableComment(Archive *fout, TableInfo *tbinfo,
4377 const char *reltypename)
4379 CommentItem *comments;
4384 /* Comments are SCHEMA not data */
4388 /* Search for comments associated with relation, using table */
4389 ncomments = findComments(fout,
4390 tbinfo->dobj.catId.tableoid,
4391 tbinfo->dobj.catId.oid,
4394 /* If comments exist, build COMMENT ON statements */
4398 query = createPQExpBuffer();
4399 target = createPQExpBuffer();
4401 while (ncomments > 0)
4403 const char *descr = comments->descr;
4404 int objsubid = comments->objsubid;
4408 resetPQExpBuffer(target);
4409 appendPQExpBuffer(target, "%s %s", reltypename,
4410 fmtId(tbinfo->dobj.name));
4412 resetPQExpBuffer(query);
4413 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4414 appendStringLiteral(query, descr, false);
4415 appendPQExpBuffer(query, ";\n");
4417 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4419 tbinfo->dobj.namespace->dobj.name,
4422 false, "COMMENT", query->data, "", NULL,
4423 &(tbinfo->dobj.dumpId), 1,
4426 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
4428 resetPQExpBuffer(target);
4429 appendPQExpBuffer(target, "COLUMN %s.",
4430 fmtId(tbinfo->dobj.name));
4431 appendPQExpBuffer(target, "%s",
4432 fmtId(tbinfo->attnames[objsubid - 1]));
4434 resetPQExpBuffer(query);
4435 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4436 appendStringLiteral(query, descr, false);
4437 appendPQExpBuffer(query, ";\n");
4439 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4441 tbinfo->dobj.namespace->dobj.name,
4444 false, "COMMENT", query->data, "", NULL,
4445 &(tbinfo->dobj.dumpId), 1,
4453 destroyPQExpBuffer(query);
4454 destroyPQExpBuffer(target);
4460 * Find the comment(s), if any, associated with the given object. All the
4461 * objsubid values associated with the given classoid/objoid are found with
4465 findComments(Archive *fout, Oid classoid, Oid objoid,
4466 CommentItem **items)
4468 /* static storage for table of comments */
4469 static CommentItem *comments = NULL;
4470 static int ncomments = -1;
4472 CommentItem *middle = NULL;
4477 /* Get comments if we didn't already */
4479 ncomments = collectComments(fout, &comments);
4482 * Pre-7.2, pg_description does not contain classoid, so collectComments
4483 * just stores a zero. If there's a collision on object OID, well, you
4484 * get duplicate comments.
4486 if (fout->remoteVersion < 70200)
4490 * Do binary search to find some item matching the object.
4493 high = &comments[ncomments - 1];
4496 middle = low + (high - low) / 2;
4498 if (classoid < middle->classoid)
4500 else if (classoid > middle->classoid)
4502 else if (objoid < middle->objoid)
4504 else if (objoid > middle->objoid)
4507 break; /* found a match */
4510 if (low > high) /* no matches */
4517 * Now determine how many items match the object. The search loop
4518 * invariant still holds: only items between low and high inclusive could
4522 while (middle > low)
4524 if (classoid != middle[-1].classoid ||
4525 objoid != middle[-1].objoid)
4534 while (middle <= high)
4536 if (classoid != middle->classoid ||
4537 objoid != middle->objoid)
4547 * collectComments --
4549 * Construct a table of all comments available for database objects.
4550 * We used to do per-object queries for the comments, but it's much faster
4551 * to pull them all over at once, and on most databases the memory cost
4554 * The table is sorted by classoid/objid/objsubid for speed in lookup.
4557 collectComments(Archive *fout, CommentItem **items)
4567 CommentItem *comments;
4570 * Note we do NOT change source schema here; preserve the caller's
4574 query = createPQExpBuffer();
4576 if (fout->remoteVersion >= 70300)
4578 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4579 "FROM pg_catalog.pg_description "
4580 "ORDER BY classoid, objoid, objsubid");
4582 else if (fout->remoteVersion >= 70200)
4584 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4585 "FROM pg_description "
4586 "ORDER BY classoid, objoid, objsubid");
4590 /* Note: this will fail to find attribute comments in pre-7.2... */
4591 appendPQExpBuffer(query, "SELECT description, 0 as classoid, objoid, 0 as objsubid "
4592 "FROM pg_description "
4596 res = PQexec(g_conn, query->data);
4597 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4599 /* Construct lookup table containing OIDs in numeric form */
4601 i_description = PQfnumber(res, "description");
4602 i_classoid = PQfnumber(res, "classoid");
4603 i_objoid = PQfnumber(res, "objoid");
4604 i_objsubid = PQfnumber(res, "objsubid");
4606 ntups = PQntuples(res);
4608 comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
4610 for (i = 0; i < ntups; i++)
4612 comments[i].descr = PQgetvalue(res, i, i_description);
4613 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
4614 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
4615 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
4618 /* Do NOT free the PGresult since we are keeping pointers into it */
4619 destroyPQExpBuffer(query);
4626 * dumpDumpableObject
4628 * This routine and its subsidiaries are responsible for creating
4629 * ArchiveEntries (TOC objects) for each object to be dumped.
4632 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
4634 switch (dobj->objType)
4637 dumpNamespace(fout, (NamespaceInfo *) dobj);
4640 dumpType(fout, (TypeInfo *) dobj);
4643 dumpShellType(fout, (ShellTypeInfo *) dobj);
4646 dumpFunc(fout, (FuncInfo *) dobj);
4649 dumpAgg(fout, (AggInfo *) dobj);
4652 dumpOpr(fout, (OprInfo *) dobj);
4655 dumpOpclass(fout, (OpclassInfo *) dobj);
4658 dumpConversion(fout, (ConvInfo *) dobj);
4661 dumpTable(fout, (TableInfo *) dobj);
4664 dumpAttrDef(fout, (AttrDefInfo *) dobj);
4667 dumpIndex(fout, (IndxInfo *) dobj);
4670 dumpRule(fout, (RuleInfo *) dobj);
4673 dumpTrigger(fout, (TriggerInfo *) dobj);
4676 dumpConstraint(fout, (ConstraintInfo *) dobj);
4678 case DO_FK_CONSTRAINT:
4679 dumpConstraint(fout, (ConstraintInfo *) dobj);
4682 dumpProcLang(fout, (ProcLangInfo *) dobj);
4685 dumpCast(fout, (CastInfo *) dobj);
4688 dumpTableData(fout, (TableDataInfo *) dobj);
4691 /* table rowtypes are never dumped separately */
4694 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4695 dobj->name, NULL, NULL, "",
4696 false, "BLOBS", "", "", NULL,
4700 case DO_BLOB_COMMENTS:
4701 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4702 dobj->name, NULL, NULL, "",
4703 false, "BLOB COMMENTS", "", "", NULL,
4705 dumpBlobComments, NULL);
4712 * writes out to fout the queries to recreate a user-defined namespace
4715 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
4721 /* Skip if not to be dumped */
4722 if (!nspinfo->dobj.dump || dataOnly)
4725 /* don't dump dummy namespace from pre-7.3 source */
4726 if (strlen(nspinfo->dobj.name) == 0)
4729 q = createPQExpBuffer();
4730 delq = createPQExpBuffer();
4732 qnspname = strdup(fmtId(nspinfo->dobj.name));
4734 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
4736 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
4738 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
4742 false, "SCHEMA", q->data, delq->data, NULL,
4743 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
4746 /* Dump Schema Comments */
4747 resetPQExpBuffer(q);
4748 appendPQExpBuffer(q, "SCHEMA %s", qnspname);
4749 dumpComment(fout, q->data,
4750 NULL, nspinfo->rolname,
4751 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
4753 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
4754 qnspname, nspinfo->dobj.name, NULL,
4755 nspinfo->rolname, nspinfo->nspacl);
4759 destroyPQExpBuffer(q);
4760 destroyPQExpBuffer(delq);
4765 * writes out to fout the queries to recreate a user-defined type
4768 dumpType(Archive *fout, TypeInfo *tinfo)
4770 /* Skip if not to be dumped */
4771 if (!tinfo->dobj.dump || dataOnly)
4774 /* Dump out in proper style */
4775 if (tinfo->typtype == 'b')
4776 dumpBaseType(fout, tinfo);
4777 else if (tinfo->typtype == 'd')
4778 dumpDomain(fout, tinfo);
4779 else if (tinfo->typtype == 'c')
4780 dumpCompositeType(fout, tinfo);
4785 * writes out to fout the queries to recreate a user-defined base type
4788 dumpBaseType(Archive *fout, TypeInfo *tinfo)
4790 PQExpBuffer q = createPQExpBuffer();
4791 PQExpBuffer delq = createPQExpBuffer();
4792 PQExpBuffer query = createPQExpBuffer();
4811 bool typdefault_is_literal = false;
4813 /* Set proper schema search path so regproc references list correctly */
4814 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4816 /* Fetch type-specific details */
4817 if (fout->remoteVersion >= 80000)
4819 appendPQExpBuffer(query, "SELECT typlen, "
4820 "typinput, typoutput, typreceive, typsend, "
4822 "typinput::pg_catalog.oid as typinputoid, "
4823 "typoutput::pg_catalog.oid as typoutputoid, "
4824 "typreceive::pg_catalog.oid as typreceiveoid, "
4825 "typsend::pg_catalog.oid as typsendoid, "
4826 "typanalyze::pg_catalog.oid as typanalyzeoid, "
4827 "typdelim, typbyval, typalign, typstorage, "
4828 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) as typdefaultbin, typdefault "
4829 "FROM pg_catalog.pg_type "
4830 "WHERE oid = '%u'::pg_catalog.oid",
4831 tinfo->dobj.catId.oid);
4833 else if (fout->remoteVersion >= 70400)
4835 appendPQExpBuffer(query, "SELECT typlen, "
4836 "typinput, typoutput, typreceive, typsend, "
4837 "'-' as typanalyze, "
4838 "typinput::pg_catalog.oid as typinputoid, "
4839 "typoutput::pg_catalog.oid as typoutputoid, "
4840 "typreceive::pg_catalog.oid as typreceiveoid, "
4841 "typsend::pg_catalog.oid as typsendoid, "
4842 "0 as typanalyzeoid, "
4843 "typdelim, typbyval, typalign, typstorage, "
4844 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) as typdefaultbin, typdefault "
4845 "FROM pg_catalog.pg_type "
4846 "WHERE oid = '%u'::pg_catalog.oid",
4847 tinfo->dobj.catId.oid);
4849 else if (fout->remoteVersion >= 70300)
4851 appendPQExpBuffer(query, "SELECT typlen, "
4852 "typinput, typoutput, "
4853 "'-' as typreceive, '-' as typsend, "
4854 "'-' as typanalyze, "
4855 "typinput::pg_catalog.oid as typinputoid, "
4856 "typoutput::pg_catalog.oid as typoutputoid, "
4857 "0 as typreceiveoid, 0 as typsendoid, "
4858 "0 as typanalyzeoid, "
4859 "typdelim, typbyval, typalign, typstorage, "
4860 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) as typdefaultbin, typdefault "
4861 "FROM pg_catalog.pg_type "
4862 "WHERE oid = '%u'::pg_catalog.oid",
4863 tinfo->dobj.catId.oid);
4865 else if (fout->remoteVersion >= 70200)
4868 * Note: although pre-7.3 catalogs contain typreceive and typsend,
4869 * ignore them because they are not right.
4871 appendPQExpBuffer(query, "SELECT typlen, "
4872 "typinput, typoutput, "
4873 "'-' as typreceive, '-' as typsend, "
4874 "'-' as typanalyze, "
4875 "typinput::oid as typinputoid, "
4876 "typoutput::oid as typoutputoid, "
4877 "0 as typreceiveoid, 0 as typsendoid, "
4878 "0 as typanalyzeoid, "
4879 "typdelim, typbyval, typalign, typstorage, "
4880 "NULL as typdefaultbin, typdefault "
4882 "WHERE oid = '%u'::oid",
4883 tinfo->dobj.catId.oid);
4885 else if (fout->remoteVersion >= 70100)
4888 * Ignore pre-7.2 typdefault; the field exists but has an unusable
4891 appendPQExpBuffer(query, "SELECT typlen, "
4892 "typinput, typoutput, "
4893 "'-' as typreceive, '-' as typsend, "
4894 "'-' as typanalyze, "
4895 "typinput::oid as typinputoid, "
4896 "typoutput::oid as typoutputoid, "
4897 "0 as typreceiveoid, 0 as typsendoid, "
4898 "0 as typanalyzeoid, "
4899 "typdelim, typbyval, typalign, typstorage, "
4900 "NULL as typdefaultbin, NULL as typdefault "
4902 "WHERE oid = '%u'::oid",
4903 tinfo->dobj.catId.oid);
4907 appendPQExpBuffer(query, "SELECT typlen, "
4908 "typinput, typoutput, "
4909 "'-' as typreceive, '-' as typsend, "
4910 "'-' as typanalyze, "
4911 "typinput::oid as typinputoid, "
4912 "typoutput::oid as typoutputoid, "
4913 "0 as typreceiveoid, 0 as typsendoid, "
4914 "0 as typanalyzeoid, "
4915 "typdelim, typbyval, typalign, "
4916 "'p'::char as typstorage, "
4917 "NULL as typdefaultbin, NULL as typdefault "
4919 "WHERE oid = '%u'::oid",
4920 tinfo->dobj.catId.oid);
4923 res = PQexec(g_conn, query->data);
4924 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4926 /* Expecting a single result only */
4927 ntups = PQntuples(res);
4930 write_msg(NULL, "Got %d rows instead of one from: %s",
4931 ntups, query->data);
4935 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
4936 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
4937 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
4938 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
4939 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
4940 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
4941 typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
4942 typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
4943 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
4944 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
4945 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
4946 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
4947 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
4948 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
4949 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
4950 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
4951 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
4952 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4954 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4955 typdefault_is_literal = true; /* it needs quotes */
4961 * DROP must be fully qualified in case same name appears in pg_catalog.
4962 * The reason we include CASCADE is that the circular dependency between
4963 * the type and its I/O functions makes it impossible to drop the type
4966 appendPQExpBuffer(delq, "DROP TYPE %s.",
4967 fmtId(tinfo->dobj.namespace->dobj.name));
4968 appendPQExpBuffer(delq, "%s CASCADE;\n",
4969 fmtId(tinfo->dobj.name));
4971 appendPQExpBuffer(q,
4972 "CREATE TYPE %s (\n"
4973 " INTERNALLENGTH = %s",
4974 fmtId(tinfo->dobj.name),
4975 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
4977 if (fout->remoteVersion >= 70300)
4979 /* regproc result is correctly quoted as of 7.3 */
4980 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
4981 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
4982 if (OidIsValid(typreceiveoid))
4983 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
4984 if (OidIsValid(typsendoid))
4985 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
4986 if (OidIsValid(typanalyzeoid))
4987 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
4991 /* regproc delivers an unquoted name before 7.3 */
4992 /* cannot combine these because fmtId uses static result area */
4993 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
4994 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
4995 /* no chance that receive/send/analyze need be printed */
4998 if (typdefault != NULL)
5000 appendPQExpBuffer(q, ",\n DEFAULT = ");
5001 if (typdefault_is_literal)
5002 appendStringLiteral(q, typdefault, true);
5004 appendPQExpBufferStr(q, typdefault);
5011 /* reselect schema in case changed by function dump */
5012 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
5013 elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
5014 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
5018 if (typdelim && strcmp(typdelim, ",") != 0)
5020 appendPQExpBuffer(q, ",\n DELIMITER = ");
5021 appendStringLiteral(q, typdelim, true);
5024 if (strcmp(typalign, "c") == 0)
5025 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
5026 else if (strcmp(typalign, "s") == 0)
5027 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
5028 else if (strcmp(typalign, "i") == 0)
5029 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
5030 else if (strcmp(typalign, "d") == 0)
5031 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
5033 if (strcmp(typstorage, "p") == 0)
5034 appendPQExpBuffer(q, ",\n STORAGE = plain");
5035 else if (strcmp(typstorage, "e") == 0)
5036 appendPQExpBuffer(q, ",\n STORAGE = external");
5037 else if (strcmp(typstorage, "x") == 0)
5038 appendPQExpBuffer(q, ",\n STORAGE = extended");
5039 else if (strcmp(typstorage, "m") == 0)
5040 appendPQExpBuffer(q, ",\n STORAGE = main");
5042 if (strcmp(typbyval, "t") == 0)
5043 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
5045 appendPQExpBuffer(q, "\n);\n");
5047 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
5049 tinfo->dobj.namespace->dobj.name,
5051 tinfo->rolname, false,
5052 "TYPE", q->data, delq->data, NULL,
5053 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
5056 /* Dump Type Comments */
5057 resetPQExpBuffer(q);
5059 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
5060 dumpComment(fout, q->data,
5061 tinfo->dobj.namespace->dobj.name, tinfo->rolname,
5062 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
5065 destroyPQExpBuffer(q);
5066 destroyPQExpBuffer(delq);
5067 destroyPQExpBuffer(query);
5072 * writes out to fout the queries to recreate a user-defined domain
5075 dumpDomain(Archive *fout, TypeInfo *tinfo)
5077 PQExpBuffer q = createPQExpBuffer();
5078 PQExpBuffer delq = createPQExpBuffer();
5079 PQExpBuffer query = createPQExpBuffer();
5086 bool typdefault_is_literal = false;
5088 /* Set proper schema search path so type references list correctly */
5089 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
5091 /* Fetch domain specific details */
5092 /* We assume here that remoteVersion must be at least 70300 */
5093 appendPQExpBuffer(query, "SELECT typnotnull, "
5094 "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
5095 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) as typdefaultbin, typdefault "
5096 "FROM pg_catalog.pg_type "
5097 "WHERE oid = '%u'::pg_catalog.oid",
5098 tinfo->dobj.catId.oid);
5100 res = PQexec(g_conn, query->data);
5101 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5103 /* Expecting a single result only */
5104 ntups = PQntuples(res);
5107 write_msg(NULL, "Got %d rows instead of one from: %s",
5108 ntups, query->data);
5112 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
5113 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
5114 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
5115 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
5116 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
5118 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
5119 typdefault_is_literal = true; /* it needs quotes */
5124 appendPQExpBuffer(q,
5125 "CREATE DOMAIN %s AS %s",
5126 fmtId(tinfo->dobj.name),
5129 if (typnotnull[0] == 't')
5130 appendPQExpBuffer(q, " NOT NULL");
5132 if (typdefault != NULL)
5134 appendPQExpBuffer(q, " DEFAULT ");
5135 if (typdefault_is_literal)
5136 appendStringLiteral(q, typdefault, true);
5138 appendPQExpBufferStr(q, typdefault);
5144 * Add any CHECK constraints for the domain
5146 for (i = 0; i < tinfo->nDomChecks; i++)
5148 ConstraintInfo *domcheck = &(tinfo->domChecks[i]);
5150 if (!domcheck->separate)
5151 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
5152 fmtId(domcheck->dobj.name), domcheck->condef);
5155 appendPQExpBuffer(q, ";\n");
5158 * DROP must be fully qualified in case same name appears in pg_catalog
5160 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
5161 fmtId(tinfo->dobj.namespace->dobj.name));
5162 appendPQExpBuffer(delq, "%s;\n",
5163 fmtId(tinfo->dobj.name));
5165 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
5167 tinfo->dobj.namespace->dobj.name,
5169 tinfo->rolname, false,
5170 "DOMAIN", q->data, delq->data, NULL,
5171 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
5174 /* Dump Domain Comments */
5175 resetPQExpBuffer(q);
5177 appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->dobj.name));
5178 dumpComment(fout, q->data,
5179 tinfo->dobj.namespace->dobj.name, tinfo->rolname,
5180 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
5182 destroyPQExpBuffer(q);
5183 destroyPQExpBuffer(delq);
5184 destroyPQExpBuffer(query);
5189 * writes out to fout the queries to recreate a user-defined stand-alone
5193 dumpCompositeType(Archive *fout, TypeInfo *tinfo)
5195 PQExpBuffer q = createPQExpBuffer();
5196 PQExpBuffer delq = createPQExpBuffer();
5197 PQExpBuffer query = createPQExpBuffer();
5204 /* Set proper schema search path so type references list correctly */
5205 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
5207 /* Fetch type specific details */
5208 /* We assume here that remoteVersion must be at least 70300 */
5210 appendPQExpBuffer(query, "SELECT a.attname, "
5211 "pg_catalog.format_type(a.atttypid, a.atttypmod) as atttypdefn "
5212 "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
5213 "WHERE t.oid = '%u'::pg_catalog.oid "
5214 "AND a.attrelid = t.typrelid "
5215 "AND NOT a.attisdropped "
5216 "ORDER BY a.attnum ",
5217 tinfo->dobj.catId.oid);
5219 res = PQexec(g_conn, query->data);
5220 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5222 /* Expecting at least a single result */
5223 ntups = PQntuples(res);
5226 write_msg(NULL, "query yielded no rows: %s\n", query->data);
5230 i_attname = PQfnumber(res, "attname");
5231 i_atttypdefn = PQfnumber(res, "atttypdefn");
5233 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
5234 fmtId(tinfo->dobj.name));
5236 for (i = 0; i < ntups; i++)
5241 attname = PQgetvalue(res, i, i_attname);
5242 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
5244 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
5246 appendPQExpBuffer(q, ",");
5248 appendPQExpBuffer(q, "\n);\n");
5251 * DROP must be fully qualified in case same name appears in pg_catalog
5253 appendPQExpBuffer(delq, "DROP TYPE %s.",
5254 fmtId(tinfo->dobj.namespace->dobj.name));
5255 appendPQExpBuffer(delq, "%s;\n",
5256 fmtId(tinfo->dobj.name));
5258 ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
5260 tinfo->dobj.namespace->dobj.name,
5262 tinfo->rolname, false,
5263 "TYPE", q->data, delq->data, NULL,
5264 tinfo->dobj.dependencies, tinfo->dobj.nDeps,
5268 /* Dump Type Comments */
5269 resetPQExpBuffer(q);
5271 appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
5272 dumpComment(fout, q->data,
5273 tinfo->dobj.namespace->dobj.name, tinfo->rolname,
5274 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
5277 destroyPQExpBuffer(q);
5278 destroyPQExpBuffer(delq);
5279 destroyPQExpBuffer(query);
5284 * writes out to fout the queries to create a shell type
5286 * We dump a shell definition in advance of the I/O functions for the type.
5289 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
5293 /* Skip if not to be dumped */
5294 if (!stinfo->dobj.dump || dataOnly)
5297 q = createPQExpBuffer();
5300 * Note the lack of a DROP command for the shell type; any required DROP
5301 * is driven off the base type entry, instead. This interacts with
5302 * _printTocEntry()'s use of the presence of a DROP command to decide
5303 * whether an entry needs an ALTER OWNER command. We don't want to
5304 * alter the shell type's owner immediately on creation; that should
5305 * happen only after it's filled in, otherwise the backend complains.
5308 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
5309 fmtId(stinfo->dobj.name));
5311 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
5313 stinfo->dobj.namespace->dobj.name,
5315 stinfo->baseType->rolname, false,
5316 "SHELL TYPE", q->data, "", NULL,
5317 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
5320 destroyPQExpBuffer(q);
5324 * Determine whether we want to dump definitions for procedural languages.
5325 * Since the languages themselves don't have schemas, we can't rely on
5326 * the normal schema-based selection mechanism. We choose to dump them
5327 * whenever neither --schema nor --table was given. (Before 8.1, we used
5328 * the dump flag of the PL's call handler function, but in 8.1 this will
5329 * probably always be false since call handlers are created in pg_catalog.)
5331 * For some backwards compatibility with the older behavior, we forcibly
5332 * dump a PL if its handler function (and validator if any) are in a
5333 * dumpable namespace. That case is not checked here.
5336 shouldDumpProcLangs(void)
5338 if (selectTableName != NULL || selectSchemaName != NULL)
5340 /* And they're schema not data */
5348 * writes out to fout the queries to recreate a user-defined
5349 * procedural language
5352 dumpProcLang(Archive *fout, ProcLangInfo *plang)
5360 FuncInfo *validatorInfo = NULL;
5366 * Try to find the support function(s). It is not an error if we don't
5367 * find them --- if the functions are in the pg_catalog schema, as is
5368 * standard in 8.1 and up, then we won't have loaded them. (In this case
5369 * we will emit a parameterless CREATE LANGUAGE command, which will
5370 * require PL template knowledge in the backend to reload.)
5373 funcInfo = findFuncByOid(plang->lanplcallfoid);
5374 if (funcInfo != NULL && !funcInfo->dobj.dump)
5375 funcInfo = NULL; /* treat not-dumped same as not-found */
5377 if (OidIsValid(plang->lanvalidator))
5379 validatorInfo = findFuncByOid(plang->lanvalidator);
5380 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
5381 validatorInfo = NULL;
5385 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
5386 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
5389 useParams = (funcInfo != NULL &&
5390 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
5392 if (!useParams && !shouldDumpProcLangs())
5395 defqry = createPQExpBuffer();
5396 delqry = createPQExpBuffer();
5398 qlanname = strdup(fmtId(plang->dobj.name));
5401 * If dumping a HANDLER clause, treat the language as being in the handler
5402 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
5403 * it doesn't really have a schema.
5406 lanschema = funcInfo->dobj.namespace->dobj.name;
5410 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
5413 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
5414 (useParams && plang->lanpltrusted) ? "TRUSTED " : "",
5418 appendPQExpBuffer(defqry, " HANDLER %s",
5419 fmtId(funcInfo->dobj.name));
5420 if (OidIsValid(plang->lanvalidator))
5422 appendPQExpBuffer(defqry, " VALIDATOR ");
5423 /* Cope with possibility that validator is in different schema */
5424 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
5425 appendPQExpBuffer(defqry, "%s.",
5426 fmtId(validatorInfo->dobj.namespace->dobj.name));
5427 appendPQExpBuffer(defqry, "%s",
5428 fmtId(validatorInfo->dobj.name));
5431 appendPQExpBuffer(defqry, ";\n");
5433 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
5435 lanschema, NULL, plang->lanowner,
5436 false, "PROCEDURAL LANGUAGE",
5437 defqry->data, delqry->data, NULL,
5438 plang->dobj.dependencies, plang->dobj.nDeps,
5441 /* Dump Proc Lang Comments */
5442 resetPQExpBuffer(defqry);
5443 appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
5444 dumpComment(fout, defqry->data,
5446 plang->dobj.catId, 0, plang->dobj.dumpId);
5448 if (plang->lanpltrusted)
5449 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
5450 qlanname, plang->dobj.name,
5452 plang->lanowner, plang->lanacl);
5456 destroyPQExpBuffer(defqry);
5457 destroyPQExpBuffer(delqry);
5461 * format_function_arguments: generate function name and argument list
5463 * The argument type names are qualified if needed. The function name
5464 * is never qualified.
5466 * Any or all of allargtypes, argmodes, argnames may be NULL.
5469 format_function_arguments(FuncInfo *finfo, int nallargs,
5477 initPQExpBuffer(&fn);
5478 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5479 for (j = 0; j < nallargs; j++)
5483 const char *argmode;
5484 const char *argname;
5486 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
5487 typname = getFormattedTypeName(typid, zeroAsOpaque);
5491 switch (argmodes[j][0])
5503 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
5511 argname = argnames ? argnames[j] : (char *) NULL;
5512 if (argname && argname[0] == '\0')
5515 appendPQExpBuffer(&fn, "%s%s%s%s%s",
5516 (j > 0) ? ", " : "",
5518 argname ? fmtId(argname) : "",
5523 appendPQExpBuffer(&fn, ")");
5528 * format_function_signature: generate function name and argument list
5530 * This is like format_function_arguments except that only a minimal
5531 * list of input argument types is generated; this is sufficient to
5532 * reference the function, but not to define it.
5534 * If honor_quotes is false then the function name is never quoted.
5535 * This is appropriate for use in TOC tags, but not in SQL commands.
5538 format_function_signature(FuncInfo *finfo, bool honor_quotes)
5543 initPQExpBuffer(&fn);
5545 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5547 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
5548 for (j = 0; j < finfo->nargs; j++)
5552 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
5554 appendPQExpBuffer(&fn, "%s%s",
5555 (j > 0) ? ", " : "",
5559 appendPQExpBuffer(&fn, ")");
5566 * dump out one function
5569 dumpFunc(Archive *fout, FuncInfo *finfo)
5582 char *proallargtypes;
5591 char **allargtypes = NULL;
5592 char **argmodes = NULL;
5593 char **argnames = NULL;
5595 /* Skip if not to be dumped */
5596 if (!finfo->dobj.dump || dataOnly)
5599 query = createPQExpBuffer();
5600 q = createPQExpBuffer();
5601 delqry = createPQExpBuffer();
5602 asPart = createPQExpBuffer();
5604 /* Set proper schema search path so type references list correctly */
5605 selectSourceSchema(finfo->dobj.namespace->dobj.name);
5607 /* Fetch function-specific details */
5608 if (g_fout->remoteVersion >= 80100)
5610 appendPQExpBuffer(query,
5611 "SELECT proretset, prosrc, probin, "
5612 "proallargtypes, proargmodes, proargnames, "
5613 "provolatile, proisstrict, prosecdef, "
5614 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5615 "FROM pg_catalog.pg_proc "
5616 "WHERE oid = '%u'::pg_catalog.oid",
5617 finfo->dobj.catId.oid);
5619 else if (g_fout->remoteVersion >= 80000)
5621 appendPQExpBuffer(query,
5622 "SELECT proretset, prosrc, probin, "
5623 "null as proallargtypes, "
5624 "null as proargmodes, "
5626 "provolatile, proisstrict, prosecdef, "
5627 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5628 "FROM pg_catalog.pg_proc "
5629 "WHERE oid = '%u'::pg_catalog.oid",
5630 finfo->dobj.catId.oid);
5632 else if (g_fout->remoteVersion >= 70300)
5634 appendPQExpBuffer(query,
5635 "SELECT proretset, prosrc, probin, "
5636 "null as proallargtypes, "
5637 "null as proargmodes, "
5638 "null as proargnames, "
5639 "provolatile, proisstrict, prosecdef, "
5640 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5641 "FROM pg_catalog.pg_proc "
5642 "WHERE oid = '%u'::pg_catalog.oid",
5643 finfo->dobj.catId.oid);
5645 else if (g_fout->remoteVersion >= 70100)
5647 appendPQExpBuffer(query,
5648 "SELECT proretset, prosrc, probin, "
5649 "null as proallargtypes, "
5650 "null as proargmodes, "
5651 "null as proargnames, "
5652 "case when proiscachable then 'i' else 'v' end as provolatile, "
5654 "'f'::boolean as prosecdef, "
5655 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5657 "WHERE oid = '%u'::oid",
5658 finfo->dobj.catId.oid);
5662 appendPQExpBuffer(query,
5663 "SELECT proretset, prosrc, probin, "
5664 "null as proallargtypes, "
5665 "null as proargmodes, "
5666 "null as proargnames, "
5667 "case when proiscachable then 'i' else 'v' end as provolatile, "
5668 "'f'::boolean as proisstrict, "
5669 "'f'::boolean as prosecdef, "
5670 "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5672 "WHERE oid = '%u'::oid",
5673 finfo->dobj.catId.oid);
5676 res = PQexec(g_conn, query->data);
5677 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5679 /* Expecting a single result only */
5680 ntups = PQntuples(res);
5683 write_msg(NULL, "Got %d rows instead of one from: %s",
5684 ntups, query->data);
5688 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
5689 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
5690 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
5691 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
5692 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
5693 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
5694 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
5695 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
5696 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
5697 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
5700 * See backend/commands/define.c for details of how the 'AS' clause is
5703 if (strcmp(probin, "-") != 0)
5705 appendPQExpBuffer(asPart, "AS ");
5706 appendStringLiteral(asPart, probin, true);
5707 if (strcmp(prosrc, "-") != 0)
5709 appendPQExpBuffer(asPart, ", ");
5712 * where we have bin, use dollar quoting if allowed and src
5713 * contains quote or backslash; else use regular quoting.
5715 if (disable_dollar_quoting)
5716 appendStringLiteral(asPart, prosrc, false);
5718 appendStringLiteralDQOpt(asPart, prosrc, false, NULL);
5723 if (strcmp(prosrc, "-") != 0)
5725 appendPQExpBuffer(asPart, "AS ");
5726 /* with no bin, dollar quote src unconditionally if allowed */
5727 if (disable_dollar_quoting)
5728 appendStringLiteral(asPart, prosrc, false);
5730 appendStringLiteralDQ(asPart, prosrc, NULL);
5734 nallargs = finfo->nargs; /* unless we learn different from allargs */
5736 if (proallargtypes && *proallargtypes)
5740 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
5741 nitems < finfo->nargs)
5743 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
5752 if (proargmodes && *proargmodes)
5756 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
5759 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
5766 if (proargnames && *proargnames)
5770 if (!parsePGArray(proargnames, &argnames, &nitems) ||
5773 write_msg(NULL, "WARNING: could not parse proargnames array\n");
5780 funcsig = format_function_arguments(finfo, nallargs, allargtypes,
5781 argmodes, argnames);
5782 funcsig_tag = format_function_signature(finfo, false);
5785 * DROP must be fully qualified in case same name appears in pg_catalog
5787 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
5788 fmtId(finfo->dobj.namespace->dobj.name),
5791 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
5793 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
5794 appendPQExpBuffer(q, "RETURNS %s%s\n %s\n LANGUAGE %s",
5795 (proretset[0] == 't') ? "SETOF " : "",
5802 if (provolatile[0] != PROVOLATILE_VOLATILE)
5804 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
5805 appendPQExpBuffer(q, " IMMUTABLE");
5806 else if (provolatile[0] == PROVOLATILE_STABLE)
5807 appendPQExpBuffer(q, " STABLE");
5808 else if (provolatile[0] != PROVOLATILE_VOLATILE)
5810 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
5816 if (proisstrict[0] == 't')
5817 appendPQExpBuffer(q, " STRICT");
5819 if (prosecdef[0] == 't')
5820 appendPQExpBuffer(q, " SECURITY DEFINER");
5822 appendPQExpBuffer(q, ";\n");
5824 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
5826 finfo->dobj.namespace->dobj.name,
5828 finfo->rolname, false,
5829 "FUNCTION", q->data, delqry->data, NULL,
5830 finfo->dobj.dependencies, finfo->dobj.nDeps,
5833 /* Dump Function Comments */
5834 resetPQExpBuffer(q);
5835 appendPQExpBuffer(q, "FUNCTION %s", funcsig);
5836 dumpComment(fout, q->data,
5837 finfo->dobj.namespace->dobj.name, finfo->rolname,
5838 finfo->dobj.catId, 0, finfo->dobj.dumpId);
5840 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
5841 funcsig, funcsig_tag,
5842 finfo->dobj.namespace->dobj.name,
5843 finfo->rolname, finfo->proacl);
5847 destroyPQExpBuffer(query);
5848 destroyPQExpBuffer(q);
5849 destroyPQExpBuffer(delqry);
5850 destroyPQExpBuffer(asPart);
5863 * Dump a user-defined cast
5866 dumpCast(Archive *fout, CastInfo *cast)
5870 PQExpBuffer castsig;
5871 FuncInfo *funcInfo = NULL;
5872 TypeInfo *sourceInfo;
5873 TypeInfo *targetInfo;
5878 if (OidIsValid(cast->castfunc))
5880 funcInfo = findFuncByOid(cast->castfunc);
5881 if (funcInfo == NULL)
5886 * As per discussion we dump casts if one or more of the underlying
5887 * objects (the conversion function and the two data types) are not
5888 * builtin AND if all of the non-builtin objects are included in the dump.
5889 * Builtin meaning, the namespace name does not start with "pg_".
5891 sourceInfo = findTypeByOid(cast->castsource);
5892 targetInfo = findTypeByOid(cast->casttarget);
5894 if (sourceInfo == NULL || targetInfo == NULL)
5898 * Skip this cast if all objects are from pg_
5900 if ((funcInfo == NULL ||
5901 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
5902 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
5903 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
5907 * Skip cast if function isn't from pg_ and is not to be dumped.
5910 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5911 !funcInfo->dobj.dump)
5915 * Same for the source type
5917 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5918 !sourceInfo->dobj.dump)
5922 * and the target type.
5924 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5925 !targetInfo->dobj.dump)
5928 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
5929 selectSourceSchema("pg_catalog");
5931 defqry = createPQExpBuffer();
5932 delqry = createPQExpBuffer();
5933 castsig = createPQExpBuffer();
5935 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
5936 getFormattedTypeName(cast->castsource, zeroAsNone),
5937 getFormattedTypeName(cast->casttarget, zeroAsNone));
5939 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
5940 getFormattedTypeName(cast->castsource, zeroAsNone),
5941 getFormattedTypeName(cast->casttarget, zeroAsNone));
5943 if (!OidIsValid(cast->castfunc))
5944 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
5948 * Always qualify the function name, in case it is not in pg_catalog
5949 * schema (format_function_signature won't qualify it).
5951 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
5952 fmtId(funcInfo->dobj.namespace->dobj.name));
5953 appendPQExpBuffer(defqry, "%s",
5954 format_function_signature(funcInfo, true));
5957 if (cast->castcontext == 'a')
5958 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
5959 else if (cast->castcontext == 'i')
5960 appendPQExpBuffer(defqry, " AS IMPLICIT");
5961 appendPQExpBuffer(defqry, ";\n");
5963 appendPQExpBuffer(castsig, "CAST (%s AS %s)",
5964 getFormattedTypeName(cast->castsource, zeroAsNone),
5965 getFormattedTypeName(cast->casttarget, zeroAsNone));
5967 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
5969 "pg_catalog", NULL, "",
5970 false, "CAST", defqry->data, delqry->data, NULL,
5971 cast->dobj.dependencies, cast->dobj.nDeps,
5974 /* Dump Cast Comments */
5975 resetPQExpBuffer(defqry);
5976 appendPQExpBuffer(defqry, "CAST (%s AS %s)",
5977 getFormattedTypeName(cast->castsource, zeroAsNone),
5978 getFormattedTypeName(cast->casttarget, zeroAsNone));
5979 dumpComment(fout, defqry->data,
5981 cast->dobj.catId, 0, cast->dobj.dumpId);
5983 destroyPQExpBuffer(defqry);
5984 destroyPQExpBuffer(delqry);
5985 destroyPQExpBuffer(castsig);
5990 * write out a single operator definition
5993 dumpOpr(Archive *fout, OprInfo *oprinfo)
5999 PQExpBuffer details;
6030 /* Skip if not to be dumped */
6031 if (!oprinfo->dobj.dump || dataOnly)
6035 * some operators are invalid because they were the result of user
6036 * defining operators before commutators exist
6038 if (!OidIsValid(oprinfo->oprcode))
6041 query = createPQExpBuffer();
6042 q = createPQExpBuffer();
6043 delq = createPQExpBuffer();
6044 oprid = createPQExpBuffer();
6045 details = createPQExpBuffer();
6047 /* Make sure we are in proper schema so regoperator works correctly */
6048 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
6050 if (g_fout->remoteVersion >= 70300)
6052 appendPQExpBuffer(query, "SELECT oprkind, "
6053 "oprcode::pg_catalog.regprocedure, "
6054 "oprleft::pg_catalog.regtype, "
6055 "oprright::pg_catalog.regtype, "
6056 "oprcom::pg_catalog.regoperator, "
6057 "oprnegate::pg_catalog.regoperator, "
6058 "oprrest::pg_catalog.regprocedure, "
6059 "oprjoin::pg_catalog.regprocedure, "
6061 "oprlsortop::pg_catalog.regoperator, "
6062 "oprrsortop::pg_catalog.regoperator, "
6063 "oprltcmpop::pg_catalog.regoperator, "
6064 "oprgtcmpop::pg_catalog.regoperator "
6065 "from pg_catalog.pg_operator "
6066 "where oid = '%u'::pg_catalog.oid",
6067 oprinfo->dobj.catId.oid);
6069 else if (g_fout->remoteVersion >= 70100)
6071 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
6072 "CASE WHEN oprleft = 0 THEN '-' "
6073 "ELSE format_type(oprleft, NULL) END as oprleft, "
6074 "CASE WHEN oprright = 0 THEN '-' "
6075 "ELSE format_type(oprright, NULL) END as oprright, "
6076 "oprcom, oprnegate, oprrest, oprjoin, "
6077 "oprcanhash, oprlsortop, oprrsortop, "
6078 "0 as oprltcmpop, 0 as oprgtcmpop "
6080 "where oid = '%u'::oid",
6081 oprinfo->dobj.catId.oid);
6085 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
6086 "CASE WHEN oprleft = 0 THEN '-'::name "
6087 "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
6088 "CASE WHEN oprright = 0 THEN '-'::name "
6089 "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
6090 "oprcom, oprnegate, oprrest, oprjoin, "
6091 "oprcanhash, oprlsortop, oprrsortop, "
6092 "0 as oprltcmpop, 0 as oprgtcmpop "
6094 "where oid = '%u'::oid",
6095 oprinfo->dobj.catId.oid);
6098 res = PQexec(g_conn, query->data);
6099 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6101 /* Expecting a single result only */
6102 ntups = PQntuples(res);
6105 write_msg(NULL, "Got %d rows instead of one from: %s",
6106 ntups, query->data);
6110 i_oprkind = PQfnumber(res, "oprkind");
6111 i_oprcode = PQfnumber(res, "oprcode");
6112 i_oprleft = PQfnumber(res, "oprleft");
6113 i_oprright = PQfnumber(res, "oprright");
6114 i_oprcom = PQfnumber(res, "oprcom");
6115 i_oprnegate = PQfnumber(res, "oprnegate");
6116 i_oprrest = PQfnumber(res, "oprrest");
6117 i_oprjoin = PQfnumber(res, "oprjoin");
6118 i_oprcanhash = PQfnumber(res, "oprcanhash");
6119 i_oprlsortop = PQfnumber(res, "oprlsortop");
6120 i_oprrsortop = PQfnumber(res, "oprrsortop");
6121 i_oprltcmpop = PQfnumber(res, "oprltcmpop");
6122 i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");
6124 oprkind = PQgetvalue(res, 0, i_oprkind);
6125 oprcode = PQgetvalue(res, 0, i_oprcode);
6126 oprleft = PQgetvalue(res, 0, i_oprleft);
6127 oprright = PQgetvalue(res, 0, i_oprright);
6128 oprcom = PQgetvalue(res, 0, i_oprcom);
6129 oprnegate = PQgetvalue(res, 0, i_oprnegate);
6130 oprrest = PQgetvalue(res, 0, i_oprrest);
6131 oprjoin = PQgetvalue(res, 0, i_oprjoin);
6132 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
6133 oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
6134 oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
6135 oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
6136 oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);
6138 appendPQExpBuffer(details, " PROCEDURE = %s",
6139 convertRegProcReference(oprcode));
6141 appendPQExpBuffer(oprid, "%s (",
6142 oprinfo->dobj.name);
6145 * right unary means there's a left arg and left unary means there's a
6148 if (strcmp(oprkind, "r") == 0 ||
6149 strcmp(oprkind, "b") == 0)
6151 if (g_fout->remoteVersion >= 70100)
6154 name = fmtId(oprleft);
6155 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
6156 appendPQExpBuffer(oprid, "%s", name);
6159 appendPQExpBuffer(oprid, "NONE");
6161 if (strcmp(oprkind, "l") == 0 ||
6162 strcmp(oprkind, "b") == 0)
6164 if (g_fout->remoteVersion >= 70100)
6167 name = fmtId(oprright);
6168 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
6169 appendPQExpBuffer(oprid, ", %s)", name);
6172 appendPQExpBuffer(oprid, ", NONE)");
6174 name = convertOperatorReference(oprcom);
6176 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
6178 name = convertOperatorReference(oprnegate);
6180 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
6182 if (strcmp(oprcanhash, "t") == 0)
6183 appendPQExpBuffer(details, ",\n HASHES");
6185 name = convertRegProcReference(oprrest);
6187 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
6189 name = convertRegProcReference(oprjoin);
6191 appendPQExpBuffer(details, ",\n JOIN = %s", name);
6193 name = convertOperatorReference(oprlsortop);
6195 appendPQExpBuffer(details, ",\n SORT1 = %s", name);
6197 name = convertOperatorReference(oprrsortop);
6199 appendPQExpBuffer(details, ",\n SORT2 = %s", name);
6201 name = convertOperatorReference(oprltcmpop);
6203 appendPQExpBuffer(details, ",\n LTCMP = %s", name);
6205 name = convertOperatorReference(oprgtcmpop);
6207 appendPQExpBuffer(details, ",\n GTCMP = %s", name);
6210 * DROP must be fully qualified in case same name appears in pg_catalog
6212 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
6213 fmtId(oprinfo->dobj.namespace->dobj.name),
6216 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
6217 oprinfo->dobj.name, details->data);
6219 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
6221 oprinfo->dobj.namespace->dobj.name,
6224 false, "OPERATOR", q->data, delq->data, NULL,
6225 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
6228 /* Dump Operator Comments */
6229 resetPQExpBuffer(q);
6230 appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
6231 dumpComment(fout, q->data,
6232 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
6233 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
6237 destroyPQExpBuffer(query);
6238 destroyPQExpBuffer(q);
6239 destroyPQExpBuffer(delq);
6240 destroyPQExpBuffer(oprid);
6241 destroyPQExpBuffer(details);
6245 * Convert a function reference obtained from pg_operator
6247 * Returns what to print, or NULL if function references is InvalidOid
6249 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
6250 * argument-types part. In prior versions, the input is a REGPROC display.
6253 convertRegProcReference(const char *proc)
6255 /* In all cases "-" means a null reference */
6256 if (strcmp(proc, "-") == 0)
6259 if (g_fout->remoteVersion >= 70300)
6265 name = strdup(proc);
6266 /* find non-double-quoted left paren */
6268 for (paren = name; *paren; paren++)
6270 if (*paren == '(' && !inquote)
6281 /* REGPROC before 7.3 does not quote its result */
6286 * Convert an operator cross-reference obtained from pg_operator
6288 * Returns what to print, or NULL to print nothing
6290 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
6291 * argument-types part, and add OPERATOR() decoration if the name is
6292 * schema-qualified. In older versions, the input is just a numeric OID,
6293 * which we search our operator list for.
6296 convertOperatorReference(const char *opr)
6300 /* In all cases "0" means a null reference */
6301 if (strcmp(opr, "0") == 0)
6304 if (g_fout->remoteVersion >= 70300)
6313 /* find non-double-quoted left paren, and check for non-quoted dot */
6316 for (ptr = name; *ptr; ptr++)
6320 else if (*ptr == '.' && !inquote)
6322 else if (*ptr == '(' && !inquote)
6328 /* If not schema-qualified, don't need to add OPERATOR() */
6331 oname = malloc(strlen(name) + 11);
6332 sprintf(oname, "OPERATOR(%s)", name);
6337 oprInfo = findOprByOid(atooid(opr));
6338 if (oprInfo == NULL)
6340 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
6344 return oprInfo->dobj.name;
6349 * write out a single operator class definition
6352 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
6380 /* Skip if not to be dumped */
6381 if (!opcinfo->dobj.dump || dataOnly)
6385 * XXX currently we do not implement dumping of operator classes from
6386 * pre-7.3 databases. This could be done but it seems not worth the
6389 if (g_fout->remoteVersion < 70300)
6392 query = createPQExpBuffer();
6393 q = createPQExpBuffer();
6394 delq = createPQExpBuffer();
6396 /* Make sure we are in proper schema so regoperator works correctly */
6397 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
6399 /* Get additional fields from the pg_opclass row */
6400 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
6401 "opckeytype::pg_catalog.regtype, "
6403 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
6404 "FROM pg_catalog.pg_opclass "
6405 "WHERE oid = '%u'::pg_catalog.oid",
6406 opcinfo->dobj.catId.oid);
6408 res = PQexec(g_conn, query->data);
6409 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6411 /* Expecting a single result only */
6412 ntups = PQntuples(res);
6415 write_msg(NULL, "Got %d rows instead of one from: %s",
6416 ntups, query->data);
6420 i_opcintype = PQfnumber(res, "opcintype");
6421 i_opckeytype = PQfnumber(res, "opckeytype");
6422 i_opcdefault = PQfnumber(res, "opcdefault");
6423 i_amname = PQfnumber(res, "amname");
6425 opcintype = PQgetvalue(res, 0, i_opcintype);
6426 opckeytype = PQgetvalue(res, 0, i_opckeytype);
6427 opcdefault = PQgetvalue(res, 0, i_opcdefault);
6428 /* amname will still be needed after we PQclear res */
6429 amname = strdup(PQgetvalue(res, 0, i_amname));
6432 * DROP must be fully qualified in case same name appears in pg_catalog
6434 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
6435 fmtId(opcinfo->dobj.namespace->dobj.name));
6436 appendPQExpBuffer(delq, ".%s",
6437 fmtId(opcinfo->dobj.name));
6438 appendPQExpBuffer(delq, " USING %s;\n",
6441 /* Build the fixed portion of the CREATE command */
6442 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
6443 fmtId(opcinfo->dobj.name));
6444 if (strcmp(opcdefault, "t") == 0)
6445 appendPQExpBuffer(q, "DEFAULT ");
6446 appendPQExpBuffer(q, "FOR TYPE %s USING %s AS\n ",
6452 if (strcmp(opckeytype, "-") != 0)
6454 appendPQExpBuffer(q, "STORAGE %s",
6462 * Now fetch and print the OPERATOR entries (pg_amop rows).
6464 resetPQExpBuffer(query);
6466 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
6467 "amopopr::pg_catalog.regoperator "
6468 "FROM pg_catalog.pg_amop "
6469 "WHERE amopclaid = '%u'::pg_catalog.oid "
6470 "ORDER BY amopstrategy",
6471 opcinfo->dobj.catId.oid);
6473 res = PQexec(g_conn, query->data);
6474 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6476 ntups = PQntuples(res);
6478 i_amopstrategy = PQfnumber(res, "amopstrategy");
6479 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
6480 i_amopopr = PQfnumber(res, "amopopr");
6482 for (i = 0; i < ntups; i++)
6484 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
6485 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
6486 amopopr = PQgetvalue(res, i, i_amopopr);
6489 appendPQExpBuffer(q, " ,\n ");
6491 appendPQExpBuffer(q, "OPERATOR %s %s",
6492 amopstrategy, amopopr);
6493 if (strcmp(amopreqcheck, "t") == 0)
6494 appendPQExpBuffer(q, " RECHECK");
6502 * Now fetch and print the FUNCTION entries (pg_amproc rows).
6504 resetPQExpBuffer(query);
6506 appendPQExpBuffer(query, "SELECT amprocnum, "
6507 "amproc::pg_catalog.regprocedure "
6508 "FROM pg_catalog.pg_amproc "
6509 "WHERE amopclaid = '%u'::pg_catalog.oid "
6510 "ORDER BY amprocnum",
6511 opcinfo->dobj.catId.oid);
6513 res = PQexec(g_conn, query->data);
6514 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6516 ntups = PQntuples(res);
6518 i_amprocnum = PQfnumber(res, "amprocnum");
6519 i_amproc = PQfnumber(res, "amproc");
6521 for (i = 0; i < ntups; i++)
6523 amprocnum = PQgetvalue(res, i, i_amprocnum);
6524 amproc = PQgetvalue(res, i, i_amproc);
6527 appendPQExpBuffer(q, " ,\n ");
6529 appendPQExpBuffer(q, "FUNCTION %s %s",
6537 appendPQExpBuffer(q, ";\n");
6539 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
6541 opcinfo->dobj.namespace->dobj.name,
6544 false, "OPERATOR CLASS", q->data, delq->data, NULL,
6545 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
6548 /* Dump Operator Class Comments */
6549 resetPQExpBuffer(q);
6550 appendPQExpBuffer(q, "OPERATOR CLASS %s",
6551 fmtId(opcinfo->dobj.name));
6552 appendPQExpBuffer(q, " USING %s",
6554 dumpComment(fout, q->data,
6555 NULL, opcinfo->rolname,
6556 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
6559 destroyPQExpBuffer(query);
6560 destroyPQExpBuffer(q);
6561 destroyPQExpBuffer(delq);
6566 * write out a single conversion definition
6569 dumpConversion(Archive *fout, ConvInfo *convinfo)
6574 PQExpBuffer details;
6578 int i_conforencoding;
6579 int i_contoencoding;
6582 const char *conname;
6583 const char *conforencoding;
6584 const char *contoencoding;
6585 const char *conproc;
6588 /* Skip if not to be dumped */
6589 if (!convinfo->dobj.dump || dataOnly)
6592 query = createPQExpBuffer();
6593 q = createPQExpBuffer();
6594 delq = createPQExpBuffer();
6595 details = createPQExpBuffer();
6597 /* Make sure we are in proper schema */
6598 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
6600 /* Get conversion-specific details */
6601 appendPQExpBuffer(query, "SELECT conname, "
6602 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
6603 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
6604 "conproc, condefault "
6605 "FROM pg_catalog.pg_conversion c "
6606 "WHERE c.oid = '%u'::pg_catalog.oid",
6607 convinfo->dobj.catId.oid);
6609 res = PQexec(g_conn, query->data);
6610 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6612 /* Expecting a single result only */
6613 ntups = PQntuples(res);
6616 write_msg(NULL, "Got %d rows instead of one from: %s",
6617 ntups, query->data);
6621 i_conname = PQfnumber(res, "conname");
6622 i_conforencoding = PQfnumber(res, "conforencoding");
6623 i_contoencoding = PQfnumber(res, "contoencoding");
6624 i_conproc = PQfnumber(res, "conproc");
6625 i_condefault = PQfnumber(res, "condefault");
6627 conname = PQgetvalue(res, 0, i_conname);
6628 conforencoding = PQgetvalue(res, 0, i_conforencoding);
6629 contoencoding = PQgetvalue(res, 0, i_contoencoding);
6630 conproc = PQgetvalue(res, 0, i_conproc);
6631 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
6634 * DROP must be fully qualified in case same name appears in pg_catalog
6636 appendPQExpBuffer(delq, "DROP CONVERSION %s",
6637 fmtId(convinfo->dobj.namespace->dobj.name));
6638 appendPQExpBuffer(delq, ".%s;\n",
6639 fmtId(convinfo->dobj.name));
6641 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
6642 (condefault) ? "DEFAULT " : "",
6643 fmtId(convinfo->dobj.name));
6644 appendStringLiteral(q, conforencoding, true);
6645 appendPQExpBuffer(q, " TO ");
6646 appendStringLiteral(q, contoencoding, true);
6647 /* regproc is automatically quoted in 7.3 and above */
6648 appendPQExpBuffer(q, " FROM %s;\n", conproc);
6650 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
6651 convinfo->dobj.name,
6652 convinfo->dobj.namespace->dobj.name,
6655 false, "CONVERSION", q->data, delq->data, NULL,
6656 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
6659 /* Dump Conversion Comments */
6660 resetPQExpBuffer(q);
6661 appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
6662 dumpComment(fout, q->data,
6663 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
6664 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
6668 destroyPQExpBuffer(query);
6669 destroyPQExpBuffer(q);
6670 destroyPQExpBuffer(delq);
6671 destroyPQExpBuffer(details);
6675 * format_aggregate_signature: generate aggregate name and argument list
6677 * The argument type names are qualified if needed. The aggregate name
6678 * is never qualified.
6681 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
6683 PQExpBufferData buf;
6685 initPQExpBuffer(&buf);
6687 appendPQExpBuffer(&buf, "%s",
6688 fmtId(agginfo->aggfn.dobj.name));
6690 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
6692 /* If using regtype or format_type, fmtbasetype is already quoted */
6693 if (fout->remoteVersion >= 70100)
6695 if (agginfo->anybasetype)
6696 appendPQExpBuffer(&buf, "(*)");
6698 appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
6702 if (agginfo->anybasetype)
6703 appendPQExpBuffer(&buf, "(*)");
6705 appendPQExpBuffer(&buf, "(%s)",
6706 fmtId(agginfo->fmtbasetype));
6714 * write out a single aggregate definition
6717 dumpAgg(Archive *fout, AggInfo *agginfo)
6722 PQExpBuffer details;
6735 const char *aggtransfn;
6736 const char *aggfinalfn;
6737 const char *aggsortop;
6738 const char *aggtranstype;
6739 const char *agginitval;
6742 /* Skip if not to be dumped */
6743 if (!agginfo->aggfn.dobj.dump || dataOnly)
6746 query = createPQExpBuffer();
6747 q = createPQExpBuffer();
6748 delq = createPQExpBuffer();
6749 details = createPQExpBuffer();
6751 /* Make sure we are in proper schema */
6752 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
6754 /* Get aggregate-specific details */
6755 if (g_fout->remoteVersion >= 80100)
6757 appendPQExpBuffer(query, "SELECT aggtransfn, "
6758 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6759 "aggsortop::pg_catalog.regoperator, "
6761 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6762 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6763 "'t'::boolean as convertok "
6764 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6765 "where a.aggfnoid = p.oid "
6766 "and p.oid = '%u'::pg_catalog.oid",
6767 agginfo->aggfn.dobj.catId.oid);
6769 else if (g_fout->remoteVersion >= 70300)
6771 appendPQExpBuffer(query, "SELECT aggtransfn, "
6772 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6775 "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6776 "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6777 "'t'::boolean as convertok "
6778 "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6779 "where a.aggfnoid = p.oid "
6780 "and p.oid = '%u'::pg_catalog.oid",
6781 agginfo->aggfn.dobj.catId.oid);
6783 else if (g_fout->remoteVersion >= 70100)
6785 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
6786 "format_type(aggtranstype, NULL) as aggtranstype, "
6789 "aggbasetype = 0 as anybasetype, "
6790 "CASE WHEN aggbasetype = 0 THEN '-' "
6791 "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
6792 "'t'::boolean as convertok "
6793 "from pg_aggregate "
6794 "where oid = '%u'::oid",
6795 agginfo->aggfn.dobj.catId.oid);
6799 appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
6801 "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
6803 "agginitval1 as agginitval, "
6804 "aggbasetype = 0 as anybasetype, "
6805 "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
6806 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
6807 "from pg_aggregate "
6808 "where oid = '%u'::oid",
6809 agginfo->aggfn.dobj.catId.oid);
6812 res = PQexec(g_conn, query->data);
6813 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6815 /* Expecting a single result only */
6816 ntups = PQntuples(res);
6819 write_msg(NULL, "Got %d rows instead of one from: %s",
6820 ntups, query->data);
6824 i_aggtransfn = PQfnumber(res, "aggtransfn");
6825 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
6826 i_aggsortop = PQfnumber(res, "aggsortop");
6827 i_aggtranstype = PQfnumber(res, "aggtranstype");
6828 i_agginitval = PQfnumber(res, "agginitval");
6829 i_anybasetype = PQfnumber(res, "anybasetype");
6830 i_fmtbasetype = PQfnumber(res, "fmtbasetype");
6831 i_convertok = PQfnumber(res, "convertok");
6833 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
6834 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
6835 aggsortop = PQgetvalue(res, 0, i_aggsortop);
6836 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
6837 agginitval = PQgetvalue(res, 0, i_agginitval);
6838 /* we save anybasetype for format_aggregate_signature */
6839 agginfo->anybasetype = (PQgetvalue(res, 0, i_anybasetype)[0] == 't');
6840 /* we save fmtbasetype for format_aggregate_signature */
6841 agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
6842 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
6844 aggsig = format_aggregate_signature(agginfo, fout, true);
6845 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
6849 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
6854 if (g_fout->remoteVersion >= 70300)
6856 /* If using 7.3's regproc or regtype, data is already quoted */
6857 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6858 agginfo->anybasetype ? "'any'" :
6859 agginfo->fmtbasetype,
6863 else if (g_fout->remoteVersion >= 70100)
6865 /* format_type quotes, regproc does not */
6866 appendPQExpBuffer(details, " BASETYPE = %s,\n SFUNC = %s,\n STYPE = %s",
6867 agginfo->anybasetype ? "'any'" :
6868 agginfo->fmtbasetype,
6874 /* need quotes all around */
6875 appendPQExpBuffer(details, " BASETYPE = %s,\n",
6876 agginfo->anybasetype ? "'any'" :
6877 fmtId(agginfo->fmtbasetype));
6878 appendPQExpBuffer(details, " SFUNC = %s,\n",
6880 appendPQExpBuffer(details, " STYPE = %s",
6881 fmtId(aggtranstype));
6884 if (!PQgetisnull(res, 0, i_agginitval))
6886 appendPQExpBuffer(details, ",\n INITCOND = ");
6887 appendStringLiteral(details, agginitval, true);
6890 if (strcmp(aggfinalfn, "-") != 0)
6892 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
6896 aggsortop = convertOperatorReference(aggsortop);
6899 appendPQExpBuffer(details, ",\n SORTOP = %s",
6904 * DROP must be fully qualified in case same name appears in pg_catalog
6906 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
6907 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
6910 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
6911 fmtId(agginfo->aggfn.dobj.name),
6914 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6916 agginfo->aggfn.dobj.namespace->dobj.name,
6918 agginfo->aggfn.rolname,
6919 false, "AGGREGATE", q->data, delq->data, NULL,
6920 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
6923 /* Dump Aggregate Comments */
6924 resetPQExpBuffer(q);
6925 appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
6926 dumpComment(fout, q->data,
6927 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
6928 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
6931 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
6932 * command look like a function's GRANT; in particular this affects the
6933 * syntax for aggregates on ANY.
6938 aggsig = format_function_signature(&agginfo->aggfn, true);
6939 aggsig_tag = format_function_signature(&agginfo->aggfn, false);
6941 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6944 agginfo->aggfn.dobj.namespace->dobj.name,
6945 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
6952 destroyPQExpBuffer(query);
6953 destroyPQExpBuffer(q);
6954 destroyPQExpBuffer(delq);
6955 destroyPQExpBuffer(details);
6960 * Write out grant/revoke information
6962 * 'objCatId' is the catalog ID of the underlying object.
6963 * 'objDumpId' is the dump ID of the underlying object.
6964 * 'type' must be TABLE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, or TABLESPACE.
6965 * 'name' is the formatted name of the object. Must be quoted etc. already.
6966 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
6967 * 'nspname' is the namespace the object is in (NULL if none).
6968 * 'owner' is the owner, NULL if there is no owner (for languages).
6969 * 'acls' is the string read out of the fooacl system catalog field;
6970 * it will be parsed here.
6974 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
6975 const char *type, const char *name,
6976 const char *tag, const char *nspname, const char *owner,
6981 /* Do nothing if ACL dump is not enabled */
6982 if (dataOnly || aclsSkip)
6985 sql = createPQExpBuffer();
6987 if (!buildACLCommands(name, type, acls, owner, fout->remoteVersion, sql))
6989 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
6995 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6999 false, "ACL", sql->data, "", NULL,
7003 destroyPQExpBuffer(sql);
7008 * write out to fout the declarations (not data) of a user-defined table
7011 dumpTable(Archive *fout, TableInfo *tbinfo)
7015 if (tbinfo->dobj.dump)
7017 if (tbinfo->relkind == RELKIND_SEQUENCE)
7018 dumpSequence(fout, tbinfo);
7020 dumpTableSchema(fout, tbinfo);
7022 /* Handle the ACL here */
7023 namecopy = strdup(fmtId(tbinfo->dobj.name));
7024 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7025 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE",
7026 namecopy, tbinfo->dobj.name,
7027 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
7035 * write the declaration (not data) of one user-defined table or view
7038 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
7040 PQExpBuffer query = createPQExpBuffer();
7041 PQExpBuffer q = createPQExpBuffer();
7042 PQExpBuffer delq = createPQExpBuffer();
7045 TableInfo **parents;
7046 int actual_atts; /* number of attrs in this CREATE statment */
7052 /* Make sure we are in proper schema */
7053 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7055 /* Is it a table or a view? */
7056 if (tbinfo->relkind == RELKIND_VIEW)
7060 reltypename = "VIEW";
7062 /* Fetch the view definition */
7063 if (g_fout->remoteVersion >= 70300)
7065 /* Beginning in 7.3, viewname is not unique; rely on OID */
7066 appendPQExpBuffer(query,
7067 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) as viewdef",
7068 tbinfo->dobj.catId.oid);
7072 appendPQExpBuffer(query, "SELECT definition as viewdef "
7073 " from pg_views where viewname = ");
7074 appendStringLiteral(query, tbinfo->dobj.name, true);
7075 appendPQExpBuffer(query, ";");
7078 res = PQexec(g_conn, query->data);
7079 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7081 if (PQntuples(res) != 1)
7083 if (PQntuples(res) < 1)
7084 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
7087 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
7092 viewdef = PQgetvalue(res, 0, 0);
7094 if (strlen(viewdef) == 0)
7096 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
7102 * DROP must be fully qualified in case same name appears in
7105 appendPQExpBuffer(delq, "DROP VIEW %s.",
7106 fmtId(tbinfo->dobj.namespace->dobj.name));
7107 appendPQExpBuffer(delq, "%s;\n",
7108 fmtId(tbinfo->dobj.name));
7110 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
7111 fmtId(tbinfo->dobj.name), viewdef);
7117 reltypename = "TABLE";
7118 numParents = tbinfo->numParents;
7119 parents = tbinfo->parents;
7122 * DROP must be fully qualified in case same name appears in
7125 appendPQExpBuffer(delq, "DROP TABLE %s.",
7126 fmtId(tbinfo->dobj.namespace->dobj.name));
7127 appendPQExpBuffer(delq, "%s;\n",
7128 fmtId(tbinfo->dobj.name));
7130 appendPQExpBuffer(q, "CREATE TABLE %s (",
7131 fmtId(tbinfo->dobj.name));
7133 for (j = 0; j < tbinfo->numatts; j++)
7135 /* Is this one of the table's own attrs, and not dropped ? */
7136 if (!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j])
7138 /* Format properly if not first attr */
7139 if (actual_atts > 0)
7140 appendPQExpBuffer(q, ",");
7141 appendPQExpBuffer(q, "\n ");
7143 /* Attribute name */
7144 appendPQExpBuffer(q, "%s ",
7145 fmtId(tbinfo->attnames[j]));
7147 /* Attribute type */
7148 if (g_fout->remoteVersion >= 70100)
7150 char *typname = tbinfo->atttypnames[j];
7152 if (tbinfo->attisserial[j])
7154 if (strcmp(typname, "integer") == 0)
7156 else if (strcmp(typname, "bigint") == 0)
7157 typname = "bigserial";
7159 appendPQExpBuffer(q, "%s", typname);
7163 /* If no format_type, fake it */
7164 appendPQExpBuffer(q, "%s",
7165 myFormatType(tbinfo->atttypnames[j],
7166 tbinfo->atttypmod[j]));
7170 * Default value --- suppress if inherited, serial, or to be
7171 * printed separately.
7173 if (tbinfo->attrdefs[j] != NULL &&
7174 !tbinfo->inhAttrDef[j] &&
7175 !tbinfo->attisserial[j] &&
7176 !tbinfo->attrdefs[j]->separate)
7177 appendPQExpBuffer(q, " DEFAULT %s",
7178 tbinfo->attrdefs[j]->adef_expr);
7181 * Not Null constraint --- suppress if inherited
7183 * Note: we could suppress this for serial columns since
7184 * SERIAL implies NOT NULL. We choose not to for forward
7185 * compatibility, since there has been some talk of making
7186 * SERIAL not imply NOT NULL, in which case the explicit
7187 * specification would be needed.
7189 if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
7190 appendPQExpBuffer(q, " NOT NULL");
7197 * Add non-inherited CHECK constraints, if any.
7199 for (j = 0; j < tbinfo->ncheck; j++)
7201 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
7203 if (constr->coninherited || constr->separate)
7206 if (actual_atts > 0)
7207 appendPQExpBuffer(q, ",\n ");
7209 appendPQExpBuffer(q, "CONSTRAINT %s ",
7210 fmtId(constr->dobj.name));
7211 appendPQExpBuffer(q, "%s", constr->condef);
7216 appendPQExpBuffer(q, "\n)");
7220 appendPQExpBuffer(q, "\nINHERITS (");
7221 for (k = 0; k < numParents; k++)
7223 TableInfo *parentRel = parents[k];
7226 appendPQExpBuffer(q, ", ");
7227 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
7228 appendPQExpBuffer(q, "%s.",
7229 fmtId(parentRel->dobj.namespace->dobj.name));
7230 appendPQExpBuffer(q, "%s",
7231 fmtId(parentRel->dobj.name));
7233 appendPQExpBuffer(q, ")");
7236 appendPQExpBuffer(q, ";\n");
7238 /* Loop dumping statistics and storage statements */
7239 for (j = 0; j < tbinfo->numatts; j++)
7242 * Dump per-column statistics information. We only issue an ALTER
7243 * TABLE statement if the attstattarget entry for this column is
7244 * non-negative (i.e. it's not the default value)
7246 if (tbinfo->attstattarget[j] >= 0 &&
7247 !tbinfo->attisdropped[j])
7249 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
7250 fmtId(tbinfo->dobj.name));
7251 appendPQExpBuffer(q, "ALTER COLUMN %s ",
7252 fmtId(tbinfo->attnames[j]));
7253 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
7254 tbinfo->attstattarget[j]);
7258 * Dump per-column storage information. The statement is only
7259 * dumped if the storage has been changed from the type's default.
7261 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
7263 switch (tbinfo->attstorage[j])
7269 storage = "EXTERNAL";
7275 storage = "EXTENDED";
7282 * Only dump the statement if it's a storage type we recognize
7284 if (storage != NULL)
7286 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
7287 fmtId(tbinfo->dobj.name));
7288 appendPQExpBuffer(q, "ALTER COLUMN %s ",
7289 fmtId(tbinfo->attnames[j]));
7290 appendPQExpBuffer(q, "SET STORAGE %s;\n",
7297 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7299 tbinfo->dobj.namespace->dobj.name,
7300 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
7302 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
7303 reltypename, q->data, delq->data, NULL,
7304 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7307 /* Dump Table Comments */
7308 dumpTableComment(fout, tbinfo, reltypename);
7310 /* Dump comments on inlined table constraints */
7311 for (j = 0; j < tbinfo->ncheck; j++)
7313 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
7315 if (constr->coninherited || constr->separate)
7318 dumpTableConstraintComment(fout, constr);
7321 destroyPQExpBuffer(query);
7322 destroyPQExpBuffer(q);
7323 destroyPQExpBuffer(delq);
7327 * dumpAttrDef --- dump an attribute's default-value declaration
7330 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
7332 TableInfo *tbinfo = adinfo->adtable;
7333 int adnum = adinfo->adnum;
7337 /* Only print it if "separate" mode is selected */
7338 if (!tbinfo->dobj.dump || !adinfo->separate || dataOnly)
7341 /* Don't print inherited or serial defaults, either */
7342 if (tbinfo->inhAttrDef[adnum - 1] || tbinfo->attisserial[adnum - 1])
7345 q = createPQExpBuffer();
7346 delq = createPQExpBuffer();
7348 appendPQExpBuffer(q, "ALTER TABLE %s ",
7349 fmtId(tbinfo->dobj.name));
7350 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
7351 fmtId(tbinfo->attnames[adnum - 1]),
7355 * DROP must be fully qualified in case same name appears in pg_catalog
7357 appendPQExpBuffer(delq, "ALTER TABLE %s.",
7358 fmtId(tbinfo->dobj.namespace->dobj.name));
7359 appendPQExpBuffer(delq, "%s ",
7360 fmtId(tbinfo->dobj.name));
7361 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
7362 fmtId(tbinfo->attnames[adnum - 1]));
7364 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
7365 tbinfo->attnames[adnum - 1],
7366 tbinfo->dobj.namespace->dobj.name,
7369 false, "DEFAULT", q->data, delq->data, NULL,
7370 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
7373 destroyPQExpBuffer(q);
7374 destroyPQExpBuffer(delq);
7378 * getAttrName: extract the correct name for an attribute
7380 * The array tblInfo->attnames[] only provides names of user attributes;
7381 * if a system attribute number is supplied, we have to fake it.
7382 * We also do a little bit of bounds checking for safety's sake.
7385 getAttrName(int attrnum, TableInfo *tblInfo)
7387 if (attrnum > 0 && attrnum <= tblInfo->numatts)
7388 return tblInfo->attnames[attrnum - 1];
7391 case SelfItemPointerAttributeNumber:
7393 case ObjectIdAttributeNumber:
7395 case MinTransactionIdAttributeNumber:
7397 case MinCommandIdAttributeNumber:
7399 case MaxTransactionIdAttributeNumber:
7401 case MaxCommandIdAttributeNumber:
7403 case TableOidAttributeNumber:
7406 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
7407 attrnum, tblInfo->dobj.name);
7409 return NULL; /* keep compiler quiet */
7414 * write out to fout a user-defined index
7417 dumpIndex(Archive *fout, IndxInfo *indxinfo)
7419 TableInfo *tbinfo = indxinfo->indextable;
7426 q = createPQExpBuffer();
7427 delq = createPQExpBuffer();
7430 * If there's an associated constraint, don't dump the index per se, but
7431 * do dump any comment for it. (This is safe because dependency ordering
7432 * will have ensured the constraint is emitted first.)
7434 if (indxinfo->indexconstraint == 0)
7436 /* Plain secondary index */
7437 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
7439 /* If the index is clustered, we need to record that. */
7440 if (indxinfo->indisclustered)
7442 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
7443 fmtId(tbinfo->dobj.name));
7444 appendPQExpBuffer(q, " ON %s;\n",
7445 fmtId(indxinfo->dobj.name));
7449 * DROP must be fully qualified in case same name appears in
7452 appendPQExpBuffer(delq, "DROP INDEX %s.",
7453 fmtId(tbinfo->dobj.namespace->dobj.name));
7454 appendPQExpBuffer(delq, "%s;\n",
7455 fmtId(indxinfo->dobj.name));
7457 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
7458 indxinfo->dobj.name,
7459 tbinfo->dobj.namespace->dobj.name,
7460 indxinfo->tablespace,
7461 tbinfo->rolname, false,
7462 "INDEX", q->data, delq->data, NULL,
7463 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
7467 /* Dump Index Comments */
7468 resetPQExpBuffer(q);
7469 appendPQExpBuffer(q, "INDEX %s",
7470 fmtId(indxinfo->dobj.name));
7471 dumpComment(fout, q->data,
7472 tbinfo->dobj.namespace->dobj.name,
7474 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
7476 destroyPQExpBuffer(q);
7477 destroyPQExpBuffer(delq);
7482 * write out to fout a user-defined constraint
7485 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
7487 TableInfo *tbinfo = coninfo->contable;
7491 /* Skip if not to be dumped */
7492 if (!coninfo->dobj.dump || dataOnly)
7495 q = createPQExpBuffer();
7496 delq = createPQExpBuffer();
7498 if (coninfo->contype == 'p' || coninfo->contype == 'u')
7500 /* Index-related constraint */
7504 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
7506 if (indxinfo == NULL)
7508 write_msg(NULL, "missing index for constraint \"%s\"\n",
7509 coninfo->dobj.name);
7513 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
7514 fmtId(tbinfo->dobj.name));
7515 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s (",
7516 fmtId(coninfo->dobj.name),
7517 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
7519 for (k = 0; k < indxinfo->indnkeys; k++)
7521 int indkey = (int) indxinfo->indkeys[k];
7522 const char *attname;
7524 if (indkey == InvalidAttrNumber)
7526 attname = getAttrName(indkey, tbinfo);
7528 appendPQExpBuffer(q, "%s%s",
7529 (k == 0) ? "" : ", ",
7533 appendPQExpBuffer(q, ");\n");
7535 /* If the index is clustered, we need to record that. */
7536 if (indxinfo->indisclustered)
7538 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
7539 fmtId(tbinfo->dobj.name));
7540 appendPQExpBuffer(q, " ON %s;\n",
7541 fmtId(indxinfo->dobj.name));
7545 * DROP must be fully qualified in case same name appears in
7548 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7549 fmtId(tbinfo->dobj.namespace->dobj.name));
7550 appendPQExpBuffer(delq, "%s ",
7551 fmtId(tbinfo->dobj.name));
7552 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7553 fmtId(coninfo->dobj.name));
7555 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7557 tbinfo->dobj.namespace->dobj.name,
7558 indxinfo->tablespace,
7559 tbinfo->rolname, false,
7560 "CONSTRAINT", q->data, delq->data, NULL,
7561 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7564 else if (coninfo->contype == 'f')
7567 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
7568 * current table data is not processed
7570 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
7571 fmtId(tbinfo->dobj.name));
7572 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7573 fmtId(coninfo->dobj.name),
7577 * DROP must be fully qualified in case same name appears in
7580 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7581 fmtId(tbinfo->dobj.namespace->dobj.name));
7582 appendPQExpBuffer(delq, "%s ",
7583 fmtId(tbinfo->dobj.name));
7584 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7585 fmtId(coninfo->dobj.name));
7587 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7589 tbinfo->dobj.namespace->dobj.name,
7591 tbinfo->rolname, false,
7592 "FK CONSTRAINT", q->data, delq->data, NULL,
7593 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7596 else if (coninfo->contype == 'c' && tbinfo)
7598 /* CHECK constraint on a table */
7600 /* Ignore if not to be dumped separately */
7601 if (coninfo->separate)
7603 /* not ONLY since we want it to propagate to children */
7604 appendPQExpBuffer(q, "ALTER TABLE %s\n",
7605 fmtId(tbinfo->dobj.name));
7606 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7607 fmtId(coninfo->dobj.name),
7611 * DROP must be fully qualified in case same name appears in
7614 appendPQExpBuffer(delq, "ALTER TABLE %s.",
7615 fmtId(tbinfo->dobj.namespace->dobj.name));
7616 appendPQExpBuffer(delq, "%s ",
7617 fmtId(tbinfo->dobj.name));
7618 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7619 fmtId(coninfo->dobj.name));
7621 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7623 tbinfo->dobj.namespace->dobj.name,
7625 tbinfo->rolname, false,
7626 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7627 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7631 else if (coninfo->contype == 'c' && tbinfo == NULL)
7633 /* CHECK constraint on a domain */
7634 TypeInfo *tinfo = coninfo->condomain;
7636 /* Ignore if not to be dumped separately */
7637 if (coninfo->separate)
7639 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
7640 fmtId(tinfo->dobj.name));
7641 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
7642 fmtId(coninfo->dobj.name),
7646 * DROP must be fully qualified in case same name appears in
7649 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
7650 fmtId(tinfo->dobj.namespace->dobj.name));
7651 appendPQExpBuffer(delq, "%s ",
7652 fmtId(tinfo->dobj.name));
7653 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7654 fmtId(coninfo->dobj.name));
7656 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7658 tinfo->dobj.namespace->dobj.name,
7660 tinfo->rolname, false,
7661 "CHECK CONSTRAINT", q->data, delq->data, NULL,
7662 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7668 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
7672 /* Dump Constraint Comments --- only works for table constraints */
7673 if (tbinfo && coninfo->separate)
7674 dumpTableConstraintComment(fout, coninfo);
7676 destroyPQExpBuffer(q);
7677 destroyPQExpBuffer(delq);
7681 * dumpTableConstraintComment --- dump a constraint's comment if any
7683 * This is split out because we need the function in two different places
7684 * depending on whether the constraint is dumped as part of CREATE TABLE
7685 * or as a separate ALTER command.
7688 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
7690 TableInfo *tbinfo = coninfo->contable;
7691 PQExpBuffer q = createPQExpBuffer();
7693 appendPQExpBuffer(q, "CONSTRAINT %s ",
7694 fmtId(coninfo->dobj.name));
7695 appendPQExpBuffer(q, "ON %s",
7696 fmtId(tbinfo->dobj.name));
7697 dumpComment(fout, q->data,
7698 tbinfo->dobj.namespace->dobj.name,
7700 coninfo->dobj.catId, 0,
7701 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
7703 destroyPQExpBuffer(q);
7707 * findLastBuiltInOid -
7708 * find the last built in oid
7710 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
7711 * pg_database entry for the current database
7714 findLastBuiltinOid_V71(const char *dbname)
7719 PQExpBuffer query = createPQExpBuffer();
7721 resetPQExpBuffer(query);
7722 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
7723 appendStringLiteral(query, dbname, true);
7725 res = PQexec(g_conn, query->data);
7726 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7728 ntups = PQntuples(res);
7731 write_msg(NULL, "missing pg_database entry for this database\n");
7736 write_msg(NULL, "found more than one pg_database entry for this database\n");
7739 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
7741 destroyPQExpBuffer(query);
7746 * findLastBuiltInOid -
7747 * find the last built in oid
7749 * For 7.0, we do this by assuming that the last thing that initdb does is to
7750 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
7751 * initdb won't be changing anymore, it'll do.
7754 findLastBuiltinOid_V70(void)
7760 res = PQexec(g_conn,
7761 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
7762 check_sql_result(res, g_conn,
7763 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
7765 ntups = PQntuples(res);
7768 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
7773 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
7776 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
7782 dumpSequence(Archive *fout, TableInfo *tbinfo)
7794 PQExpBuffer query = createPQExpBuffer();
7795 PQExpBuffer delqry = createPQExpBuffer();
7797 /* Make sure we are in proper schema */
7798 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7800 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
7801 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
7803 appendPQExpBuffer(query,
7804 "SELECT sequence_name, last_value, increment_by, "
7805 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
7806 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
7808 "END AS max_value, "
7809 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
7810 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
7812 "END AS min_value, "
7813 "cache_value, is_cycled, is_called from %s",
7815 fmtId(tbinfo->dobj.name));
7817 res = PQexec(g_conn, query->data);
7818 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7820 if (PQntuples(res) != 1)
7822 write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
7823 tbinfo->dobj.name, PQntuples(res));
7827 /* Disable this check: it fails if sequence has been renamed */
7829 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
7831 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
7832 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
7837 last = PQgetvalue(res, 0, 1);
7838 incby = PQgetvalue(res, 0, 2);
7839 if (!PQgetisnull(res, 0, 3))
7840 maxv = PQgetvalue(res, 0, 3);
7841 if (!PQgetisnull(res, 0, 4))
7842 minv = PQgetvalue(res, 0, 4);
7843 cache = PQgetvalue(res, 0, 5);
7844 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
7845 called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
7848 * The logic we use for restoring sequences is as follows:
7850 * Add a basic CREATE SEQUENCE statement (use last_val for start if called
7851 * is false, else use min_val for start_val). Skip this if the sequence
7852 * came from a SERIAL column.
7854 * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
7855 * data. We do this for serial sequences too.
7858 if (!dataOnly && !OidIsValid(tbinfo->owning_tab))
7860 resetPQExpBuffer(delqry);
7863 * DROP must be fully qualified in case same name appears in
7866 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
7867 fmtId(tbinfo->dobj.namespace->dobj.name));
7868 appendPQExpBuffer(delqry, "%s;\n",
7869 fmtId(tbinfo->dobj.name));
7871 resetPQExpBuffer(query);
7872 appendPQExpBuffer(query,
7873 "CREATE SEQUENCE %s\n",
7874 fmtId(tbinfo->dobj.name));
7877 appendPQExpBuffer(query, " START WITH %s\n", last);
7879 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
7882 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
7884 appendPQExpBuffer(query, " NO MAXVALUE\n");
7887 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
7889 appendPQExpBuffer(query, " NO MINVALUE\n");
7891 appendPQExpBuffer(query,
7893 cache, (cycled ? "\n CYCLE" : ""));
7895 appendPQExpBuffer(query, ";\n");
7897 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7899 tbinfo->dobj.namespace->dobj.name,
7902 false, "SEQUENCE", query->data, delqry->data, NULL,
7903 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7909 TableInfo *owning_tab;
7911 resetPQExpBuffer(query);
7912 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
7915 * If this is a SERIAL sequence, then use the pg_get_serial_sequence
7916 * function to avoid hard-coding the sequence name. Note that this
7917 * implicitly assumes that the sequence and its owning table are in
7918 * the same schema, because we don't schema-qualify the reference.
7920 if (OidIsValid(tbinfo->owning_tab) &&
7921 (owning_tab = findTableByOid(tbinfo->owning_tab)) != NULL)
7923 appendPQExpBuffer(query, "pg_catalog.pg_get_serial_sequence(");
7924 appendStringLiteral(query, fmtId(owning_tab->dobj.name), true);
7925 appendPQExpBuffer(query, ", ");
7926 appendStringLiteral(query, owning_tab->attnames[tbinfo->owning_col - 1], true);
7927 appendPQExpBuffer(query, ")");
7930 appendStringLiteral(query, fmtId(tbinfo->dobj.name), true);
7931 appendPQExpBuffer(query, ", %s, %s);\n",
7932 last, (called ? "true" : "false"));
7934 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7936 tbinfo->dobj.namespace->dobj.name,
7939 false, "SEQUENCE SET", query->data, "", NULL,
7940 &(tbinfo->dobj.dumpId), 1,
7946 /* Dump Sequence Comments */
7947 resetPQExpBuffer(query);
7948 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
7949 dumpComment(fout, query->data,
7950 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
7951 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
7956 destroyPQExpBuffer(query);
7957 destroyPQExpBuffer(delqry);
7961 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
7963 TableInfo *tbinfo = tginfo->tgtable;
7972 query = createPQExpBuffer();
7973 delqry = createPQExpBuffer();
7976 * DROP must be fully qualified in case same name appears in pg_catalog
7978 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
7979 fmtId(tginfo->dobj.name));
7980 appendPQExpBuffer(delqry, "ON %s.",
7981 fmtId(tbinfo->dobj.namespace->dobj.name));
7982 appendPQExpBuffer(delqry, "%s;\n",
7983 fmtId(tbinfo->dobj.name));
7985 if (tginfo->tgisconstraint)
7987 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
7988 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
7992 appendPQExpBuffer(query, "CREATE TRIGGER ");
7993 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
7995 appendPQExpBuffer(query, "\n ");
7999 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
8000 appendPQExpBuffer(query, "BEFORE");
8002 appendPQExpBuffer(query, "AFTER");
8003 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
8005 appendPQExpBuffer(query, " INSERT");
8008 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
8011 appendPQExpBuffer(query, " OR DELETE");
8013 appendPQExpBuffer(query, " DELETE");
8016 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
8019 appendPQExpBuffer(query, " OR UPDATE");
8021 appendPQExpBuffer(query, " UPDATE");
8023 appendPQExpBuffer(query, " ON %s\n",
8024 fmtId(tbinfo->dobj.name));
8026 if (tginfo->tgisconstraint)
8028 if (OidIsValid(tginfo->tgconstrrelid))
8030 /* If we are using regclass, name is already quoted */
8031 if (g_fout->remoteVersion >= 70300)
8032 appendPQExpBuffer(query, " FROM %s\n ",
8033 tginfo->tgconstrrelname);
8035 appendPQExpBuffer(query, " FROM %s\n ",
8036 fmtId(tginfo->tgconstrrelname));
8038 if (!tginfo->tgdeferrable)
8039 appendPQExpBuffer(query, "NOT ");
8040 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
8041 if (tginfo->tginitdeferred)
8042 appendPQExpBuffer(query, "DEFERRED\n");
8044 appendPQExpBuffer(query, "IMMEDIATE\n");
8047 if (TRIGGER_FOR_ROW(tginfo->tgtype))
8048 appendPQExpBuffer(query, " FOR EACH ROW\n ");
8050 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
8052 /* In 7.3, result of regproc is already quoted */
8053 if (g_fout->remoteVersion >= 70300)
8054 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
8057 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
8058 fmtId(tginfo->tgfname));
8061 for (findx = 0; findx < tginfo->tgnargs; findx++)
8066 /* Set 'p' to end of arg string. marked by '\000' */
8069 p = strchr(p, '\\');
8072 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
8079 if (*p == '\\') /* is it '\\'? */
8084 if (p[0] == '0' && p[1] == '0' && p[2] == '0') /* is it '\000'? */
8092 appendPQExpBufferChar(query, ESCAPE_STRING_SYNTAX);
8096 appendPQExpBufferChar(query, '\'');
8099 if (*s == '\'') /* bytea already doubles backslashes */
8100 appendPQExpBufferChar(query, '\'');
8101 appendPQExpBufferChar(query, *s++);
8103 appendPQExpBufferChar(query, '\'');
8104 appendPQExpBuffer(query,
8105 (findx < tginfo->tgnargs - 1) ? ", " : "");
8108 appendPQExpBuffer(query, ");\n");
8110 if (!tginfo->tgenabled)
8112 appendPQExpBuffer(query, "\nALTER TABLE %s ",
8113 fmtId(tbinfo->dobj.name));
8114 appendPQExpBuffer(query, "DISABLE TRIGGER %s;\n",
8115 fmtId(tginfo->dobj.name));
8118 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
8120 tbinfo->dobj.namespace->dobj.name,
8122 tbinfo->rolname, false,
8123 "TRIGGER", query->data, delqry->data, NULL,
8124 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
8127 resetPQExpBuffer(query);
8128 appendPQExpBuffer(query, "TRIGGER %s ",
8129 fmtId(tginfo->dobj.name));
8130 appendPQExpBuffer(query, "ON %s",
8131 fmtId(tbinfo->dobj.name));
8133 dumpComment(fout, query->data,
8134 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
8135 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
8137 destroyPQExpBuffer(query);
8138 destroyPQExpBuffer(delqry);
8146 dumpRule(Archive *fout, RuleInfo *rinfo)
8148 TableInfo *tbinfo = rinfo->ruletable;
8154 /* Skip if not to be dumped */
8155 if (!rinfo->dobj.dump || dataOnly)
8159 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
8160 * we do not want to dump it as a separate object.
8162 if (!rinfo->separate)
8166 * Make sure we are in proper schema.
8168 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
8170 query = createPQExpBuffer();
8171 cmd = createPQExpBuffer();
8172 delcmd = createPQExpBuffer();
8174 if (g_fout->remoteVersion >= 70300)
8176 appendPQExpBuffer(query,
8177 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
8178 rinfo->dobj.catId.oid);
8182 /* Rule name was unique before 7.3 ... */
8183 appendPQExpBuffer(query,
8184 "SELECT pg_get_ruledef('%s') AS definition",
8188 res = PQexec(g_conn, query->data);
8189 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8191 if (PQntuples(res) != 1)
8193 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
8194 rinfo->dobj.name, tbinfo->dobj.name);
8198 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
8201 * DROP must be fully qualified in case same name appears in pg_catalog
8203 appendPQExpBuffer(delcmd, "DROP RULE %s ",
8204 fmtId(rinfo->dobj.name));
8205 appendPQExpBuffer(delcmd, "ON %s.",
8206 fmtId(tbinfo->dobj.namespace->dobj.name));
8207 appendPQExpBuffer(delcmd, "%s;\n",
8208 fmtId(tbinfo->dobj.name));
8210 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
8212 tbinfo->dobj.namespace->dobj.name,
8214 tbinfo->rolname, false,
8215 "RULE", cmd->data, delcmd->data, NULL,
8216 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
8219 /* Dump rule comments */
8220 resetPQExpBuffer(query);
8221 appendPQExpBuffer(query, "RULE %s",
8222 fmtId(rinfo->dobj.name));
8223 appendPQExpBuffer(query, " ON %s",
8224 fmtId(tbinfo->dobj.name));
8225 dumpComment(fout, query->data,
8226 tbinfo->dobj.namespace->dobj.name,
8228 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
8232 destroyPQExpBuffer(query);
8233 destroyPQExpBuffer(cmd);
8234 destroyPQExpBuffer(delcmd);
8238 * getDependencies --- obtain available dependency data
8241 getDependencies(void)
8252 DumpableObject *dobj,
8255 /* No dependency info available before 7.3 */
8256 if (g_fout->remoteVersion < 70300)
8260 write_msg(NULL, "reading dependency data\n");
8262 /* Make sure we are in proper schema */
8263 selectSourceSchema("pg_catalog");
8265 query = createPQExpBuffer();
8267 appendPQExpBuffer(query, "SELECT "
8268 "classid, objid, refclassid, refobjid, deptype "
8270 "WHERE deptype != 'p' "
8273 res = PQexec(g_conn, query->data);
8274 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8276 ntups = PQntuples(res);
8278 i_classid = PQfnumber(res, "classid");
8279 i_objid = PQfnumber(res, "objid");
8280 i_refclassid = PQfnumber(res, "refclassid");
8281 i_refobjid = PQfnumber(res, "refobjid");
8282 i_deptype = PQfnumber(res, "deptype");
8285 * Since we ordered the SELECT by referencing ID, we can expect that
8286 * multiple entries for the same object will appear together; this saves
8291 for (i = 0; i < ntups; i++)
8297 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
8298 objId.oid = atooid(PQgetvalue(res, i, i_objid));
8299 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
8300 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
8301 deptype = *(PQgetvalue(res, i, i_deptype));
8304 dobj->catId.tableoid != objId.tableoid ||
8305 dobj->catId.oid != objId.oid)
8306 dobj = findObjectByCatalogId(objId);
8309 * Failure to find objects mentioned in pg_depend is not unexpected,
8310 * since for example we don't collect info about TOAST tables.
8315 fprintf(stderr, "no referencing object %u %u\n",
8316 objId.tableoid, objId.oid);
8321 refdobj = findObjectByCatalogId(refobjId);
8323 if (refdobj == NULL)
8326 fprintf(stderr, "no referenced object %u %u\n",
8327 refobjId.tableoid, refobjId.oid);
8333 * Ordinarily, table rowtypes have implicit dependencies on their
8334 * tables. However, for a composite type the implicit dependency goes
8335 * the other way in pg_depend; which is the right thing for DROP but
8336 * it doesn't produce the dependency ordering we need. So in that one
8337 * case, we reverse the direction of the dependency.
8339 if (deptype == 'i' &&
8340 dobj->objType == DO_TABLE &&
8341 refdobj->objType == DO_TYPE)
8342 addObjectDependency(refdobj, dobj->dumpId);
8345 addObjectDependency(dobj, refdobj->dumpId);
8350 destroyPQExpBuffer(query);
8355 * selectSourceSchema - make the specified schema the active search path
8356 * in the source database.
8358 * NB: pg_catalog is explicitly searched after the specified schema;
8359 * so user names are only qualified if they are cross-schema references,
8360 * and system names are only qualified if they conflict with a user name
8361 * in the current schema.
8363 * Whenever the selected schema is not pg_catalog, be careful to qualify
8364 * references to system catalogs and types in our emitted commands!
8367 selectSourceSchema(const char *schemaName)
8369 static char *curSchemaName = NULL;
8372 /* Not relevant if fetching from pre-7.3 DB */
8373 if (g_fout->remoteVersion < 70300)
8375 /* Ignore null schema names */
8376 if (schemaName == NULL || *schemaName == '\0')
8378 /* Optimize away repeated selection of same schema */
8379 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
8382 query = createPQExpBuffer();
8383 appendPQExpBuffer(query, "SET search_path = %s",
8385 if (strcmp(schemaName, "pg_catalog") != 0)
8386 appendPQExpBuffer(query, ", pg_catalog");
8388 do_sql_command(g_conn, query->data);
8390 destroyPQExpBuffer(query);
8392 free(curSchemaName);
8393 curSchemaName = strdup(schemaName);
8397 * getFormattedTypeName - retrieve a nicely-formatted type name for the
8400 * NB: in 7.3 and up the result may depend on the currently-selected
8401 * schema; this is why we don't try to cache the names.
8404 getFormattedTypeName(Oid oid, OidOptions opts)
8413 if ((opts & zeroAsOpaque) != 0)
8414 return strdup(g_opaque_type);
8415 else if ((opts & zeroAsAny) != 0)
8416 return strdup("'any'");
8417 else if ((opts & zeroAsStar) != 0)
8419 else if ((opts & zeroAsNone) != 0)
8420 return strdup("NONE");
8423 query = createPQExpBuffer();
8424 if (g_fout->remoteVersion >= 70300)
8426 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
8429 else if (g_fout->remoteVersion >= 70100)
8431 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
8436 appendPQExpBuffer(query, "SELECT typname "
8438 "WHERE oid = '%u'::oid",
8442 res = PQexec(g_conn, query->data);
8443 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8445 /* Expecting a single result only */
8446 ntups = PQntuples(res);
8449 write_msg(NULL, "query yielded %d rows instead of one: %s\n",
8450 ntups, query->data);
8454 if (g_fout->remoteVersion >= 70100)
8456 /* already quoted */
8457 result = strdup(PQgetvalue(res, 0, 0));
8461 /* may need to quote it */
8462 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
8466 destroyPQExpBuffer(query);
8472 * myFormatType --- local implementation of format_type for use with 7.0.
8475 myFormatType(const char *typname, int32 typmod)
8478 bool isarray = false;
8479 PQExpBuffer buf = createPQExpBuffer();
8481 /* Handle array types */
8482 if (typname[0] == '_')
8488 /* Show lengths on bpchar and varchar */
8489 if (!strcmp(typname, "bpchar"))
8491 int len = (typmod - VARHDRSZ);
8493 appendPQExpBuffer(buf, "character");
8495 appendPQExpBuffer(buf, "(%d)",
8498 else if (!strcmp(typname, "varchar"))
8500 appendPQExpBuffer(buf, "character varying");
8502 appendPQExpBuffer(buf, "(%d)",
8505 else if (!strcmp(typname, "numeric"))
8507 appendPQExpBuffer(buf, "numeric");
8514 tmp_typmod = typmod - VARHDRSZ;
8515 precision = (tmp_typmod >> 16) & 0xffff;
8516 scale = tmp_typmod & 0xffff;
8517 appendPQExpBuffer(buf, "(%d,%d)",
8523 * char is an internal single-byte data type; Let's make sure we force it
8524 * through with quotes. - thomas 1998-12-13
8526 else if (strcmp(typname, "char") == 0)
8527 appendPQExpBuffer(buf, "\"char\"");
8529 appendPQExpBuffer(buf, "%s", fmtId(typname));
8531 /* Append array qualifier for array types */
8533 appendPQExpBuffer(buf, "[]");
8535 result = strdup(buf->data);
8536 destroyPQExpBuffer(buf);
8542 * fmtQualifiedId - convert a qualified name to the proper format for
8543 * the source database.
8545 * Like fmtId, use the result before calling again.
8548 fmtQualifiedId(const char *schema, const char *id)
8550 static PQExpBuffer id_return = NULL;
8552 if (id_return) /* first time through? */
8553 resetPQExpBuffer(id_return);
8555 id_return = createPQExpBuffer();
8557 /* Suppress schema name if fetching from pre-7.3 DB */
8558 if (g_fout->remoteVersion >= 70300 && schema && *schema)
8560 appendPQExpBuffer(id_return, "%s.",
8563 appendPQExpBuffer(id_return, "%s",
8566 return id_return->data;
8570 * Return a column list clause for the given relation.
8572 * Special case: if there are no undropped columns in the relation, return
8573 * "", not an invalid "()" column list.
8576 fmtCopyColumnList(const TableInfo *ti)
8578 static PQExpBuffer q = NULL;
8579 int numatts = ti->numatts;
8580 char **attnames = ti->attnames;
8581 bool *attisdropped = ti->attisdropped;
8585 if (q) /* first time through? */
8586 resetPQExpBuffer(q);
8588 q = createPQExpBuffer();
8590 appendPQExpBuffer(q, "(");
8592 for (i = 0; i < numatts; i++)
8594 if (attisdropped[i])
8597 appendPQExpBuffer(q, ", ");
8598 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
8603 return ""; /* no undropped columns */
8605 appendPQExpBuffer(q, ")");
8610 * Convenience subroutine to execute a SQL command and check for
8611 * COMMAND_OK status.
8614 do_sql_command(PGconn *conn, const char *query)
8618 res = PQexec(conn, query);
8619 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
8624 * Convenience subroutine to verify a SQL command succeeded,
8625 * and exit with a useful error message if not.
8628 check_sql_result(PGresult *res, PGconn *conn, const char *query,
8629 ExecStatusType expected)
8633 if (res && PQresultStatus(res) == expected)
8636 write_msg(NULL, "SQL command failed\n");
8638 err = PQresultErrorMessage(res);
8640 err = PQerrorMessage(conn);
8641 write_msg(NULL, "Error message from server: %s", err);
8642 write_msg(NULL, "The command was: %s\n", query);