1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2012, 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
14 * Note that pg_dump runs in a transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to run on
18 * SnapshotNow time, ie they look at the currently committed state. So
19 * it is possible to get 'cache lookup failed' error if someone
20 * performs DDL changes while a dump is happening. The window for this
21 * sort of thing is from the acquisition of the transaction snapshot to
22 * getSchemaData() (when pg_dump acquires AccessShareLock on every
23 * table it intends to dump). It isn't very large, but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
33 #include "postgres_fe.h"
44 #include "getopt_long.h"
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_largeobject.h"
53 #include "catalog/pg_largeobject_metadata.h"
54 #include "catalog/pg_proc.h"
55 #include "catalog/pg_trigger.h"
56 #include "catalog/pg_type.h"
57 #include "libpq/libpq-fs.h"
59 #include "pg_backup_archiver.h"
60 #include "pg_backup_db.h"
62 #include "dumputils.h"
71 const char *descr; /* comment for an object */
72 Oid classoid; /* object class (catalog OID) */
73 Oid objoid; /* object OID */
74 int objsubid; /* subobject (table column #) */
79 const char *provider; /* label provider of this security label */
80 const char *label; /* security label for an object */
81 Oid classoid; /* object class (catalog OID) */
82 Oid objoid; /* object OID */
83 int objsubid; /* subobject (table column #) */
87 bool g_verbose; /* User wants verbose narration of our
90 /* various user-settable parameters */
93 int dumpSections; /* bitmask of chosen sections */
95 const char *lockWaitTimeout;
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
100 /* obsolete as of 7.3: */
101 static Oid g_last_builtin_oid; /* value of the last builtin oid */
104 * Object inclusion/exclusion lists
106 * The string lists record the patterns given by command-line switches,
107 * which we then convert to lists of OIDs of matching objects.
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
124 char g_opaque_type[10]; /* name for the opaque type */
126 /* placeholders for the delimiters for comments */
127 char g_comment_start[10];
128 char g_comment_end[10];
130 static const CatalogId nilCatalogId = {0, 0};
132 /* flags for various command-line long options */
133 static int binary_upgrade = 0;
134 static int disable_dollar_quoting = 0;
135 static int dump_inserts = 0;
136 static int column_inserts = 0;
137 static int no_security_labels = 0;
138 static int no_unlogged_table_data = 0;
139 static int serializable_deferrable = 0;
142 static void help(const char *progname);
143 static void setup_connection(Archive *AH, const char *dumpencoding,
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(Archive *fout,
147 SimpleStringList *patterns,
148 SimpleOidList *oids);
149 static void expand_table_name_patterns(Archive *fout,
150 SimpleStringList *patterns,
151 SimpleOidList *oids);
152 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
153 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
154 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
155 static void dumpComment(Archive *fout, const char *target,
156 const char *namespace, const char *owner,
157 CatalogId catalogId, int subid, DumpId dumpId);
158 static int findComments(Archive *fout, Oid classoid, Oid objoid,
159 CommentItem **items);
160 static int collectComments(Archive *fout, CommentItem **items);
161 static void dumpSecLabel(Archive *fout, const char *target,
162 const char *namespace, const char *owner,
163 CatalogId catalogId, int subid, DumpId dumpId);
164 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
165 SecLabelItem **items);
166 static int collectSecLabels(Archive *fout, SecLabelItem **items);
167 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
168 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
169 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
170 static void dumpType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
175 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
177 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
178 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
179 static void dumpFunc(Archive *fout, FuncInfo *finfo);
180 static void dumpCast(Archive *fout, CastInfo *cast);
181 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *convinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpTable(Archive *fout, TableInfo *tbinfo);
190 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
191 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
192 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
193 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
194 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
195 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
196 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
197 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
198 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
199 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
200 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
201 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
202 static void dumpUserMappings(Archive *fout,
203 const char *servername, const char *namespace,
204 const char *owner, CatalogId catalogId, DumpId dumpId);
205 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
207 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
208 const char *type, const char *name, const char *subname,
209 const char *tag, const char *nspname, const char *owner,
212 static void getDependencies(Archive *fout);
213 static void BuildArchiveDependencies(Archive *fout);
214 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
215 DumpId **dependencies, int *nDeps, int *allocDeps);
217 static DumpableObject *createBoundaryObjects(void);
218 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
219 DumpableObject *boundaryObjs);
221 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
222 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
223 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
224 static void getTableDataFKConstraints(void);
225 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
226 static char *format_function_arguments_old(Archive *fout,
227 FuncInfo *finfo, int nallargs,
231 static char *format_function_signature(Archive *fout,
232 FuncInfo *finfo, bool honor_quotes);
233 static const char *convertRegProcReference(Archive *fout,
235 static const char *convertOperatorReference(Archive *fout, const char *opr);
236 static const char *convertTSFunction(Archive *fout, Oid funcOid);
237 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
238 static Oid findLastBuiltinOid_V70(Archive *fout);
239 static void selectSourceSchema(Archive *fout, const char *schemaName);
240 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
241 static char *myFormatType(const char *typname, int32 typmod);
242 static const char *fmtQualifiedId(Archive *fout,
243 const char *schema, const char *id);
244 static void getBlobs(Archive *fout);
245 static void dumpBlob(Archive *fout, BlobInfo *binfo);
246 static int dumpBlobs(Archive *fout, void *arg);
247 static void dumpDatabase(Archive *AH);
248 static void dumpEncoding(Archive *AH);
249 static void dumpStdStrings(Archive *AH);
250 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
251 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
252 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
253 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
254 static void binary_upgrade_set_pg_class_oids(Archive *fout,
255 PQExpBuffer upgrade_buffer,
256 Oid pg_class_oid, bool is_index);
257 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
258 DumpableObject *dobj,
259 const char *objlabel);
260 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
261 static const char *fmtCopyColumnList(const TableInfo *ti);
262 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
266 main(int argc, char **argv)
269 const char *filename = NULL;
270 const char *format = "p";
271 const char *dbname = NULL;
272 const char *pghost = NULL;
273 const char *pgport = NULL;
274 const char *username = NULL;
275 const char *dumpencoding = NULL;
279 DumpableObject **dobjs;
281 DumpableObject *boundaryObjs;
283 enum trivalue prompt_password = TRI_DEFAULT;
284 int compressLevel = -1;
287 int outputCreateDB = 0;
288 bool outputBlobs = false;
289 int outputNoOwner = 0;
290 char *outputSuperuser = NULL;
291 char *use_role = NULL;
294 RestoreOptions *ropt;
295 ArchiveFormat archiveFormat = archUnknown;
296 ArchiveMode archiveMode;
297 Archive *fout; /* the script file */
299 static int disable_triggers = 0;
300 static int outputNoTablespaces = 0;
301 static int use_setsessauth = 0;
303 static struct option long_options[] = {
304 {"data-only", no_argument, NULL, 'a'},
305 {"blobs", no_argument, NULL, 'b'},
306 {"clean", no_argument, NULL, 'c'},
307 {"create", no_argument, NULL, 'C'},
308 {"file", required_argument, NULL, 'f'},
309 {"format", required_argument, NULL, 'F'},
310 {"host", required_argument, NULL, 'h'},
311 {"ignore-version", no_argument, NULL, 'i'},
312 {"no-reconnect", no_argument, NULL, 'R'},
313 {"oids", no_argument, NULL, 'o'},
314 {"no-owner", no_argument, NULL, 'O'},
315 {"port", required_argument, NULL, 'p'},
316 {"schema", required_argument, NULL, 'n'},
317 {"exclude-schema", required_argument, NULL, 'N'},
318 {"schema-only", no_argument, NULL, 's'},
319 {"superuser", required_argument, NULL, 'S'},
320 {"table", required_argument, NULL, 't'},
321 {"exclude-table", required_argument, NULL, 'T'},
322 {"no-password", no_argument, NULL, 'w'},
323 {"password", no_argument, NULL, 'W'},
324 {"username", required_argument, NULL, 'U'},
325 {"verbose", no_argument, NULL, 'v'},
326 {"no-privileges", no_argument, NULL, 'x'},
327 {"no-acl", no_argument, NULL, 'x'},
328 {"compress", required_argument, NULL, 'Z'},
329 {"encoding", required_argument, NULL, 'E'},
330 {"help", no_argument, NULL, '?'},
331 {"version", no_argument, NULL, 'V'},
334 * the following options don't have an equivalent short option letter
336 {"attribute-inserts", no_argument, &column_inserts, 1},
337 {"binary-upgrade", no_argument, &binary_upgrade, 1},
338 {"column-inserts", no_argument, &column_inserts, 1},
339 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
340 {"disable-triggers", no_argument, &disable_triggers, 1},
341 {"exclude-table-data", required_argument, NULL, 4},
342 {"inserts", no_argument, &dump_inserts, 1},
343 {"lock-wait-timeout", required_argument, NULL, 2},
344 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
345 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
346 {"role", required_argument, NULL, 3},
347 {"section", required_argument, NULL, 5},
348 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
349 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
350 {"no-security-labels", no_argument, &no_security_labels, 1},
351 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
356 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
360 strcpy(g_comment_start, "-- ");
361 g_comment_end[0] = '\0';
362 strcpy(g_opaque_type, "opaque");
364 dataOnly = schemaOnly = false;
365 dumpSections = DUMP_UNSECTIONED;
366 lockWaitTimeout = NULL;
368 progname = get_progname(argv[0]);
370 /* Set default options based on progname */
371 if (strcmp(progname, "pg_backup") == 0)
376 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
381 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
383 puts("pg_dump (PostgreSQL) " PG_VERSION);
388 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
389 long_options, &optindex)) != -1)
393 case 'a': /* Dump data only */
397 case 'b': /* Dump blobs */
401 case 'c': /* clean (i.e., drop) schema prior to create */
405 case 'C': /* Create DB */
409 case 'E': /* Dump encoding */
410 dumpencoding = optarg;
421 case 'h': /* server host */
426 /* ignored, deprecated option */
429 case 'n': /* include schema(s) */
430 simple_string_list_append(&schema_include_patterns, optarg);
431 include_everything = false;
434 case 'N': /* exclude schema(s) */
435 simple_string_list_append(&schema_exclude_patterns, optarg);
438 case 'o': /* Dump oids */
442 case 'O': /* Don't reconnect to match owner */
446 case 'p': /* server port */
451 /* no-op, still accepted for backwards compatibility */
454 case 's': /* dump schema only */
458 case 'S': /* Username for superuser in plain text output */
459 outputSuperuser = pg_strdup(optarg);
462 case 't': /* include table(s) */
463 simple_string_list_append(&table_include_patterns, optarg);
464 include_everything = false;
467 case 'T': /* exclude table(s) */
468 simple_string_list_append(&table_exclude_patterns, optarg);
475 case 'v': /* verbose */
480 prompt_password = TRI_NO;
484 prompt_password = TRI_YES;
487 case 'x': /* skip ACL dump */
491 case 'Z': /* Compression Level */
492 compressLevel = atoi(optarg);
496 /* This covers the long options. */
499 case 2: /* lock-wait-timeout */
500 lockWaitTimeout = optarg;
503 case 3: /* SET ROLE */
507 case 4: /* exclude table(s) data */
508 simple_string_list_append(&tabledata_exclude_patterns, optarg);
511 case 5: /* section */
512 set_dump_section(optarg, &dumpSections);
516 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
521 /* Get database name from command line */
523 dbname = argv[optind++];
525 /* Complain if any arguments remain */
528 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
529 progname, argv[optind]);
530 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
535 /* --column-inserts implies --inserts */
539 if (dataOnly && schemaOnly)
540 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
542 if (dataOnly && outputClean)
543 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
545 if (dump_inserts && oids)
547 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
548 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
552 /* Identify archive format to emit */
553 archiveFormat = parseArchiveFormat(format, &archiveMode);
555 /* archiveFormat specific setup */
556 if (archiveFormat == archNull)
559 /* Custom and directory formats are compressed by default, others not */
560 if (compressLevel == -1)
562 if (archiveFormat == archCustom || archiveFormat == archDirectory)
563 compressLevel = Z_DEFAULT_COMPRESSION;
568 /* Open the output file */
569 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
571 /* Register the cleanup hook */
572 on_exit_close_archive(fout);
575 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
577 /* Let the archiver know how noisy to be */
578 fout->verbose = g_verbose;
580 my_version = parse_version(PG_VERSION);
582 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
585 * We allow the server to be back to 7.0, and up to any minor release of
586 * our own major version. (See also version check in pg_dumpall.c.)
588 fout->minRemoteVersion = 70000;
589 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
592 * Open the database using the Archiver, so it knows about it. Errors mean
595 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
596 setup_connection(fout, dumpencoding, use_role);
599 * Disable security label support if server version < v9.1.x (prevents
600 * access to nonexistent pg_seclabel catalog)
602 if (fout->remoteVersion < 90100)
603 no_security_labels = 1;
606 * Start transaction-snapshot mode transaction to dump consistent data.
608 ExecuteSqlStatement(fout, "BEGIN");
609 if (fout->remoteVersion >= 90100)
611 if (serializable_deferrable)
612 ExecuteSqlStatement(fout,
613 "SET TRANSACTION ISOLATION LEVEL "
614 "SERIALIZABLE, READ ONLY, DEFERRABLE");
616 ExecuteSqlStatement(fout,
617 "SET TRANSACTION ISOLATION LEVEL "
621 ExecuteSqlStatement(fout,
622 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
624 /* Select the appropriate subquery to convert user IDs to names */
625 if (fout->remoteVersion >= 80100)
626 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
627 else if (fout->remoteVersion >= 70300)
628 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
630 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
632 /* Find the last built-in OID, if needed */
633 if (fout->remoteVersion < 70300)
635 if (fout->remoteVersion >= 70100)
636 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
637 PQdb(GetConnection(fout)));
639 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
641 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
644 /* Expand schema selection patterns into OID lists */
645 if (schema_include_patterns.head != NULL)
647 expand_schema_name_patterns(fout, &schema_include_patterns,
648 &schema_include_oids);
649 if (schema_include_oids.head == NULL)
650 exit_horribly(NULL, "No matching schemas were found\n");
652 expand_schema_name_patterns(fout, &schema_exclude_patterns,
653 &schema_exclude_oids);
654 /* non-matching exclusion patterns aren't an error */
656 /* Expand table selection patterns into OID lists */
657 if (table_include_patterns.head != NULL)
659 expand_table_name_patterns(fout, &table_include_patterns,
660 &table_include_oids);
661 if (table_include_oids.head == NULL)
662 exit_horribly(NULL, "No matching tables were found\n");
664 expand_table_name_patterns(fout, &table_exclude_patterns,
665 &table_exclude_oids);
667 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
668 &tabledata_exclude_oids);
670 /* non-matching exclusion patterns aren't an error */
673 * Dumping blobs is now default unless we saw an inclusion switch or -s
674 * ... but even if we did see one of these, -b turns it back on.
676 if (include_everything && !schemaOnly)
680 * Now scan the database and create DumpableObject structs for all the
681 * objects we intend to dump.
683 tblinfo = getSchemaData(fout, &numTables);
685 if (fout->remoteVersion < 80400)
686 guessConstraintInheritance(tblinfo, numTables);
690 getTableData(tblinfo, numTables, oids);
692 getTableDataFKConstraints();
699 * Collect dependency data to assist in ordering the objects.
701 getDependencies(fout);
703 /* Lastly, create dummy objects to represent the section boundaries */
704 boundaryObjs = createBoundaryObjects();
706 /* Get pointers to all the known DumpableObjects */
707 getDumpableObjects(&dobjs, &numObjs);
710 * Add dummy dependencies to enforce the dump section ordering.
712 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
715 * Sort the objects into a safe dump order (no forward references).
717 * In 7.3 or later, we can rely on dependency information to help us
718 * determine a safe order, so the initial sort is mostly for cosmetic
719 * purposes: we sort by name to ensure that logically identical schemas
720 * will dump identically. Before 7.3 we don't have dependencies and we
721 * use OID ordering as an (unreliable) guide to creation order.
723 if (fout->remoteVersion >= 70300)
724 sortDumpableObjectsByTypeName(dobjs, numObjs);
726 sortDumpableObjectsByTypeOid(dobjs, numObjs);
728 sortDumpableObjects(dobjs, numObjs,
729 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
732 * Create archive TOC entries for all the objects to be dumped, in a safe
736 /* First the special ENCODING and STDSTRINGS entries. */
738 dumpStdStrings(fout);
740 /* The database item is always next, unless we don't want it at all */
741 if (include_everything && !dataOnly)
744 /* Now the rearrangeable objects. */
745 for (i = 0; i < numObjs; i++)
746 dumpDumpableObject(fout, dobjs[i]);
749 * Set up options info to ensure we dump what we want.
751 ropt = NewRestoreOptions();
752 ropt->filename = filename;
753 ropt->dropSchema = outputClean;
754 ropt->dataOnly = dataOnly;
755 ropt->schemaOnly = schemaOnly;
756 ropt->dumpSections = dumpSections;
757 ropt->aclsSkip = aclsSkip;
758 ropt->superuser = outputSuperuser;
759 ropt->createDB = outputCreateDB;
760 ropt->noOwner = outputNoOwner;
761 ropt->noTablespace = outputNoTablespaces;
762 ropt->disable_triggers = disable_triggers;
763 ropt->use_setsessauth = use_setsessauth;
765 if (compressLevel == -1)
766 ropt->compression = 0;
768 ropt->compression = compressLevel;
770 ropt->suppressDumpWarnings = true; /* We've already shown them */
772 SetArchiveRestoreOptions(fout, ropt);
775 * The archive's TOC entries are now marked as to which ones will
776 * actually be output, so we can set up their dependency lists properly.
777 * This isn't necessary for plain-text output, though.
780 BuildArchiveDependencies(fout);
783 * And finally we can do the actual output.
785 * Note: for non-plain-text output formats, the output file is written
786 * inside CloseArchive(). This is, um, bizarre; but not worth changing
790 RestoreArchive(fout);
799 help(const char *progname)
801 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
802 printf(_("Usage:\n"));
803 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
805 printf(_("\nGeneral options:\n"));
806 printf(_(" -f, --file=FILENAME output file or directory name\n"));
807 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
808 " plain text (default))\n"));
809 printf(_(" -v, --verbose verbose mode\n"));
810 printf(_(" -V, --version output version information, then exit\n"));
811 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
812 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
813 printf(_(" -?, --help show this help, then exit\n"));
815 printf(_("\nOptions controlling the output content:\n"));
816 printf(_(" -a, --data-only dump only the data, not the schema\n"));
817 printf(_(" -b, --blobs include large objects in dump\n"));
818 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
819 printf(_(" -C, --create include commands to create database in dump\n"));
820 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
821 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
822 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
823 printf(_(" -o, --oids include OIDs in dump\n"));
824 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
825 " plain-text format\n"));
826 printf(_(" -s, --schema-only dump only the schema, no data\n"));
827 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
828 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
829 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
830 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
831 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
832 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
833 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
834 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
835 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
836 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
837 printf(_(" --no-security-labels do not dump security label assignments\n"));
838 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
839 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
840 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
841 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
842 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
843 printf(_(" --use-set-session-authorization\n"
844 " use SET SESSION AUTHORIZATION commands instead of\n"
845 " ALTER OWNER commands to set ownership\n"));
847 printf(_("\nConnection options:\n"));
848 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
849 printf(_(" -p, --port=PORT database server port number\n"));
850 printf(_(" -U, --username=NAME connect as specified database user\n"));
851 printf(_(" -w, --no-password never prompt for password\n"));
852 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
853 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
855 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
856 "variable value is used.\n\n"));
857 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
861 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
863 PGconn *conn = GetConnection(AH);
864 const char *std_strings;
866 /* Set the client encoding if requested */
869 if (PQsetClientEncoding(conn, dumpencoding) < 0)
870 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
875 * Get the active encoding and the standard_conforming_strings setting, so
876 * we know how to escape strings.
878 AH->encoding = PQclientEncoding(conn);
880 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
881 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
883 /* Set the role if requested */
884 if (use_role && AH->remoteVersion >= 80100)
886 PQExpBuffer query = createPQExpBuffer();
888 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
889 ExecuteSqlStatement(AH, query->data);
890 destroyPQExpBuffer(query);
893 /* Set the datestyle to ISO to ensure the dump's portability */
894 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
896 /* Likewise, avoid using sql_standard intervalstyle */
897 if (AH->remoteVersion >= 80400)
898 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
901 * If supported, set extra_float_digits so that we can dump float data
902 * exactly (given correctly implemented float I/O code, anyway)
904 if (AH->remoteVersion >= 90000)
905 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
906 else if (AH->remoteVersion >= 70400)
907 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
910 * If synchronized scanning is supported, disable it, to prevent
911 * unpredictable changes in row ordering across a dump and reload.
913 if (AH->remoteVersion >= 80300)
914 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
917 * Disable timeouts if supported.
919 if (AH->remoteVersion >= 70300)
920 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
923 * Quote all identifiers, if requested.
925 if (quote_all_identifiers && AH->remoteVersion >= 90100)
926 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
930 parseArchiveFormat(const char *format, ArchiveMode *mode)
932 ArchiveFormat archiveFormat;
934 *mode = archModeWrite;
936 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
938 /* This is used by pg_dumpall, and is not documented */
939 archiveFormat = archNull;
940 *mode = archModeAppend;
942 else if (pg_strcasecmp(format, "c") == 0)
943 archiveFormat = archCustom;
944 else if (pg_strcasecmp(format, "custom") == 0)
945 archiveFormat = archCustom;
946 else if (pg_strcasecmp(format, "d") == 0)
947 archiveFormat = archDirectory;
948 else if (pg_strcasecmp(format, "directory") == 0)
949 archiveFormat = archDirectory;
950 else if (pg_strcasecmp(format, "p") == 0)
951 archiveFormat = archNull;
952 else if (pg_strcasecmp(format, "plain") == 0)
953 archiveFormat = archNull;
954 else if (pg_strcasecmp(format, "t") == 0)
955 archiveFormat = archTar;
956 else if (pg_strcasecmp(format, "tar") == 0)
957 archiveFormat = archTar;
959 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
960 return archiveFormat;
964 * Find the OIDs of all schemas matching the given list of patterns,
965 * and append them to the given OID list.
968 expand_schema_name_patterns(Archive *fout,
969 SimpleStringList *patterns,
974 SimpleStringListCell *cell;
977 if (patterns->head == NULL)
978 return; /* nothing to do */
980 if (fout->remoteVersion < 70300)
981 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
983 query = createPQExpBuffer();
986 * We use UNION ALL rather than UNION; this might sometimes result in
987 * duplicate entries in the OID list, but we don't care.
990 for (cell = patterns->head; cell; cell = cell->next)
992 if (cell != patterns->head)
993 appendPQExpBuffer(query, "UNION ALL\n");
994 appendPQExpBuffer(query,
995 "SELECT oid FROM pg_catalog.pg_namespace n\n");
996 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
997 false, NULL, "n.nspname", NULL, NULL);
1000 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1002 for (i = 0; i < PQntuples(res); i++)
1004 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1008 destroyPQExpBuffer(query);
1012 * Find the OIDs of all tables matching the given list of patterns,
1013 * and append them to the given OID list.
1016 expand_table_name_patterns(Archive *fout,
1017 SimpleStringList *patterns, SimpleOidList *oids)
1021 SimpleStringListCell *cell;
1024 if (patterns->head == NULL)
1025 return; /* nothing to do */
1027 query = createPQExpBuffer();
1030 * We use UNION ALL rather than UNION; this might sometimes result in
1031 * duplicate entries in the OID list, but we don't care.
1034 for (cell = patterns->head; cell; cell = cell->next)
1036 if (cell != patterns->head)
1037 appendPQExpBuffer(query, "UNION ALL\n");
1038 appendPQExpBuffer(query,
1040 "\nFROM pg_catalog.pg_class c"
1041 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1042 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1043 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1044 RELKIND_FOREIGN_TABLE);
1045 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1046 false, "n.nspname", "c.relname", NULL,
1047 "pg_catalog.pg_table_is_visible(c.oid)");
1050 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1052 for (i = 0; i < PQntuples(res); i++)
1054 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1058 destroyPQExpBuffer(query);
1062 * selectDumpableNamespace: policy-setting subroutine
1063 * Mark a namespace as to be dumped or not
1066 selectDumpableNamespace(NamespaceInfo *nsinfo)
1069 * If specific tables are being dumped, do not dump any complete
1070 * namespaces. If specific namespaces are being dumped, dump just those
1071 * namespaces. Otherwise, dump all non-system namespaces.
1073 if (table_include_oids.head != NULL)
1074 nsinfo->dobj.dump = false;
1075 else if (schema_include_oids.head != NULL)
1076 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1077 nsinfo->dobj.catId.oid);
1078 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1079 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1080 nsinfo->dobj.dump = false;
1082 nsinfo->dobj.dump = true;
1085 * In any case, a namespace can be excluded by an exclusion switch
1087 if (nsinfo->dobj.dump &&
1088 simple_oid_list_member(&schema_exclude_oids,
1089 nsinfo->dobj.catId.oid))
1090 nsinfo->dobj.dump = false;
1094 * selectDumpableTable: policy-setting subroutine
1095 * Mark a table as to be dumped or not
1098 selectDumpableTable(TableInfo *tbinfo)
1101 * If specific tables are being dumped, dump just those tables; else, dump
1102 * according to the parent namespace's dump flag.
1104 if (table_include_oids.head != NULL)
1105 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1106 tbinfo->dobj.catId.oid);
1108 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1111 * In any case, a table can be excluded by an exclusion switch
1113 if (tbinfo->dobj.dump &&
1114 simple_oid_list_member(&table_exclude_oids,
1115 tbinfo->dobj.catId.oid))
1116 tbinfo->dobj.dump = false;
1120 * selectDumpableType: policy-setting subroutine
1121 * Mark a type as to be dumped or not
1123 * If it's a table's rowtype or an autogenerated array type, we also apply a
1124 * special type code to facilitate sorting into the desired order. (We don't
1125 * want to consider those to be ordinary types because that would bring tables
1126 * up into the datatype part of the dump order.) We still set the object's
1127 * dump flag; that's not going to cause the dummy type to be dumped, but we
1128 * need it so that casts involving such types will be dumped correctly -- see
1129 * dumpCast. This means the flag should be set the same as for the underlying
1130 * object (the table or base type).
1133 selectDumpableType(TypeInfo *tyinfo)
1135 /* skip complex types, except for standalone composite types */
1136 if (OidIsValid(tyinfo->typrelid) &&
1137 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1139 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1141 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1142 if (tytable != NULL)
1143 tyinfo->dobj.dump = tytable->dobj.dump;
1145 tyinfo->dobj.dump = false;
1149 /* skip auto-generated array types */
1150 if (tyinfo->isArray)
1152 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1155 * Fall through to set the dump flag; we assume that the subsequent
1156 * rules will do the same thing as they would for the array's base
1157 * type. (We cannot reliably look up the base type here, since
1158 * getTypes may not have processed it yet.)
1162 /* dump only types in dumpable namespaces */
1163 if (!tyinfo->dobj.namespace->dobj.dump)
1164 tyinfo->dobj.dump = false;
1166 /* skip undefined placeholder types */
1167 else if (!tyinfo->isDefined)
1168 tyinfo->dobj.dump = false;
1171 tyinfo->dobj.dump = true;
1175 * selectDumpableDefaultACL: policy-setting subroutine
1176 * Mark a default ACL as to be dumped or not
1178 * For per-schema default ACLs, dump if the schema is to be dumped.
1179 * Otherwise dump if we are dumping "everything". Note that dataOnly
1180 * and aclsSkip are checked separately.
1183 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1185 if (dinfo->dobj.namespace)
1186 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1188 dinfo->dobj.dump = include_everything;
1192 * selectDumpableExtension: policy-setting subroutine
1193 * Mark an extension as to be dumped or not
1195 * Normally, we dump all extensions, or none of them if include_everything
1196 * is false (i.e., a --schema or --table switch was given). However, in
1197 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1198 * assume those will already be installed in the target database. We identify
1199 * such extensions by their having OIDs in the range reserved for initdb.
1202 selectDumpableExtension(ExtensionInfo *extinfo)
1204 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1205 extinfo->dobj.dump = false;
1207 extinfo->dobj.dump = include_everything;
1211 * selectDumpableObject: policy-setting subroutine
1212 * Mark a generic dumpable object as to be dumped or not
1214 * Use this only for object types without a special-case routine above.
1217 selectDumpableObject(DumpableObject *dobj)
1220 * Default policy is to dump if parent namespace is dumpable, or always
1221 * for non-namespace-associated items.
1223 if (dobj->namespace)
1224 dobj->dump = dobj->namespace->dobj.dump;
1230 * Dump a table's contents for loading using the COPY command
1231 * - this routine is called by the Archiver when it wants the table
1236 dumpTableData_copy(Archive *fout, void *dcontext)
1238 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1239 TableInfo *tbinfo = tdinfo->tdtable;
1240 const char *classname = tbinfo->dobj.name;
1241 const bool hasoids = tbinfo->hasoids;
1242 const bool oids = tdinfo->oids;
1243 PQExpBuffer q = createPQExpBuffer();
1244 PGconn *conn = GetConnection(fout);
1248 const char *column_list;
1251 write_msg(NULL, "dumping contents of table %s\n", classname);
1254 * Make sure we are in proper schema. We will qualify the table name
1255 * below anyway (in case its name conflicts with a pg_catalog table); but
1256 * this ensures reproducible results in case the table contains regproc,
1257 * regclass, etc columns.
1259 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1262 * If possible, specify the column list explicitly so that we have no
1263 * possibility of retrieving data in the wrong column order. (The default
1264 * column ordering of COPY will not be what we want in certain corner
1265 * cases involving ADD COLUMN and inheritance.)
1267 if (fout->remoteVersion >= 70300)
1268 column_list = fmtCopyColumnList(tbinfo);
1270 column_list = ""; /* can't select columns in COPY */
1272 if (oids && hasoids)
1274 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1275 fmtQualifiedId(fout,
1276 tbinfo->dobj.namespace->dobj.name,
1280 else if (tdinfo->filtercond)
1282 /* Note: this syntax is only supported in 8.2 and up */
1283 appendPQExpBufferStr(q, "COPY (SELECT ");
1284 /* klugery to get rid of parens in column list */
1285 if (strlen(column_list) > 2)
1287 appendPQExpBufferStr(q, column_list + 1);
1288 q->data[q->len - 1] = ' ';
1291 appendPQExpBufferStr(q, "* ");
1292 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1293 fmtQualifiedId(fout,
1294 tbinfo->dobj.namespace->dobj.name,
1296 tdinfo->filtercond);
1300 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1301 fmtQualifiedId(fout,
1302 tbinfo->dobj.namespace->dobj.name,
1306 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1311 ret = PQgetCopyData(conn, ©buf, 0);
1314 break; /* done or error */
1318 WriteData(fout, copybuf, ret);
1325 * There was considerable discussion in late July, 2000 regarding
1326 * slowing down pg_dump when backing up large tables. Users with both
1327 * slow & fast (multi-processor) machines experienced performance
1328 * degradation when doing a backup.
1330 * Initial attempts based on sleeping for a number of ms for each ms
1331 * of work were deemed too complex, then a simple 'sleep in each loop'
1332 * implementation was suggested. The latter failed because the loop
1333 * was too tight. Finally, the following was implemented:
1335 * If throttle is non-zero, then
1336 * See how long since the last sleep.
1337 * Work out how long to sleep (based on ratio).
1338 * If sleep is more than 100ms, then
1344 * where the throttle value was the number of ms to sleep per ms of
1345 * work. The calculation was done in each loop.
1347 * Most of the hard work is done in the backend, and this solution
1348 * still did not work particularly well: on slow machines, the ratio
1349 * was 50:1, and on medium paced machines, 1:1, and on fast
1350 * multi-processor machines, it had little or no effect, for reasons
1351 * that were unclear.
1353 * Further discussion ensued, and the proposal was dropped.
1355 * For those people who want this feature, it can be implemented using
1356 * gettimeofday in each loop, calculating the time since last sleep,
1357 * multiplying that by the sleep ratio, then if the result is more
1358 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1359 * function to sleep for a subsecond period ie.
1361 * select(0, NULL, NULL, NULL, &tvi);
1363 * This will return after the interval specified in the structure tvi.
1364 * Finally, call gettimeofday again to save the 'last sleep time'.
1368 archprintf(fout, "\\.\n\n\n");
1372 /* copy data transfer failed */
1373 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1374 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1375 write_msg(NULL, "The command was: %s\n", q->data);
1379 /* Check command status and return to normal libpq state */
1380 res = PQgetResult(conn);
1381 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1383 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1384 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1385 write_msg(NULL, "The command was: %s\n", q->data);
1390 destroyPQExpBuffer(q);
1395 * Dump table data using INSERT commands.
1397 * Caution: when we restore from an archive file direct to database, the
1398 * INSERT commands emitted by this function have to be parsed by
1399 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1400 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1403 dumpTableData_insert(Archive *fout, void *dcontext)
1405 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1406 TableInfo *tbinfo = tdinfo->tdtable;
1407 const char *classname = tbinfo->dobj.name;
1408 PQExpBuffer q = createPQExpBuffer();
1415 * Make sure we are in proper schema. We will qualify the table name
1416 * below anyway (in case its name conflicts with a pg_catalog table); but
1417 * this ensures reproducible results in case the table contains regproc,
1418 * regclass, etc columns.
1420 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1422 if (fout->remoteVersion >= 70100)
1424 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1425 "SELECT * FROM ONLY %s",
1426 fmtQualifiedId(fout,
1427 tbinfo->dobj.namespace->dobj.name,
1432 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1434 fmtQualifiedId(fout,
1435 tbinfo->dobj.namespace->dobj.name,
1438 if (tdinfo->filtercond)
1439 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1441 ExecuteSqlStatement(fout, q->data);
1445 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1447 nfields = PQnfields(res);
1448 for (tuple = 0; tuple < PQntuples(res); tuple++)
1450 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1453 /* corner case for zero-column table */
1454 archprintf(fout, "DEFAULT VALUES;\n");
1459 resetPQExpBuffer(q);
1460 appendPQExpBuffer(q, "(");
1461 for (field = 0; field < nfields; field++)
1464 appendPQExpBuffer(q, ", ");
1465 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1467 appendPQExpBuffer(q, ") ");
1468 archputs(q->data, fout);
1470 archprintf(fout, "VALUES (");
1471 for (field = 0; field < nfields; field++)
1474 archprintf(fout, ", ");
1475 if (PQgetisnull(res, tuple, field))
1477 archprintf(fout, "NULL");
1481 /* XXX This code is partially duplicated in ruleutils.c */
1482 switch (PQftype(res, field))
1493 * These types are printed without quotes unless
1494 * they contain values that aren't accepted by the
1495 * scanner unquoted (e.g., 'NaN'). Note that
1496 * strtod() and friends might accept NaN, so we
1497 * can't use that to test.
1499 * In reality we only need to defend against
1500 * infinity and NaN, so we need not get too crazy
1501 * about pattern matching here.
1503 const char *s = PQgetvalue(res, tuple, field);
1505 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1506 archprintf(fout, "%s", s);
1508 archprintf(fout, "'%s'", s);
1514 archprintf(fout, "B'%s'",
1515 PQgetvalue(res, tuple, field));
1519 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1520 archprintf(fout, "true");
1522 archprintf(fout, "false");
1526 /* All other types are printed as string literals. */
1527 resetPQExpBuffer(q);
1528 appendStringLiteralAH(q,
1529 PQgetvalue(res, tuple, field),
1531 archputs(q->data, fout);
1535 archprintf(fout, ");\n");
1538 if (PQntuples(res) <= 0)
1546 archprintf(fout, "\n\n");
1548 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1550 destroyPQExpBuffer(q);
1557 * dump the contents of a single table
1559 * Actually, this just makes an ArchiveEntry for the table contents.
1562 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1564 TableInfo *tbinfo = tdinfo->tdtable;
1565 PQExpBuffer copyBuf = createPQExpBuffer();
1566 DataDumperPtr dumpFn;
1571 /* Dump/restore using COPY */
1572 dumpFn = dumpTableData_copy;
1573 /* must use 2 steps here 'cause fmtId is nonreentrant */
1574 appendPQExpBuffer(copyBuf, "COPY %s ",
1575 fmtId(tbinfo->dobj.name));
1576 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1577 fmtCopyColumnList(tbinfo),
1578 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1579 copyStmt = copyBuf->data;
1583 /* Restore using INSERT */
1584 dumpFn = dumpTableData_insert;
1589 * Note: although the TableDataInfo is a full DumpableObject, we treat its
1590 * dependency on its table as "special" and pass it to ArchiveEntry now.
1591 * See comments for BuildArchiveDependencies.
1593 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1594 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1595 NULL, tbinfo->rolname,
1596 false, "TABLE DATA", SECTION_DATA,
1598 &(tbinfo->dobj.dumpId), 1,
1601 destroyPQExpBuffer(copyBuf);
1606 * set up dumpable objects representing the contents of tables
1609 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1613 for (i = 0; i < numTables; i++)
1615 if (tblinfo[i].dobj.dump)
1616 makeTableDataInfo(&(tblinfo[i]), oids);
1621 * Make a dumpable object for the data of this specific table
1623 * Note: we make a TableDataInfo if and only if we are going to dump the
1624 * table data; the "dump" flag in such objects isn't used.
1627 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1629 TableDataInfo *tdinfo;
1632 * Nothing to do if we already decided to dump the table. This will
1633 * happen for "config" tables.
1635 if (tbinfo->dataObj != NULL)
1638 /* Skip VIEWs (no data to dump) */
1639 if (tbinfo->relkind == RELKIND_VIEW)
1641 /* Skip SEQUENCEs (handled elsewhere) */
1642 if (tbinfo->relkind == RELKIND_SEQUENCE)
1644 /* Skip FOREIGN TABLEs (no data to dump) */
1645 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1648 /* Don't dump data in unlogged tables, if so requested */
1649 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1650 no_unlogged_table_data)
1653 /* Check that the data is not explicitly excluded */
1654 if (simple_oid_list_member(&tabledata_exclude_oids,
1655 tbinfo->dobj.catId.oid))
1658 /* OK, let's dump it */
1659 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1661 tdinfo->dobj.objType = DO_TABLE_DATA;
1664 * Note: use tableoid 0 so that this object won't be mistaken for
1665 * something that pg_depend entries apply to.
1667 tdinfo->dobj.catId.tableoid = 0;
1668 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1669 AssignDumpId(&tdinfo->dobj);
1670 tdinfo->dobj.name = tbinfo->dobj.name;
1671 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1672 tdinfo->tdtable = tbinfo;
1673 tdinfo->oids = oids;
1674 tdinfo->filtercond = NULL; /* might get set later */
1675 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1677 tbinfo->dataObj = tdinfo;
1681 * getTableDataFKConstraints -
1682 * add dump-order dependencies reflecting foreign key constraints
1684 * This code is executed only in a data-only dump --- in schema+data dumps
1685 * we handle foreign key issues by not creating the FK constraints until
1686 * after the data is loaded. In a data-only dump, however, we want to
1687 * order the table data objects in such a way that a table's referenced
1688 * tables are restored first. (In the presence of circular references or
1689 * self-references this may be impossible; we'll detect and complain about
1690 * that during the dependency sorting step.)
1693 getTableDataFKConstraints(void)
1695 DumpableObject **dobjs;
1699 /* Search through all the dumpable objects for FK constraints */
1700 getDumpableObjects(&dobjs, &numObjs);
1701 for (i = 0; i < numObjs; i++)
1703 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1705 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1708 /* Not interesting unless both tables are to be dumped */
1709 if (cinfo->contable == NULL ||
1710 cinfo->contable->dataObj == NULL)
1712 ftable = findTableByOid(cinfo->confrelid);
1713 if (ftable == NULL ||
1714 ftable->dataObj == NULL)
1718 * Okay, make referencing table's TABLE_DATA object depend on the
1719 * referenced table's TABLE_DATA object.
1721 addObjectDependency(&cinfo->contable->dataObj->dobj,
1722 ftable->dataObj->dobj.dumpId);
1730 * guessConstraintInheritance:
1731 * In pre-8.4 databases, we can't tell for certain which constraints
1732 * are inherited. We assume a CHECK constraint is inherited if its name
1733 * matches the name of any constraint in the parent. Originally this code
1734 * tried to compare the expression texts, but that can fail for various
1735 * reasons --- for example, if the parent and child tables are in different
1736 * schemas, reverse-listing of function calls may produce different text
1737 * (schema-qualified or not) depending on search path.
1739 * In 8.4 and up we can rely on the conislocal field to decide which
1740 * constraints must be dumped; much safer.
1742 * This function assumes all conislocal flags were initialized to TRUE.
1743 * It clears the flag on anything that seems to be inherited.
1746 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1752 for (i = 0; i < numTables; i++)
1754 TableInfo *tbinfo = &(tblinfo[i]);
1756 TableInfo **parents;
1759 /* Sequences and views never have parents */
1760 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1761 tbinfo->relkind == RELKIND_VIEW)
1764 /* Don't bother computing anything for non-target tables, either */
1765 if (!tbinfo->dobj.dump)
1768 numParents = tbinfo->numParents;
1769 parents = tbinfo->parents;
1771 if (numParents == 0)
1772 continue; /* nothing to see here, move along */
1774 /* scan for inherited CHECK constraints */
1775 for (j = 0; j < tbinfo->ncheck; j++)
1777 ConstraintInfo *constr;
1779 constr = &(tbinfo->checkexprs[j]);
1781 for (k = 0; k < numParents; k++)
1785 parent = parents[k];
1786 for (l = 0; l < parent->ncheck; l++)
1788 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1790 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1792 constr->conislocal = false;
1796 if (!constr->conislocal)
1806 * dump the database definition
1809 dumpDatabase(Archive *fout)
1811 PQExpBuffer dbQry = createPQExpBuffer();
1812 PQExpBuffer delQry = createPQExpBuffer();
1813 PQExpBuffer creaQry = createPQExpBuffer();
1814 PGconn *conn = GetConnection(fout);
1826 const char *datname,
1834 datname = PQdb(conn);
1837 write_msg(NULL, "saving database definition\n");
1839 /* Make sure we are in proper schema */
1840 selectSourceSchema(fout, "pg_catalog");
1842 /* Get the database owner and parameters from pg_database */
1843 if (fout->remoteVersion >= 80400)
1845 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1846 "(%s datdba) AS dba, "
1847 "pg_encoding_to_char(encoding) AS encoding, "
1848 "datcollate, datctype, datfrozenxid, "
1849 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1850 "shobj_description(oid, 'pg_database') AS description "
1855 appendStringLiteralAH(dbQry, datname, fout);
1857 else if (fout->remoteVersion >= 80200)
1859 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1860 "(%s datdba) AS dba, "
1861 "pg_encoding_to_char(encoding) AS encoding, "
1862 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1863 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1864 "shobj_description(oid, 'pg_database') AS description "
1869 appendStringLiteralAH(dbQry, datname, fout);
1871 else if (fout->remoteVersion >= 80000)
1873 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1874 "(%s datdba) AS dba, "
1875 "pg_encoding_to_char(encoding) AS encoding, "
1876 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1877 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1881 appendStringLiteralAH(dbQry, datname, fout);
1883 else if (fout->remoteVersion >= 70100)
1885 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1886 "(%s datdba) AS dba, "
1887 "pg_encoding_to_char(encoding) AS encoding, "
1888 "NULL AS datcollate, NULL AS datctype, "
1889 "0 AS datfrozenxid, "
1890 "NULL AS tablespace "
1894 appendStringLiteralAH(dbQry, datname, fout);
1898 appendPQExpBuffer(dbQry, "SELECT "
1899 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1901 "(%s datdba) AS dba, "
1902 "pg_encoding_to_char(encoding) AS encoding, "
1903 "NULL AS datcollate, NULL AS datctype, "
1904 "0 AS datfrozenxid, "
1905 "NULL AS tablespace "
1909 appendStringLiteralAH(dbQry, datname, fout);
1912 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1914 i_tableoid = PQfnumber(res, "tableoid");
1915 i_oid = PQfnumber(res, "oid");
1916 i_dba = PQfnumber(res, "dba");
1917 i_encoding = PQfnumber(res, "encoding");
1918 i_collate = PQfnumber(res, "datcollate");
1919 i_ctype = PQfnumber(res, "datctype");
1920 i_frozenxid = PQfnumber(res, "datfrozenxid");
1921 i_tablespace = PQfnumber(res, "tablespace");
1923 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1924 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1925 dba = PQgetvalue(res, 0, i_dba);
1926 encoding = PQgetvalue(res, 0, i_encoding);
1927 collate = PQgetvalue(res, 0, i_collate);
1928 ctype = PQgetvalue(res, 0, i_ctype);
1929 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1930 tablespace = PQgetvalue(res, 0, i_tablespace);
1932 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1934 if (strlen(encoding) > 0)
1936 appendPQExpBuffer(creaQry, " ENCODING = ");
1937 appendStringLiteralAH(creaQry, encoding, fout);
1939 if (strlen(collate) > 0)
1941 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1942 appendStringLiteralAH(creaQry, collate, fout);
1944 if (strlen(ctype) > 0)
1946 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1947 appendStringLiteralAH(creaQry, ctype, fout);
1949 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1950 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1952 appendPQExpBuffer(creaQry, ";\n");
1956 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1957 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1958 "SET datfrozenxid = '%u'\n"
1961 appendStringLiteralAH(creaQry, datname, fout);
1962 appendPQExpBuffer(creaQry, ";\n");
1966 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1969 dbDumpId = createDumpId();
1972 dbCatId, /* catalog ID */
1973 dbDumpId, /* dump ID */
1975 NULL, /* Namespace */
1976 NULL, /* Tablespace */
1978 false, /* with oids */
1979 "DATABASE", /* Desc */
1980 SECTION_PRE_DATA, /* Section */
1981 creaQry->data, /* Create */
1982 delQry->data, /* Del */
1987 NULL); /* Dumper Arg */
1990 * pg_largeobject and pg_largeobject_metadata come from the old system
1991 * intact, so set their relfrozenxids.
1996 PQExpBuffer loFrozenQry = createPQExpBuffer();
1997 PQExpBuffer loOutQry = createPQExpBuffer();
2003 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2004 "FROM pg_catalog.pg_class\n"
2005 "WHERE oid = %u;\n",
2006 LargeObjectRelationId);
2008 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2010 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2012 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2013 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2014 "SET relfrozenxid = '%u'\n"
2015 "WHERE oid = %u;\n",
2016 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2017 LargeObjectRelationId);
2018 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2019 "pg_largeobject", NULL, NULL, "",
2020 false, "pg_largeobject", SECTION_PRE_DATA,
2021 loOutQry->data, "", NULL,
2028 * pg_largeobject_metadata
2030 if (fout->remoteVersion >= 90000)
2032 resetPQExpBuffer(loFrozenQry);
2033 resetPQExpBuffer(loOutQry);
2035 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2036 "FROM pg_catalog.pg_class\n"
2037 "WHERE oid = %u;\n",
2038 LargeObjectMetadataRelationId);
2040 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2042 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2044 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2045 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2046 "SET relfrozenxid = '%u'\n"
2047 "WHERE oid = %u;\n",
2048 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2049 LargeObjectMetadataRelationId);
2050 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2051 "pg_largeobject_metadata", NULL, NULL, "",
2052 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2053 loOutQry->data, "", NULL,
2060 destroyPQExpBuffer(loFrozenQry);
2061 destroyPQExpBuffer(loOutQry);
2064 /* Dump DB comment if any */
2065 if (fout->remoteVersion >= 80200)
2068 * 8.2 keeps comments on shared objects in a shared table, so we
2069 * cannot use the dumpComment used for other database objects.
2071 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2073 if (comment && strlen(comment))
2075 resetPQExpBuffer(dbQry);
2078 * Generates warning when loaded into a differently-named
2081 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2082 appendStringLiteralAH(dbQry, comment, fout);
2083 appendPQExpBuffer(dbQry, ";\n");
2085 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2086 dba, false, "COMMENT", SECTION_NONE,
2087 dbQry->data, "", NULL,
2088 &dbDumpId, 1, NULL, NULL);
2093 resetPQExpBuffer(dbQry);
2094 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2095 dumpComment(fout, dbQry->data, NULL, "",
2096 dbCatId, 0, dbDumpId);
2101 /* Dump shared security label. */
2102 if (!no_security_labels && fout->remoteVersion >= 90200)
2104 PQExpBuffer seclabelQry = createPQExpBuffer();
2106 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2107 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2108 resetPQExpBuffer(seclabelQry);
2109 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2110 if (strlen(seclabelQry->data))
2111 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2112 dba, false, "SECURITY LABEL", SECTION_NONE,
2113 seclabelQry->data, "", NULL,
2114 &dbDumpId, 1, NULL, NULL);
2115 destroyPQExpBuffer(seclabelQry);
2118 destroyPQExpBuffer(dbQry);
2119 destroyPQExpBuffer(delQry);
2120 destroyPQExpBuffer(creaQry);
2125 * dumpEncoding: put the correct encoding into the archive
2128 dumpEncoding(Archive *AH)
2130 const char *encname = pg_encoding_to_char(AH->encoding);
2131 PQExpBuffer qry = createPQExpBuffer();
2134 write_msg(NULL, "saving encoding = %s\n", encname);
2136 appendPQExpBuffer(qry, "SET client_encoding = ");
2137 appendStringLiteralAH(qry, encname, AH);
2138 appendPQExpBuffer(qry, ";\n");
2140 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2141 "ENCODING", NULL, NULL, "",
2142 false, "ENCODING", SECTION_PRE_DATA,
2143 qry->data, "", NULL,
2147 destroyPQExpBuffer(qry);
2152 * dumpStdStrings: put the correct escape string behavior into the archive
2155 dumpStdStrings(Archive *AH)
2157 const char *stdstrings = AH->std_strings ? "on" : "off";
2158 PQExpBuffer qry = createPQExpBuffer();
2161 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2164 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2167 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2168 "STDSTRINGS", NULL, NULL, "",
2169 false, "STDSTRINGS", SECTION_PRE_DATA,
2170 qry->data, "", NULL,
2174 destroyPQExpBuffer(qry);
2180 * Collect schema-level data about large objects
2183 getBlobs(Archive *fout)
2185 PQExpBuffer blobQry = createPQExpBuffer();
2187 DumpableObject *bdata;
2192 /* Verbose message */
2194 write_msg(NULL, "reading large objects\n");
2196 /* Make sure we are in proper schema */
2197 selectSourceSchema(fout, "pg_catalog");
2199 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2200 if (fout->remoteVersion >= 90000)
2201 appendPQExpBuffer(blobQry,
2202 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2203 " FROM pg_largeobject_metadata",
2205 else if (fout->remoteVersion >= 70100)
2206 appendPQExpBuffer(blobQry,
2207 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2208 " FROM pg_largeobject");
2210 appendPQExpBuffer(blobQry,
2211 "SELECT oid, NULL::oid, NULL::oid"
2212 " FROM pg_class WHERE relkind = 'l'");
2214 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2216 ntups = PQntuples(res);
2220 * Each large object has its own BLOB archive entry.
2222 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2224 for (i = 0; i < ntups; i++)
2226 binfo[i].dobj.objType = DO_BLOB;
2227 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2228 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2229 AssignDumpId(&binfo[i].dobj);
2231 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2232 if (!PQgetisnull(res, i, 1))
2233 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2235 binfo[i].rolname = "";
2236 if (!PQgetisnull(res, i, 2))
2237 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2239 binfo[i].blobacl = NULL;
2243 * If we have any large objects, a "BLOBS" archive entry is needed.
2244 * This is just a placeholder for sorting; it carries no data now.
2246 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2247 bdata->objType = DO_BLOB_DATA;
2248 bdata->catId = nilCatalogId;
2249 AssignDumpId(bdata);
2250 bdata->name = pg_strdup("BLOBS");
2254 destroyPQExpBuffer(blobQry);
2260 * dump the definition (metadata) of the given large object
2263 dumpBlob(Archive *fout, BlobInfo *binfo)
2265 PQExpBuffer cquery = createPQExpBuffer();
2266 PQExpBuffer dquery = createPQExpBuffer();
2268 appendPQExpBuffer(cquery,
2269 "SELECT pg_catalog.lo_create('%s');\n",
2272 appendPQExpBuffer(dquery,
2273 "SELECT pg_catalog.lo_unlink('%s');\n",
2276 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2279 binfo->rolname, false,
2280 "BLOB", SECTION_PRE_DATA,
2281 cquery->data, dquery->data, NULL,
2285 /* set up tag for comment and/or ACL */
2286 resetPQExpBuffer(cquery);
2287 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2289 /* Dump comment if any */
2290 dumpComment(fout, cquery->data,
2291 NULL, binfo->rolname,
2292 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2294 /* Dump security label if any */
2295 dumpSecLabel(fout, cquery->data,
2296 NULL, binfo->rolname,
2297 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2299 /* Dump ACL if any */
2301 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2302 binfo->dobj.name, NULL, cquery->data,
2303 NULL, binfo->rolname, binfo->blobacl);
2305 destroyPQExpBuffer(cquery);
2306 destroyPQExpBuffer(dquery);
2311 * dump the data contents of all large objects
2314 dumpBlobs(Archive *fout, void *arg)
2316 const char *blobQry;
2317 const char *blobFetchQry;
2318 PGconn *conn = GetConnection(fout);
2320 char buf[LOBBUFSIZE];
2326 write_msg(NULL, "saving large objects\n");
2328 /* Make sure we are in proper schema */
2329 selectSourceSchema(fout, "pg_catalog");
2332 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2333 * the already-in-memory dumpable objects instead...
2335 if (fout->remoteVersion >= 90000)
2336 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2337 else if (fout->remoteVersion >= 70100)
2338 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2340 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2342 ExecuteSqlStatement(fout, blobQry);
2344 /* Command to fetch from cursor */
2345 blobFetchQry = "FETCH 1000 IN bloboid";
2350 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2352 /* Process the tuples, if any */
2353 ntups = PQntuples(res);
2354 for (i = 0; i < ntups; i++)
2359 blobOid = atooid(PQgetvalue(res, i, 0));
2361 loFd = lo_open(conn, blobOid, INV_READ);
2363 exit_horribly(NULL, "could not open large object %u: %s",
2364 blobOid, PQerrorMessage(conn));
2366 StartBlob(fout, blobOid);
2368 /* Now read it in chunks, sending data to archive */
2371 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2373 exit_horribly(NULL, "error reading large object %u: %s",
2374 blobOid, PQerrorMessage(conn));
2376 WriteData(fout, buf, cnt);
2379 lo_close(conn, loFd);
2381 EndBlob(fout, blobOid);
2385 } while (ntups > 0);
2391 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2392 PQExpBuffer upgrade_buffer,
2395 PQExpBuffer upgrade_query = createPQExpBuffer();
2396 PGresult *upgrade_res;
2397 Oid pg_type_array_oid;
2399 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2400 appendPQExpBuffer(upgrade_buffer,
2401 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2404 /* we only support old >= 8.3 for binary upgrades */
2405 appendPQExpBuffer(upgrade_query,
2407 "FROM pg_catalog.pg_type "
2408 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2411 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2413 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2415 if (OidIsValid(pg_type_array_oid))
2417 appendPQExpBuffer(upgrade_buffer,
2418 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2419 appendPQExpBuffer(upgrade_buffer,
2420 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2424 PQclear(upgrade_res);
2425 destroyPQExpBuffer(upgrade_query);
2429 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2430 PQExpBuffer upgrade_buffer,
2433 PQExpBuffer upgrade_query = createPQExpBuffer();
2434 PGresult *upgrade_res;
2436 bool toast_set = false;
2438 /* we only support old >= 8.3 for binary upgrades */
2439 appendPQExpBuffer(upgrade_query,
2440 "SELECT c.reltype AS crel, t.reltype AS trel "
2441 "FROM pg_catalog.pg_class c "
2442 "LEFT JOIN pg_catalog.pg_class t ON "
2443 " (c.reltoastrelid = t.oid) "
2444 "WHERE c.oid = '%u'::pg_catalog.oid;",
2447 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2449 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2451 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2454 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2456 /* Toast tables do not have pg_type array rows */
2457 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2458 PQfnumber(upgrade_res, "trel")));
2460 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2461 appendPQExpBuffer(upgrade_buffer,
2462 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2468 PQclear(upgrade_res);
2469 destroyPQExpBuffer(upgrade_query);
2475 binary_upgrade_set_pg_class_oids(Archive *fout,
2476 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2479 PQExpBuffer upgrade_query = createPQExpBuffer();
2480 PGresult *upgrade_res;
2481 Oid pg_class_reltoastrelid;
2482 Oid pg_class_reltoastidxid;
2484 appendPQExpBuffer(upgrade_query,
2485 "SELECT c.reltoastrelid, t.reltoastidxid "
2486 "FROM pg_catalog.pg_class c LEFT JOIN "
2487 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2488 "WHERE c.oid = '%u'::pg_catalog.oid;",
2491 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2493 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2494 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2496 appendPQExpBuffer(upgrade_buffer,
2497 "\n-- For binary upgrade, must preserve pg_class oids\n");
2501 appendPQExpBuffer(upgrade_buffer,
2502 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2504 /* only tables have toast tables, not indexes */
2505 if (OidIsValid(pg_class_reltoastrelid))
2508 * One complexity is that the table definition might not require
2509 * the creation of a TOAST table, and the TOAST table might have
2510 * been created long after table creation, when the table was
2511 * loaded with wide data. By setting the TOAST oid we force
2512 * creation of the TOAST heap and TOAST index by the backend so we
2513 * can cleanly copy the files during binary upgrade.
2516 appendPQExpBuffer(upgrade_buffer,
2517 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2518 pg_class_reltoastrelid);
2520 /* every toast table has an index */
2521 appendPQExpBuffer(upgrade_buffer,
2522 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2523 pg_class_reltoastidxid);
2527 appendPQExpBuffer(upgrade_buffer,
2528 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2531 appendPQExpBuffer(upgrade_buffer, "\n");
2533 PQclear(upgrade_res);
2534 destroyPQExpBuffer(upgrade_query);
2538 * If the DumpableObject is a member of an extension, add a suitable
2539 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2542 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2543 DumpableObject *dobj,
2544 const char *objlabel)
2546 DumpableObject *extobj = NULL;
2549 if (!dobj->ext_member)
2553 * Find the parent extension. We could avoid this search if we wanted to
2554 * add a link field to DumpableObject, but the space costs of that would
2555 * be considerable. We assume that member objects could only have a
2556 * direct dependency on their own extension, not any others.
2558 for (i = 0; i < dobj->nDeps; i++)
2560 extobj = findObjectByDumpId(dobj->dependencies[i]);
2561 if (extobj && extobj->objType == DO_EXTENSION)
2566 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2568 appendPQExpBuffer(upgrade_buffer,
2569 "\n-- For binary upgrade, handle extension membership the hard way\n");
2570 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2571 fmtId(extobj->name),
2577 * read all namespaces in the system catalogs and return them in the
2578 * NamespaceInfo* structure
2580 * numNamespaces is set to the number of namespaces read in
2583 getNamespaces(Archive *fout, int *numNamespaces)
2589 NamespaceInfo *nsinfo;
2597 * Before 7.3, there are no real namespaces; create two dummy entries, one
2598 * for user stuff and one for system stuff.
2600 if (fout->remoteVersion < 70300)
2602 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2604 nsinfo[0].dobj.objType = DO_NAMESPACE;
2605 nsinfo[0].dobj.catId.tableoid = 0;
2606 nsinfo[0].dobj.catId.oid = 0;
2607 AssignDumpId(&nsinfo[0].dobj);
2608 nsinfo[0].dobj.name = pg_strdup("public");
2609 nsinfo[0].rolname = pg_strdup("");
2610 nsinfo[0].nspacl = pg_strdup("");
2612 selectDumpableNamespace(&nsinfo[0]);
2614 nsinfo[1].dobj.objType = DO_NAMESPACE;
2615 nsinfo[1].dobj.catId.tableoid = 0;
2616 nsinfo[1].dobj.catId.oid = 1;
2617 AssignDumpId(&nsinfo[1].dobj);
2618 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2619 nsinfo[1].rolname = pg_strdup("");
2620 nsinfo[1].nspacl = pg_strdup("");
2622 selectDumpableNamespace(&nsinfo[1]);
2629 query = createPQExpBuffer();
2631 /* Make sure we are in proper schema */
2632 selectSourceSchema(fout, "pg_catalog");
2635 * we fetch all namespaces including system ones, so that every object we
2636 * read in can be linked to a containing namespace.
2638 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2639 "(%s nspowner) AS rolname, "
2640 "nspacl FROM pg_namespace",
2643 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2645 ntups = PQntuples(res);
2647 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2649 i_tableoid = PQfnumber(res, "tableoid");
2650 i_oid = PQfnumber(res, "oid");
2651 i_nspname = PQfnumber(res, "nspname");
2652 i_rolname = PQfnumber(res, "rolname");
2653 i_nspacl = PQfnumber(res, "nspacl");
2655 for (i = 0; i < ntups; i++)
2657 nsinfo[i].dobj.objType = DO_NAMESPACE;
2658 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2659 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2660 AssignDumpId(&nsinfo[i].dobj);
2661 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2662 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2663 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2665 /* Decide whether to dump this namespace */
2666 selectDumpableNamespace(&nsinfo[i]);
2668 if (strlen(nsinfo[i].rolname) == 0)
2669 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2670 nsinfo[i].dobj.name);
2674 destroyPQExpBuffer(query);
2676 *numNamespaces = ntups;
2683 * given a namespace OID and an object OID, look up the info read by
2686 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2687 * a system object or not. In 7.3 and later there is no guessing, and we
2688 * don't use objoid at all.
2690 static NamespaceInfo *
2691 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2693 NamespaceInfo *nsinfo;
2695 if (fout->remoteVersion >= 70300)
2697 nsinfo = findNamespaceByOid(nsoid);
2701 /* This code depends on the dummy objects set up by getNamespaces. */
2704 if (objoid > g_last_builtin_oid)
2705 i = 0; /* user object */
2707 i = 1; /* system object */
2708 nsinfo = findNamespaceByOid(i);
2712 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2719 * read all extensions in the system catalogs and return them in the
2720 * ExtensionInfo* structure
2722 * numExtensions is set to the number of extensions read in
2725 getExtensions(Archive *fout, int *numExtensions)
2731 ExtensionInfo *extinfo;
2736 int i_extrelocatable;
2742 * Before 9.1, there are no extensions.
2744 if (fout->remoteVersion < 90100)
2750 query = createPQExpBuffer();
2752 /* Make sure we are in proper schema */
2753 selectSourceSchema(fout, "pg_catalog");
2755 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2756 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2757 "FROM pg_extension x "
2758 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2760 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2762 ntups = PQntuples(res);
2764 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2766 i_tableoid = PQfnumber(res, "tableoid");
2767 i_oid = PQfnumber(res, "oid");
2768 i_extname = PQfnumber(res, "extname");
2769 i_nspname = PQfnumber(res, "nspname");
2770 i_extrelocatable = PQfnumber(res, "extrelocatable");
2771 i_extversion = PQfnumber(res, "extversion");
2772 i_extconfig = PQfnumber(res, "extconfig");
2773 i_extcondition = PQfnumber(res, "extcondition");
2775 for (i = 0; i < ntups; i++)
2777 extinfo[i].dobj.objType = DO_EXTENSION;
2778 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2779 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2780 AssignDumpId(&extinfo[i].dobj);
2781 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2782 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2783 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2784 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2785 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2786 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2788 /* Decide whether we want to dump it */
2789 selectDumpableExtension(&(extinfo[i]));
2793 destroyPQExpBuffer(query);
2795 *numExtensions = ntups;
2802 * read all types in the system catalogs and return them in the
2803 * TypeInfo* structure
2805 * numTypes is set to the number of types read in
2807 * NB: this must run after getFuncs() because we assume we can do
2811 getTypes(Archive *fout, int *numTypes)
2816 PQExpBuffer query = createPQExpBuffer();
2818 ShellTypeInfo *stinfo;
2834 * we include even the built-in types because those may be used as array
2835 * elements by user-defined types
2837 * we filter out the built-in types when we dump out the types
2839 * same approach for undefined (shell) types and array types
2841 * Note: as of 8.3 we can reliably detect whether a type is an
2842 * auto-generated array type by checking the element type's typarray.
2843 * (Before that the test is capable of generating false positives.) We
2844 * still check for name beginning with '_', though, so as to avoid the
2845 * cost of the subselect probe for all standard types. This would have to
2846 * be revisited if the backend ever allows renaming of array types.
2849 /* Make sure we are in proper schema */
2850 selectSourceSchema(fout, "pg_catalog");
2852 if (fout->remoteVersion >= 80300)
2854 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2856 "(%s typowner) AS rolname, "
2857 "typinput::oid AS typinput, "
2858 "typoutput::oid AS typoutput, typelem, typrelid, "
2859 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2860 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2861 "typtype, typisdefined, "
2862 "typname[0] = '_' AND typelem != 0 AND "
2863 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2867 else if (fout->remoteVersion >= 70300)
2869 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2871 "(%s typowner) AS rolname, "
2872 "typinput::oid AS typinput, "
2873 "typoutput::oid AS typoutput, typelem, typrelid, "
2874 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2875 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2876 "typtype, typisdefined, "
2877 "typname[0] = '_' AND typelem != 0 AS isarray "
2881 else if (fout->remoteVersion >= 70100)
2883 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2884 "0::oid AS typnamespace, "
2885 "(%s typowner) AS rolname, "
2886 "typinput::oid AS typinput, "
2887 "typoutput::oid AS typoutput, typelem, typrelid, "
2888 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2889 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2890 "typtype, typisdefined, "
2891 "typname[0] = '_' AND typelem != 0 AS isarray "
2897 appendPQExpBuffer(query, "SELECT "
2898 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2900 "0::oid AS typnamespace, "
2901 "(%s typowner) AS rolname, "
2902 "typinput::oid AS typinput, "
2903 "typoutput::oid AS typoutput, typelem, typrelid, "
2904 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2905 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2906 "typtype, typisdefined, "
2907 "typname[0] = '_' AND typelem != 0 AS isarray "
2912 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2914 ntups = PQntuples(res);
2916 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2918 i_tableoid = PQfnumber(res, "tableoid");
2919 i_oid = PQfnumber(res, "oid");
2920 i_typname = PQfnumber(res, "typname");
2921 i_typnamespace = PQfnumber(res, "typnamespace");
2922 i_rolname = PQfnumber(res, "rolname");
2923 i_typinput = PQfnumber(res, "typinput");
2924 i_typoutput = PQfnumber(res, "typoutput");
2925 i_typelem = PQfnumber(res, "typelem");
2926 i_typrelid = PQfnumber(res, "typrelid");
2927 i_typrelkind = PQfnumber(res, "typrelkind");
2928 i_typtype = PQfnumber(res, "typtype");
2929 i_typisdefined = PQfnumber(res, "typisdefined");
2930 i_isarray = PQfnumber(res, "isarray");
2932 for (i = 0; i < ntups; i++)
2934 tyinfo[i].dobj.objType = DO_TYPE;
2935 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2936 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2937 AssignDumpId(&tyinfo[i].dobj);
2938 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2939 tyinfo[i].dobj.namespace =
2941 atooid(PQgetvalue(res, i, i_typnamespace)),
2942 tyinfo[i].dobj.catId.oid);
2943 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2944 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2945 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2946 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2947 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2948 tyinfo[i].shellType = NULL;
2950 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2951 tyinfo[i].isDefined = true;
2953 tyinfo[i].isDefined = false;
2955 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2956 tyinfo[i].isArray = true;
2958 tyinfo[i].isArray = false;
2960 /* Decide whether we want to dump it */
2961 selectDumpableType(&tyinfo[i]);
2964 * If it's a domain, fetch info about its constraints, if any
2966 tyinfo[i].nDomChecks = 0;
2967 tyinfo[i].domChecks = NULL;
2968 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2969 getDomainConstraints(fout, &(tyinfo[i]));
2972 * If it's a base type, make a DumpableObject representing a shell
2973 * definition of the type. We will need to dump that ahead of the I/O
2974 * functions for the type. Similarly, range types need a shell
2975 * definition in case they have a canonicalize function.
2977 * Note: the shell type doesn't have a catId. You might think it
2978 * should copy the base type's catId, but then it might capture the
2979 * pg_depend entries for the type, which we don't want.
2981 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2982 tyinfo[i].typtype == TYPTYPE_RANGE))
2984 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2985 stinfo->dobj.objType = DO_SHELL_TYPE;
2986 stinfo->dobj.catId = nilCatalogId;
2987 AssignDumpId(&stinfo->dobj);
2988 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2989 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2990 stinfo->baseType = &(tyinfo[i]);
2991 tyinfo[i].shellType = stinfo;
2994 * Initially mark the shell type as not to be dumped. We'll only
2995 * dump it if the I/O or canonicalize functions need to be dumped;
2996 * this is taken care of while sorting dependencies.
2998 stinfo->dobj.dump = false;
3001 * However, if dumping from pre-7.3, there will be no dependency
3002 * info so we have to fake it here. We only need to worry about
3003 * typinput and typoutput since the other functions only exist
3006 if (fout->remoteVersion < 70300)
3012 typinput = atooid(PQgetvalue(res, i, i_typinput));
3013 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3015 funcInfo = findFuncByOid(typinput);
3016 if (funcInfo && funcInfo->dobj.dump)
3018 /* base type depends on function */
3019 addObjectDependency(&tyinfo[i].dobj,
3020 funcInfo->dobj.dumpId);
3021 /* function depends on shell type */
3022 addObjectDependency(&funcInfo->dobj,
3023 stinfo->dobj.dumpId);
3024 /* mark shell type as to be dumped */
3025 stinfo->dobj.dump = true;
3028 funcInfo = findFuncByOid(typoutput);
3029 if (funcInfo && funcInfo->dobj.dump)
3031 /* base type depends on function */
3032 addObjectDependency(&tyinfo[i].dobj,
3033 funcInfo->dobj.dumpId);
3034 /* function depends on shell type */
3035 addObjectDependency(&funcInfo->dobj,
3036 stinfo->dobj.dumpId);
3037 /* mark shell type as to be dumped */
3038 stinfo->dobj.dump = true;
3043 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3044 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3045 tyinfo[i].dobj.name);
3052 destroyPQExpBuffer(query);
3059 * read all operators in the system catalogs and return them in the
3060 * OprInfo* structure
3062 * numOprs is set to the number of operators read in
3065 getOperators(Archive *fout, int *numOprs)
3070 PQExpBuffer query = createPQExpBuffer();
3081 * find all operators, including builtin operators; we filter out
3082 * system-defined operators at dump-out time.
3085 /* Make sure we are in proper schema */
3086 selectSourceSchema(fout, "pg_catalog");
3088 if (fout->remoteVersion >= 70300)
3090 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3092 "(%s oprowner) AS rolname, "
3094 "oprcode::oid AS oprcode "
3098 else if (fout->remoteVersion >= 70100)
3100 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3101 "0::oid AS oprnamespace, "
3102 "(%s oprowner) AS rolname, "
3104 "oprcode::oid AS oprcode "
3110 appendPQExpBuffer(query, "SELECT "
3111 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3113 "0::oid AS oprnamespace, "
3114 "(%s oprowner) AS rolname, "
3116 "oprcode::oid AS oprcode "
3121 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3123 ntups = PQntuples(res);
3126 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3128 i_tableoid = PQfnumber(res, "tableoid");
3129 i_oid = PQfnumber(res, "oid");
3130 i_oprname = PQfnumber(res, "oprname");
3131 i_oprnamespace = PQfnumber(res, "oprnamespace");
3132 i_rolname = PQfnumber(res, "rolname");
3133 i_oprkind = PQfnumber(res, "oprkind");
3134 i_oprcode = PQfnumber(res, "oprcode");
3136 for (i = 0; i < ntups; i++)
3138 oprinfo[i].dobj.objType = DO_OPERATOR;
3139 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3140 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3141 AssignDumpId(&oprinfo[i].dobj);
3142 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3143 oprinfo[i].dobj.namespace =
3145 atooid(PQgetvalue(res, i, i_oprnamespace)),
3146 oprinfo[i].dobj.catId.oid);
3147 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3148 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3149 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3151 /* Decide whether we want to dump it */
3152 selectDumpableObject(&(oprinfo[i].dobj));
3154 if (strlen(oprinfo[i].rolname) == 0)
3155 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3156 oprinfo[i].dobj.name);
3161 destroyPQExpBuffer(query);
3168 * read all collations in the system catalogs and return them in the
3169 * CollInfo* structure
3171 * numCollations is set to the number of collations read in
3174 getCollations(Archive *fout, int *numCollations)
3184 int i_collnamespace;
3187 /* Collations didn't exist pre-9.1 */
3188 if (fout->remoteVersion < 90100)
3194 query = createPQExpBuffer();
3197 * find all collations, including builtin collations; we filter out
3198 * system-defined collations at dump-out time.
3201 /* Make sure we are in proper schema */
3202 selectSourceSchema(fout, "pg_catalog");
3204 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3206 "(%s collowner) AS rolname "
3207 "FROM pg_collation",
3210 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3212 ntups = PQntuples(res);
3213 *numCollations = ntups;
3215 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3217 i_tableoid = PQfnumber(res, "tableoid");
3218 i_oid = PQfnumber(res, "oid");
3219 i_collname = PQfnumber(res, "collname");
3220 i_collnamespace = PQfnumber(res, "collnamespace");
3221 i_rolname = PQfnumber(res, "rolname");
3223 for (i = 0; i < ntups; i++)
3225 collinfo[i].dobj.objType = DO_COLLATION;
3226 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3227 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3228 AssignDumpId(&collinfo[i].dobj);
3229 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3230 collinfo[i].dobj.namespace =
3232 atooid(PQgetvalue(res, i, i_collnamespace)),
3233 collinfo[i].dobj.catId.oid);
3234 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3236 /* Decide whether we want to dump it */
3237 selectDumpableObject(&(collinfo[i].dobj));
3242 destroyPQExpBuffer(query);
3249 * read all conversions in the system catalogs and return them in the
3250 * ConvInfo* structure
3252 * numConversions is set to the number of conversions read in
3255 getConversions(Archive *fout, int *numConversions)
3260 PQExpBuffer query = createPQExpBuffer();
3268 /* Conversions didn't exist pre-7.3 */
3269 if (fout->remoteVersion < 70300)
3271 *numConversions = 0;
3276 * find all conversions, including builtin conversions; we filter out
3277 * system-defined conversions at dump-out time.
3280 /* Make sure we are in proper schema */
3281 selectSourceSchema(fout, "pg_catalog");
3283 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3285 "(%s conowner) AS rolname "
3286 "FROM pg_conversion",
3289 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3291 ntups = PQntuples(res);
3292 *numConversions = ntups;
3294 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3296 i_tableoid = PQfnumber(res, "tableoid");
3297 i_oid = PQfnumber(res, "oid");
3298 i_conname = PQfnumber(res, "conname");
3299 i_connamespace = PQfnumber(res, "connamespace");
3300 i_rolname = PQfnumber(res, "rolname");
3302 for (i = 0; i < ntups; i++)
3304 convinfo[i].dobj.objType = DO_CONVERSION;
3305 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3306 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3307 AssignDumpId(&convinfo[i].dobj);
3308 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3309 convinfo[i].dobj.namespace =
3311 atooid(PQgetvalue(res, i, i_connamespace)),
3312 convinfo[i].dobj.catId.oid);
3313 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3315 /* Decide whether we want to dump it */
3316 selectDumpableObject(&(convinfo[i].dobj));
3321 destroyPQExpBuffer(query);
3328 * read all opclasses in the system catalogs and return them in the
3329 * OpclassInfo* structure
3331 * numOpclasses is set to the number of opclasses read in
3334 getOpclasses(Archive *fout, int *numOpclasses)
3339 PQExpBuffer query = createPQExpBuffer();
3340 OpclassInfo *opcinfo;
3348 * find all opclasses, including builtin opclasses; we filter out
3349 * system-defined opclasses at dump-out time.
3352 /* Make sure we are in proper schema */
3353 selectSourceSchema(fout, "pg_catalog");
3355 if (fout->remoteVersion >= 70300)
3357 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3359 "(%s opcowner) AS rolname "
3363 else if (fout->remoteVersion >= 70100)
3365 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3366 "0::oid AS opcnamespace, "
3367 "''::name AS rolname "
3372 appendPQExpBuffer(query, "SELECT "
3373 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3375 "0::oid AS opcnamespace, "
3376 "''::name AS rolname "
3380 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3382 ntups = PQntuples(res);
3383 *numOpclasses = ntups;
3385 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3387 i_tableoid = PQfnumber(res, "tableoid");
3388 i_oid = PQfnumber(res, "oid");
3389 i_opcname = PQfnumber(res, "opcname");
3390 i_opcnamespace = PQfnumber(res, "opcnamespace");
3391 i_rolname = PQfnumber(res, "rolname");
3393 for (i = 0; i < ntups; i++)
3395 opcinfo[i].dobj.objType = DO_OPCLASS;
3396 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3397 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3398 AssignDumpId(&opcinfo[i].dobj);
3399 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3400 opcinfo[i].dobj.namespace =
3402 atooid(PQgetvalue(res, i, i_opcnamespace)),
3403 opcinfo[i].dobj.catId.oid);
3404 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3406 /* Decide whether we want to dump it */
3407 selectDumpableObject(&(opcinfo[i].dobj));
3409 if (fout->remoteVersion >= 70300)
3411 if (strlen(opcinfo[i].rolname) == 0)
3412 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3413 opcinfo[i].dobj.name);
3419 destroyPQExpBuffer(query);
3426 * read all opfamilies in the system catalogs and return them in the
3427 * OpfamilyInfo* structure
3429 * numOpfamilies is set to the number of opfamilies read in
3432 getOpfamilies(Archive *fout, int *numOpfamilies)
3438 OpfamilyInfo *opfinfo;
3445 /* Before 8.3, there is no separate concept of opfamilies */
3446 if (fout->remoteVersion < 80300)
3452 query = createPQExpBuffer();
3455 * find all opfamilies, including builtin opfamilies; we filter out
3456 * system-defined opfamilies at dump-out time.
3459 /* Make sure we are in proper schema */
3460 selectSourceSchema(fout, "pg_catalog");
3462 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3464 "(%s opfowner) AS rolname "
3468 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3470 ntups = PQntuples(res);
3471 *numOpfamilies = ntups;
3473 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3475 i_tableoid = PQfnumber(res, "tableoid");
3476 i_oid = PQfnumber(res, "oid");
3477 i_opfname = PQfnumber(res, "opfname");
3478 i_opfnamespace = PQfnumber(res, "opfnamespace");
3479 i_rolname = PQfnumber(res, "rolname");
3481 for (i = 0; i < ntups; i++)
3483 opfinfo[i].dobj.objType = DO_OPFAMILY;
3484 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3485 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3486 AssignDumpId(&opfinfo[i].dobj);
3487 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3488 opfinfo[i].dobj.namespace =
3490 atooid(PQgetvalue(res, i, i_opfnamespace)),
3491 opfinfo[i].dobj.catId.oid);
3492 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3494 /* Decide whether we want to dump it */
3495 selectDumpableObject(&(opfinfo[i].dobj));
3497 if (fout->remoteVersion >= 70300)
3499 if (strlen(opfinfo[i].rolname) == 0)
3500 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3501 opfinfo[i].dobj.name);
3507 destroyPQExpBuffer(query);
3514 * read all the user-defined aggregates in the system catalogs and
3515 * return them in the AggInfo* structure
3517 * numAggs is set to the number of aggregates read in
3520 getAggregates(Archive *fout, int *numAggs)
3525 PQExpBuffer query = createPQExpBuffer();
3536 /* Make sure we are in proper schema */
3537 selectSourceSchema(fout, "pg_catalog");
3540 * Find all user-defined aggregates. See comment in getFuncs() for the
3541 * rationale behind the filtering logic.
3544 if (fout->remoteVersion >= 80200)
3546 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3547 "pronamespace AS aggnamespace, "
3548 "pronargs, proargtypes, "
3549 "(%s proowner) AS rolname, "
3552 "WHERE proisagg AND ("
3554 "(SELECT oid FROM pg_namespace "
3555 "WHERE nspname = 'pg_catalog')",
3557 if (binary_upgrade && fout->remoteVersion >= 90100)
3558 appendPQExpBuffer(query,
3559 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3560 "classid = 'pg_proc'::regclass AND "
3561 "objid = p.oid AND "
3562 "refclassid = 'pg_extension'::regclass AND "
3564 appendPQExpBuffer(query, ")");
3566 else if (fout->remoteVersion >= 70300)
3568 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3569 "pronamespace AS aggnamespace, "
3570 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3572 "(%s proowner) AS rolname, "
3576 "AND pronamespace != "
3577 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3580 else if (fout->remoteVersion >= 70100)
3582 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3583 "0::oid AS aggnamespace, "
3584 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3585 "aggbasetype AS proargtypes, "
3586 "(%s aggowner) AS rolname, "
3588 "FROM pg_aggregate "
3589 "where oid > '%u'::oid",
3591 g_last_builtin_oid);
3595 appendPQExpBuffer(query, "SELECT "
3596 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3598 "0::oid AS aggnamespace, "
3599 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3600 "aggbasetype AS proargtypes, "
3601 "(%s aggowner) AS rolname, "
3603 "FROM pg_aggregate "
3604 "where oid > '%u'::oid",
3606 g_last_builtin_oid);
3609 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3611 ntups = PQntuples(res);
3614 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3616 i_tableoid = PQfnumber(res, "tableoid");
3617 i_oid = PQfnumber(res, "oid");
3618 i_aggname = PQfnumber(res, "aggname");
3619 i_aggnamespace = PQfnumber(res, "aggnamespace");
3620 i_pronargs = PQfnumber(res, "pronargs");
3621 i_proargtypes = PQfnumber(res, "proargtypes");
3622 i_rolname = PQfnumber(res, "rolname");
3623 i_aggacl = PQfnumber(res, "aggacl");
3625 for (i = 0; i < ntups; i++)
3627 agginfo[i].aggfn.dobj.objType = DO_AGG;
3628 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3629 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3630 AssignDumpId(&agginfo[i].aggfn.dobj);
3631 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3632 agginfo[i].aggfn.dobj.namespace =
3634 atooid(PQgetvalue(res, i, i_aggnamespace)),
3635 agginfo[i].aggfn.dobj.catId.oid);
3636 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3637 if (strlen(agginfo[i].aggfn.rolname) == 0)
3638 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3639 agginfo[i].aggfn.dobj.name);
3640 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3641 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3642 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3643 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3644 if (agginfo[i].aggfn.nargs == 0)
3645 agginfo[i].aggfn.argtypes = NULL;
3648 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3649 if (fout->remoteVersion >= 70300)
3650 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3651 agginfo[i].aggfn.argtypes,
3652 agginfo[i].aggfn.nargs);
3654 /* it's just aggbasetype */
3655 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3658 /* Decide whether we want to dump it */
3659 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3664 destroyPQExpBuffer(query);
3671 * read all the user-defined functions in the system catalogs and
3672 * return them in the FuncInfo* structure
3674 * numFuncs is set to the number of functions read in
3677 getFuncs(Archive *fout, int *numFuncs)
3682 PQExpBuffer query = createPQExpBuffer();
3695 /* Make sure we are in proper schema */
3696 selectSourceSchema(fout, "pg_catalog");
3699 * Find all user-defined functions. Normally we can exclude functions in
3700 * pg_catalog, which is worth doing since there are several thousand of
3701 * 'em. However, there are some extensions that create functions in
3702 * pg_catalog. In normal dumps we can still ignore those --- but in
3703 * binary-upgrade mode, we must dump the member objects of the extension,
3704 * so be sure to fetch any such functions.
3706 * Also, in 9.2 and up, exclude functions that are internally dependent on
3707 * something else, since presumably those will be created as a result of
3708 * creating the something else. This currently only acts to suppress
3709 * constructor functions for range types. Note that this is OK only
3710 * because the constructors don't have any dependencies the range type
3711 * doesn't have; otherwise we might not get creation ordering correct.
3714 if (fout->remoteVersion >= 70300)
3716 appendPQExpBuffer(query,
3717 "SELECT tableoid, oid, proname, prolang, "
3718 "pronargs, proargtypes, prorettype, proacl, "
3720 "(%s proowner) AS rolname "
3722 "WHERE NOT proisagg AND ("
3724 "(SELECT oid FROM pg_namespace "
3725 "WHERE nspname = 'pg_catalog')",
3727 if (fout->remoteVersion >= 90200)
3728 appendPQExpBuffer(query,
3729 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3730 "WHERE classid = 'pg_proc'::regclass AND "
3731 "objid = p.oid AND deptype = 'i')");
3732 if (binary_upgrade && fout->remoteVersion >= 90100)
3733 appendPQExpBuffer(query,
3734 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3735 "classid = 'pg_proc'::regclass AND "
3736 "objid = p.oid AND "
3737 "refclassid = 'pg_extension'::regclass AND "
3739 appendPQExpBuffer(query, ")");
3741 else if (fout->remoteVersion >= 70100)
3743 appendPQExpBuffer(query,
3744 "SELECT tableoid, oid, proname, prolang, "
3745 "pronargs, proargtypes, prorettype, "
3746 "'{=X}' AS proacl, "
3747 "0::oid AS pronamespace, "
3748 "(%s proowner) AS rolname "
3750 "WHERE pg_proc.oid > '%u'::oid",
3752 g_last_builtin_oid);
3756 appendPQExpBuffer(query,
3758 "(SELECT oid FROM pg_class "
3759 " WHERE relname = 'pg_proc') AS tableoid, "
3760 "oid, proname, prolang, "
3761 "pronargs, proargtypes, prorettype, "
3762 "'{=X}' AS proacl, "
3763 "0::oid AS pronamespace, "
3764 "(%s proowner) AS rolname "
3766 "where pg_proc.oid > '%u'::oid",
3768 g_last_builtin_oid);
3771 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3773 ntups = PQntuples(res);
3777 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3779 i_tableoid = PQfnumber(res, "tableoid");
3780 i_oid = PQfnumber(res, "oid");
3781 i_proname = PQfnumber(res, "proname");
3782 i_pronamespace = PQfnumber(res, "pronamespace");
3783 i_rolname = PQfnumber(res, "rolname");
3784 i_prolang = PQfnumber(res, "prolang");
3785 i_pronargs = PQfnumber(res, "pronargs");
3786 i_proargtypes = PQfnumber(res, "proargtypes");
3787 i_prorettype = PQfnumber(res, "prorettype");
3788 i_proacl = PQfnumber(res, "proacl");
3790 for (i = 0; i < ntups; i++)
3792 finfo[i].dobj.objType = DO_FUNC;
3793 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3794 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3795 AssignDumpId(&finfo[i].dobj);
3796 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3797 finfo[i].dobj.namespace =
3799 atooid(PQgetvalue(res, i, i_pronamespace)),
3800 finfo[i].dobj.catId.oid);
3801 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3802 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3803 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3804 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3805 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3806 if (finfo[i].nargs == 0)
3807 finfo[i].argtypes = NULL;
3810 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3811 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3812 finfo[i].argtypes, finfo[i].nargs);
3815 /* Decide whether we want to dump it */
3816 selectDumpableObject(&(finfo[i].dobj));
3818 if (strlen(finfo[i].rolname) == 0)
3820 "WARNING: owner of function \"%s\" appears to be invalid\n",
3821 finfo[i].dobj.name);
3826 destroyPQExpBuffer(query);
3833 * read all the user-defined tables (no indexes, no catalogs)
3834 * in the system catalogs return them in the TableInfo* structure
3836 * numTables is set to the number of tables read in
3839 getTables(Archive *fout, int *numTables)
3844 PQExpBuffer query = createPQExpBuffer();
3854 int i_relhastriggers;
3860 int i_toastfrozenxid;
3861 int i_relpersistence;
3864 int i_reltablespace;
3866 int i_toastreloptions;
3869 /* Make sure we are in proper schema */
3870 selectSourceSchema(fout, "pg_catalog");
3873 * Find all the tables and table-like objects.
3875 * We include system catalogs, so that we can work if a user table is
3876 * defined to inherit from a system catalog (pretty weird, but...)
3878 * We ignore relations that are not ordinary tables, sequences, views,
3879 * composite types, or foreign tables.
3881 * Composite-type table entries won't be dumped as such, but we have to
3882 * make a DumpableObject for them so that we can track dependencies of the
3883 * composite type (pg_depend entries for columns of the composite type
3884 * link to the pg_class entry not the pg_type entry).
3886 * Note: in this phase we should collect only a minimal amount of
3887 * information about each table, basically just enough to decide if it is
3888 * interesting. We must fetch all tables in this phase because otherwise
3889 * we cannot correctly identify inherited columns, owned sequences, etc.
3892 if (fout->remoteVersion >= 90100)
3895 * Left join to pick up dependency info linking sequences to their
3896 * owning column, if any (note this dependency is AUTO as of 8.2)
3898 appendPQExpBuffer(query,
3899 "SELECT c.tableoid, c.oid, c.relname, "
3900 "c.relacl, c.relkind, c.relnamespace, "
3901 "(%s c.relowner) AS rolname, "
3902 "c.relchecks, c.relhastriggers, "
3903 "c.relhasindex, c.relhasrules, c.relhasoids, "
3904 "c.relfrozenxid, tc.oid AS toid, "
3905 "tc.relfrozenxid AS tfrozenxid, "
3906 "c.relpersistence, "
3907 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3908 "d.refobjid AS owning_tab, "
3909 "d.refobjsubid AS owning_col, "
3910 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3911 "array_to_string(c.reloptions, ', ') AS reloptions, "
3912 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3914 "LEFT JOIN pg_depend d ON "
3915 "(c.relkind = '%c' AND "
3916 "d.classid = c.tableoid AND d.objid = c.oid AND "
3917 "d.objsubid = 0 AND "
3918 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3919 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3920 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3924 RELKIND_RELATION, RELKIND_SEQUENCE,
3925 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3926 RELKIND_FOREIGN_TABLE);
3928 else if (fout->remoteVersion >= 90000)
3931 * Left join to pick up dependency info linking sequences to their
3932 * owning column, if any (note this dependency is AUTO as of 8.2)
3934 appendPQExpBuffer(query,
3935 "SELECT c.tableoid, c.oid, c.relname, "
3936 "c.relacl, c.relkind, c.relnamespace, "
3937 "(%s c.relowner) AS rolname, "
3938 "c.relchecks, c.relhastriggers, "
3939 "c.relhasindex, c.relhasrules, c.relhasoids, "
3940 "c.relfrozenxid, tc.oid AS toid, "
3941 "tc.relfrozenxid AS tfrozenxid, "
3942 "'p' AS relpersistence, "
3943 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3944 "d.refobjid AS owning_tab, "
3945 "d.refobjsubid AS owning_col, "
3946 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3947 "array_to_string(c.reloptions, ', ') AS reloptions, "
3948 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3950 "LEFT JOIN pg_depend d ON "
3951 "(c.relkind = '%c' AND "
3952 "d.classid = c.tableoid AND d.objid = c.oid AND "
3953 "d.objsubid = 0 AND "
3954 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3955 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3956 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3960 RELKIND_RELATION, RELKIND_SEQUENCE,
3961 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3963 else if (fout->remoteVersion >= 80400)
3966 * Left join to pick up dependency info linking sequences to their
3967 * owning column, if any (note this dependency is AUTO as of 8.2)
3969 appendPQExpBuffer(query,
3970 "SELECT c.tableoid, c.oid, c.relname, "
3971 "c.relacl, c.relkind, c.relnamespace, "
3972 "(%s c.relowner) AS rolname, "
3973 "c.relchecks, c.relhastriggers, "
3974 "c.relhasindex, c.relhasrules, c.relhasoids, "
3975 "c.relfrozenxid, tc.oid AS toid, "
3976 "tc.relfrozenxid AS tfrozenxid, "
3977 "'p' AS relpersistence, "
3978 "NULL AS reloftype, "
3979 "d.refobjid AS owning_tab, "
3980 "d.refobjsubid AS owning_col, "
3981 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3982 "array_to_string(c.reloptions, ', ') AS reloptions, "
3983 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3985 "LEFT JOIN pg_depend d ON "
3986 "(c.relkind = '%c' AND "
3987 "d.classid = c.tableoid AND d.objid = c.oid AND "
3988 "d.objsubid = 0 AND "
3989 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3990 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3991 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3995 RELKIND_RELATION, RELKIND_SEQUENCE,
3996 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3998 else if (fout->remoteVersion >= 80200)
4001 * Left join to pick up dependency info linking sequences to their
4002 * owning column, if any (note this dependency is AUTO as of 8.2)
4004 appendPQExpBuffer(query,
4005 "SELECT c.tableoid, c.oid, c.relname, "
4006 "c.relacl, c.relkind, c.relnamespace, "
4007 "(%s c.relowner) AS rolname, "
4008 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4009 "c.relhasindex, c.relhasrules, c.relhasoids, "
4010 "c.relfrozenxid, tc.oid AS toid, "
4011 "tc.relfrozenxid AS tfrozenxid, "
4012 "'p' AS relpersistence, "
4013 "NULL AS reloftype, "
4014 "d.refobjid AS owning_tab, "
4015 "d.refobjsubid AS owning_col, "
4016 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4017 "array_to_string(c.reloptions, ', ') AS reloptions, "
4018 "NULL AS toast_reloptions "
4020 "LEFT JOIN pg_depend d ON "
4021 "(c.relkind = '%c' AND "
4022 "d.classid = c.tableoid AND d.objid = c.oid AND "
4023 "d.objsubid = 0 AND "
4024 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4025 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4026 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4030 RELKIND_RELATION, RELKIND_SEQUENCE,
4031 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4033 else if (fout->remoteVersion >= 80000)
4036 * Left join to pick up dependency info linking sequences to their
4037 * owning column, if any
4039 appendPQExpBuffer(query,
4040 "SELECT c.tableoid, c.oid, relname, "
4041 "relacl, relkind, relnamespace, "
4042 "(%s relowner) AS rolname, "
4043 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4044 "relhasindex, relhasrules, relhasoids, "
4045 "0 AS relfrozenxid, "
4048 "'p' AS relpersistence, "
4049 "NULL AS reloftype, "
4050 "d.refobjid AS owning_tab, "
4051 "d.refobjsubid AS owning_col, "
4052 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4053 "NULL AS reloptions, "
4054 "NULL AS toast_reloptions "
4056 "LEFT JOIN pg_depend d ON "
4057 "(c.relkind = '%c' AND "
4058 "d.classid = c.tableoid AND d.objid = c.oid AND "
4059 "d.objsubid = 0 AND "
4060 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4061 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4065 RELKIND_RELATION, RELKIND_SEQUENCE,
4066 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4068 else if (fout->remoteVersion >= 70300)
4071 * Left join to pick up dependency info linking sequences to their
4072 * owning column, if any
4074 appendPQExpBuffer(query,
4075 "SELECT c.tableoid, c.oid, relname, "
4076 "relacl, relkind, relnamespace, "
4077 "(%s relowner) AS rolname, "
4078 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4079 "relhasindex, relhasrules, relhasoids, "
4080 "0 AS relfrozenxid, "
4083 "'p' AS relpersistence, "
4084 "NULL AS reloftype, "
4085 "d.refobjid AS owning_tab, "
4086 "d.refobjsubid AS owning_col, "
4087 "NULL AS reltablespace, "
4088 "NULL AS reloptions, "
4089 "NULL AS toast_reloptions "
4091 "LEFT JOIN pg_depend d ON "
4092 "(c.relkind = '%c' AND "
4093 "d.classid = c.tableoid AND d.objid = c.oid AND "
4094 "d.objsubid = 0 AND "
4095 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4096 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4100 RELKIND_RELATION, RELKIND_SEQUENCE,
4101 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4103 else if (fout->remoteVersion >= 70200)
4105 appendPQExpBuffer(query,
4106 "SELECT tableoid, oid, relname, relacl, relkind, "
4107 "0::oid AS relnamespace, "
4108 "(%s relowner) AS rolname, "
4109 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4110 "relhasindex, relhasrules, relhasoids, "
4111 "0 AS relfrozenxid, "
4114 "'p' AS relpersistence, "
4115 "NULL AS reloftype, "
4116 "NULL::oid AS owning_tab, "
4117 "NULL::int4 AS owning_col, "
4118 "NULL AS reltablespace, "
4119 "NULL AS reloptions, "
4120 "NULL AS toast_reloptions "
4122 "WHERE relkind IN ('%c', '%c', '%c') "
4125 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4127 else if (fout->remoteVersion >= 70100)
4129 /* all tables have oids in 7.1 */
4130 appendPQExpBuffer(query,
4131 "SELECT tableoid, oid, relname, relacl, relkind, "
4132 "0::oid AS relnamespace, "
4133 "(%s relowner) AS rolname, "
4134 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4135 "relhasindex, relhasrules, "
4136 "'t'::bool AS relhasoids, "
4137 "0 AS relfrozenxid, "
4140 "'p' AS relpersistence, "
4141 "NULL AS reloftype, "
4142 "NULL::oid AS owning_tab, "
4143 "NULL::int4 AS owning_col, "
4144 "NULL AS reltablespace, "
4145 "NULL AS reloptions, "
4146 "NULL AS toast_reloptions "
4148 "WHERE relkind IN ('%c', '%c', '%c') "
4151 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4156 * Before 7.1, view relkind was not set to 'v', so we must check if we
4157 * have a view by looking for a rule in pg_rewrite.
4159 appendPQExpBuffer(query,
4161 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4162 "oid, relname, relacl, "
4163 "CASE WHEN relhasrules and relkind = 'r' "
4164 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4165 " r.ev_class = c.oid AND r.ev_type = '1') "
4166 "THEN '%c'::\"char\" "
4167 "ELSE relkind END AS relkind,"
4168 "0::oid AS relnamespace, "
4169 "(%s relowner) AS rolname, "
4170 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4171 "relhasindex, relhasrules, "
4172 "'t'::bool AS relhasoids, "
4173 "0 as relfrozenxid, "
4176 "'p' AS relpersistence, "
4177 "NULL AS reloftype, "
4178 "NULL::oid AS owning_tab, "
4179 "NULL::int4 AS owning_col, "
4180 "NULL AS reltablespace, "
4181 "NULL AS reloptions, "
4182 "NULL AS toast_reloptions "
4184 "WHERE relkind IN ('%c', '%c') "
4188 RELKIND_RELATION, RELKIND_SEQUENCE);
4191 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4193 ntups = PQntuples(res);
4198 * Extract data from result and lock dumpable tables. We do the locking
4199 * before anything else, to minimize the window wherein a table could
4200 * disappear under us.
4202 * Note that we have to save info about all tables here, even when dumping
4203 * only one, because we don't yet know which tables might be inheritance
4204 * ancestors of the target table.
4206 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4208 i_reltableoid = PQfnumber(res, "tableoid");
4209 i_reloid = PQfnumber(res, "oid");
4210 i_relname = PQfnumber(res, "relname");
4211 i_relnamespace = PQfnumber(res, "relnamespace");
4212 i_relacl = PQfnumber(res, "relacl");
4213 i_relkind = PQfnumber(res, "relkind");
4214 i_rolname = PQfnumber(res, "rolname");
4215 i_relchecks = PQfnumber(res, "relchecks");
4216 i_relhastriggers = PQfnumber(res, "relhastriggers");
4217 i_relhasindex = PQfnumber(res, "relhasindex");
4218 i_relhasrules = PQfnumber(res, "relhasrules");
4219 i_relhasoids = PQfnumber(res, "relhasoids");
4220 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4221 i_toastoid = PQfnumber(res, "toid");
4222 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4223 i_relpersistence = PQfnumber(res, "relpersistence");
4224 i_owning_tab = PQfnumber(res, "owning_tab");
4225 i_owning_col = PQfnumber(res, "owning_col");
4226 i_reltablespace = PQfnumber(res, "reltablespace");
4227 i_reloptions = PQfnumber(res, "reloptions");
4228 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4229 i_reloftype = PQfnumber(res, "reloftype");
4231 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4234 * Arrange to fail instead of waiting forever for a table lock.
4236 * NB: this coding assumes that the only queries issued within the
4237 * following loop are LOCK TABLEs; else the timeout may be undesirably
4238 * applied to other things too.
4240 resetPQExpBuffer(query);
4241 appendPQExpBuffer(query, "SET statement_timeout = ");
4242 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4243 ExecuteSqlStatement(fout, query->data);
4246 for (i = 0; i < ntups; i++)
4248 tblinfo[i].dobj.objType = DO_TABLE;
4249 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4250 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4251 AssignDumpId(&tblinfo[i].dobj);
4252 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4253 tblinfo[i].dobj.namespace =
4255 atooid(PQgetvalue(res, i, i_relnamespace)),
4256 tblinfo[i].dobj.catId.oid);
4257 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4258 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4259 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4260 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4261 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4262 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4263 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4264 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4265 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4266 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4267 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4268 if (PQgetisnull(res, i, i_reloftype))
4269 tblinfo[i].reloftype = NULL;
4271 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4272 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4273 if (PQgetisnull(res, i, i_owning_tab))
4275 tblinfo[i].owning_tab = InvalidOid;
4276 tblinfo[i].owning_col = 0;
4280 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4281 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4283 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4284 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4285 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4287 /* other fields were zeroed above */
4290 * Decide whether we want to dump this table.
4292 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4293 tblinfo[i].dobj.dump = false;
4295 selectDumpableTable(&tblinfo[i]);
4296 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4299 * Read-lock target tables to make sure they aren't DROPPED or altered
4300 * in schema before we get around to dumping them.
4302 * Note that we don't explicitly lock parents of the target tables; we
4303 * assume our lock on the child is enough to prevent schema
4304 * alterations to parent tables.
4306 * NOTE: it'd be kinda nice to lock other relations too, not only
4307 * plain tables, but the backend doesn't presently allow that.
4309 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4311 resetPQExpBuffer(query);
4312 appendPQExpBuffer(query,
4313 "LOCK TABLE %s IN ACCESS SHARE MODE",
4314 fmtQualifiedId(fout,
4315 tblinfo[i].dobj.namespace->dobj.name,
4316 tblinfo[i].dobj.name));
4317 ExecuteSqlStatement(fout, query->data);
4320 /* Emit notice if join for owner failed */
4321 if (strlen(tblinfo[i].rolname) == 0)
4322 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4323 tblinfo[i].dobj.name);
4326 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4328 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4333 destroyPQExpBuffer(query);
4340 * identify owned sequences and mark them as dumpable if owning table is
4342 * We used to do this in getTables(), but it's better to do it after the
4343 * index used by findTableByOid() has been set up.
4346 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4351 * Force sequences that are "owned" by table columns to be dumped whenever
4352 * their owning table is being dumped.
4354 for (i = 0; i < numTables; i++)
4356 TableInfo *seqinfo = &tblinfo[i];
4357 TableInfo *owning_tab;
4359 if (!OidIsValid(seqinfo->owning_tab))
4360 continue; /* not an owned sequence */
4361 if (seqinfo->dobj.dump)
4362 continue; /* no need to search */
4363 owning_tab = findTableByOid(seqinfo->owning_tab);
4364 if (owning_tab && owning_tab->dobj.dump)
4366 seqinfo->interesting = true;
4367 seqinfo->dobj.dump = true;
4374 * read all the inheritance information
4375 * from the system catalogs return them in the InhInfo* structure
4377 * numInherits is set to the number of pairs read in
4380 getInherits(Archive *fout, int *numInherits)
4385 PQExpBuffer query = createPQExpBuffer();
4391 /* Make sure we are in proper schema */
4392 selectSourceSchema(fout, "pg_catalog");
4394 /* find all the inheritance information */
4396 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4398 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4400 ntups = PQntuples(res);
4402 *numInherits = ntups;
4404 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4406 i_inhrelid = PQfnumber(res, "inhrelid");
4407 i_inhparent = PQfnumber(res, "inhparent");
4409 for (i = 0; i < ntups; i++)
4411 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4412 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4417 destroyPQExpBuffer(query);
4424 * get information about every index on a dumpable table
4426 * Note: index data is not returned directly to the caller, but it
4427 * does get entered into the DumpableObject tables.
4430 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4434 PQExpBuffer query = createPQExpBuffer();
4437 ConstraintInfo *constrinfo;
4456 for (i = 0; i < numTables; i++)
4458 TableInfo *tbinfo = &tblinfo[i];
4460 /* Only plain tables have indexes */
4461 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4464 /* Ignore indexes of tables not to be dumped */
4465 if (!tbinfo->dobj.dump)
4469 write_msg(NULL, "reading indexes for table \"%s\"\n",
4472 /* Make sure we are in proper schema so indexdef is right */
4473 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4476 * The point of the messy-looking outer join is to find a constraint
4477 * that is related by an internal dependency link to the index. If we
4478 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4479 * assume an index won't have more than one internal dependency.
4481 * As of 9.0 we don't need to look at pg_depend but can check for a
4482 * match to pg_constraint.conindid. The check on conrelid is
4483 * redundant but useful because that column is indexed while conindid
4486 resetPQExpBuffer(query);
4487 if (fout->remoteVersion >= 90000)
4489 appendPQExpBuffer(query,
4490 "SELECT t.tableoid, t.oid, "
4491 "t.relname AS indexname, "
4492 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4493 "t.relnatts AS indnkeys, "
4494 "i.indkey, i.indisclustered, "
4495 "c.contype, c.conname, "
4496 "c.condeferrable, c.condeferred, "
4497 "c.tableoid AS contableoid, "
4499 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4500 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4501 "array_to_string(t.reloptions, ', ') AS options "
4502 "FROM pg_catalog.pg_index i "
4503 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4504 "LEFT JOIN pg_catalog.pg_constraint c "
4505 "ON (i.indrelid = c.conrelid AND "
4506 "i.indexrelid = c.conindid AND "
4507 "c.contype IN ('p','u','x')) "
4508 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4509 "ORDER BY indexname",
4510 tbinfo->dobj.catId.oid);
4512 else if (fout->remoteVersion >= 80200)
4514 appendPQExpBuffer(query,
4515 "SELECT t.tableoid, t.oid, "
4516 "t.relname AS indexname, "
4517 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4518 "t.relnatts AS indnkeys, "
4519 "i.indkey, i.indisclustered, "
4520 "c.contype, c.conname, "
4521 "c.condeferrable, c.condeferred, "
4522 "c.tableoid AS contableoid, "
4525 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4526 "array_to_string(t.reloptions, ', ') AS options "
4527 "FROM pg_catalog.pg_index i "
4528 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4529 "LEFT JOIN pg_catalog.pg_depend d "
4530 "ON (d.classid = t.tableoid "
4531 "AND d.objid = t.oid "
4532 "AND d.deptype = 'i') "
4533 "LEFT JOIN pg_catalog.pg_constraint c "
4534 "ON (d.refclassid = c.tableoid "
4535 "AND d.refobjid = c.oid) "
4536 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4537 "ORDER BY indexname",
4538 tbinfo->dobj.catId.oid);
4540 else if (fout->remoteVersion >= 80000)
4542 appendPQExpBuffer(query,
4543 "SELECT t.tableoid, t.oid, "
4544 "t.relname AS indexname, "
4545 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4546 "t.relnatts AS indnkeys, "
4547 "i.indkey, i.indisclustered, "
4548 "c.contype, c.conname, "
4549 "c.condeferrable, c.condeferred, "
4550 "c.tableoid AS contableoid, "
4553 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4555 "FROM pg_catalog.pg_index i "
4556 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4557 "LEFT JOIN pg_catalog.pg_depend d "
4558 "ON (d.classid = t.tableoid "
4559 "AND d.objid = t.oid "
4560 "AND d.deptype = 'i') "
4561 "LEFT JOIN pg_catalog.pg_constraint c "
4562 "ON (d.refclassid = c.tableoid "
4563 "AND d.refobjid = c.oid) "
4564 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4565 "ORDER BY indexname",
4566 tbinfo->dobj.catId.oid);
4568 else if (fout->remoteVersion >= 70300)
4570 appendPQExpBuffer(query,
4571 "SELECT t.tableoid, t.oid, "
4572 "t.relname AS indexname, "
4573 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4574 "t.relnatts AS indnkeys, "
4575 "i.indkey, i.indisclustered, "
4576 "c.contype, c.conname, "
4577 "c.condeferrable, c.condeferred, "
4578 "c.tableoid AS contableoid, "
4581 "NULL AS tablespace, "
4583 "FROM pg_catalog.pg_index i "
4584 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4585 "LEFT JOIN pg_catalog.pg_depend d "
4586 "ON (d.classid = t.tableoid "
4587 "AND d.objid = t.oid "
4588 "AND d.deptype = 'i') "
4589 "LEFT JOIN pg_catalog.pg_constraint c "
4590 "ON (d.refclassid = c.tableoid "
4591 "AND d.refobjid = c.oid) "
4592 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4593 "ORDER BY indexname",
4594 tbinfo->dobj.catId.oid);
4596 else if (fout->remoteVersion >= 70100)
4598 appendPQExpBuffer(query,
4599 "SELECT t.tableoid, t.oid, "
4600 "t.relname AS indexname, "
4601 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4602 "t.relnatts AS indnkeys, "
4603 "i.indkey, false AS indisclustered, "
4604 "CASE WHEN i.indisprimary THEN 'p'::char "
4605 "ELSE '0'::char END AS contype, "
4606 "t.relname AS conname, "
4607 "false AS condeferrable, "
4608 "false AS condeferred, "
4609 "0::oid AS contableoid, "
4612 "NULL AS tablespace, "
4614 "FROM pg_index i, pg_class t "
4615 "WHERE t.oid = i.indexrelid "
4616 "AND i.indrelid = '%u'::oid "
4617 "ORDER BY indexname",
4618 tbinfo->dobj.catId.oid);
4622 appendPQExpBuffer(query,
4624 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4626 "t.relname AS indexname, "
4627 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4628 "t.relnatts AS indnkeys, "
4629 "i.indkey, false AS indisclustered, "
4630 "CASE WHEN i.indisprimary THEN 'p'::char "
4631 "ELSE '0'::char END AS contype, "
4632 "t.relname AS conname, "
4633 "false AS condeferrable, "
4634 "false AS condeferred, "
4635 "0::oid AS contableoid, "
4638 "NULL AS tablespace, "
4640 "FROM pg_index i, pg_class t "
4641 "WHERE t.oid = i.indexrelid "
4642 "AND i.indrelid = '%u'::oid "
4643 "ORDER BY indexname",
4644 tbinfo->dobj.catId.oid);
4647 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4649 ntups = PQntuples(res);
4651 i_tableoid = PQfnumber(res, "tableoid");
4652 i_oid = PQfnumber(res, "oid");
4653 i_indexname = PQfnumber(res, "indexname");
4654 i_indexdef = PQfnumber(res, "indexdef");
4655 i_indnkeys = PQfnumber(res, "indnkeys");
4656 i_indkey = PQfnumber(res, "indkey");
4657 i_indisclustered = PQfnumber(res, "indisclustered");
4658 i_contype = PQfnumber(res, "contype");
4659 i_conname = PQfnumber(res, "conname");
4660 i_condeferrable = PQfnumber(res, "condeferrable");
4661 i_condeferred = PQfnumber(res, "condeferred");
4662 i_contableoid = PQfnumber(res, "contableoid");
4663 i_conoid = PQfnumber(res, "conoid");
4664 i_condef = PQfnumber(res, "condef");
4665 i_tablespace = PQfnumber(res, "tablespace");
4666 i_options = PQfnumber(res, "options");
4668 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4669 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4671 for (j = 0; j < ntups; j++)
4675 indxinfo[j].dobj.objType = DO_INDEX;
4676 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4677 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4678 AssignDumpId(&indxinfo[j].dobj);
4679 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4680 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4681 indxinfo[j].indextable = tbinfo;
4682 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4683 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4684 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4685 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4688 * In pre-7.4 releases, indkeys may contain more entries than
4689 * indnkeys says (since indnkeys will be 1 for a functional
4690 * index). We don't actually care about this case since we don't
4691 * examine indkeys except for indexes associated with PRIMARY and
4692 * UNIQUE constraints, which are never functional indexes. But we
4693 * have to allocate enough space to keep parseOidArray from
4696 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4697 parseOidArray(PQgetvalue(res, j, i_indkey),
4698 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4699 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4700 contype = *(PQgetvalue(res, j, i_contype));
4702 if (contype == 'p' || contype == 'u' || contype == 'x')
4705 * If we found a constraint matching the index, create an
4708 * In a pre-7.3 database, we take this path iff the index was
4709 * marked indisprimary.
4711 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4712 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4713 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4714 AssignDumpId(&constrinfo[j].dobj);
4715 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4716 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4717 constrinfo[j].contable = tbinfo;
4718 constrinfo[j].condomain = NULL;
4719 constrinfo[j].contype = contype;
4721 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4723 constrinfo[j].condef = NULL;
4724 constrinfo[j].confrelid = InvalidOid;
4725 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4726 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4727 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4728 constrinfo[j].conislocal = true;
4729 constrinfo[j].separate = true;
4731 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4733 /* If pre-7.3 DB, better make sure table comes first */
4734 addObjectDependency(&constrinfo[j].dobj,
4735 tbinfo->dobj.dumpId);
4739 /* Plain secondary index */
4740 indxinfo[j].indexconstraint = 0;
4747 destroyPQExpBuffer(query);
4753 * Get info about constraints on dumpable tables.
4755 * Currently handles foreign keys only.
4756 * Unique and primary key constraints are handled with indexes,
4757 * while check constraints are processed in getTableAttrs().
4760 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4764 ConstraintInfo *constrinfo;
4774 /* pg_constraint was created in 7.3, so nothing to do if older */
4775 if (fout->remoteVersion < 70300)
4778 query = createPQExpBuffer();
4780 for (i = 0; i < numTables; i++)
4782 TableInfo *tbinfo = &tblinfo[i];
4784 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4788 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4792 * select table schema to ensure constraint expr is qualified if
4795 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4797 resetPQExpBuffer(query);
4798 appendPQExpBuffer(query,
4799 "SELECT tableoid, oid, conname, confrelid, "
4800 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4801 "FROM pg_catalog.pg_constraint "
4802 "WHERE conrelid = '%u'::pg_catalog.oid "
4803 "AND contype = 'f'",
4804 tbinfo->dobj.catId.oid);
4805 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4807 ntups = PQntuples(res);
4809 i_contableoid = PQfnumber(res, "tableoid");
4810 i_conoid = PQfnumber(res, "oid");
4811 i_conname = PQfnumber(res, "conname");
4812 i_confrelid = PQfnumber(res, "confrelid");
4813 i_condef = PQfnumber(res, "condef");
4815 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4817 for (j = 0; j < ntups; j++)
4819 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4820 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4821 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4822 AssignDumpId(&constrinfo[j].dobj);
4823 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4824 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4825 constrinfo[j].contable = tbinfo;
4826 constrinfo[j].condomain = NULL;
4827 constrinfo[j].contype = 'f';
4828 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4829 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4830 constrinfo[j].conindex = 0;
4831 constrinfo[j].condeferrable = false;
4832 constrinfo[j].condeferred = false;
4833 constrinfo[j].conislocal = true;
4834 constrinfo[j].separate = true;
4840 destroyPQExpBuffer(query);
4844 * getDomainConstraints
4846 * Get info about constraints on a domain.
4849 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4852 ConstraintInfo *constrinfo;
4861 /* pg_constraint was created in 7.3, so nothing to do if older */
4862 if (fout->remoteVersion < 70300)
4866 * select appropriate schema to ensure names in constraint are properly
4869 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4871 query = createPQExpBuffer();
4873 if (fout->remoteVersion >= 90100)
4874 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4875 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4877 "FROM pg_catalog.pg_constraint "
4878 "WHERE contypid = '%u'::pg_catalog.oid "
4880 tyinfo->dobj.catId.oid);
4882 else if (fout->remoteVersion >= 70400)
4883 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4884 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4885 "true as convalidated "
4886 "FROM pg_catalog.pg_constraint "
4887 "WHERE contypid = '%u'::pg_catalog.oid "
4889 tyinfo->dobj.catId.oid);
4891 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4892 "'CHECK (' || consrc || ')' AS consrc, "
4893 "true as convalidated "
4894 "FROM pg_catalog.pg_constraint "
4895 "WHERE contypid = '%u'::pg_catalog.oid "
4897 tyinfo->dobj.catId.oid);
4899 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4901 ntups = PQntuples(res);
4903 i_tableoid = PQfnumber(res, "tableoid");
4904 i_oid = PQfnumber(res, "oid");
4905 i_conname = PQfnumber(res, "conname");
4906 i_consrc = PQfnumber(res, "consrc");
4908 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4910 tyinfo->nDomChecks = ntups;
4911 tyinfo->domChecks = constrinfo;
4913 for (i = 0; i < ntups; i++)
4915 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4917 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4918 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4919 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4920 AssignDumpId(&constrinfo[i].dobj);
4921 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4922 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4923 constrinfo[i].contable = NULL;
4924 constrinfo[i].condomain = tyinfo;
4925 constrinfo[i].contype = 'c';
4926 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4927 constrinfo[i].confrelid = InvalidOid;
4928 constrinfo[i].conindex = 0;
4929 constrinfo[i].condeferrable = false;
4930 constrinfo[i].condeferred = false;
4931 constrinfo[i].conislocal = true;
4933 constrinfo[i].separate = !validated;
4936 * Make the domain depend on the constraint, ensuring it won't be
4937 * output till any constraint dependencies are OK. If the constraint
4938 * has not been validated, it's going to be dumped after the domain
4939 * anyway, so this doesn't matter.
4942 addObjectDependency(&tyinfo->dobj,
4943 constrinfo[i].dobj.dumpId);
4948 destroyPQExpBuffer(query);
4953 * get basic information about every rule in the system
4955 * numRules is set to the number of rules read in
4958 getRules(Archive *fout, int *numRules)
4963 PQExpBuffer query = createPQExpBuffer();
4973 /* Make sure we are in proper schema */
4974 selectSourceSchema(fout, "pg_catalog");
4976 if (fout->remoteVersion >= 80300)
4978 appendPQExpBuffer(query, "SELECT "
4979 "tableoid, oid, rulename, "
4980 "ev_class AS ruletable, ev_type, is_instead, "
4985 else if (fout->remoteVersion >= 70100)
4987 appendPQExpBuffer(query, "SELECT "
4988 "tableoid, oid, rulename, "
4989 "ev_class AS ruletable, ev_type, is_instead, "
4990 "'O'::char AS ev_enabled "
4996 appendPQExpBuffer(query, "SELECT "
4997 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4999 "ev_class AS ruletable, ev_type, is_instead, "
5000 "'O'::char AS ev_enabled "
5005 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5007 ntups = PQntuples(res);
5011 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5013 i_tableoid = PQfnumber(res, "tableoid");
5014 i_oid = PQfnumber(res, "oid");
5015 i_rulename = PQfnumber(res, "rulename");
5016 i_ruletable = PQfnumber(res, "ruletable");
5017 i_ev_type = PQfnumber(res, "ev_type");
5018 i_is_instead = PQfnumber(res, "is_instead");
5019 i_ev_enabled = PQfnumber(res, "ev_enabled");
5021 for (i = 0; i < ntups; i++)
5025 ruleinfo[i].dobj.objType = DO_RULE;
5026 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5027 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5028 AssignDumpId(&ruleinfo[i].dobj);
5029 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5030 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5031 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5032 if (ruleinfo[i].ruletable == NULL)
5033 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5034 ruletableoid, ruleinfo[i].dobj.catId.oid);
5035 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5036 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5037 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5038 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5039 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5040 if (ruleinfo[i].ruletable)
5043 * If the table is a view, force its ON SELECT rule to be sorted
5044 * before the view itself --- this ensures that any dependencies
5045 * for the rule affect the table's positioning. Other rules are
5046 * forced to appear after their table.
5048 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5049 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5051 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5052 ruleinfo[i].dobj.dumpId);
5053 /* We'll merge the rule into CREATE VIEW, if possible */
5054 ruleinfo[i].separate = false;
5058 addObjectDependency(&ruleinfo[i].dobj,
5059 ruleinfo[i].ruletable->dobj.dumpId);
5060 ruleinfo[i].separate = true;
5064 ruleinfo[i].separate = true;
5069 destroyPQExpBuffer(query);
5076 * get information about every trigger on a dumpable table
5078 * Note: trigger data is not returned directly to the caller, but it
5079 * does get entered into the DumpableObject tables.
5082 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5086 PQExpBuffer query = createPQExpBuffer();
5088 TriggerInfo *tginfo;
5106 for (i = 0; i < numTables; i++)
5108 TableInfo *tbinfo = &tblinfo[i];
5110 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5114 write_msg(NULL, "reading triggers for table \"%s\"\n",
5118 * select table schema to ensure regproc name is qualified if needed
5120 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5122 resetPQExpBuffer(query);
5123 if (fout->remoteVersion >= 90000)
5126 * NB: think not to use pretty=true in pg_get_triggerdef. It
5127 * could result in non-forward-compatible dumps of WHEN clauses
5128 * due to under-parenthesization.
5130 appendPQExpBuffer(query,
5132 "tgfoid::pg_catalog.regproc AS tgfname, "
5133 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5134 "tgenabled, tableoid, oid "
5135 "FROM pg_catalog.pg_trigger t "
5136 "WHERE tgrelid = '%u'::pg_catalog.oid "
5137 "AND NOT tgisinternal",
5138 tbinfo->dobj.catId.oid);
5140 else if (fout->remoteVersion >= 80300)
5143 * We ignore triggers that are tied to a foreign-key constraint
5145 appendPQExpBuffer(query,
5147 "tgfoid::pg_catalog.regproc AS tgfname, "
5148 "tgtype, tgnargs, tgargs, tgenabled, "
5149 "tgisconstraint, tgconstrname, tgdeferrable, "
5150 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5151 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5152 "FROM pg_catalog.pg_trigger t "
5153 "WHERE tgrelid = '%u'::pg_catalog.oid "
5154 "AND tgconstraint = 0",
5155 tbinfo->dobj.catId.oid);
5157 else if (fout->remoteVersion >= 70300)
5160 * We ignore triggers that are tied to a foreign-key constraint,
5161 * but in these versions we have to grovel through pg_constraint
5164 appendPQExpBuffer(query,
5166 "tgfoid::pg_catalog.regproc AS tgfname, "
5167 "tgtype, tgnargs, tgargs, tgenabled, "
5168 "tgisconstraint, tgconstrname, tgdeferrable, "
5169 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5170 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5171 "FROM pg_catalog.pg_trigger t "
5172 "WHERE tgrelid = '%u'::pg_catalog.oid "
5173 "AND (NOT tgisconstraint "
5175 " (SELECT 1 FROM pg_catalog.pg_depend d "
5176 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5177 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5178 tbinfo->dobj.catId.oid);
5180 else if (fout->remoteVersion >= 70100)
5182 appendPQExpBuffer(query,
5183 "SELECT tgname, tgfoid::regproc AS tgfname, "
5184 "tgtype, tgnargs, tgargs, tgenabled, "
5185 "tgisconstraint, tgconstrname, tgdeferrable, "
5186 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5187 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5188 " AS tgconstrrelname "
5190 "WHERE tgrelid = '%u'::oid",
5191 tbinfo->dobj.catId.oid);
5195 appendPQExpBuffer(query,
5196 "SELECT tgname, tgfoid::regproc AS tgfname, "
5197 "tgtype, tgnargs, tgargs, tgenabled, "
5198 "tgisconstraint, tgconstrname, tgdeferrable, "
5199 "tgconstrrelid, tginitdeferred, "
5200 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5202 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5203 " AS tgconstrrelname "
5205 "WHERE tgrelid = '%u'::oid",
5206 tbinfo->dobj.catId.oid);
5208 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5210 ntups = PQntuples(res);
5212 i_tableoid = PQfnumber(res, "tableoid");
5213 i_oid = PQfnumber(res, "oid");
5214 i_tgname = PQfnumber(res, "tgname");
5215 i_tgfname = PQfnumber(res, "tgfname");
5216 i_tgtype = PQfnumber(res, "tgtype");
5217 i_tgnargs = PQfnumber(res, "tgnargs");
5218 i_tgargs = PQfnumber(res, "tgargs");
5219 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5220 i_tgconstrname = PQfnumber(res, "tgconstrname");
5221 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5222 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5223 i_tgenabled = PQfnumber(res, "tgenabled");
5224 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5225 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5226 i_tgdef = PQfnumber(res, "tgdef");
5228 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5230 for (j = 0; j < ntups; j++)
5232 tginfo[j].dobj.objType = DO_TRIGGER;
5233 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5234 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5235 AssignDumpId(&tginfo[j].dobj);
5236 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5237 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5238 tginfo[j].tgtable = tbinfo;
5239 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5242 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5244 /* remaining fields are not valid if we have tgdef */
5245 tginfo[j].tgfname = NULL;
5246 tginfo[j].tgtype = 0;
5247 tginfo[j].tgnargs = 0;
5248 tginfo[j].tgargs = NULL;
5249 tginfo[j].tgisconstraint = false;
5250 tginfo[j].tgdeferrable = false;
5251 tginfo[j].tginitdeferred = false;
5252 tginfo[j].tgconstrname = NULL;
5253 tginfo[j].tgconstrrelid = InvalidOid;
5254 tginfo[j].tgconstrrelname = NULL;
5258 tginfo[j].tgdef = NULL;
5260 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5261 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5262 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5263 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5264 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5265 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5266 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5268 if (tginfo[j].tgisconstraint)
5270 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5271 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5272 if (OidIsValid(tginfo[j].tgconstrrelid))
5274 if (PQgetisnull(res, j, i_tgconstrrelname))
5275 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5276 tginfo[j].dobj.name,
5278 tginfo[j].tgconstrrelid);
5279 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5282 tginfo[j].tgconstrrelname = NULL;
5286 tginfo[j].tgconstrname = NULL;
5287 tginfo[j].tgconstrrelid = InvalidOid;
5288 tginfo[j].tgconstrrelname = NULL;
5296 destroyPQExpBuffer(query);
5301 * get basic information about every procedural language in the system
5303 * numProcLangs is set to the number of langs read in
5305 * NB: this must run after getFuncs() because we assume we can do
5309 getProcLangs(Archive *fout, int *numProcLangs)
5314 PQExpBuffer query = createPQExpBuffer();
5315 ProcLangInfo *planginfo;
5320 int i_lanplcallfoid;
5326 /* Make sure we are in proper schema */
5327 selectSourceSchema(fout, "pg_catalog");
5329 if (fout->remoteVersion >= 90000)
5331 /* pg_language has a laninline column */
5332 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5333 "lanname, lanpltrusted, lanplcallfoid, "
5334 "laninline, lanvalidator, lanacl, "
5335 "(%s lanowner) AS lanowner "
5341 else if (fout->remoteVersion >= 80300)
5343 /* pg_language has a lanowner column */
5344 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5345 "lanname, lanpltrusted, lanplcallfoid, "
5346 "lanvalidator, lanacl, "
5347 "(%s lanowner) AS lanowner "
5353 else if (fout->remoteVersion >= 80100)
5355 /* Languages are owned by the bootstrap superuser, OID 10 */
5356 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5357 "(%s '10') AS lanowner "
5363 else if (fout->remoteVersion >= 70400)
5365 /* Languages are owned by the bootstrap superuser, sysid 1 */
5366 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5367 "(%s '1') AS lanowner "
5373 else if (fout->remoteVersion >= 70100)
5375 /* No clear notion of an owner at all before 7.4 ... */
5376 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5382 appendPQExpBuffer(query, "SELECT "
5383 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5384 "oid, * FROM pg_language "
5389 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5391 ntups = PQntuples(res);
5393 *numProcLangs = ntups;
5395 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5397 i_tableoid = PQfnumber(res, "tableoid");
5398 i_oid = PQfnumber(res, "oid");
5399 i_lanname = PQfnumber(res, "lanname");
5400 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5401 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5402 /* these may fail and return -1: */
5403 i_laninline = PQfnumber(res, "laninline");
5404 i_lanvalidator = PQfnumber(res, "lanvalidator");
5405 i_lanacl = PQfnumber(res, "lanacl");
5406 i_lanowner = PQfnumber(res, "lanowner");
5408 for (i = 0; i < ntups; i++)
5410 planginfo[i].dobj.objType = DO_PROCLANG;
5411 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5412 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5413 AssignDumpId(&planginfo[i].dobj);
5415 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5416 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5417 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5418 if (i_laninline >= 0)
5419 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5421 planginfo[i].laninline = InvalidOid;
5422 if (i_lanvalidator >= 0)
5423 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5425 planginfo[i].lanvalidator = InvalidOid;
5427 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5429 planginfo[i].lanacl = pg_strdup("{=U}");
5430 if (i_lanowner >= 0)
5431 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5433 planginfo[i].lanowner = pg_strdup("");
5435 if (fout->remoteVersion < 70300)
5438 * We need to make a dependency to ensure the function will be
5439 * dumped first. (In 7.3 and later the regular dependency
5440 * mechanism will handle this for us.)
5442 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5445 addObjectDependency(&planginfo[i].dobj,
5446 funcInfo->dobj.dumpId);
5452 destroyPQExpBuffer(query);
5459 * get basic information about every cast in the system
5461 * numCasts is set to the number of casts read in
5464 getCasts(Archive *fout, int *numCasts)
5469 PQExpBuffer query = createPQExpBuffer();
5479 /* Make sure we are in proper schema */
5480 selectSourceSchema(fout, "pg_catalog");
5482 if (fout->remoteVersion >= 80400)
5484 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5485 "castsource, casttarget, castfunc, castcontext, "
5487 "FROM pg_cast ORDER BY 3,4");
5489 else if (fout->remoteVersion >= 70300)
5491 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5492 "castsource, casttarget, castfunc, castcontext, "
5493 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5494 "FROM pg_cast ORDER BY 3,4");
5498 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5499 "t1.oid AS castsource, t2.oid AS casttarget, "
5500 "p.oid AS castfunc, 'e' AS castcontext, "
5501 "'f' AS castmethod "
5502 "FROM pg_type t1, pg_type t2, pg_proc p "
5503 "WHERE p.pronargs = 1 AND "
5504 "p.proargtypes[0] = t1.oid AND "
5505 "p.prorettype = t2.oid AND p.proname = t2.typname "
5509 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5511 ntups = PQntuples(res);
5515 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5517 i_tableoid = PQfnumber(res, "tableoid");
5518 i_oid = PQfnumber(res, "oid");
5519 i_castsource = PQfnumber(res, "castsource");
5520 i_casttarget = PQfnumber(res, "casttarget");
5521 i_castfunc = PQfnumber(res, "castfunc");
5522 i_castcontext = PQfnumber(res, "castcontext");
5523 i_castmethod = PQfnumber(res, "castmethod");
5525 for (i = 0; i < ntups; i++)
5527 PQExpBufferData namebuf;
5528 TypeInfo *sTypeInfo;
5529 TypeInfo *tTypeInfo;
5531 castinfo[i].dobj.objType = DO_CAST;
5532 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5533 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5534 AssignDumpId(&castinfo[i].dobj);
5535 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5536 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5537 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5538 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5539 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5542 * Try to name cast as concatenation of typnames. This is only used
5543 * for purposes of sorting. If we fail to find either type, the name
5544 * will be an empty string.
5546 initPQExpBuffer(&namebuf);
5547 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5548 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5549 if (sTypeInfo && tTypeInfo)
5550 appendPQExpBuffer(&namebuf, "%s %s",
5551 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5552 castinfo[i].dobj.name = namebuf.data;
5554 if (OidIsValid(castinfo[i].castfunc))
5557 * We need to make a dependency to ensure the function will be
5558 * dumped first. (In 7.3 and later the regular dependency
5559 * mechanism will handle this for us.)
5563 funcInfo = findFuncByOid(castinfo[i].castfunc);
5565 addObjectDependency(&castinfo[i].dobj,
5566 funcInfo->dobj.dumpId);
5572 destroyPQExpBuffer(query);
5579 * for each interesting table, read info about its attributes
5580 * (names, types, default values, CHECK constraints, etc)
5582 * This is implemented in a very inefficient way right now, looping
5583 * through the tblinfo and doing a join per table to find the attrs and their
5584 * types. However, because we want type names and so forth to be named
5585 * relative to the schema of each table, we couldn't do it in just one
5586 * query. (Maybe one query per schema?)
5591 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5595 PQExpBuffer q = createPQExpBuffer();
5600 int i_attstattarget;
5611 int i_attfdwoptions;
5616 for (i = 0; i < numTables; i++)
5618 TableInfo *tbinfo = &tblinfo[i];
5620 /* Don't bother to collect info for sequences */
5621 if (tbinfo->relkind == RELKIND_SEQUENCE)
5624 /* Don't bother with uninteresting tables, either */
5625 if (!tbinfo->interesting)
5629 * Make sure we are in proper schema for this table; this allows
5630 * correct retrieval of formatted type names and default exprs
5632 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5634 /* find all the user attributes and their types */
5637 * we must read the attribute names in attribute number order! because
5638 * we will use the attnum to index into the attnames array later. We
5639 * actually ask to order by "attrelid, attnum" because (at least up to
5640 * 7.3) the planner is not smart enough to realize it needn't re-sort
5641 * the output of an indexscan on pg_attribute_relid_attnum_index.
5644 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5647 resetPQExpBuffer(q);
5649 if (fout->remoteVersion >= 90200)
5652 * attfdwoptions is new in 9.2.
5654 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5655 "a.attstattarget, a.attstorage, t.typstorage, "
5656 "a.attnotnull, a.atthasdef, a.attisdropped, "
5657 "a.attlen, a.attalign, a.attislocal, "
5658 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5659 "array_to_string(a.attoptions, ', ') AS attoptions, "
5660 "CASE WHEN a.attcollation <> t.typcollation "
5661 "THEN a.attcollation ELSE 0 END AS attcollation, "
5662 "pg_catalog.array_to_string(ARRAY("
5663 "SELECT pg_catalog.quote_ident(option_name) || "
5664 "' ' || pg_catalog.quote_literal(option_value) "
5665 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5666 "ORDER BY option_name"
5667 "), E',\n ') AS attfdwoptions "
5668 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5669 "ON a.atttypid = t.oid "
5670 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5671 "AND a.attnum > 0::pg_catalog.int2 "
5672 "ORDER BY a.attrelid, a.attnum",
5673 tbinfo->dobj.catId.oid);
5675 else if (fout->remoteVersion >= 90100)
5678 * attcollation is new in 9.1. Since we only want to dump COLLATE
5679 * clauses for attributes whose collation is different from their
5680 * type's default, we use a CASE here to suppress uninteresting
5681 * attcollations cheaply.
5683 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5684 "a.attstattarget, a.attstorage, t.typstorage, "
5685 "a.attnotnull, a.atthasdef, a.attisdropped, "
5686 "a.attlen, a.attalign, a.attislocal, "
5687 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5688 "array_to_string(a.attoptions, ', ') AS attoptions, "
5689 "CASE WHEN a.attcollation <> t.typcollation "
5690 "THEN a.attcollation ELSE 0 END AS attcollation, "
5691 "NULL AS attfdwoptions "
5692 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5693 "ON a.atttypid = t.oid "
5694 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5695 "AND a.attnum > 0::pg_catalog.int2 "
5696 "ORDER BY a.attrelid, a.attnum",
5697 tbinfo->dobj.catId.oid);
5699 else if (fout->remoteVersion >= 90000)
5701 /* attoptions is new in 9.0 */
5702 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5703 "a.attstattarget, a.attstorage, t.typstorage, "
5704 "a.attnotnull, a.atthasdef, a.attisdropped, "
5705 "a.attlen, a.attalign, a.attislocal, "
5706 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5707 "array_to_string(a.attoptions, ', ') AS attoptions, "
5708 "0 AS attcollation, "
5709 "NULL AS attfdwoptions "
5710 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5711 "ON a.atttypid = t.oid "
5712 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5713 "AND a.attnum > 0::pg_catalog.int2 "
5714 "ORDER BY a.attrelid, a.attnum",
5715 tbinfo->dobj.catId.oid);
5717 else if (fout->remoteVersion >= 70300)
5719 /* need left join here to not fail on dropped columns ... */
5720 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5721 "a.attstattarget, a.attstorage, t.typstorage, "
5722 "a.attnotnull, a.atthasdef, a.attisdropped, "
5723 "a.attlen, a.attalign, a.attislocal, "
5724 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5725 "'' AS attoptions, 0 AS attcollation, "
5726 "NULL AS attfdwoptions "
5727 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5728 "ON a.atttypid = t.oid "
5729 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5730 "AND a.attnum > 0::pg_catalog.int2 "
5731 "ORDER BY a.attrelid, a.attnum",
5732 tbinfo->dobj.catId.oid);
5734 else if (fout->remoteVersion >= 70100)
5737 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5738 * we don't dump it because we can't tell whether it's been
5739 * explicitly set or was just a default.
5741 * attislocal doesn't exist before 7.3, either; in older databases
5742 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5744 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5745 "-1 AS attstattarget, a.attstorage, "
5746 "t.typstorage, a.attnotnull, a.atthasdef, "
5747 "false AS attisdropped, a.attlen, "
5748 "a.attalign, true AS attislocal, "
5749 "format_type(t.oid,a.atttypmod) AS atttypname, "
5750 "'' AS attoptions, 0 AS attcollation, "
5751 "NULL AS attfdwoptions "
5752 "FROM pg_attribute a LEFT JOIN pg_type t "
5753 "ON a.atttypid = t.oid "
5754 "WHERE a.attrelid = '%u'::oid "
5755 "AND a.attnum > 0::int2 "
5756 "ORDER BY a.attrelid, a.attnum",
5757 tbinfo->dobj.catId.oid);
5761 /* format_type not available before 7.1 */
5762 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5763 "-1 AS attstattarget, "
5764 "attstorage, attstorage AS typstorage, "
5765 "attnotnull, atthasdef, false AS attisdropped, "
5766 "attlen, attalign, "
5767 "true AS attislocal, "
5768 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5769 "'' AS attoptions, 0 AS attcollation, "
5770 "NULL AS attfdwoptions "
5771 "FROM pg_attribute a "
5772 "WHERE attrelid = '%u'::oid "
5773 "AND attnum > 0::int2 "
5774 "ORDER BY attrelid, attnum",
5775 tbinfo->dobj.catId.oid);
5778 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5780 ntups = PQntuples(res);
5782 i_attnum = PQfnumber(res, "attnum");
5783 i_attname = PQfnumber(res, "attname");
5784 i_atttypname = PQfnumber(res, "atttypname");
5785 i_atttypmod = PQfnumber(res, "atttypmod");
5786 i_attstattarget = PQfnumber(res, "attstattarget");
5787 i_attstorage = PQfnumber(res, "attstorage");
5788 i_typstorage = PQfnumber(res, "typstorage");
5789 i_attnotnull = PQfnumber(res, "attnotnull");
5790 i_atthasdef = PQfnumber(res, "atthasdef");
5791 i_attisdropped = PQfnumber(res, "attisdropped");
5792 i_attlen = PQfnumber(res, "attlen");
5793 i_attalign = PQfnumber(res, "attalign");
5794 i_attislocal = PQfnumber(res, "attislocal");
5795 i_attoptions = PQfnumber(res, "attoptions");
5796 i_attcollation = PQfnumber(res, "attcollation");
5797 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5799 tbinfo->numatts = ntups;
5800 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5801 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5802 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5803 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5804 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5805 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5806 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5807 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5808 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5809 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5810 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5811 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5812 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5813 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5814 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5815 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5816 hasdefaults = false;
5818 for (j = 0; j < ntups; j++)
5820 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5822 "invalid column numbering in table \"%s\"\n",
5824 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5825 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5826 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5827 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5828 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5829 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5830 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5831 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5832 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5833 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5834 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5835 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5836 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5837 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5838 tbinfo->attrdefs[j] = NULL; /* fix below */
5839 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5841 /* these flags will be set in flagInhAttrs() */
5842 tbinfo->inhNotNull[j] = false;
5848 * Get info about column defaults
5852 AttrDefInfo *attrdefs;
5856 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5859 resetPQExpBuffer(q);
5860 if (fout->remoteVersion >= 70300)
5862 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5863 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5864 "FROM pg_catalog.pg_attrdef "
5865 "WHERE adrelid = '%u'::pg_catalog.oid",
5866 tbinfo->dobj.catId.oid);
5868 else if (fout->remoteVersion >= 70200)
5870 /* 7.2 did not have OIDs in pg_attrdef */
5871 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5872 "pg_get_expr(adbin, adrelid) AS adsrc "
5874 "WHERE adrelid = '%u'::oid",
5875 tbinfo->dobj.catId.oid);
5877 else if (fout->remoteVersion >= 70100)
5879 /* no pg_get_expr, so must rely on adsrc */
5880 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5882 "WHERE adrelid = '%u'::oid",
5883 tbinfo->dobj.catId.oid);
5887 /* no pg_get_expr, no tableoid either */
5888 appendPQExpBuffer(q, "SELECT "
5889 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5890 "oid, adnum, adsrc "
5892 "WHERE adrelid = '%u'::oid",
5893 tbinfo->dobj.catId.oid);
5895 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5897 numDefaults = PQntuples(res);
5898 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5900 for (j = 0; j < numDefaults; j++)
5904 adnum = atoi(PQgetvalue(res, j, 2));
5906 if (adnum <= 0 || adnum > ntups)
5908 "invalid adnum value %d for table \"%s\"\n",
5909 adnum, tbinfo->dobj.name);
5912 * dropped columns shouldn't have defaults, but just in case,
5915 if (tbinfo->attisdropped[adnum - 1])
5918 attrdefs[j].dobj.objType = DO_ATTRDEF;
5919 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5920 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5921 AssignDumpId(&attrdefs[j].dobj);
5922 attrdefs[j].adtable = tbinfo;
5923 attrdefs[j].adnum = adnum;
5924 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5926 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5927 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5929 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5932 * Defaults on a VIEW must always be dumped as separate ALTER
5933 * TABLE commands. Defaults on regular tables are dumped as
5934 * part of the CREATE TABLE if possible, which it won't be if
5935 * the column is not going to be emitted explicitly.
5937 if (tbinfo->relkind == RELKIND_VIEW)
5939 attrdefs[j].separate = true;
5940 /* needed in case pre-7.3 DB: */
5941 addObjectDependency(&attrdefs[j].dobj,
5942 tbinfo->dobj.dumpId);
5944 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5946 /* column will be suppressed, print default separately */
5947 attrdefs[j].separate = true;
5948 /* needed in case pre-7.3 DB: */
5949 addObjectDependency(&attrdefs[j].dobj,
5950 tbinfo->dobj.dumpId);
5954 attrdefs[j].separate = false;
5957 * Mark the default as needing to appear before the table,
5958 * so that any dependencies it has must be emitted before
5959 * the CREATE TABLE. If this is not possible, we'll
5960 * change to "separate" mode while sorting dependencies.
5962 addObjectDependency(&tbinfo->dobj,
5963 attrdefs[j].dobj.dumpId);
5966 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5972 * Get info about table CHECK constraints
5974 if (tbinfo->ncheck > 0)
5976 ConstraintInfo *constrs;
5980 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5983 resetPQExpBuffer(q);
5984 if (fout->remoteVersion >= 90200)
5987 * convalidated is new in 9.2 (actually, it is there in 9.1,
5988 * but it wasn't ever false for check constraints until 9.2).
5990 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5991 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5992 "conislocal, convalidated "
5993 "FROM pg_catalog.pg_constraint "
5994 "WHERE conrelid = '%u'::pg_catalog.oid "
5995 " AND contype = 'c' "
5997 tbinfo->dobj.catId.oid);
5999 else if (fout->remoteVersion >= 80400)
6001 /* conislocal is new in 8.4 */
6002 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6003 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6004 "conislocal, true AS convalidated "
6005 "FROM pg_catalog.pg_constraint "
6006 "WHERE conrelid = '%u'::pg_catalog.oid "
6007 " AND contype = 'c' "
6009 tbinfo->dobj.catId.oid);
6011 else if (fout->remoteVersion >= 70400)
6013 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6014 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6015 "true AS conislocal, true AS convalidated "
6016 "FROM pg_catalog.pg_constraint "
6017 "WHERE conrelid = '%u'::pg_catalog.oid "
6018 " AND contype = 'c' "
6020 tbinfo->dobj.catId.oid);
6022 else if (fout->remoteVersion >= 70300)
6024 /* no pg_get_constraintdef, must use consrc */
6025 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6026 "'CHECK (' || consrc || ')' AS consrc, "
6027 "true AS conislocal, true AS convalidated "
6028 "FROM pg_catalog.pg_constraint "
6029 "WHERE conrelid = '%u'::pg_catalog.oid "
6030 " AND contype = 'c' "
6032 tbinfo->dobj.catId.oid);
6034 else if (fout->remoteVersion >= 70200)
6036 /* 7.2 did not have OIDs in pg_relcheck */
6037 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6038 "rcname AS conname, "
6039 "'CHECK (' || rcsrc || ')' AS consrc, "
6040 "true AS conislocal, true AS convalidated "
6042 "WHERE rcrelid = '%u'::oid "
6044 tbinfo->dobj.catId.oid);
6046 else if (fout->remoteVersion >= 70100)
6048 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6049 "rcname AS conname, "
6050 "'CHECK (' || rcsrc || ')' AS consrc, "
6051 "true AS conislocal, true AS convalidated "
6053 "WHERE rcrelid = '%u'::oid "
6055 tbinfo->dobj.catId.oid);
6059 /* no tableoid in 7.0 */
6060 appendPQExpBuffer(q, "SELECT "
6061 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6062 "oid, rcname AS conname, "
6063 "'CHECK (' || rcsrc || ')' AS consrc, "
6064 "true AS conislocal, true AS convalidated "
6066 "WHERE rcrelid = '%u'::oid "
6068 tbinfo->dobj.catId.oid);
6070 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6072 numConstrs = PQntuples(res);
6073 if (numConstrs != tbinfo->ncheck)
6075 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6076 "expected %d check constraints on table \"%s\" but found %d\n",
6078 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6079 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6083 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6084 tbinfo->checkexprs = constrs;
6086 for (j = 0; j < numConstrs; j++)
6088 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6090 constrs[j].dobj.objType = DO_CONSTRAINT;
6091 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6092 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6093 AssignDumpId(&constrs[j].dobj);
6094 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6095 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6096 constrs[j].contable = tbinfo;
6097 constrs[j].condomain = NULL;
6098 constrs[j].contype = 'c';
6099 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6100 constrs[j].confrelid = InvalidOid;
6101 constrs[j].conindex = 0;
6102 constrs[j].condeferrable = false;
6103 constrs[j].condeferred = false;
6104 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6107 * An unvalidated constraint needs to be dumped separately, so
6108 * that potentially-violating existing data is loaded before
6111 constrs[j].separate = !validated;
6113 constrs[j].dobj.dump = tbinfo->dobj.dump;
6116 * Mark the constraint as needing to appear before the table
6117 * --- this is so that any other dependencies of the
6118 * constraint will be emitted before we try to create the
6119 * table. If the constraint is to be dumped separately, it
6120 * will be dumped after data is loaded anyway, so don't do it.
6121 * (There's an automatic dependency in the opposite direction
6122 * anyway, so don't need to add one manually here.)
6124 if (!constrs[j].separate)
6125 addObjectDependency(&tbinfo->dobj,
6126 constrs[j].dobj.dumpId);
6129 * If the constraint is inherited, this will be detected later
6130 * (in pre-8.4 databases). We also detect later if the
6131 * constraint must be split out from the table definition.
6138 destroyPQExpBuffer(q);
6142 * Test whether a column should be printed as part of table's CREATE TABLE.
6143 * Column number is zero-based.
6145 * Normally this is always true, but it's false for dropped columns, as well
6146 * as those that were inherited without any local definition. (If we print
6147 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6148 * However, in binary_upgrade mode, we must print all such columns anyway and
6149 * fix the attislocal/attisdropped state later, so as to keep control of the
6150 * physical column order.
6152 * This function exists because there are scattered nonobvious places that
6153 * must be kept in sync with this decision.
6156 shouldPrintColumn(TableInfo *tbinfo, int colno)
6160 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6166 * read all text search parsers in the system catalogs and return them
6167 * in the TSParserInfo* structure
6169 * numTSParsers is set to the number of parsers read in
6172 getTSParsers(Archive *fout, int *numTSParsers)
6178 TSParserInfo *prsinfo;
6189 /* Before 8.3, there is no built-in text search support */
6190 if (fout->remoteVersion < 80300)
6196 query = createPQExpBuffer();
6199 * find all text search objects, including builtin ones; we filter out
6200 * system-defined objects at dump-out time.
6203 /* Make sure we are in proper schema */
6204 selectSourceSchema(fout, "pg_catalog");
6206 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6207 "prsstart::oid, prstoken::oid, "
6208 "prsend::oid, prsheadline::oid, prslextype::oid "
6209 "FROM pg_ts_parser");
6211 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6213 ntups = PQntuples(res);
6214 *numTSParsers = ntups;
6216 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6218 i_tableoid = PQfnumber(res, "tableoid");
6219 i_oid = PQfnumber(res, "oid");
6220 i_prsname = PQfnumber(res, "prsname");
6221 i_prsnamespace = PQfnumber(res, "prsnamespace");
6222 i_prsstart = PQfnumber(res, "prsstart");
6223 i_prstoken = PQfnumber(res, "prstoken");
6224 i_prsend = PQfnumber(res, "prsend");
6225 i_prsheadline = PQfnumber(res, "prsheadline");
6226 i_prslextype = PQfnumber(res, "prslextype");
6228 for (i = 0; i < ntups; i++)
6230 prsinfo[i].dobj.objType = DO_TSPARSER;
6231 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6232 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6233 AssignDumpId(&prsinfo[i].dobj);
6234 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6235 prsinfo[i].dobj.namespace =
6237 atooid(PQgetvalue(res, i, i_prsnamespace)),
6238 prsinfo[i].dobj.catId.oid);
6239 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6240 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6241 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6242 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6243 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6245 /* Decide whether we want to dump it */
6246 selectDumpableObject(&(prsinfo[i].dobj));
6251 destroyPQExpBuffer(query);
6257 * getTSDictionaries:
6258 * read all text search dictionaries in the system catalogs and return them
6259 * in the TSDictInfo* structure
6261 * numTSDicts is set to the number of dictionaries read in
6264 getTSDictionaries(Archive *fout, int *numTSDicts)
6270 TSDictInfo *dictinfo;
6274 int i_dictnamespace;
6277 int i_dictinitoption;
6279 /* Before 8.3, there is no built-in text search support */
6280 if (fout->remoteVersion < 80300)
6286 query = createPQExpBuffer();
6288 /* Make sure we are in proper schema */
6289 selectSourceSchema(fout, "pg_catalog");
6291 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6292 "dictnamespace, (%s dictowner) AS rolname, "
6293 "dicttemplate, dictinitoption "
6297 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6299 ntups = PQntuples(res);
6300 *numTSDicts = ntups;
6302 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6304 i_tableoid = PQfnumber(res, "tableoid");
6305 i_oid = PQfnumber(res, "oid");
6306 i_dictname = PQfnumber(res, "dictname");
6307 i_dictnamespace = PQfnumber(res, "dictnamespace");
6308 i_rolname = PQfnumber(res, "rolname");
6309 i_dictinitoption = PQfnumber(res, "dictinitoption");
6310 i_dicttemplate = PQfnumber(res, "dicttemplate");
6312 for (i = 0; i < ntups; i++)
6314 dictinfo[i].dobj.objType = DO_TSDICT;
6315 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6316 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6317 AssignDumpId(&dictinfo[i].dobj);
6318 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6319 dictinfo[i].dobj.namespace =
6321 atooid(PQgetvalue(res, i, i_dictnamespace)),
6322 dictinfo[i].dobj.catId.oid);
6323 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6324 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6325 if (PQgetisnull(res, i, i_dictinitoption))
6326 dictinfo[i].dictinitoption = NULL;
6328 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6330 /* Decide whether we want to dump it */
6331 selectDumpableObject(&(dictinfo[i].dobj));
6336 destroyPQExpBuffer(query);
6343 * read all text search templates in the system catalogs and return them
6344 * in the TSTemplateInfo* structure
6346 * numTSTemplates is set to the number of templates read in
6349 getTSTemplates(Archive *fout, int *numTSTemplates)
6355 TSTemplateInfo *tmplinfo;
6359 int i_tmplnamespace;
6363 /* Before 8.3, there is no built-in text search support */
6364 if (fout->remoteVersion < 80300)
6366 *numTSTemplates = 0;
6370 query = createPQExpBuffer();
6372 /* Make sure we are in proper schema */
6373 selectSourceSchema(fout, "pg_catalog");
6375 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6376 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6377 "FROM pg_ts_template");
6379 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6381 ntups = PQntuples(res);
6382 *numTSTemplates = ntups;
6384 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6386 i_tableoid = PQfnumber(res, "tableoid");
6387 i_oid = PQfnumber(res, "oid");
6388 i_tmplname = PQfnumber(res, "tmplname");
6389 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6390 i_tmplinit = PQfnumber(res, "tmplinit");
6391 i_tmpllexize = PQfnumber(res, "tmpllexize");
6393 for (i = 0; i < ntups; i++)
6395 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6396 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6397 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6398 AssignDumpId(&tmplinfo[i].dobj);
6399 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6400 tmplinfo[i].dobj.namespace =
6402 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6403 tmplinfo[i].dobj.catId.oid);
6404 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6405 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6407 /* Decide whether we want to dump it */
6408 selectDumpableObject(&(tmplinfo[i].dobj));
6413 destroyPQExpBuffer(query);
6419 * getTSConfigurations:
6420 * read all text search configurations in the system catalogs and return
6421 * them in the TSConfigInfo* structure
6423 * numTSConfigs is set to the number of configurations read in
6426 getTSConfigurations(Archive *fout, int *numTSConfigs)
6432 TSConfigInfo *cfginfo;
6440 /* Before 8.3, there is no built-in text search support */
6441 if (fout->remoteVersion < 80300)
6447 query = createPQExpBuffer();
6449 /* Make sure we are in proper schema */
6450 selectSourceSchema(fout, "pg_catalog");
6452 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6453 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6454 "FROM pg_ts_config",
6457 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6459 ntups = PQntuples(res);
6460 *numTSConfigs = ntups;
6462 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6464 i_tableoid = PQfnumber(res, "tableoid");
6465 i_oid = PQfnumber(res, "oid");
6466 i_cfgname = PQfnumber(res, "cfgname");
6467 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6468 i_rolname = PQfnumber(res, "rolname");
6469 i_cfgparser = PQfnumber(res, "cfgparser");
6471 for (i = 0; i < ntups; i++)
6473 cfginfo[i].dobj.objType = DO_TSCONFIG;
6474 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6475 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6476 AssignDumpId(&cfginfo[i].dobj);
6477 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6478 cfginfo[i].dobj.namespace =
6480 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6481 cfginfo[i].dobj.catId.oid);
6482 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6483 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6485 /* Decide whether we want to dump it */
6486 selectDumpableObject(&(cfginfo[i].dobj));
6491 destroyPQExpBuffer(query);
6497 * getForeignDataWrappers:
6498 * read all foreign-data wrappers in the system catalogs and return
6499 * them in the FdwInfo* structure
6501 * numForeignDataWrappers is set to the number of fdws read in
6504 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6509 PQExpBuffer query = createPQExpBuffer();
6520 /* Before 8.4, there are no foreign-data wrappers */
6521 if (fout->remoteVersion < 80400)
6523 *numForeignDataWrappers = 0;
6527 /* Make sure we are in proper schema */
6528 selectSourceSchema(fout, "pg_catalog");
6530 if (fout->remoteVersion >= 90100)
6532 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6533 "(%s fdwowner) AS rolname, "
6534 "fdwhandler::pg_catalog.regproc, "
6535 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6536 "array_to_string(ARRAY("
6537 "SELECT quote_ident(option_name) || ' ' || "
6538 "quote_literal(option_value) "
6539 "FROM pg_options_to_table(fdwoptions) "
6540 "ORDER BY option_name"
6541 "), E',\n ') AS fdwoptions "
6542 "FROM pg_foreign_data_wrapper",
6547 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6548 "(%s fdwowner) AS rolname, "
6549 "'-' AS fdwhandler, "
6550 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6551 "array_to_string(ARRAY("
6552 "SELECT quote_ident(option_name) || ' ' || "
6553 "quote_literal(option_value) "
6554 "FROM pg_options_to_table(fdwoptions) "
6555 "ORDER BY option_name"
6556 "), E',\n ') AS fdwoptions "
6557 "FROM pg_foreign_data_wrapper",
6561 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6563 ntups = PQntuples(res);
6564 *numForeignDataWrappers = ntups;
6566 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6568 i_tableoid = PQfnumber(res, "tableoid");
6569 i_oid = PQfnumber(res, "oid");
6570 i_fdwname = PQfnumber(res, "fdwname");
6571 i_rolname = PQfnumber(res, "rolname");
6572 i_fdwhandler = PQfnumber(res, "fdwhandler");
6573 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6574 i_fdwacl = PQfnumber(res, "fdwacl");
6575 i_fdwoptions = PQfnumber(res, "fdwoptions");
6577 for (i = 0; i < ntups; i++)
6579 fdwinfo[i].dobj.objType = DO_FDW;
6580 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6581 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6582 AssignDumpId(&fdwinfo[i].dobj);
6583 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6584 fdwinfo[i].dobj.namespace = NULL;
6585 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6586 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6587 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6588 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6589 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6591 /* Decide whether we want to dump it */
6592 selectDumpableObject(&(fdwinfo[i].dobj));
6597 destroyPQExpBuffer(query);
6603 * getForeignServers:
6604 * read all foreign servers in the system catalogs and return
6605 * them in the ForeignServerInfo * structure
6607 * numForeignServers is set to the number of servers read in
6610 getForeignServers(Archive *fout, int *numForeignServers)
6615 PQExpBuffer query = createPQExpBuffer();
6616 ForeignServerInfo *srvinfo;
6627 /* Before 8.4, there are no foreign servers */
6628 if (fout->remoteVersion < 80400)
6630 *numForeignServers = 0;
6634 /* Make sure we are in proper schema */
6635 selectSourceSchema(fout, "pg_catalog");
6637 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6638 "(%s srvowner) AS rolname, "
6639 "srvfdw, srvtype, srvversion, srvacl,"
6640 "array_to_string(ARRAY("
6641 "SELECT quote_ident(option_name) || ' ' || "
6642 "quote_literal(option_value) "
6643 "FROM pg_options_to_table(srvoptions) "
6644 "ORDER BY option_name"
6645 "), E',\n ') AS srvoptions "
6646 "FROM pg_foreign_server",
6649 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6651 ntups = PQntuples(res);
6652 *numForeignServers = ntups;
6654 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6656 i_tableoid = PQfnumber(res, "tableoid");
6657 i_oid = PQfnumber(res, "oid");
6658 i_srvname = PQfnumber(res, "srvname");
6659 i_rolname = PQfnumber(res, "rolname");
6660 i_srvfdw = PQfnumber(res, "srvfdw");
6661 i_srvtype = PQfnumber(res, "srvtype");
6662 i_srvversion = PQfnumber(res, "srvversion");
6663 i_srvacl = PQfnumber(res, "srvacl");
6664 i_srvoptions = PQfnumber(res, "srvoptions");
6666 for (i = 0; i < ntups; i++)
6668 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6669 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6670 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6671 AssignDumpId(&srvinfo[i].dobj);
6672 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6673 srvinfo[i].dobj.namespace = NULL;
6674 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6675 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6676 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6677 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6678 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6679 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6681 /* Decide whether we want to dump it */
6682 selectDumpableObject(&(srvinfo[i].dobj));
6687 destroyPQExpBuffer(query);
6694 * read all default ACL information in the system catalogs and return
6695 * them in the DefaultACLInfo structure
6697 * numDefaultACLs is set to the number of ACLs read in
6700 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6702 DefaultACLInfo *daclinfo;
6708 int i_defaclnamespace;
6709 int i_defaclobjtype;
6714 if (fout->remoteVersion < 90000)
6716 *numDefaultACLs = 0;
6720 query = createPQExpBuffer();
6722 /* Make sure we are in proper schema */
6723 selectSourceSchema(fout, "pg_catalog");
6725 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6726 "(%s defaclrole) AS defaclrole, "
6730 "FROM pg_default_acl",
6733 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6735 ntups = PQntuples(res);
6736 *numDefaultACLs = ntups;
6738 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6740 i_oid = PQfnumber(res, "oid");
6741 i_tableoid = PQfnumber(res, "tableoid");
6742 i_defaclrole = PQfnumber(res, "defaclrole");
6743 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6744 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6745 i_defaclacl = PQfnumber(res, "defaclacl");
6747 for (i = 0; i < ntups; i++)
6749 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6751 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6752 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6753 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6754 AssignDumpId(&daclinfo[i].dobj);
6755 /* cheesy ... is it worth coming up with a better object name? */
6756 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6758 if (nspid != InvalidOid)
6759 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6760 daclinfo[i].dobj.catId.oid);
6762 daclinfo[i].dobj.namespace = NULL;
6764 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6765 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6766 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6768 /* Decide whether we want to dump it */
6769 selectDumpableDefaultACL(&(daclinfo[i]));
6774 destroyPQExpBuffer(query);
6782 * This routine is used to dump any comments associated with the
6783 * object handed to this routine. The routine takes a constant character
6784 * string for the target part of the comment-creation command, plus
6785 * the namespace and owner of the object (for labeling the ArchiveEntry),
6786 * plus catalog ID and subid which are the lookup key for pg_description,
6787 * plus the dump ID for the object (for setting a dependency).
6788 * If a matching pg_description entry is found, it is dumped.
6790 * Note: although this routine takes a dumpId for dependency purposes,
6791 * that purpose is just to mark the dependency in the emitted dump file
6792 * for possible future use by pg_restore. We do NOT use it for determining
6793 * ordering of the comment in the dump file, because this routine is called
6794 * after dependency sorting occurs. This routine should be called just after
6795 * calling ArchiveEntry() for the specified object.
6798 dumpComment(Archive *fout, const char *target,
6799 const char *namespace, const char *owner,
6800 CatalogId catalogId, int subid, DumpId dumpId)
6802 CommentItem *comments;
6805 /* Comments are schema not data ... except blob comments are data */
6806 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6817 /* Search for comments associated with catalogId, using table */
6818 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6821 /* Is there one matching the subid? */
6822 while (ncomments > 0)
6824 if (comments->objsubid == subid)
6830 /* If a comment exists, build COMMENT ON statement */
6833 PQExpBuffer query = createPQExpBuffer();
6835 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6836 appendStringLiteralAH(query, comments->descr, fout);
6837 appendPQExpBuffer(query, ";\n");
6840 * We mark comments as SECTION_NONE because they really belong in the
6841 * same section as their parent, whether that is pre-data or
6844 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6845 target, namespace, NULL, owner,
6846 false, "COMMENT", SECTION_NONE,
6847 query->data, "", NULL,
6851 destroyPQExpBuffer(query);
6856 * dumpTableComment --
6858 * As above, but dump comments for both the specified table (or view)
6862 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6863 const char *reltypename)
6865 CommentItem *comments;
6870 /* Comments are SCHEMA not data */
6874 /* Search for comments associated with relation, using table */
6875 ncomments = findComments(fout,
6876 tbinfo->dobj.catId.tableoid,
6877 tbinfo->dobj.catId.oid,
6880 /* If comments exist, build COMMENT ON statements */
6884 query = createPQExpBuffer();
6885 target = createPQExpBuffer();
6887 while (ncomments > 0)
6889 const char *descr = comments->descr;
6890 int objsubid = comments->objsubid;
6894 resetPQExpBuffer(target);
6895 appendPQExpBuffer(target, "%s %s", reltypename,
6896 fmtId(tbinfo->dobj.name));
6898 resetPQExpBuffer(query);
6899 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6900 appendStringLiteralAH(query, descr, fout);
6901 appendPQExpBuffer(query, ";\n");
6903 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6905 tbinfo->dobj.namespace->dobj.name,
6906 NULL, tbinfo->rolname,
6907 false, "COMMENT", SECTION_NONE,
6908 query->data, "", NULL,
6909 &(tbinfo->dobj.dumpId), 1,
6912 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6914 resetPQExpBuffer(target);
6915 appendPQExpBuffer(target, "COLUMN %s.",
6916 fmtId(tbinfo->dobj.name));
6917 appendPQExpBuffer(target, "%s",
6918 fmtId(tbinfo->attnames[objsubid - 1]));
6920 resetPQExpBuffer(query);
6921 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6922 appendStringLiteralAH(query, descr, fout);
6923 appendPQExpBuffer(query, ";\n");
6925 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6927 tbinfo->dobj.namespace->dobj.name,
6928 NULL, tbinfo->rolname,
6929 false, "COMMENT", SECTION_NONE,
6930 query->data, "", NULL,
6931 &(tbinfo->dobj.dumpId), 1,
6939 destroyPQExpBuffer(query);
6940 destroyPQExpBuffer(target);
6946 * Find the comment(s), if any, associated with the given object. All the
6947 * objsubid values associated with the given classoid/objoid are found with
6951 findComments(Archive *fout, Oid classoid, Oid objoid,
6952 CommentItem **items)
6954 /* static storage for table of comments */
6955 static CommentItem *comments = NULL;
6956 static int ncomments = -1;
6958 CommentItem *middle = NULL;
6963 /* Get comments if we didn't already */
6965 ncomments = collectComments(fout, &comments);
6968 * Pre-7.2, pg_description does not contain classoid, so collectComments
6969 * just stores a zero. If there's a collision on object OID, well, you
6970 * get duplicate comments.
6972 if (fout->remoteVersion < 70200)
6976 * Do binary search to find some item matching the object.
6979 high = &comments[ncomments - 1];
6982 middle = low + (high - low) / 2;
6984 if (classoid < middle->classoid)
6986 else if (classoid > middle->classoid)
6988 else if (objoid < middle->objoid)
6990 else if (objoid > middle->objoid)
6993 break; /* found a match */
6996 if (low > high) /* no matches */
7003 * Now determine how many items match the object. The search loop
7004 * invariant still holds: only items between low and high inclusive could
7008 while (middle > low)
7010 if (classoid != middle[-1].classoid ||
7011 objoid != middle[-1].objoid)
7020 while (middle <= high)
7022 if (classoid != middle->classoid ||
7023 objoid != middle->objoid)
7033 * collectComments --
7035 * Construct a table of all comments available for database objects.
7036 * We used to do per-object queries for the comments, but it's much faster
7037 * to pull them all over at once, and on most databases the memory cost
7040 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7043 collectComments(Archive *fout, CommentItem **items)
7053 CommentItem *comments;
7056 * Note we do NOT change source schema here; preserve the caller's
7060 query = createPQExpBuffer();
7062 if (fout->remoteVersion >= 70300)
7064 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7065 "FROM pg_catalog.pg_description "
7066 "ORDER BY classoid, objoid, objsubid");
7068 else if (fout->remoteVersion >= 70200)
7070 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7071 "FROM pg_description "
7072 "ORDER BY classoid, objoid, objsubid");
7076 /* Note: this will fail to find attribute comments in pre-7.2... */
7077 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7078 "FROM pg_description "
7082 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7084 /* Construct lookup table containing OIDs in numeric form */
7086 i_description = PQfnumber(res, "description");
7087 i_classoid = PQfnumber(res, "classoid");
7088 i_objoid = PQfnumber(res, "objoid");
7089 i_objsubid = PQfnumber(res, "objsubid");
7091 ntups = PQntuples(res);
7093 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7095 for (i = 0; i < ntups; i++)
7097 comments[i].descr = PQgetvalue(res, i, i_description);
7098 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7099 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7100 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7103 /* Do NOT free the PGresult since we are keeping pointers into it */
7104 destroyPQExpBuffer(query);
7111 * dumpDumpableObject
7113 * This routine and its subsidiaries are responsible for creating
7114 * ArchiveEntries (TOC objects) for each object to be dumped.
7117 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7119 switch (dobj->objType)
7122 dumpNamespace(fout, (NamespaceInfo *) dobj);
7125 dumpExtension(fout, (ExtensionInfo *) dobj);
7128 dumpType(fout, (TypeInfo *) dobj);
7131 dumpShellType(fout, (ShellTypeInfo *) dobj);
7134 dumpFunc(fout, (FuncInfo *) dobj);
7137 dumpAgg(fout, (AggInfo *) dobj);
7140 dumpOpr(fout, (OprInfo *) dobj);
7143 dumpOpclass(fout, (OpclassInfo *) dobj);
7146 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7149 dumpCollation(fout, (CollInfo *) dobj);
7152 dumpConversion(fout, (ConvInfo *) dobj);
7155 dumpTable(fout, (TableInfo *) dobj);
7158 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7161 dumpIndex(fout, (IndxInfo *) dobj);
7164 dumpRule(fout, (RuleInfo *) dobj);
7167 dumpTrigger(fout, (TriggerInfo *) dobj);
7170 dumpConstraint(fout, (ConstraintInfo *) dobj);
7172 case DO_FK_CONSTRAINT:
7173 dumpConstraint(fout, (ConstraintInfo *) dobj);
7176 dumpProcLang(fout, (ProcLangInfo *) dobj);
7179 dumpCast(fout, (CastInfo *) dobj);
7182 dumpTableData(fout, (TableDataInfo *) dobj);
7185 /* table rowtypes and array types are never dumped separately */
7188 dumpTSParser(fout, (TSParserInfo *) dobj);
7191 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7194 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7197 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7200 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7202 case DO_FOREIGN_SERVER:
7203 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7205 case DO_DEFAULT_ACL:
7206 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7209 dumpBlob(fout, (BlobInfo *) dobj);
7212 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7213 dobj->name, NULL, NULL, "",
7214 false, "BLOBS", SECTION_DATA,
7219 case DO_PRE_DATA_BOUNDARY:
7220 case DO_POST_DATA_BOUNDARY:
7221 /* never dumped, nothing to do */
7228 * writes out to fout the queries to recreate a user-defined namespace
7231 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7238 /* Skip if not to be dumped */
7239 if (!nspinfo->dobj.dump || dataOnly)
7242 /* don't dump dummy namespace from pre-7.3 source */
7243 if (strlen(nspinfo->dobj.name) == 0)
7246 q = createPQExpBuffer();
7247 delq = createPQExpBuffer();
7248 labelq = createPQExpBuffer();
7250 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7252 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7254 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7256 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7259 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7261 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7265 false, "SCHEMA", SECTION_PRE_DATA,
7266 q->data, delq->data, NULL,
7270 /* Dump Schema Comments and Security Labels */
7271 dumpComment(fout, labelq->data,
7272 NULL, nspinfo->rolname,
7273 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7274 dumpSecLabel(fout, labelq->data,
7275 NULL, nspinfo->rolname,
7276 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7278 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7279 qnspname, NULL, nspinfo->dobj.name, NULL,
7280 nspinfo->rolname, nspinfo->nspacl);
7284 destroyPQExpBuffer(q);
7285 destroyPQExpBuffer(delq);
7286 destroyPQExpBuffer(labelq);
7291 * writes out to fout the queries to recreate an extension
7294 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7301 /* Skip if not to be dumped */
7302 if (!extinfo->dobj.dump || dataOnly)
7305 q = createPQExpBuffer();
7306 delq = createPQExpBuffer();
7307 labelq = createPQExpBuffer();
7309 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7311 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7313 if (!binary_upgrade)
7316 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7317 * problem if the extension already exists in the target database;
7318 * this is essential for installed-by-default extensions such as
7321 * In binary-upgrade mode, that doesn't work well, so instead we skip
7322 * built-in extensions based on their OIDs; see
7323 * selectDumpableExtension.
7325 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7326 qextname, fmtId(extinfo->namespace));
7333 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7334 appendPQExpBuffer(q,
7335 "SELECT binary_upgrade.create_empty_extension(");
7336 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7337 appendPQExpBuffer(q, ", ");
7338 appendStringLiteralAH(q, extinfo->namespace, fout);
7339 appendPQExpBuffer(q, ", ");
7340 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7341 appendStringLiteralAH(q, extinfo->extversion, fout);
7342 appendPQExpBuffer(q, ", ");
7345 * Note that we're pushing extconfig (an OID array) back into
7346 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7347 * preserved in binary upgrade.
7349 if (strlen(extinfo->extconfig) > 2)
7350 appendStringLiteralAH(q, extinfo->extconfig, fout);
7352 appendPQExpBuffer(q, "NULL");
7353 appendPQExpBuffer(q, ", ");
7354 if (strlen(extinfo->extcondition) > 2)
7355 appendStringLiteralAH(q, extinfo->extcondition, fout);
7357 appendPQExpBuffer(q, "NULL");
7358 appendPQExpBuffer(q, ", ");
7359 appendPQExpBuffer(q, "ARRAY[");
7361 for (i = 0; i < extinfo->dobj.nDeps; i++)
7363 DumpableObject *extobj;
7365 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7366 if (extobj && extobj->objType == DO_EXTENSION)
7369 appendPQExpBuffer(q, ",");
7370 appendStringLiteralAH(q, extobj->name, fout);
7373 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7374 appendPQExpBuffer(q, ");\n");
7377 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7379 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7383 false, "EXTENSION", SECTION_PRE_DATA,
7384 q->data, delq->data, NULL,
7388 /* Dump Extension Comments and Security Labels */
7389 dumpComment(fout, labelq->data,
7391 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7392 dumpSecLabel(fout, labelq->data,
7394 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7398 destroyPQExpBuffer(q);
7399 destroyPQExpBuffer(delq);
7400 destroyPQExpBuffer(labelq);
7405 * writes out to fout the queries to recreate a user-defined type
7408 dumpType(Archive *fout, TypeInfo *tyinfo)
7410 /* Skip if not to be dumped */
7411 if (!tyinfo->dobj.dump || dataOnly)
7414 /* Dump out in proper style */
7415 if (tyinfo->typtype == TYPTYPE_BASE)
7416 dumpBaseType(fout, tyinfo);
7417 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7418 dumpDomain(fout, tyinfo);
7419 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7420 dumpCompositeType(fout, tyinfo);
7421 else if (tyinfo->typtype == TYPTYPE_ENUM)
7422 dumpEnumType(fout, tyinfo);
7423 else if (tyinfo->typtype == TYPTYPE_RANGE)
7424 dumpRangeType(fout, tyinfo);
7426 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7432 * writes out to fout the queries to recreate a user-defined enum type
7435 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7437 PQExpBuffer q = createPQExpBuffer();
7438 PQExpBuffer delq = createPQExpBuffer();
7439 PQExpBuffer labelq = createPQExpBuffer();
7440 PQExpBuffer query = createPQExpBuffer();
7447 /* Set proper schema search path */
7448 selectSourceSchema(fout, "pg_catalog");
7450 if (fout->remoteVersion >= 90100)
7451 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7452 "FROM pg_catalog.pg_enum "
7453 "WHERE enumtypid = '%u'"
7454 "ORDER BY enumsortorder",
7455 tyinfo->dobj.catId.oid);
7457 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7458 "FROM pg_catalog.pg_enum "
7459 "WHERE enumtypid = '%u'"
7461 tyinfo->dobj.catId.oid);
7463 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7465 num = PQntuples(res);
7468 * DROP must be fully qualified in case same name appears in pg_catalog.
7469 * CASCADE shouldn't be required here as for normal types since the I/O
7470 * functions are generic and do not get dropped.
7472 appendPQExpBuffer(delq, "DROP TYPE %s.",
7473 fmtId(tyinfo->dobj.namespace->dobj.name));
7474 appendPQExpBuffer(delq, "%s;\n",
7475 fmtId(tyinfo->dobj.name));
7478 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7479 tyinfo->dobj.catId.oid);
7481 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7482 fmtId(tyinfo->dobj.name));
7484 if (!binary_upgrade)
7486 /* Labels with server-assigned oids */
7487 for (i = 0; i < num; i++)
7489 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7491 appendPQExpBuffer(q, ",");
7492 appendPQExpBuffer(q, "\n ");
7493 appendStringLiteralAH(q, label, fout);
7497 appendPQExpBuffer(q, "\n);\n");
7501 /* Labels with dump-assigned (preserved) oids */
7502 for (i = 0; i < num; i++)
7504 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7505 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7508 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7509 appendPQExpBuffer(q,
7510 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7512 appendPQExpBuffer(q, "ALTER TYPE %s.",
7513 fmtId(tyinfo->dobj.namespace->dobj.name));
7514 appendPQExpBuffer(q, "%s ADD VALUE ",
7515 fmtId(tyinfo->dobj.name));
7516 appendStringLiteralAH(q, label, fout);
7517 appendPQExpBuffer(q, ";\n\n");
7521 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7524 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7526 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7528 tyinfo->dobj.namespace->dobj.name,
7530 tyinfo->rolname, false,
7531 "TYPE", SECTION_PRE_DATA,
7532 q->data, delq->data, NULL,
7536 /* Dump Type Comments and Security Labels */
7537 dumpComment(fout, labelq->data,
7538 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7539 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7540 dumpSecLabel(fout, labelq->data,
7541 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7542 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7545 destroyPQExpBuffer(q);
7546 destroyPQExpBuffer(delq);
7547 destroyPQExpBuffer(labelq);
7548 destroyPQExpBuffer(query);
7553 * writes out to fout the queries to recreate a user-defined range type
7556 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7558 PQExpBuffer q = createPQExpBuffer();
7559 PQExpBuffer delq = createPQExpBuffer();
7560 PQExpBuffer labelq = createPQExpBuffer();
7561 PQExpBuffer query = createPQExpBuffer();
7567 * select appropriate schema to ensure names in CREATE are properly
7570 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7572 appendPQExpBuffer(query,
7573 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7574 "opc.opcname AS opcname, "
7575 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7576 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7578 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7579 " ELSE rngcollation END AS collation, "
7580 "rngcanonical, rngsubdiff "
7581 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7582 " pg_catalog.pg_opclass opc "
7583 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7585 tyinfo->dobj.catId.oid);
7587 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7590 * DROP must be fully qualified in case same name appears in pg_catalog.
7591 * CASCADE shouldn't be required here as for normal types since the I/O
7592 * functions are generic and do not get dropped.
7594 appendPQExpBuffer(delq, "DROP TYPE %s.",
7595 fmtId(tyinfo->dobj.namespace->dobj.name));
7596 appendPQExpBuffer(delq, "%s;\n",
7597 fmtId(tyinfo->dobj.name));
7600 binary_upgrade_set_type_oids_by_type_oid(fout,
7601 q, tyinfo->dobj.catId.oid);
7603 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7604 fmtId(tyinfo->dobj.name));
7606 appendPQExpBuffer(q, "\n subtype = %s",
7607 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7609 /* print subtype_opclass only if not default for subtype */
7610 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7612 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7613 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7615 /* always schema-qualify, don't try to be smart */
7616 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7618 appendPQExpBuffer(q, "%s", fmtId(opcname));
7621 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7622 if (OidIsValid(collationOid))
7624 CollInfo *coll = findCollationByOid(collationOid);
7628 /* always schema-qualify, don't try to be smart */
7629 appendPQExpBuffer(q, ",\n collation = %s.",
7630 fmtId(coll->dobj.namespace->dobj.name));
7631 appendPQExpBuffer(q, "%s",
7632 fmtId(coll->dobj.name));
7636 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7637 if (strcmp(procname, "-") != 0)
7638 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7640 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7641 if (strcmp(procname, "-") != 0)
7642 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7644 appendPQExpBuffer(q, "\n);\n");
7646 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7649 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7651 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7653 tyinfo->dobj.namespace->dobj.name,
7655 tyinfo->rolname, false,
7656 "TYPE", SECTION_PRE_DATA,
7657 q->data, delq->data, NULL,
7661 /* Dump Type Comments and Security Labels */
7662 dumpComment(fout, labelq->data,
7663 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7664 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7665 dumpSecLabel(fout, labelq->data,
7666 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7667 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7670 destroyPQExpBuffer(q);
7671 destroyPQExpBuffer(delq);
7672 destroyPQExpBuffer(labelq);
7673 destroyPQExpBuffer(query);
7678 * writes out to fout the queries to recreate a user-defined base type
7681 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7683 PQExpBuffer q = createPQExpBuffer();
7684 PQExpBuffer delq = createPQExpBuffer();
7685 PQExpBuffer labelq = createPQExpBuffer();
7686 PQExpBuffer query = createPQExpBuffer();
7702 char *typispreferred;
7707 char *typcollatable;
7709 bool typdefault_is_literal = false;
7711 /* Set proper schema search path so regproc references list correctly */
7712 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7714 /* Fetch type-specific details */
7715 if (fout->remoteVersion >= 90100)
7717 appendPQExpBuffer(query, "SELECT typlen, "
7718 "typinput, typoutput, typreceive, typsend, "
7719 "typmodin, typmodout, typanalyze, "
7720 "typreceive::pg_catalog.oid AS typreceiveoid, "
7721 "typsend::pg_catalog.oid AS typsendoid, "
7722 "typmodin::pg_catalog.oid AS typmodinoid, "
7723 "typmodout::pg_catalog.oid AS typmodoutoid, "
7724 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7725 "typcategory, typispreferred, "
7726 "typdelim, typbyval, typalign, typstorage, "
7727 "(typcollation <> 0) AS typcollatable, "
7728 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7729 "FROM pg_catalog.pg_type "
7730 "WHERE oid = '%u'::pg_catalog.oid",
7731 tyinfo->dobj.catId.oid);
7733 else if (fout->remoteVersion >= 80400)
7735 appendPQExpBuffer(query, "SELECT typlen, "
7736 "typinput, typoutput, typreceive, typsend, "
7737 "typmodin, typmodout, typanalyze, "
7738 "typreceive::pg_catalog.oid AS typreceiveoid, "
7739 "typsend::pg_catalog.oid AS typsendoid, "
7740 "typmodin::pg_catalog.oid AS typmodinoid, "
7741 "typmodout::pg_catalog.oid AS typmodoutoid, "
7742 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7743 "typcategory, typispreferred, "
7744 "typdelim, typbyval, typalign, typstorage, "
7745 "false AS typcollatable, "
7746 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7747 "FROM pg_catalog.pg_type "
7748 "WHERE oid = '%u'::pg_catalog.oid",
7749 tyinfo->dobj.catId.oid);
7751 else if (fout->remoteVersion >= 80300)
7753 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7754 appendPQExpBuffer(query, "SELECT typlen, "
7755 "typinput, typoutput, typreceive, typsend, "
7756 "typmodin, typmodout, typanalyze, "
7757 "typreceive::pg_catalog.oid AS typreceiveoid, "
7758 "typsend::pg_catalog.oid AS typsendoid, "
7759 "typmodin::pg_catalog.oid AS typmodinoid, "
7760 "typmodout::pg_catalog.oid AS typmodoutoid, "
7761 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7762 "'U' AS typcategory, false AS typispreferred, "
7763 "typdelim, typbyval, typalign, typstorage, "
7764 "false AS typcollatable, "
7765 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7766 "FROM pg_catalog.pg_type "
7767 "WHERE oid = '%u'::pg_catalog.oid",
7768 tyinfo->dobj.catId.oid);
7770 else if (fout->remoteVersion >= 80000)
7772 appendPQExpBuffer(query, "SELECT typlen, "
7773 "typinput, typoutput, typreceive, typsend, "
7774 "'-' AS typmodin, '-' AS typmodout, "
7776 "typreceive::pg_catalog.oid AS typreceiveoid, "
7777 "typsend::pg_catalog.oid AS typsendoid, "
7778 "0 AS typmodinoid, 0 AS typmodoutoid, "
7779 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7780 "'U' AS typcategory, false AS typispreferred, "
7781 "typdelim, typbyval, typalign, typstorage, "
7782 "false AS typcollatable, "
7783 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7784 "FROM pg_catalog.pg_type "
7785 "WHERE oid = '%u'::pg_catalog.oid",
7786 tyinfo->dobj.catId.oid);
7788 else if (fout->remoteVersion >= 70400)
7790 appendPQExpBuffer(query, "SELECT typlen, "
7791 "typinput, typoutput, typreceive, typsend, "
7792 "'-' AS typmodin, '-' AS typmodout, "
7793 "'-' AS typanalyze, "
7794 "typreceive::pg_catalog.oid AS typreceiveoid, "
7795 "typsend::pg_catalog.oid AS typsendoid, "
7796 "0 AS typmodinoid, 0 AS typmodoutoid, "
7797 "0 AS typanalyzeoid, "
7798 "'U' AS typcategory, false AS typispreferred, "
7799 "typdelim, typbyval, typalign, typstorage, "
7800 "false AS typcollatable, "
7801 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7802 "FROM pg_catalog.pg_type "
7803 "WHERE oid = '%u'::pg_catalog.oid",
7804 tyinfo->dobj.catId.oid);
7806 else if (fout->remoteVersion >= 70300)
7808 appendPQExpBuffer(query, "SELECT typlen, "
7809 "typinput, typoutput, "
7810 "'-' AS typreceive, '-' AS typsend, "
7811 "'-' AS typmodin, '-' AS typmodout, "
7812 "'-' AS typanalyze, "
7813 "0 AS typreceiveoid, 0 AS typsendoid, "
7814 "0 AS typmodinoid, 0 AS typmodoutoid, "
7815 "0 AS typanalyzeoid, "
7816 "'U' AS typcategory, false AS typispreferred, "
7817 "typdelim, typbyval, typalign, typstorage, "
7818 "false AS typcollatable, "
7819 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7820 "FROM pg_catalog.pg_type "
7821 "WHERE oid = '%u'::pg_catalog.oid",
7822 tyinfo->dobj.catId.oid);
7824 else if (fout->remoteVersion >= 70200)
7827 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7828 * ignore them because they are not right.
7830 appendPQExpBuffer(query, "SELECT typlen, "
7831 "typinput, typoutput, "
7832 "'-' AS typreceive, '-' AS typsend, "
7833 "'-' AS typmodin, '-' AS typmodout, "
7834 "'-' AS typanalyze, "
7835 "0 AS typreceiveoid, 0 AS typsendoid, "
7836 "0 AS typmodinoid, 0 AS typmodoutoid, "
7837 "0 AS typanalyzeoid, "
7838 "'U' AS typcategory, false AS typispreferred, "
7839 "typdelim, typbyval, typalign, typstorage, "
7840 "false AS typcollatable, "
7841 "NULL AS typdefaultbin, typdefault "
7843 "WHERE oid = '%u'::oid",
7844 tyinfo->dobj.catId.oid);
7846 else if (fout->remoteVersion >= 70100)
7849 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7852 appendPQExpBuffer(query, "SELECT typlen, "
7853 "typinput, typoutput, "
7854 "'-' AS typreceive, '-' AS typsend, "
7855 "'-' AS typmodin, '-' AS typmodout, "
7856 "'-' AS typanalyze, "
7857 "0 AS typreceiveoid, 0 AS typsendoid, "
7858 "0 AS typmodinoid, 0 AS typmodoutoid, "
7859 "0 AS typanalyzeoid, "
7860 "'U' AS typcategory, false AS typispreferred, "
7861 "typdelim, typbyval, typalign, typstorage, "
7862 "false AS typcollatable, "
7863 "NULL AS typdefaultbin, NULL AS typdefault "
7865 "WHERE oid = '%u'::oid",
7866 tyinfo->dobj.catId.oid);
7870 appendPQExpBuffer(query, "SELECT typlen, "
7871 "typinput, typoutput, "
7872 "'-' AS typreceive, '-' AS typsend, "
7873 "'-' AS typmodin, '-' AS typmodout, "
7874 "'-' AS typanalyze, "
7875 "0 AS typreceiveoid, 0 AS typsendoid, "
7876 "0 AS typmodinoid, 0 AS typmodoutoid, "
7877 "0 AS typanalyzeoid, "
7878 "'U' AS typcategory, false AS typispreferred, "
7879 "typdelim, typbyval, typalign, "
7880 "'p'::char AS typstorage, "
7881 "false AS typcollatable, "
7882 "NULL AS typdefaultbin, NULL AS typdefault "
7884 "WHERE oid = '%u'::oid",
7885 tyinfo->dobj.catId.oid);
7888 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7890 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7891 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7892 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7893 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7894 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7895 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7896 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7897 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7898 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7899 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7900 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7901 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7902 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7903 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7904 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7905 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7906 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7907 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7908 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7909 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7910 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7911 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7912 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7914 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7915 typdefault_is_literal = true; /* it needs quotes */
7921 * DROP must be fully qualified in case same name appears in pg_catalog.
7922 * The reason we include CASCADE is that the circular dependency between
7923 * the type and its I/O functions makes it impossible to drop the type any
7926 appendPQExpBuffer(delq, "DROP TYPE %s.",
7927 fmtId(tyinfo->dobj.namespace->dobj.name));
7928 appendPQExpBuffer(delq, "%s CASCADE;\n",
7929 fmtId(tyinfo->dobj.name));
7931 /* We might already have a shell type, but setting pg_type_oid is harmless */
7933 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7934 tyinfo->dobj.catId.oid);
7936 appendPQExpBuffer(q,
7937 "CREATE TYPE %s (\n"
7938 " INTERNALLENGTH = %s",
7939 fmtId(tyinfo->dobj.name),
7940 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7942 if (fout->remoteVersion >= 70300)
7944 /* regproc result is correctly quoted as of 7.3 */
7945 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7946 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7947 if (OidIsValid(typreceiveoid))
7948 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7949 if (OidIsValid(typsendoid))
7950 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7951 if (OidIsValid(typmodinoid))
7952 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7953 if (OidIsValid(typmodoutoid))
7954 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7955 if (OidIsValid(typanalyzeoid))
7956 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7960 /* regproc delivers an unquoted name before 7.3 */
7961 /* cannot combine these because fmtId uses static result area */
7962 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7963 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7964 /* receive/send/typmodin/typmodout/analyze need not be printed */
7967 if (strcmp(typcollatable, "t") == 0)
7968 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7970 if (typdefault != NULL)
7972 appendPQExpBuffer(q, ",\n DEFAULT = ");
7973 if (typdefault_is_literal)
7974 appendStringLiteralAH(q, typdefault, fout);
7976 appendPQExpBufferStr(q, typdefault);
7979 if (OidIsValid(tyinfo->typelem))
7983 /* reselect schema in case changed by function dump */
7984 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7985 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7986 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
7990 if (strcmp(typcategory, "U") != 0)
7992 appendPQExpBuffer(q, ",\n CATEGORY = ");
7993 appendStringLiteralAH(q, typcategory, fout);
7996 if (strcmp(typispreferred, "t") == 0)
7997 appendPQExpBuffer(q, ",\n PREFERRED = true");
7999 if (typdelim && strcmp(typdelim, ",") != 0)
8001 appendPQExpBuffer(q, ",\n DELIMITER = ");
8002 appendStringLiteralAH(q, typdelim, fout);
8005 if (strcmp(typalign, "c") == 0)
8006 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8007 else if (strcmp(typalign, "s") == 0)
8008 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8009 else if (strcmp(typalign, "i") == 0)
8010 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8011 else if (strcmp(typalign, "d") == 0)
8012 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8014 if (strcmp(typstorage, "p") == 0)
8015 appendPQExpBuffer(q, ",\n STORAGE = plain");
8016 else if (strcmp(typstorage, "e") == 0)
8017 appendPQExpBuffer(q, ",\n STORAGE = external");
8018 else if (strcmp(typstorage, "x") == 0)
8019 appendPQExpBuffer(q, ",\n STORAGE = extended");
8020 else if (strcmp(typstorage, "m") == 0)
8021 appendPQExpBuffer(q, ",\n STORAGE = main");
8023 if (strcmp(typbyval, "t") == 0)
8024 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8026 appendPQExpBuffer(q, "\n);\n");
8028 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8031 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8033 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8035 tyinfo->dobj.namespace->dobj.name,
8037 tyinfo->rolname, false,
8038 "TYPE", SECTION_PRE_DATA,
8039 q->data, delq->data, NULL,
8043 /* Dump Type Comments and Security Labels */
8044 dumpComment(fout, labelq->data,
8045 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8046 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8047 dumpSecLabel(fout, labelq->data,
8048 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8049 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8052 destroyPQExpBuffer(q);
8053 destroyPQExpBuffer(delq);
8054 destroyPQExpBuffer(labelq);
8055 destroyPQExpBuffer(query);
8060 * writes out to fout the queries to recreate a user-defined domain
8063 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8065 PQExpBuffer q = createPQExpBuffer();
8066 PQExpBuffer delq = createPQExpBuffer();
8067 PQExpBuffer labelq = createPQExpBuffer();
8068 PQExpBuffer query = createPQExpBuffer();
8075 bool typdefault_is_literal = false;
8077 /* Set proper schema search path so type references list correctly */
8078 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8080 /* Fetch domain specific details */
8081 if (fout->remoteVersion >= 90100)
8083 /* typcollation is new in 9.1 */
8084 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8085 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8086 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8088 "CASE WHEN t.typcollation <> u.typcollation "
8089 "THEN t.typcollation ELSE 0 END AS typcollation "
8090 "FROM pg_catalog.pg_type t "
8091 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8092 "WHERE t.oid = '%u'::pg_catalog.oid",
8093 tyinfo->dobj.catId.oid);
8097 /* We assume here that remoteVersion must be at least 70300 */
8098 appendPQExpBuffer(query, "SELECT typnotnull, "
8099 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8100 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8101 "typdefault, 0 AS typcollation "
8102 "FROM pg_catalog.pg_type "
8103 "WHERE oid = '%u'::pg_catalog.oid",
8104 tyinfo->dobj.catId.oid);
8107 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8109 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8110 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8111 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8112 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8113 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8115 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8116 typdefault_is_literal = true; /* it needs quotes */
8120 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8123 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8124 tyinfo->dobj.catId.oid);
8126 appendPQExpBuffer(q,
8127 "CREATE DOMAIN %s AS %s",
8128 fmtId(tyinfo->dobj.name),
8131 /* Print collation only if different from base type's collation */
8132 if (OidIsValid(typcollation))
8136 coll = findCollationByOid(typcollation);
8139 /* always schema-qualify, don't try to be smart */
8140 appendPQExpBuffer(q, " COLLATE %s.",
8141 fmtId(coll->dobj.namespace->dobj.name));
8142 appendPQExpBuffer(q, "%s",
8143 fmtId(coll->dobj.name));
8147 if (typnotnull[0] == 't')
8148 appendPQExpBuffer(q, " NOT NULL");
8150 if (typdefault != NULL)
8152 appendPQExpBuffer(q, " DEFAULT ");
8153 if (typdefault_is_literal)
8154 appendStringLiteralAH(q, typdefault, fout);
8156 appendPQExpBufferStr(q, typdefault);
8162 * Add any CHECK constraints for the domain
8164 for (i = 0; i < tyinfo->nDomChecks; i++)
8166 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8168 if (!domcheck->separate)
8169 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8170 fmtId(domcheck->dobj.name), domcheck->condef);
8173 appendPQExpBuffer(q, ";\n");
8176 * DROP must be fully qualified in case same name appears in pg_catalog
8178 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8179 fmtId(tyinfo->dobj.namespace->dobj.name));
8180 appendPQExpBuffer(delq, "%s;\n",
8181 fmtId(tyinfo->dobj.name));
8183 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8186 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8188 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8190 tyinfo->dobj.namespace->dobj.name,
8192 tyinfo->rolname, false,
8193 "DOMAIN", SECTION_PRE_DATA,
8194 q->data, delq->data, NULL,
8198 /* Dump Domain Comments and Security Labels */
8199 dumpComment(fout, labelq->data,
8200 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8201 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8202 dumpSecLabel(fout, labelq->data,
8203 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8204 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8206 destroyPQExpBuffer(q);
8207 destroyPQExpBuffer(delq);
8208 destroyPQExpBuffer(labelq);
8209 destroyPQExpBuffer(query);
8214 * writes out to fout the queries to recreate a user-defined stand-alone
8218 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8220 PQExpBuffer q = createPQExpBuffer();
8221 PQExpBuffer dropped = createPQExpBuffer();
8222 PQExpBuffer delq = createPQExpBuffer();
8223 PQExpBuffer labelq = createPQExpBuffer();
8224 PQExpBuffer query = createPQExpBuffer();
8237 /* Set proper schema search path so type references list correctly */
8238 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8240 /* Fetch type specific details */
8241 if (fout->remoteVersion >= 90100)
8244 * attcollation is new in 9.1. Since we only want to dump COLLATE
8245 * clauses for attributes whose collation is different from their
8246 * type's default, we use a CASE here to suppress uninteresting
8247 * attcollations cheaply. atttypid will be 0 for dropped columns;
8248 * collation does not matter for those.
8250 appendPQExpBuffer(query, "SELECT a.attname, "
8251 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8252 "a.attlen, a.attalign, a.attisdropped, "
8253 "CASE WHEN a.attcollation <> at.typcollation "
8254 "THEN a.attcollation ELSE 0 END AS attcollation, "
8256 "FROM pg_catalog.pg_type ct "
8257 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8258 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8259 "WHERE ct.oid = '%u'::pg_catalog.oid "
8260 "ORDER BY a.attnum ",
8261 tyinfo->dobj.catId.oid);
8266 * We assume here that remoteVersion must be at least 70300. Since
8267 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8270 appendPQExpBuffer(query, "SELECT a.attname, "
8271 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8272 "a.attlen, a.attalign, a.attisdropped, "
8273 "0 AS attcollation, "
8275 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8276 "WHERE ct.oid = '%u'::pg_catalog.oid "
8277 "AND a.attrelid = ct.typrelid "
8278 "ORDER BY a.attnum ",
8279 tyinfo->dobj.catId.oid);
8282 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8284 ntups = PQntuples(res);
8286 i_attname = PQfnumber(res, "attname");
8287 i_atttypdefn = PQfnumber(res, "atttypdefn");
8288 i_attlen = PQfnumber(res, "attlen");
8289 i_attalign = PQfnumber(res, "attalign");
8290 i_attisdropped = PQfnumber(res, "attisdropped");
8291 i_attcollation = PQfnumber(res, "attcollation");
8292 i_typrelid = PQfnumber(res, "typrelid");
8296 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8298 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8299 tyinfo->dobj.catId.oid);
8300 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8303 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8304 fmtId(tyinfo->dobj.name));
8307 for (i = 0; i < ntups; i++)
8316 attname = PQgetvalue(res, i, i_attname);
8317 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8318 attlen = PQgetvalue(res, i, i_attlen);
8319 attalign = PQgetvalue(res, i, i_attalign);
8320 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8321 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8323 if (attisdropped && !binary_upgrade)
8326 /* Format properly if not first attr */
8327 if (actual_atts++ > 0)
8328 appendPQExpBuffer(q, ",");
8329 appendPQExpBuffer(q, "\n\t");
8333 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8335 /* Add collation if not default for the column type */
8336 if (OidIsValid(attcollation))
8340 coll = findCollationByOid(attcollation);
8343 /* always schema-qualify, don't try to be smart */
8344 appendPQExpBuffer(q, " COLLATE %s.",
8345 fmtId(coll->dobj.namespace->dobj.name));
8346 appendPQExpBuffer(q, "%s",
8347 fmtId(coll->dobj.name));
8354 * This is a dropped attribute and we're in binary_upgrade mode.
8355 * Insert a placeholder for it in the CREATE TYPE command, and set
8356 * length and alignment with direct UPDATE to the catalogs
8357 * afterwards. See similar code in dumpTableSchema().
8359 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8361 /* stash separately for insertion after the CREATE TYPE */
8362 appendPQExpBuffer(dropped,
8363 "\n-- For binary upgrade, recreate dropped column.\n");
8364 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8366 "attalign = '%s', attbyval = false\n"
8367 "WHERE attname = ", attlen, attalign);
8368 appendStringLiteralAH(dropped, attname, fout);
8369 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8370 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8371 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8373 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8374 fmtId(tyinfo->dobj.name));
8375 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8379 appendPQExpBuffer(q, "\n);\n");
8380 appendPQExpBufferStr(q, dropped->data);
8383 * DROP must be fully qualified in case same name appears in pg_catalog
8385 appendPQExpBuffer(delq, "DROP TYPE %s.",
8386 fmtId(tyinfo->dobj.namespace->dobj.name));
8387 appendPQExpBuffer(delq, "%s;\n",
8388 fmtId(tyinfo->dobj.name));
8390 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8393 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8395 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8397 tyinfo->dobj.namespace->dobj.name,
8399 tyinfo->rolname, false,
8400 "TYPE", SECTION_PRE_DATA,
8401 q->data, delq->data, NULL,
8406 /* Dump Type Comments and Security Labels */
8407 dumpComment(fout, labelq->data,
8408 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8409 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8410 dumpSecLabel(fout, labelq->data,
8411 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8412 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8415 destroyPQExpBuffer(q);
8416 destroyPQExpBuffer(dropped);
8417 destroyPQExpBuffer(delq);
8418 destroyPQExpBuffer(labelq);
8419 destroyPQExpBuffer(query);
8421 /* Dump any per-column comments */
8422 dumpCompositeTypeColComments(fout, tyinfo);
8426 * dumpCompositeTypeColComments
8427 * writes out to fout the queries to recreate comments on the columns of
8428 * a user-defined stand-alone composite type
8431 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8433 CommentItem *comments;
8444 query = createPQExpBuffer();
8446 /* We assume here that remoteVersion must be at least 70300 */
8447 appendPQExpBuffer(query,
8448 "SELECT c.tableoid, a.attname, a.attnum "
8449 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8450 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8451 " AND NOT a.attisdropped "
8452 "ORDER BY a.attnum ",
8455 /* Fetch column attnames */
8456 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8458 ntups = PQntuples(res);
8462 destroyPQExpBuffer(query);
8466 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8468 /* Search for comments associated with type's pg_class OID */
8469 ncomments = findComments(fout,
8474 /* If no comments exist, we're done */
8478 destroyPQExpBuffer(query);
8482 /* Build COMMENT ON statements */
8483 target = createPQExpBuffer();
8485 i_attnum = PQfnumber(res, "attnum");
8486 i_attname = PQfnumber(res, "attname");
8487 while (ncomments > 0)
8489 const char *attname;
8492 for (i = 0; i < ntups; i++)
8494 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8496 attname = PQgetvalue(res, i, i_attname);
8500 if (attname) /* just in case we don't find it */
8502 const char *descr = comments->descr;
8504 resetPQExpBuffer(target);
8505 appendPQExpBuffer(target, "COLUMN %s.",
8506 fmtId(tyinfo->dobj.name));
8507 appendPQExpBuffer(target, "%s",
8510 resetPQExpBuffer(query);
8511 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8512 appendStringLiteralAH(query, descr, fout);
8513 appendPQExpBuffer(query, ";\n");
8515 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8517 tyinfo->dobj.namespace->dobj.name,
8518 NULL, tyinfo->rolname,
8519 false, "COMMENT", SECTION_NONE,
8520 query->data, "", NULL,
8521 &(tyinfo->dobj.dumpId), 1,
8530 destroyPQExpBuffer(query);
8531 destroyPQExpBuffer(target);
8536 * writes out to fout the queries to create a shell type
8538 * We dump a shell definition in advance of the I/O functions for the type.
8541 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8545 /* Skip if not to be dumped */
8546 if (!stinfo->dobj.dump || dataOnly)
8549 q = createPQExpBuffer();
8552 * Note the lack of a DROP command for the shell type; any required DROP
8553 * is driven off the base type entry, instead. This interacts with
8554 * _printTocEntry()'s use of the presence of a DROP command to decide
8555 * whether an entry needs an ALTER OWNER command. We don't want to alter
8556 * the shell type's owner immediately on creation; that should happen only
8557 * after it's filled in, otherwise the backend complains.
8561 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8562 stinfo->baseType->dobj.catId.oid);
8564 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8565 fmtId(stinfo->dobj.name));
8567 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8569 stinfo->dobj.namespace->dobj.name,
8571 stinfo->baseType->rolname, false,
8572 "SHELL TYPE", SECTION_PRE_DATA,
8577 destroyPQExpBuffer(q);
8581 * Determine whether we want to dump definitions for procedural languages.
8582 * Since the languages themselves don't have schemas, we can't rely on
8583 * the normal schema-based selection mechanism. We choose to dump them
8584 * whenever neither --schema nor --table was given. (Before 8.1, we used
8585 * the dump flag of the PL's call handler function, but in 8.1 this will
8586 * probably always be false since call handlers are created in pg_catalog.)
8588 * For some backwards compatibility with the older behavior, we forcibly
8589 * dump a PL if its handler function (and validator if any) are in a
8590 * dumpable namespace. That case is not checked here.
8592 * Also, if the PL belongs to an extension, we do not use this heuristic.
8593 * That case isn't checked here either.
8596 shouldDumpProcLangs(void)
8598 if (!include_everything)
8600 /* And they're schema not data */
8608 * writes out to fout the queries to recreate a user-defined
8609 * procedural language
8612 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8621 FuncInfo *inlineInfo = NULL;
8622 FuncInfo *validatorInfo = NULL;
8624 /* Skip if not to be dumped */
8625 if (!plang->dobj.dump || dataOnly)
8629 * Try to find the support function(s). It is not an error if we don't
8630 * find them --- if the functions are in the pg_catalog schema, as is
8631 * standard in 8.1 and up, then we won't have loaded them. (In this case
8632 * we will emit a parameterless CREATE LANGUAGE command, which will
8633 * require PL template knowledge in the backend to reload.)
8636 funcInfo = findFuncByOid(plang->lanplcallfoid);
8637 if (funcInfo != NULL && !funcInfo->dobj.dump)
8638 funcInfo = NULL; /* treat not-dumped same as not-found */
8640 if (OidIsValid(plang->laninline))
8642 inlineInfo = findFuncByOid(plang->laninline);
8643 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8647 if (OidIsValid(plang->lanvalidator))
8649 validatorInfo = findFuncByOid(plang->lanvalidator);
8650 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8651 validatorInfo = NULL;
8655 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8656 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8659 * However, for a language that belongs to an extension, we must not use
8660 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8661 * told to (via dobj.dump). Generally the support functions will belong
8662 * to the same extension and so have the same dump flags ... if they
8663 * don't, this might not work terribly nicely.
8665 useParams = (funcInfo != NULL &&
8666 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8667 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8669 if (!plang->dobj.ext_member)
8671 if (!useParams && !shouldDumpProcLangs())
8675 defqry = createPQExpBuffer();
8676 delqry = createPQExpBuffer();
8677 labelq = createPQExpBuffer();
8679 qlanname = pg_strdup(fmtId(plang->dobj.name));
8682 * If dumping a HANDLER clause, treat the language as being in the handler
8683 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8684 * it doesn't really have a schema.
8687 lanschema = funcInfo->dobj.namespace->dobj.name;
8691 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8696 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8697 plang->lanpltrusted ? "TRUSTED " : "",
8699 appendPQExpBuffer(defqry, " HANDLER %s",
8700 fmtId(funcInfo->dobj.name));
8701 if (OidIsValid(plang->laninline))
8703 appendPQExpBuffer(defqry, " INLINE ");
8704 /* Cope with possibility that inline is in different schema */
8705 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8706 appendPQExpBuffer(defqry, "%s.",
8707 fmtId(inlineInfo->dobj.namespace->dobj.name));
8708 appendPQExpBuffer(defqry, "%s",
8709 fmtId(inlineInfo->dobj.name));
8711 if (OidIsValid(plang->lanvalidator))
8713 appendPQExpBuffer(defqry, " VALIDATOR ");
8714 /* Cope with possibility that validator is in different schema */
8715 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8716 appendPQExpBuffer(defqry, "%s.",
8717 fmtId(validatorInfo->dobj.namespace->dobj.name));
8718 appendPQExpBuffer(defqry, "%s",
8719 fmtId(validatorInfo->dobj.name));
8725 * If not dumping parameters, then use CREATE OR REPLACE so that the
8726 * command will not fail if the language is preinstalled in the target
8727 * database. We restrict the use of REPLACE to this case so as to
8728 * eliminate the risk of replacing a language with incompatible
8729 * parameter settings: this command will only succeed at all if there
8730 * is a pg_pltemplate entry, and if there is one, the existing entry
8731 * must match it too.
8733 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8736 appendPQExpBuffer(defqry, ";\n");
8738 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8741 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8743 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8745 lanschema, NULL, plang->lanowner,
8746 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8747 defqry->data, delqry->data, NULL,
8751 /* Dump Proc Lang Comments and Security Labels */
8752 dumpComment(fout, labelq->data,
8754 plang->dobj.catId, 0, plang->dobj.dumpId);
8755 dumpSecLabel(fout, labelq->data,
8757 plang->dobj.catId, 0, plang->dobj.dumpId);
8759 if (plang->lanpltrusted)
8760 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8761 qlanname, NULL, plang->dobj.name,
8763 plang->lanowner, plang->lanacl);
8767 destroyPQExpBuffer(defqry);
8768 destroyPQExpBuffer(delqry);
8769 destroyPQExpBuffer(labelq);
8773 * format_function_arguments: generate function name and argument list
8775 * This is used when we can rely on pg_get_function_arguments to format
8776 * the argument list.
8779 format_function_arguments(FuncInfo *finfo, char *funcargs)
8783 initPQExpBuffer(&fn);
8784 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8789 * format_function_arguments_old: generate function name and argument list
8791 * The argument type names are qualified if needed. The function name
8792 * is never qualified.
8794 * This is used only with pre-8.4 servers, so we aren't expecting to see
8795 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8797 * Any or all of allargtypes, argmodes, argnames may be NULL.
8800 format_function_arguments_old(Archive *fout,
8801 FuncInfo *finfo, int nallargs,
8809 initPQExpBuffer(&fn);
8810 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8811 for (j = 0; j < nallargs; j++)
8815 const char *argmode;
8816 const char *argname;
8818 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8819 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8823 switch (argmodes[j][0])
8828 case PROARGMODE_OUT:
8831 case PROARGMODE_INOUT:
8835 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8843 argname = argnames ? argnames[j] : (char *) NULL;
8844 if (argname && argname[0] == '\0')
8847 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8848 (j > 0) ? ", " : "",
8850 argname ? fmtId(argname) : "",
8855 appendPQExpBuffer(&fn, ")");
8860 * format_function_signature: generate function name and argument list
8862 * This is like format_function_arguments_old except that only a minimal
8863 * list of input argument types is generated; this is sufficient to
8864 * reference the function, but not to define it.
8866 * If honor_quotes is false then the function name is never quoted.
8867 * This is appropriate for use in TOC tags, but not in SQL commands.
8870 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8875 initPQExpBuffer(&fn);
8877 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8879 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8880 for (j = 0; j < finfo->nargs; j++)
8884 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8887 appendPQExpBuffer(&fn, "%s%s",
8888 (j > 0) ? ", " : "",
8892 appendPQExpBuffer(&fn, ")");
8899 * dump out one function
8902 dumpFunc(Archive *fout, FuncInfo *finfo)
8910 char *funcsig; /* identity signature */
8911 char *funcfullsig; /* full signature */
8919 char *proallargtypes;
8933 char **allargtypes = NULL;
8934 char **argmodes = NULL;
8935 char **argnames = NULL;
8936 char **configitems = NULL;
8937 int nconfigitems = 0;
8940 /* Skip if not to be dumped */
8941 if (!finfo->dobj.dump || dataOnly)
8944 query = createPQExpBuffer();
8945 q = createPQExpBuffer();
8946 delqry = createPQExpBuffer();
8947 labelq = createPQExpBuffer();
8948 asPart = createPQExpBuffer();
8950 /* Set proper schema search path so type references list correctly */
8951 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8953 /* Fetch function-specific details */
8954 if (fout->remoteVersion >= 90200)
8957 * proleakproof was added at v9.2
8959 appendPQExpBuffer(query,
8960 "SELECT proretset, prosrc, probin, "
8961 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8962 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8963 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8964 "proiswindow, provolatile, proisstrict, prosecdef, "
8965 "proleakproof, proconfig, procost, prorows, "
8966 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8967 "FROM pg_catalog.pg_proc "
8968 "WHERE oid = '%u'::pg_catalog.oid",
8969 finfo->dobj.catId.oid);
8971 else if (fout->remoteVersion >= 80400)
8974 * In 8.4 and up we rely on pg_get_function_arguments and
8975 * pg_get_function_result instead of examining proallargtypes etc.
8977 appendPQExpBuffer(query,
8978 "SELECT proretset, prosrc, probin, "
8979 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8980 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8981 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8982 "proiswindow, provolatile, proisstrict, prosecdef, "
8983 "false AS proleakproof, "
8984 " proconfig, procost, prorows, "
8985 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8986 "FROM pg_catalog.pg_proc "
8987 "WHERE oid = '%u'::pg_catalog.oid",
8988 finfo->dobj.catId.oid);
8990 else if (fout->remoteVersion >= 80300)
8992 appendPQExpBuffer(query,
8993 "SELECT proretset, prosrc, probin, "
8994 "proallargtypes, proargmodes, proargnames, "
8995 "false AS proiswindow, "
8996 "provolatile, proisstrict, prosecdef, "
8997 "false AS proleakproof, "
8998 "proconfig, procost, prorows, "
8999 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9000 "FROM pg_catalog.pg_proc "
9001 "WHERE oid = '%u'::pg_catalog.oid",
9002 finfo->dobj.catId.oid);
9004 else if (fout->remoteVersion >= 80100)
9006 appendPQExpBuffer(query,
9007 "SELECT proretset, prosrc, probin, "
9008 "proallargtypes, proargmodes, proargnames, "
9009 "false AS proiswindow, "
9010 "provolatile, proisstrict, prosecdef, "
9011 "false AS proleakproof, "
9012 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9013 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9014 "FROM pg_catalog.pg_proc "
9015 "WHERE oid = '%u'::pg_catalog.oid",
9016 finfo->dobj.catId.oid);
9018 else if (fout->remoteVersion >= 80000)
9020 appendPQExpBuffer(query,
9021 "SELECT proretset, prosrc, probin, "
9022 "null AS proallargtypes, "
9023 "null AS proargmodes, "
9025 "false AS proiswindow, "
9026 "provolatile, proisstrict, prosecdef, "
9027 "false AS proleakproof, "
9028 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9029 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9030 "FROM pg_catalog.pg_proc "
9031 "WHERE oid = '%u'::pg_catalog.oid",
9032 finfo->dobj.catId.oid);
9034 else if (fout->remoteVersion >= 70300)
9036 appendPQExpBuffer(query,
9037 "SELECT proretset, prosrc, probin, "
9038 "null AS proallargtypes, "
9039 "null AS proargmodes, "
9040 "null AS proargnames, "
9041 "false AS proiswindow, "
9042 "provolatile, proisstrict, prosecdef, "
9043 "false AS proleakproof, "
9044 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9045 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9046 "FROM pg_catalog.pg_proc "
9047 "WHERE oid = '%u'::pg_catalog.oid",
9048 finfo->dobj.catId.oid);
9050 else if (fout->remoteVersion >= 70100)
9052 appendPQExpBuffer(query,
9053 "SELECT proretset, prosrc, probin, "
9054 "null AS proallargtypes, "
9055 "null AS proargmodes, "
9056 "null AS proargnames, "
9057 "false AS proiswindow, "
9058 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9060 "false AS prosecdef, "
9061 "false AS proleakproof, "
9062 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9063 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9065 "WHERE oid = '%u'::oid",
9066 finfo->dobj.catId.oid);
9070 appendPQExpBuffer(query,
9071 "SELECT proretset, prosrc, probin, "
9072 "null AS proallargtypes, "
9073 "null AS proargmodes, "
9074 "null AS proargnames, "
9075 "false AS proiswindow, "
9076 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9077 "false AS proisstrict, "
9078 "false AS prosecdef, "
9079 "false AS proleakproof, "
9080 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9081 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9083 "WHERE oid = '%u'::oid",
9084 finfo->dobj.catId.oid);
9087 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9089 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9090 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9091 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9092 if (fout->remoteVersion >= 80400)
9094 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9095 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9096 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9097 proallargtypes = proargmodes = proargnames = NULL;
9101 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9102 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9103 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9104 funcargs = funciargs = funcresult = NULL;
9106 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9107 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9108 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9109 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9110 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9111 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9112 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9113 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9114 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9117 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9118 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9119 * versions would set it to "-". There are no known cases in which prosrc
9120 * is unused, so the tests below for "-" are probably useless.
9122 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9124 appendPQExpBuffer(asPart, "AS ");
9125 appendStringLiteralAH(asPart, probin, fout);
9126 if (strcmp(prosrc, "-") != 0)
9128 appendPQExpBuffer(asPart, ", ");
9131 * where we have bin, use dollar quoting if allowed and src
9132 * contains quote or backslash; else use regular quoting.
9134 if (disable_dollar_quoting ||
9135 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9136 appendStringLiteralAH(asPart, prosrc, fout);
9138 appendStringLiteralDQ(asPart, prosrc, NULL);
9143 if (strcmp(prosrc, "-") != 0)
9145 appendPQExpBuffer(asPart, "AS ");
9146 /* with no bin, dollar quote src unconditionally if allowed */
9147 if (disable_dollar_quoting)
9148 appendStringLiteralAH(asPart, prosrc, fout);
9150 appendStringLiteralDQ(asPart, prosrc, NULL);
9154 nallargs = finfo->nargs; /* unless we learn different from allargs */
9156 if (proallargtypes && *proallargtypes)
9160 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9161 nitems < finfo->nargs)
9163 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9172 if (proargmodes && *proargmodes)
9176 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9179 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9186 if (proargnames && *proargnames)
9190 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9193 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9200 if (proconfig && *proconfig)
9202 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9204 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9214 /* 8.4 or later; we rely on server-side code for most of the work */
9215 funcfullsig = format_function_arguments(finfo, funcargs);
9216 funcsig = format_function_arguments(finfo, funciargs);
9220 /* pre-8.4, do it ourselves */
9221 funcsig = format_function_arguments_old(fout,
9222 finfo, nallargs, allargtypes,
9223 argmodes, argnames);
9224 funcfullsig = funcsig;
9227 funcsig_tag = format_function_signature(fout, finfo, false);
9230 * DROP must be fully qualified in case same name appears in pg_catalog
9232 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9233 fmtId(finfo->dobj.namespace->dobj.name),
9236 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9238 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9241 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9243 appendPQExpBuffer(q, "RETURNS %s%s",
9244 (proretset[0] == 't') ? "SETOF " : "",
9249 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9251 if (proiswindow[0] == 't')
9252 appendPQExpBuffer(q, " WINDOW");
9254 if (provolatile[0] != PROVOLATILE_VOLATILE)
9256 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9257 appendPQExpBuffer(q, " IMMUTABLE");
9258 else if (provolatile[0] == PROVOLATILE_STABLE)
9259 appendPQExpBuffer(q, " STABLE");
9260 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9261 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9265 if (proisstrict[0] == 't')
9266 appendPQExpBuffer(q, " STRICT");
9268 if (prosecdef[0] == 't')
9269 appendPQExpBuffer(q, " SECURITY DEFINER");
9271 if (proleakproof[0] == 't')
9272 appendPQExpBuffer(q, " LEAKPROOF");
9275 * COST and ROWS are emitted only if present and not default, so as not to
9276 * break backwards-compatibility of the dump without need. Keep this code
9277 * in sync with the defaults in functioncmds.c.
9279 if (strcmp(procost, "0") != 0)
9281 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9283 /* default cost is 1 */
9284 if (strcmp(procost, "1") != 0)
9285 appendPQExpBuffer(q, " COST %s", procost);
9289 /* default cost is 100 */
9290 if (strcmp(procost, "100") != 0)
9291 appendPQExpBuffer(q, " COST %s", procost);
9294 if (proretset[0] == 't' &&
9295 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9296 appendPQExpBuffer(q, " ROWS %s", prorows);
9298 for (i = 0; i < nconfigitems; i++)
9300 /* we feel free to scribble on configitems[] here */
9301 char *configitem = configitems[i];
9304 pos = strchr(configitem, '=');
9308 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9311 * Some GUC variable names are 'LIST' type and hence must not be
9314 if (pg_strcasecmp(configitem, "DateStyle") == 0
9315 || pg_strcasecmp(configitem, "search_path") == 0)
9316 appendPQExpBuffer(q, "%s", pos);
9318 appendStringLiteralAH(q, pos, fout);
9321 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9323 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9326 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9328 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9330 finfo->dobj.namespace->dobj.name,
9332 finfo->rolname, false,
9333 "FUNCTION", SECTION_PRE_DATA,
9334 q->data, delqry->data, NULL,
9338 /* Dump Function Comments and Security Labels */
9339 dumpComment(fout, labelq->data,
9340 finfo->dobj.namespace->dobj.name, finfo->rolname,
9341 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9342 dumpSecLabel(fout, labelq->data,
9343 finfo->dobj.namespace->dobj.name, finfo->rolname,
9344 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9346 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9347 funcsig, NULL, funcsig_tag,
9348 finfo->dobj.namespace->dobj.name,
9349 finfo->rolname, finfo->proacl);
9353 destroyPQExpBuffer(query);
9354 destroyPQExpBuffer(q);
9355 destroyPQExpBuffer(delqry);
9356 destroyPQExpBuffer(labelq);
9357 destroyPQExpBuffer(asPart);
9372 * Dump a user-defined cast
9375 dumpCast(Archive *fout, CastInfo *cast)
9380 FuncInfo *funcInfo = NULL;
9382 /* Skip if not to be dumped */
9383 if (!cast->dobj.dump || dataOnly)
9386 /* Cannot dump if we don't have the cast function's info */
9387 if (OidIsValid(cast->castfunc))
9389 funcInfo = findFuncByOid(cast->castfunc);
9390 if (funcInfo == NULL)
9395 * As per discussion we dump casts if one or more of the underlying
9396 * objects (the conversion function and the two data types) are not
9397 * builtin AND if all of the non-builtin objects are included in the dump.
9398 * Builtin meaning, the namespace name does not start with "pg_".
9400 * However, for a cast that belongs to an extension, we must not use this
9401 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9403 if (!cast->dobj.ext_member)
9405 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9406 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9408 if (sourceInfo == NULL || targetInfo == NULL)
9412 * Skip this cast if all objects are from pg_
9414 if ((funcInfo == NULL ||
9415 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9416 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9417 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9421 * Skip cast if function isn't from pg_ and is not to be dumped.
9424 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9425 !funcInfo->dobj.dump)
9429 * Same for the source type
9431 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9432 !sourceInfo->dobj.dump)
9436 * and the target type.
9438 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9439 !targetInfo->dobj.dump)
9443 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9444 selectSourceSchema(fout, "pg_catalog");
9446 defqry = createPQExpBuffer();
9447 delqry = createPQExpBuffer();
9448 labelq = createPQExpBuffer();
9450 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9451 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9452 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9454 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9455 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9456 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9458 switch (cast->castmethod)
9460 case COERCION_METHOD_BINARY:
9461 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9463 case COERCION_METHOD_INOUT:
9464 appendPQExpBuffer(defqry, "WITH INOUT");
9466 case COERCION_METHOD_FUNCTION:
9469 char *fsig = format_function_signature(fout, funcInfo, true);
9472 * Always qualify the function name, in case it is not in
9473 * pg_catalog schema (format_function_signature won't qualify
9476 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9477 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9481 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9484 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9487 if (cast->castcontext == 'a')
9488 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9489 else if (cast->castcontext == 'i')
9490 appendPQExpBuffer(defqry, " AS IMPLICIT");
9491 appendPQExpBuffer(defqry, ";\n");
9493 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9494 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9495 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9498 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9500 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9502 "pg_catalog", NULL, "",
9503 false, "CAST", SECTION_PRE_DATA,
9504 defqry->data, delqry->data, NULL,
9508 /* Dump Cast Comments */
9509 dumpComment(fout, labelq->data,
9511 cast->dobj.catId, 0, cast->dobj.dumpId);
9513 destroyPQExpBuffer(defqry);
9514 destroyPQExpBuffer(delqry);
9515 destroyPQExpBuffer(labelq);
9520 * write out a single operator definition
9523 dumpOpr(Archive *fout, OprInfo *oprinfo)
9530 PQExpBuffer details;
9554 /* Skip if not to be dumped */
9555 if (!oprinfo->dobj.dump || dataOnly)
9559 * some operators are invalid because they were the result of user
9560 * defining operators before commutators exist
9562 if (!OidIsValid(oprinfo->oprcode))
9565 query = createPQExpBuffer();
9566 q = createPQExpBuffer();
9567 delq = createPQExpBuffer();
9568 labelq = createPQExpBuffer();
9569 oprid = createPQExpBuffer();
9570 details = createPQExpBuffer();
9572 /* Make sure we are in proper schema so regoperator works correctly */
9573 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9575 if (fout->remoteVersion >= 80300)
9577 appendPQExpBuffer(query, "SELECT oprkind, "
9578 "oprcode::pg_catalog.regprocedure, "
9579 "oprleft::pg_catalog.regtype, "
9580 "oprright::pg_catalog.regtype, "
9581 "oprcom::pg_catalog.regoperator, "
9582 "oprnegate::pg_catalog.regoperator, "
9583 "oprrest::pg_catalog.regprocedure, "
9584 "oprjoin::pg_catalog.regprocedure, "
9585 "oprcanmerge, oprcanhash "
9586 "FROM pg_catalog.pg_operator "
9587 "WHERE oid = '%u'::pg_catalog.oid",
9588 oprinfo->dobj.catId.oid);
9590 else if (fout->remoteVersion >= 70300)
9592 appendPQExpBuffer(query, "SELECT oprkind, "
9593 "oprcode::pg_catalog.regprocedure, "
9594 "oprleft::pg_catalog.regtype, "
9595 "oprright::pg_catalog.regtype, "
9596 "oprcom::pg_catalog.regoperator, "
9597 "oprnegate::pg_catalog.regoperator, "
9598 "oprrest::pg_catalog.regprocedure, "
9599 "oprjoin::pg_catalog.regprocedure, "
9600 "(oprlsortop != 0) AS oprcanmerge, "
9602 "FROM pg_catalog.pg_operator "
9603 "WHERE oid = '%u'::pg_catalog.oid",
9604 oprinfo->dobj.catId.oid);
9606 else if (fout->remoteVersion >= 70100)
9608 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9609 "CASE WHEN oprleft = 0 THEN '-' "
9610 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9611 "CASE WHEN oprright = 0 THEN '-' "
9612 "ELSE format_type(oprright, NULL) END AS oprright, "
9613 "oprcom, oprnegate, oprrest, oprjoin, "
9614 "(oprlsortop != 0) AS oprcanmerge, "
9617 "WHERE oid = '%u'::oid",
9618 oprinfo->dobj.catId.oid);
9622 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9623 "CASE WHEN oprleft = 0 THEN '-'::name "
9624 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9625 "CASE WHEN oprright = 0 THEN '-'::name "
9626 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9627 "oprcom, oprnegate, oprrest, oprjoin, "
9628 "(oprlsortop != 0) AS oprcanmerge, "
9631 "WHERE oid = '%u'::oid",
9632 oprinfo->dobj.catId.oid);
9635 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9637 i_oprkind = PQfnumber(res, "oprkind");
9638 i_oprcode = PQfnumber(res, "oprcode");
9639 i_oprleft = PQfnumber(res, "oprleft");
9640 i_oprright = PQfnumber(res, "oprright");
9641 i_oprcom = PQfnumber(res, "oprcom");
9642 i_oprnegate = PQfnumber(res, "oprnegate");
9643 i_oprrest = PQfnumber(res, "oprrest");
9644 i_oprjoin = PQfnumber(res, "oprjoin");
9645 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9646 i_oprcanhash = PQfnumber(res, "oprcanhash");
9648 oprkind = PQgetvalue(res, 0, i_oprkind);
9649 oprcode = PQgetvalue(res, 0, i_oprcode);
9650 oprleft = PQgetvalue(res, 0, i_oprleft);
9651 oprright = PQgetvalue(res, 0, i_oprright);
9652 oprcom = PQgetvalue(res, 0, i_oprcom);
9653 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9654 oprrest = PQgetvalue(res, 0, i_oprrest);
9655 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9656 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9657 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9659 appendPQExpBuffer(details, " PROCEDURE = %s",
9660 convertRegProcReference(fout, oprcode));
9662 appendPQExpBuffer(oprid, "%s (",
9663 oprinfo->dobj.name);
9666 * right unary means there's a left arg and left unary means there's a
9669 if (strcmp(oprkind, "r") == 0 ||
9670 strcmp(oprkind, "b") == 0)
9672 if (fout->remoteVersion >= 70100)
9675 name = fmtId(oprleft);
9676 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9677 appendPQExpBuffer(oprid, "%s", name);
9680 appendPQExpBuffer(oprid, "NONE");
9682 if (strcmp(oprkind, "l") == 0 ||
9683 strcmp(oprkind, "b") == 0)
9685 if (fout->remoteVersion >= 70100)
9688 name = fmtId(oprright);
9689 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9690 appendPQExpBuffer(oprid, ", %s)", name);
9693 appendPQExpBuffer(oprid, ", NONE)");
9695 name = convertOperatorReference(fout, oprcom);
9697 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9699 name = convertOperatorReference(fout, oprnegate);
9701 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9703 if (strcmp(oprcanmerge, "t") == 0)
9704 appendPQExpBuffer(details, ",\n MERGES");
9706 if (strcmp(oprcanhash, "t") == 0)
9707 appendPQExpBuffer(details, ",\n HASHES");
9709 name = convertRegProcReference(fout, oprrest);
9711 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9713 name = convertRegProcReference(fout, oprjoin);
9715 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9718 * DROP must be fully qualified in case same name appears in pg_catalog
9720 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9721 fmtId(oprinfo->dobj.namespace->dobj.name),
9724 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9725 oprinfo->dobj.name, details->data);
9727 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9730 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9732 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9734 oprinfo->dobj.namespace->dobj.name,
9737 false, "OPERATOR", SECTION_PRE_DATA,
9738 q->data, delq->data, NULL,
9742 /* Dump Operator Comments */
9743 dumpComment(fout, labelq->data,
9744 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9745 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9749 destroyPQExpBuffer(query);
9750 destroyPQExpBuffer(q);
9751 destroyPQExpBuffer(delq);
9752 destroyPQExpBuffer(labelq);
9753 destroyPQExpBuffer(oprid);
9754 destroyPQExpBuffer(details);
9758 * Convert a function reference obtained from pg_operator
9760 * Returns what to print, or NULL if function references is InvalidOid
9762 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9763 * argument-types part. In prior versions, the input is a REGPROC display.
9766 convertRegProcReference(Archive *fout, const char *proc)
9768 /* In all cases "-" means a null reference */
9769 if (strcmp(proc, "-") == 0)
9772 if (fout->remoteVersion >= 70300)
9778 name = pg_strdup(proc);
9779 /* find non-double-quoted left paren */
9781 for (paren = name; *paren; paren++)
9783 if (*paren == '(' && !inquote)
9794 /* REGPROC before 7.3 does not quote its result */
9799 * Convert an operator cross-reference obtained from pg_operator
9801 * Returns what to print, or NULL to print nothing
9803 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9804 * argument-types part, and add OPERATOR() decoration if the name is
9805 * schema-qualified. In older versions, the input is just a numeric OID,
9806 * which we search our operator list for.
9809 convertOperatorReference(Archive *fout, const char *opr)
9813 /* In all cases "0" means a null reference */
9814 if (strcmp(opr, "0") == 0)
9817 if (fout->remoteVersion >= 70300)
9825 name = pg_strdup(opr);
9826 /* find non-double-quoted left paren, and check for non-quoted dot */
9829 for (ptr = name; *ptr; ptr++)
9833 else if (*ptr == '.' && !inquote)
9835 else if (*ptr == '(' && !inquote)
9841 /* If not schema-qualified, don't need to add OPERATOR() */
9844 oname = pg_malloc(strlen(name) + 11);
9845 sprintf(oname, "OPERATOR(%s)", name);
9850 oprInfo = findOprByOid(atooid(opr));
9851 if (oprInfo == NULL)
9853 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9857 return oprInfo->dobj.name;
9861 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9863 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9864 * argument lists of these functions are predetermined. Note that the
9865 * caller should ensure we are in the proper schema, because the results
9866 * are search path dependent!
9869 convertTSFunction(Archive *fout, Oid funcOid)
9875 snprintf(query, sizeof(query),
9876 "SELECT '%u'::pg_catalog.regproc", funcOid);
9877 res = ExecuteSqlQueryForSingleRow(fout, query);
9879 result = pg_strdup(PQgetvalue(res, 0, 0));
9889 * write out a single operator class definition
9892 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9904 int i_opcfamilyname;
9911 int i_sortfamilynsp;
9914 int i_amproclefttype;
9915 int i_amprocrighttype;
9920 char *opcfamilyname;
9927 char *sortfamilynsp;
9930 char *amproclefttype;
9931 char *amprocrighttype;
9935 /* Skip if not to be dumped */
9936 if (!opcinfo->dobj.dump || dataOnly)
9940 * XXX currently we do not implement dumping of operator classes from
9941 * pre-7.3 databases. This could be done but it seems not worth the
9944 if (fout->remoteVersion < 70300)
9947 query = createPQExpBuffer();
9948 q = createPQExpBuffer();
9949 delq = createPQExpBuffer();
9950 labelq = createPQExpBuffer();
9952 /* Make sure we are in proper schema so regoperator works correctly */
9953 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9955 /* Get additional fields from the pg_opclass row */
9956 if (fout->remoteVersion >= 80300)
9958 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9959 "opckeytype::pg_catalog.regtype, "
9960 "opcdefault, opcfamily, "
9961 "opfname AS opcfamilyname, "
9962 "nspname AS opcfamilynsp, "
9963 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9964 "FROM pg_catalog.pg_opclass c "
9965 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9966 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9967 "WHERE c.oid = '%u'::pg_catalog.oid",
9968 opcinfo->dobj.catId.oid);
9972 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9973 "opckeytype::pg_catalog.regtype, "
9974 "opcdefault, NULL AS opcfamily, "
9975 "NULL AS opcfamilyname, "
9976 "NULL AS opcfamilynsp, "
9977 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9978 "FROM pg_catalog.pg_opclass "
9979 "WHERE oid = '%u'::pg_catalog.oid",
9980 opcinfo->dobj.catId.oid);
9983 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9985 i_opcintype = PQfnumber(res, "opcintype");
9986 i_opckeytype = PQfnumber(res, "opckeytype");
9987 i_opcdefault = PQfnumber(res, "opcdefault");
9988 i_opcfamily = PQfnumber(res, "opcfamily");
9989 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9990 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9991 i_amname = PQfnumber(res, "amname");
9993 opcintype = PQgetvalue(res, 0, i_opcintype);
9994 opckeytype = PQgetvalue(res, 0, i_opckeytype);
9995 opcdefault = PQgetvalue(res, 0, i_opcdefault);
9996 /* opcfamily will still be needed after we PQclear res */
9997 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9998 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9999 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10000 /* amname will still be needed after we PQclear res */
10001 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10004 * DROP must be fully qualified in case same name appears in pg_catalog
10006 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10007 fmtId(opcinfo->dobj.namespace->dobj.name));
10008 appendPQExpBuffer(delq, ".%s",
10009 fmtId(opcinfo->dobj.name));
10010 appendPQExpBuffer(delq, " USING %s;\n",
10013 /* Build the fixed portion of the CREATE command */
10014 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10015 fmtId(opcinfo->dobj.name));
10016 if (strcmp(opcdefault, "t") == 0)
10017 appendPQExpBuffer(q, "DEFAULT ");
10018 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10021 if (strlen(opcfamilyname) > 0 &&
10022 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10023 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10025 appendPQExpBuffer(q, " FAMILY ");
10026 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10027 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10028 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10030 appendPQExpBuffer(q, " AS\n ");
10034 if (strcmp(opckeytype, "-") != 0)
10036 appendPQExpBuffer(q, "STORAGE %s",
10044 * Now fetch and print the OPERATOR entries (pg_amop rows).
10046 * Print only those opfamily members that are tied to the opclass by
10047 * pg_depend entries.
10049 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10050 * older server's opclass in which it is used. This is to avoid
10051 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10052 * older server and then reload into that old version. This can go away
10053 * once 8.3 is so old as to not be of interest to anyone.
10055 resetPQExpBuffer(query);
10057 if (fout->remoteVersion >= 90100)
10059 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10060 "amopopr::pg_catalog.regoperator, "
10061 "opfname AS sortfamily, "
10062 "nspname AS sortfamilynsp "
10063 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10064 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10065 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10066 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10067 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10068 "AND refobjid = '%u'::pg_catalog.oid "
10069 "AND amopfamily = '%s'::pg_catalog.oid "
10070 "ORDER BY amopstrategy",
10071 opcinfo->dobj.catId.oid,
10074 else if (fout->remoteVersion >= 80400)
10076 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10077 "amopopr::pg_catalog.regoperator, "
10078 "NULL AS sortfamily, "
10079 "NULL AS sortfamilynsp "
10080 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10081 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10082 "AND refobjid = '%u'::pg_catalog.oid "
10083 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10084 "AND objid = ao.oid "
10085 "ORDER BY amopstrategy",
10086 opcinfo->dobj.catId.oid);
10088 else if (fout->remoteVersion >= 80300)
10090 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10091 "amopopr::pg_catalog.regoperator, "
10092 "NULL AS sortfamily, "
10093 "NULL AS sortfamilynsp "
10094 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10095 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10096 "AND refobjid = '%u'::pg_catalog.oid "
10097 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10098 "AND objid = ao.oid "
10099 "ORDER BY amopstrategy",
10100 opcinfo->dobj.catId.oid);
10105 * Here, we print all entries since there are no opfamilies and hence
10106 * no loose operators to worry about.
10108 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10109 "amopopr::pg_catalog.regoperator, "
10110 "NULL AS sortfamily, "
10111 "NULL AS sortfamilynsp "
10112 "FROM pg_catalog.pg_amop "
10113 "WHERE amopclaid = '%u'::pg_catalog.oid "
10114 "ORDER BY amopstrategy",
10115 opcinfo->dobj.catId.oid);
10118 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10120 ntups = PQntuples(res);
10122 i_amopstrategy = PQfnumber(res, "amopstrategy");
10123 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10124 i_amopopr = PQfnumber(res, "amopopr");
10125 i_sortfamily = PQfnumber(res, "sortfamily");
10126 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10128 for (i = 0; i < ntups; i++)
10130 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10131 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10132 amopopr = PQgetvalue(res, i, i_amopopr);
10133 sortfamily = PQgetvalue(res, i, i_sortfamily);
10134 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10137 appendPQExpBuffer(q, " ,\n ");
10139 appendPQExpBuffer(q, "OPERATOR %s %s",
10140 amopstrategy, amopopr);
10142 if (strlen(sortfamily) > 0)
10144 appendPQExpBuffer(q, " FOR ORDER BY ");
10145 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10146 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10147 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10150 if (strcmp(amopreqcheck, "t") == 0)
10151 appendPQExpBuffer(q, " RECHECK");
10159 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10161 * Print only those opfamily members that are tied to the opclass by
10162 * pg_depend entries.
10164 * We print the amproclefttype/amprocrighttype even though in most cases
10165 * the backend could deduce the right values, because of the corner case
10166 * of a btree sort support function for a cross-type comparison. That's
10167 * only allowed in 9.2 and later, but for simplicity print them in all
10168 * versions that have the columns.
10170 resetPQExpBuffer(query);
10172 if (fout->remoteVersion >= 80300)
10174 appendPQExpBuffer(query, "SELECT amprocnum, "
10175 "amproc::pg_catalog.regprocedure, "
10176 "amproclefttype::pg_catalog.regtype, "
10177 "amprocrighttype::pg_catalog.regtype "
10178 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10179 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10180 "AND refobjid = '%u'::pg_catalog.oid "
10181 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10182 "AND objid = ap.oid "
10183 "ORDER BY amprocnum",
10184 opcinfo->dobj.catId.oid);
10188 appendPQExpBuffer(query, "SELECT amprocnum, "
10189 "amproc::pg_catalog.regprocedure, "
10190 "'' AS amproclefttype, "
10191 "'' AS amprocrighttype "
10192 "FROM pg_catalog.pg_amproc "
10193 "WHERE amopclaid = '%u'::pg_catalog.oid "
10194 "ORDER BY amprocnum",
10195 opcinfo->dobj.catId.oid);
10198 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10200 ntups = PQntuples(res);
10202 i_amprocnum = PQfnumber(res, "amprocnum");
10203 i_amproc = PQfnumber(res, "amproc");
10204 i_amproclefttype = PQfnumber(res, "amproclefttype");
10205 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10207 for (i = 0; i < ntups; i++)
10209 amprocnum = PQgetvalue(res, i, i_amprocnum);
10210 amproc = PQgetvalue(res, i, i_amproc);
10211 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10212 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10215 appendPQExpBuffer(q, " ,\n ");
10217 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10219 if (*amproclefttype && *amprocrighttype)
10220 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10222 appendPQExpBuffer(q, " %s", amproc);
10229 appendPQExpBuffer(q, ";\n");
10231 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10232 fmtId(opcinfo->dobj.name));
10233 appendPQExpBuffer(labelq, " USING %s",
10236 if (binary_upgrade)
10237 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10239 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10240 opcinfo->dobj.name,
10241 opcinfo->dobj.namespace->dobj.name,
10244 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10245 q->data, delq->data, NULL,
10249 /* Dump Operator Class Comments */
10250 dumpComment(fout, labelq->data,
10251 NULL, opcinfo->rolname,
10252 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10255 destroyPQExpBuffer(query);
10256 destroyPQExpBuffer(q);
10257 destroyPQExpBuffer(delq);
10258 destroyPQExpBuffer(labelq);
10263 * write out a single operator family definition
10265 * Note: this also dumps any "loose" operator members that aren't bound to a
10266 * specific opclass within the opfamily.
10269 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10274 PQExpBuffer labelq;
10277 PGresult *res_procs;
10280 int i_amopstrategy;
10281 int i_amopreqcheck;
10284 int i_sortfamilynsp;
10287 int i_amproclefttype;
10288 int i_amprocrighttype;
10290 char *amopstrategy;
10291 char *amopreqcheck;
10294 char *sortfamilynsp;
10297 char *amproclefttype;
10298 char *amprocrighttype;
10302 /* Skip if not to be dumped */
10303 if (!opfinfo->dobj.dump || dataOnly)
10307 * We want to dump the opfamily only if (1) it contains "loose" operators
10308 * or functions, or (2) it contains an opclass with a different name or
10309 * owner. Otherwise it's sufficient to let it be created during creation
10310 * of the contained opclass, and not dumping it improves portability of
10311 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10315 query = createPQExpBuffer();
10316 q = createPQExpBuffer();
10317 delq = createPQExpBuffer();
10318 labelq = createPQExpBuffer();
10320 /* Make sure we are in proper schema so regoperator works correctly */
10321 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10324 * Fetch only those opfamily members that are tied directly to the
10325 * opfamily by pg_depend entries.
10327 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10328 * older server's opclass in which it is used. This is to avoid
10329 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10330 * older server and then reload into that old version. This can go away
10331 * once 8.3 is so old as to not be of interest to anyone.
10333 if (fout->remoteVersion >= 90100)
10335 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10336 "amopopr::pg_catalog.regoperator, "
10337 "opfname AS sortfamily, "
10338 "nspname AS sortfamilynsp "
10339 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10340 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10341 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10342 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10343 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10344 "AND refobjid = '%u'::pg_catalog.oid "
10345 "AND amopfamily = '%u'::pg_catalog.oid "
10346 "ORDER BY amopstrategy",
10347 opfinfo->dobj.catId.oid,
10348 opfinfo->dobj.catId.oid);
10350 else if (fout->remoteVersion >= 80400)
10352 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10353 "amopopr::pg_catalog.regoperator, "
10354 "NULL AS sortfamily, "
10355 "NULL AS sortfamilynsp "
10356 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10357 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10358 "AND refobjid = '%u'::pg_catalog.oid "
10359 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10360 "AND objid = ao.oid "
10361 "ORDER BY amopstrategy",
10362 opfinfo->dobj.catId.oid);
10366 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10367 "amopopr::pg_catalog.regoperator, "
10368 "NULL AS sortfamily, "
10369 "NULL AS sortfamilynsp "
10370 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10371 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10372 "AND refobjid = '%u'::pg_catalog.oid "
10373 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10374 "AND objid = ao.oid "
10375 "ORDER BY amopstrategy",
10376 opfinfo->dobj.catId.oid);
10379 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10381 resetPQExpBuffer(query);
10383 appendPQExpBuffer(query, "SELECT amprocnum, "
10384 "amproc::pg_catalog.regprocedure, "
10385 "amproclefttype::pg_catalog.regtype, "
10386 "amprocrighttype::pg_catalog.regtype "
10387 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10388 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10389 "AND refobjid = '%u'::pg_catalog.oid "
10390 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10391 "AND objid = ap.oid "
10392 "ORDER BY amprocnum",
10393 opfinfo->dobj.catId.oid);
10395 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10397 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10399 /* No loose members, so check contained opclasses */
10400 resetPQExpBuffer(query);
10402 appendPQExpBuffer(query, "SELECT 1 "
10403 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10404 "WHERE f.oid = '%u'::pg_catalog.oid "
10405 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10406 "AND refobjid = f.oid "
10407 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10408 "AND objid = c.oid "
10409 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10411 opfinfo->dobj.catId.oid);
10413 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10415 if (PQntuples(res) == 0)
10417 /* no need to dump it, so bail out */
10420 PQclear(res_procs);
10421 destroyPQExpBuffer(query);
10422 destroyPQExpBuffer(q);
10423 destroyPQExpBuffer(delq);
10424 destroyPQExpBuffer(labelq);
10431 /* Get additional fields from the pg_opfamily row */
10432 resetPQExpBuffer(query);
10434 appendPQExpBuffer(query, "SELECT "
10435 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10436 "FROM pg_catalog.pg_opfamily "
10437 "WHERE oid = '%u'::pg_catalog.oid",
10438 opfinfo->dobj.catId.oid);
10440 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10442 i_amname = PQfnumber(res, "amname");
10444 /* amname will still be needed after we PQclear res */
10445 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10448 * DROP must be fully qualified in case same name appears in pg_catalog
10450 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10451 fmtId(opfinfo->dobj.namespace->dobj.name));
10452 appendPQExpBuffer(delq, ".%s",
10453 fmtId(opfinfo->dobj.name));
10454 appendPQExpBuffer(delq, " USING %s;\n",
10457 /* Build the fixed portion of the CREATE command */
10458 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10459 fmtId(opfinfo->dobj.name));
10460 appendPQExpBuffer(q, " USING %s;\n",
10465 /* Do we need an ALTER to add loose members? */
10466 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10468 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10469 fmtId(opfinfo->dobj.name));
10470 appendPQExpBuffer(q, " USING %s ADD\n ",
10476 * Now fetch and print the OPERATOR entries (pg_amop rows).
10478 ntups = PQntuples(res_ops);
10480 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10481 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10482 i_amopopr = PQfnumber(res_ops, "amopopr");
10483 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10484 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10486 for (i = 0; i < ntups; i++)
10488 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10489 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10490 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10491 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10492 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10495 appendPQExpBuffer(q, " ,\n ");
10497 appendPQExpBuffer(q, "OPERATOR %s %s",
10498 amopstrategy, amopopr);
10500 if (strlen(sortfamily) > 0)
10502 appendPQExpBuffer(q, " FOR ORDER BY ");
10503 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10504 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10505 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10508 if (strcmp(amopreqcheck, "t") == 0)
10509 appendPQExpBuffer(q, " RECHECK");
10515 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10517 ntups = PQntuples(res_procs);
10519 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10520 i_amproc = PQfnumber(res_procs, "amproc");
10521 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10522 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10524 for (i = 0; i < ntups; i++)
10526 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10527 amproc = PQgetvalue(res_procs, i, i_amproc);
10528 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10529 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10532 appendPQExpBuffer(q, " ,\n ");
10534 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10535 amprocnum, amproclefttype, amprocrighttype,
10541 appendPQExpBuffer(q, ";\n");
10544 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10545 fmtId(opfinfo->dobj.name));
10546 appendPQExpBuffer(labelq, " USING %s",
10549 if (binary_upgrade)
10550 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10552 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10553 opfinfo->dobj.name,
10554 opfinfo->dobj.namespace->dobj.name,
10557 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10558 q->data, delq->data, NULL,
10562 /* Dump Operator Family Comments */
10563 dumpComment(fout, labelq->data,
10564 NULL, opfinfo->rolname,
10565 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10569 PQclear(res_procs);
10570 destroyPQExpBuffer(query);
10571 destroyPQExpBuffer(q);
10572 destroyPQExpBuffer(delq);
10573 destroyPQExpBuffer(labelq);
10578 * write out a single collation definition
10581 dumpCollation(Archive *fout, CollInfo *collinfo)
10586 PQExpBuffer labelq;
10590 const char *collcollate;
10591 const char *collctype;
10593 /* Skip if not to be dumped */
10594 if (!collinfo->dobj.dump || dataOnly)
10597 query = createPQExpBuffer();
10598 q = createPQExpBuffer();
10599 delq = createPQExpBuffer();
10600 labelq = createPQExpBuffer();
10602 /* Make sure we are in proper schema */
10603 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10605 /* Get conversion-specific details */
10606 appendPQExpBuffer(query, "SELECT "
10609 "FROM pg_catalog.pg_collation c "
10610 "WHERE c.oid = '%u'::pg_catalog.oid",
10611 collinfo->dobj.catId.oid);
10613 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10615 i_collcollate = PQfnumber(res, "collcollate");
10616 i_collctype = PQfnumber(res, "collctype");
10618 collcollate = PQgetvalue(res, 0, i_collcollate);
10619 collctype = PQgetvalue(res, 0, i_collctype);
10622 * DROP must be fully qualified in case same name appears in pg_catalog
10624 appendPQExpBuffer(delq, "DROP COLLATION %s",
10625 fmtId(collinfo->dobj.namespace->dobj.name));
10626 appendPQExpBuffer(delq, ".%s;\n",
10627 fmtId(collinfo->dobj.name));
10629 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10630 fmtId(collinfo->dobj.name));
10631 appendStringLiteralAH(q, collcollate, fout);
10632 appendPQExpBuffer(q, ", lc_ctype = ");
10633 appendStringLiteralAH(q, collctype, fout);
10634 appendPQExpBuffer(q, ");\n");
10636 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10638 if (binary_upgrade)
10639 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10641 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10642 collinfo->dobj.name,
10643 collinfo->dobj.namespace->dobj.name,
10646 false, "COLLATION", SECTION_PRE_DATA,
10647 q->data, delq->data, NULL,
10651 /* Dump Collation Comments */
10652 dumpComment(fout, labelq->data,
10653 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10654 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10658 destroyPQExpBuffer(query);
10659 destroyPQExpBuffer(q);
10660 destroyPQExpBuffer(delq);
10661 destroyPQExpBuffer(labelq);
10666 * write out a single conversion definition
10669 dumpConversion(Archive *fout, ConvInfo *convinfo)
10674 PQExpBuffer labelq;
10676 int i_conforencoding;
10677 int i_contoencoding;
10680 const char *conforencoding;
10681 const char *contoencoding;
10682 const char *conproc;
10685 /* Skip if not to be dumped */
10686 if (!convinfo->dobj.dump || dataOnly)
10689 query = createPQExpBuffer();
10690 q = createPQExpBuffer();
10691 delq = createPQExpBuffer();
10692 labelq = createPQExpBuffer();
10694 /* Make sure we are in proper schema */
10695 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10697 /* Get conversion-specific details */
10698 appendPQExpBuffer(query, "SELECT "
10699 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10700 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10701 "conproc, condefault "
10702 "FROM pg_catalog.pg_conversion c "
10703 "WHERE c.oid = '%u'::pg_catalog.oid",
10704 convinfo->dobj.catId.oid);
10706 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10708 i_conforencoding = PQfnumber(res, "conforencoding");
10709 i_contoencoding = PQfnumber(res, "contoencoding");
10710 i_conproc = PQfnumber(res, "conproc");
10711 i_condefault = PQfnumber(res, "condefault");
10713 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10714 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10715 conproc = PQgetvalue(res, 0, i_conproc);
10716 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10719 * DROP must be fully qualified in case same name appears in pg_catalog
10721 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10722 fmtId(convinfo->dobj.namespace->dobj.name));
10723 appendPQExpBuffer(delq, ".%s;\n",
10724 fmtId(convinfo->dobj.name));
10726 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10727 (condefault) ? "DEFAULT " : "",
10728 fmtId(convinfo->dobj.name));
10729 appendStringLiteralAH(q, conforencoding, fout);
10730 appendPQExpBuffer(q, " TO ");
10731 appendStringLiteralAH(q, contoencoding, fout);
10732 /* regproc is automatically quoted in 7.3 and above */
10733 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10735 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10737 if (binary_upgrade)
10738 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10740 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10741 convinfo->dobj.name,
10742 convinfo->dobj.namespace->dobj.name,
10745 false, "CONVERSION", SECTION_PRE_DATA,
10746 q->data, delq->data, NULL,
10750 /* Dump Conversion Comments */
10751 dumpComment(fout, labelq->data,
10752 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10753 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10757 destroyPQExpBuffer(query);
10758 destroyPQExpBuffer(q);
10759 destroyPQExpBuffer(delq);
10760 destroyPQExpBuffer(labelq);
10764 * format_aggregate_signature: generate aggregate name and argument list
10766 * The argument type names are qualified if needed. The aggregate name
10767 * is never qualified.
10770 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10772 PQExpBufferData buf;
10775 initPQExpBuffer(&buf);
10777 appendPQExpBuffer(&buf, "%s",
10778 fmtId(agginfo->aggfn.dobj.name));
10780 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10782 if (agginfo->aggfn.nargs == 0)
10783 appendPQExpBuffer(&buf, "(*)");
10786 appendPQExpBuffer(&buf, "(");
10787 for (j = 0; j < agginfo->aggfn.nargs; j++)
10791 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10794 appendPQExpBuffer(&buf, "%s%s",
10795 (j > 0) ? ", " : "",
10799 appendPQExpBuffer(&buf, ")");
10806 * write out a single aggregate definition
10809 dumpAgg(Archive *fout, AggInfo *agginfo)
10814 PQExpBuffer labelq;
10815 PQExpBuffer details;
10822 int i_aggtranstype;
10825 const char *aggtransfn;
10826 const char *aggfinalfn;
10827 const char *aggsortop;
10828 const char *aggtranstype;
10829 const char *agginitval;
10832 /* Skip if not to be dumped */
10833 if (!agginfo->aggfn.dobj.dump || dataOnly)
10836 query = createPQExpBuffer();
10837 q = createPQExpBuffer();
10838 delq = createPQExpBuffer();
10839 labelq = createPQExpBuffer();
10840 details = createPQExpBuffer();
10842 /* Make sure we are in proper schema */
10843 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10845 /* Get aggregate-specific details */
10846 if (fout->remoteVersion >= 80100)
10848 appendPQExpBuffer(query, "SELECT aggtransfn, "
10849 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10850 "aggsortop::pg_catalog.regoperator, "
10852 "'t'::boolean AS convertok "
10853 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10854 "WHERE a.aggfnoid = p.oid "
10855 "AND p.oid = '%u'::pg_catalog.oid",
10856 agginfo->aggfn.dobj.catId.oid);
10858 else if (fout->remoteVersion >= 70300)
10860 appendPQExpBuffer(query, "SELECT aggtransfn, "
10861 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10864 "'t'::boolean AS convertok "
10865 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10866 "WHERE a.aggfnoid = p.oid "
10867 "AND p.oid = '%u'::pg_catalog.oid",
10868 agginfo->aggfn.dobj.catId.oid);
10870 else if (fout->remoteVersion >= 70100)
10872 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10873 "format_type(aggtranstype, NULL) AS aggtranstype, "
10876 "'t'::boolean AS convertok "
10877 "FROM pg_aggregate "
10878 "WHERE oid = '%u'::oid",
10879 agginfo->aggfn.dobj.catId.oid);
10883 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10885 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10887 "agginitval1 AS agginitval, "
10888 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10889 "FROM pg_aggregate "
10890 "WHERE oid = '%u'::oid",
10891 agginfo->aggfn.dobj.catId.oid);
10894 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10896 i_aggtransfn = PQfnumber(res, "aggtransfn");
10897 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10898 i_aggsortop = PQfnumber(res, "aggsortop");
10899 i_aggtranstype = PQfnumber(res, "aggtranstype");
10900 i_agginitval = PQfnumber(res, "agginitval");
10901 i_convertok = PQfnumber(res, "convertok");
10903 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10904 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10905 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10906 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10907 agginitval = PQgetvalue(res, 0, i_agginitval);
10908 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10910 aggsig = format_aggregate_signature(agginfo, fout, true);
10911 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10915 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10920 if (fout->remoteVersion >= 70300)
10922 /* If using 7.3's regproc or regtype, data is already quoted */
10923 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10927 else if (fout->remoteVersion >= 70100)
10929 /* format_type quotes, regproc does not */
10930 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10936 /* need quotes all around */
10937 appendPQExpBuffer(details, " SFUNC = %s,\n",
10938 fmtId(aggtransfn));
10939 appendPQExpBuffer(details, " STYPE = %s",
10940 fmtId(aggtranstype));
10943 if (!PQgetisnull(res, 0, i_agginitval))
10945 appendPQExpBuffer(details, ",\n INITCOND = ");
10946 appendStringLiteralAH(details, agginitval, fout);
10949 if (strcmp(aggfinalfn, "-") != 0)
10951 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
10955 aggsortop = convertOperatorReference(fout, aggsortop);
10958 appendPQExpBuffer(details, ",\n SORTOP = %s",
10963 * DROP must be fully qualified in case same name appears in pg_catalog
10965 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10966 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10969 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10970 aggsig, details->data);
10972 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10974 if (binary_upgrade)
10975 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10977 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10979 agginfo->aggfn.dobj.namespace->dobj.name,
10981 agginfo->aggfn.rolname,
10982 false, "AGGREGATE", SECTION_PRE_DATA,
10983 q->data, delq->data, NULL,
10987 /* Dump Aggregate Comments */
10988 dumpComment(fout, labelq->data,
10989 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10990 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10991 dumpSecLabel(fout, labelq->data,
10992 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10993 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10996 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10997 * command look like a function's GRANT; in particular this affects the
10998 * syntax for zero-argument aggregates.
11003 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11004 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11006 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11008 aggsig, NULL, aggsig_tag,
11009 agginfo->aggfn.dobj.namespace->dobj.name,
11010 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11017 destroyPQExpBuffer(query);
11018 destroyPQExpBuffer(q);
11019 destroyPQExpBuffer(delq);
11020 destroyPQExpBuffer(labelq);
11021 destroyPQExpBuffer(details);
11026 * write out a single text search parser
11029 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11033 PQExpBuffer labelq;
11035 /* Skip if not to be dumped */
11036 if (!prsinfo->dobj.dump || dataOnly)
11039 q = createPQExpBuffer();
11040 delq = createPQExpBuffer();
11041 labelq = createPQExpBuffer();
11043 /* Make sure we are in proper schema */
11044 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11046 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11047 fmtId(prsinfo->dobj.name));
11049 appendPQExpBuffer(q, " START = %s,\n",
11050 convertTSFunction(fout, prsinfo->prsstart));
11051 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11052 convertTSFunction(fout, prsinfo->prstoken));
11053 appendPQExpBuffer(q, " END = %s,\n",
11054 convertTSFunction(fout, prsinfo->prsend));
11055 if (prsinfo->prsheadline != InvalidOid)
11056 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11057 convertTSFunction(fout, prsinfo->prsheadline));
11058 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11059 convertTSFunction(fout, prsinfo->prslextype));
11062 * DROP must be fully qualified in case same name appears in pg_catalog
11064 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11065 fmtId(prsinfo->dobj.namespace->dobj.name));
11066 appendPQExpBuffer(delq, ".%s;\n",
11067 fmtId(prsinfo->dobj.name));
11069 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11070 fmtId(prsinfo->dobj.name));
11072 if (binary_upgrade)
11073 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11075 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11076 prsinfo->dobj.name,
11077 prsinfo->dobj.namespace->dobj.name,
11080 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11081 q->data, delq->data, NULL,
11085 /* Dump Parser Comments */
11086 dumpComment(fout, labelq->data,
11088 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11090 destroyPQExpBuffer(q);
11091 destroyPQExpBuffer(delq);
11092 destroyPQExpBuffer(labelq);
11097 * write out a single text search dictionary
11100 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11104 PQExpBuffer labelq;
11110 /* Skip if not to be dumped */
11111 if (!dictinfo->dobj.dump || dataOnly)
11114 q = createPQExpBuffer();
11115 delq = createPQExpBuffer();
11116 labelq = createPQExpBuffer();
11117 query = createPQExpBuffer();
11119 /* Fetch name and namespace of the dictionary's template */
11120 selectSourceSchema(fout, "pg_catalog");
11121 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11122 "FROM pg_ts_template p, pg_namespace n "
11123 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11124 dictinfo->dicttemplate);
11125 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11126 nspname = PQgetvalue(res, 0, 0);
11127 tmplname = PQgetvalue(res, 0, 1);
11129 /* Make sure we are in proper schema */
11130 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11132 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11133 fmtId(dictinfo->dobj.name));
11135 appendPQExpBuffer(q, " TEMPLATE = ");
11136 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11137 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11138 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11142 /* the dictinitoption can be dumped straight into the command */
11143 if (dictinfo->dictinitoption)
11144 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11146 appendPQExpBuffer(q, " );\n");
11149 * DROP must be fully qualified in case same name appears in pg_catalog
11151 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11152 fmtId(dictinfo->dobj.namespace->dobj.name));
11153 appendPQExpBuffer(delq, ".%s;\n",
11154 fmtId(dictinfo->dobj.name));
11156 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11157 fmtId(dictinfo->dobj.name));
11159 if (binary_upgrade)
11160 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11162 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11163 dictinfo->dobj.name,
11164 dictinfo->dobj.namespace->dobj.name,
11167 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11168 q->data, delq->data, NULL,
11172 /* Dump Dictionary Comments */
11173 dumpComment(fout, labelq->data,
11174 NULL, dictinfo->rolname,
11175 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11177 destroyPQExpBuffer(q);
11178 destroyPQExpBuffer(delq);
11179 destroyPQExpBuffer(labelq);
11180 destroyPQExpBuffer(query);
11185 * write out a single text search template
11188 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11192 PQExpBuffer labelq;
11194 /* Skip if not to be dumped */
11195 if (!tmplinfo->dobj.dump || dataOnly)
11198 q = createPQExpBuffer();
11199 delq = createPQExpBuffer();
11200 labelq = createPQExpBuffer();
11202 /* Make sure we are in proper schema */
11203 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11205 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11206 fmtId(tmplinfo->dobj.name));
11208 if (tmplinfo->tmplinit != InvalidOid)
11209 appendPQExpBuffer(q, " INIT = %s,\n",
11210 convertTSFunction(fout, tmplinfo->tmplinit));
11211 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11212 convertTSFunction(fout, tmplinfo->tmpllexize));
11215 * DROP must be fully qualified in case same name appears in pg_catalog
11217 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11218 fmtId(tmplinfo->dobj.namespace->dobj.name));
11219 appendPQExpBuffer(delq, ".%s;\n",
11220 fmtId(tmplinfo->dobj.name));
11222 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11223 fmtId(tmplinfo->dobj.name));
11225 if (binary_upgrade)
11226 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11228 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11229 tmplinfo->dobj.name,
11230 tmplinfo->dobj.namespace->dobj.name,
11233 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11234 q->data, delq->data, NULL,
11238 /* Dump Template Comments */
11239 dumpComment(fout, labelq->data,
11241 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11243 destroyPQExpBuffer(q);
11244 destroyPQExpBuffer(delq);
11245 destroyPQExpBuffer(labelq);
11250 * write out a single text search configuration
11253 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11257 PQExpBuffer labelq;
11267 /* Skip if not to be dumped */
11268 if (!cfginfo->dobj.dump || dataOnly)
11271 q = createPQExpBuffer();
11272 delq = createPQExpBuffer();
11273 labelq = createPQExpBuffer();
11274 query = createPQExpBuffer();
11276 /* Fetch name and namespace of the config's parser */
11277 selectSourceSchema(fout, "pg_catalog");
11278 appendPQExpBuffer(query, "SELECT nspname, prsname "
11279 "FROM pg_ts_parser p, pg_namespace n "
11280 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11281 cfginfo->cfgparser);
11282 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11283 nspname = PQgetvalue(res, 0, 0);
11284 prsname = PQgetvalue(res, 0, 1);
11286 /* Make sure we are in proper schema */
11287 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11289 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11290 fmtId(cfginfo->dobj.name));
11292 appendPQExpBuffer(q, " PARSER = ");
11293 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11294 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11295 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11299 resetPQExpBuffer(query);
11300 appendPQExpBuffer(query,
11302 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11303 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11304 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11305 "FROM pg_catalog.pg_ts_config_map AS m \n"
11306 "WHERE m.mapcfg = '%u' \n"
11307 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11308 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11310 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11311 ntups = PQntuples(res);
11313 i_tokenname = PQfnumber(res, "tokenname");
11314 i_dictname = PQfnumber(res, "dictname");
11316 for (i = 0; i < ntups; i++)
11318 char *tokenname = PQgetvalue(res, i, i_tokenname);
11319 char *dictname = PQgetvalue(res, i, i_dictname);
11322 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11324 /* starting a new token type, so start a new command */
11326 appendPQExpBuffer(q, ";\n");
11327 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11328 fmtId(cfginfo->dobj.name));
11329 /* tokenname needs quoting, dictname does NOT */
11330 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11331 fmtId(tokenname), dictname);
11334 appendPQExpBuffer(q, ", %s", dictname);
11338 appendPQExpBuffer(q, ";\n");
11343 * DROP must be fully qualified in case same name appears in pg_catalog
11345 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11346 fmtId(cfginfo->dobj.namespace->dobj.name));
11347 appendPQExpBuffer(delq, ".%s;\n",
11348 fmtId(cfginfo->dobj.name));
11350 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11351 fmtId(cfginfo->dobj.name));
11353 if (binary_upgrade)
11354 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11356 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11357 cfginfo->dobj.name,
11358 cfginfo->dobj.namespace->dobj.name,
11361 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11362 q->data, delq->data, NULL,
11366 /* Dump Configuration Comments */
11367 dumpComment(fout, labelq->data,
11368 NULL, cfginfo->rolname,
11369 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11371 destroyPQExpBuffer(q);
11372 destroyPQExpBuffer(delq);
11373 destroyPQExpBuffer(labelq);
11374 destroyPQExpBuffer(query);
11378 * dumpForeignDataWrapper
11379 * write out a single foreign-data wrapper definition
11382 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11386 PQExpBuffer labelq;
11389 /* Skip if not to be dumped */
11390 if (!fdwinfo->dobj.dump || dataOnly)
11394 * FDWs that belong to an extension are dumped based on their "dump"
11395 * field. Otherwise omit them if we are only dumping some specific object.
11397 if (!fdwinfo->dobj.ext_member)
11398 if (!include_everything)
11401 q = createPQExpBuffer();
11402 delq = createPQExpBuffer();
11403 labelq = createPQExpBuffer();
11405 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11407 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11410 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11411 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11413 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11414 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11416 if (strlen(fdwinfo->fdwoptions) > 0)
11417 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11419 appendPQExpBuffer(q, ";\n");
11421 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11424 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11427 if (binary_upgrade)
11428 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11430 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11431 fdwinfo->dobj.name,
11435 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11436 q->data, delq->data, NULL,
11440 /* Handle the ACL */
11441 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11442 "FOREIGN DATA WRAPPER",
11443 qfdwname, NULL, fdwinfo->dobj.name,
11444 NULL, fdwinfo->rolname,
11447 /* Dump Foreign Data Wrapper Comments */
11448 dumpComment(fout, labelq->data,
11449 NULL, fdwinfo->rolname,
11450 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11454 destroyPQExpBuffer(q);
11455 destroyPQExpBuffer(delq);
11456 destroyPQExpBuffer(labelq);
11460 * dumpForeignServer
11461 * write out a foreign server definition
11464 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11468 PQExpBuffer labelq;
11474 /* Skip if not to be dumped */
11475 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11478 q = createPQExpBuffer();
11479 delq = createPQExpBuffer();
11480 labelq = createPQExpBuffer();
11481 query = createPQExpBuffer();
11483 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11485 /* look up the foreign-data wrapper */
11486 selectSourceSchema(fout, "pg_catalog");
11487 appendPQExpBuffer(query, "SELECT fdwname "
11488 "FROM pg_foreign_data_wrapper w "
11489 "WHERE w.oid = '%u'",
11491 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11492 fdwname = PQgetvalue(res, 0, 0);
11494 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11495 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11497 appendPQExpBuffer(q, " TYPE ");
11498 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11500 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11502 appendPQExpBuffer(q, " VERSION ");
11503 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11506 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11507 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11509 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11510 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11512 appendPQExpBuffer(q, ";\n");
11514 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11517 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11519 if (binary_upgrade)
11520 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11522 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11523 srvinfo->dobj.name,
11527 false, "SERVER", SECTION_PRE_DATA,
11528 q->data, delq->data, NULL,
11532 /* Handle the ACL */
11533 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11535 qsrvname, NULL, srvinfo->dobj.name,
11536 NULL, srvinfo->rolname,
11539 /* Dump user mappings */
11540 dumpUserMappings(fout,
11541 srvinfo->dobj.name, NULL,
11543 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11545 /* Dump Foreign Server Comments */
11546 dumpComment(fout, labelq->data,
11547 NULL, srvinfo->rolname,
11548 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11552 destroyPQExpBuffer(q);
11553 destroyPQExpBuffer(delq);
11554 destroyPQExpBuffer(labelq);
11560 * This routine is used to dump any user mappings associated with the
11561 * server handed to this routine. Should be called after ArchiveEntry()
11565 dumpUserMappings(Archive *fout,
11566 const char *servername, const char *namespace,
11568 CatalogId catalogId, DumpId dumpId)
11580 q = createPQExpBuffer();
11581 tag = createPQExpBuffer();
11582 delq = createPQExpBuffer();
11583 query = createPQExpBuffer();
11586 * We read from the publicly accessible view pg_user_mappings, so as not
11587 * to fail if run by a non-superuser. Note that the view will show
11588 * umoptions as null if the user hasn't got privileges for the associated
11589 * server; this means that pg_dump will dump such a mapping, but with no
11590 * OPTIONS clause. A possible alternative is to skip such mappings
11591 * altogether, but it's not clear that that's an improvement.
11593 selectSourceSchema(fout, "pg_catalog");
11595 appendPQExpBuffer(query,
11597 "array_to_string(ARRAY("
11598 "SELECT quote_ident(option_name) || ' ' || "
11599 "quote_literal(option_value) "
11600 "FROM pg_options_to_table(umoptions) "
11601 "ORDER BY option_name"
11602 "), E',\n ') AS umoptions "
11603 "FROM pg_user_mappings "
11604 "WHERE srvid = '%u' "
11605 "ORDER BY usename",
11608 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11610 ntups = PQntuples(res);
11611 i_usename = PQfnumber(res, "usename");
11612 i_umoptions = PQfnumber(res, "umoptions");
11614 for (i = 0; i < ntups; i++)
11619 usename = PQgetvalue(res, i, i_usename);
11620 umoptions = PQgetvalue(res, i, i_umoptions);
11622 resetPQExpBuffer(q);
11623 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11624 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11626 if (umoptions && strlen(umoptions) > 0)
11627 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11629 appendPQExpBuffer(q, ";\n");
11631 resetPQExpBuffer(delq);
11632 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11633 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11635 resetPQExpBuffer(tag);
11636 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11637 usename, servername);
11639 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11644 "USER MAPPING", SECTION_PRE_DATA,
11645 q->data, delq->data, NULL,
11652 destroyPQExpBuffer(query);
11653 destroyPQExpBuffer(delq);
11654 destroyPQExpBuffer(q);
11658 * Write out default privileges information
11661 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11667 /* Skip if not to be dumped */
11668 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11671 q = createPQExpBuffer();
11672 tag = createPQExpBuffer();
11674 switch (daclinfo->defaclobjtype)
11676 case DEFACLOBJ_RELATION:
11679 case DEFACLOBJ_SEQUENCE:
11680 type = "SEQUENCES";
11682 case DEFACLOBJ_FUNCTION:
11683 type = "FUNCTIONS";
11686 /* shouldn't get here */
11687 exit_horribly(NULL,
11688 "unknown object type (%d) in default privileges\n",
11689 (int) daclinfo->defaclobjtype);
11690 type = ""; /* keep compiler quiet */
11693 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11695 /* build the actual command(s) for this tuple */
11696 if (!buildDefaultACLCommands(type,
11697 daclinfo->dobj.namespace != NULL ?
11698 daclinfo->dobj.namespace->dobj.name : NULL,
11699 daclinfo->defaclacl,
11700 daclinfo->defaclrole,
11701 fout->remoteVersion,
11703 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11704 daclinfo->defaclacl);
11706 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11708 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11710 daclinfo->defaclrole,
11711 false, "DEFAULT ACL", SECTION_POST_DATA,
11716 destroyPQExpBuffer(tag);
11717 destroyPQExpBuffer(q);
11721 * Write out grant/revoke information
11723 * 'objCatId' is the catalog ID of the underlying object.
11724 * 'objDumpId' is the dump ID of the underlying object.
11725 * 'type' must be one of
11726 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11727 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11728 * 'name' is the formatted name of the object. Must be quoted etc. already.
11729 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11730 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11731 * 'nspname' is the namespace the object is in (NULL if none).
11732 * 'owner' is the owner, NULL if there is no owner (for languages).
11733 * 'acls' is the string read out of the fooacl system catalog field;
11734 * it will be parsed here.
11738 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11739 const char *type, const char *name, const char *subname,
11740 const char *tag, const char *nspname, const char *owner,
11745 /* Do nothing if ACL dump is not enabled */
11749 /* --data-only skips ACLs *except* BLOB ACLs */
11750 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11753 sql = createPQExpBuffer();
11755 if (!buildACLCommands(name, subname, type, acls, owner,
11756 "", fout->remoteVersion, sql))
11757 exit_horribly(NULL,
11758 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11762 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11765 owner ? owner : "",
11766 false, "ACL", SECTION_NONE,
11767 sql->data, "", NULL,
11771 destroyPQExpBuffer(sql);
11777 * This routine is used to dump any security labels associated with the
11778 * object handed to this routine. The routine takes a constant character
11779 * string for the target part of the security-label command, plus
11780 * the namespace and owner of the object (for labeling the ArchiveEntry),
11781 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11782 * plus the dump ID for the object (for setting a dependency).
11783 * If a matching pg_seclabel entry is found, it is dumped.
11785 * Note: although this routine takes a dumpId for dependency purposes,
11786 * that purpose is just to mark the dependency in the emitted dump file
11787 * for possible future use by pg_restore. We do NOT use it for determining
11788 * ordering of the label in the dump file, because this routine is called
11789 * after dependency sorting occurs. This routine should be called just after
11790 * calling ArchiveEntry() for the specified object.
11793 dumpSecLabel(Archive *fout, const char *target,
11794 const char *namespace, const char *owner,
11795 CatalogId catalogId, int subid, DumpId dumpId)
11797 SecLabelItem *labels;
11802 /* do nothing, if --no-security-labels is supplied */
11803 if (no_security_labels)
11806 /* Comments are schema not data ... except blob comments are data */
11807 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11818 /* Search for security labels associated with catalogId, using table */
11819 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11821 query = createPQExpBuffer();
11823 for (i = 0; i < nlabels; i++)
11826 * Ignore label entries for which the subid doesn't match.
11828 if (labels[i].objsubid != subid)
11831 appendPQExpBuffer(query,
11832 "SECURITY LABEL FOR %s ON %s IS ",
11833 fmtId(labels[i].provider), target);
11834 appendStringLiteralAH(query, labels[i].label, fout);
11835 appendPQExpBuffer(query, ";\n");
11838 if (query->len > 0)
11840 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11841 target, namespace, NULL, owner,
11842 false, "SECURITY LABEL", SECTION_NONE,
11843 query->data, "", NULL,
11847 destroyPQExpBuffer(query);
11851 * dumpTableSecLabel
11853 * As above, but dump security label for both the specified table (or view)
11857 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11859 SecLabelItem *labels;
11863 PQExpBuffer target;
11865 /* do nothing, if --no-security-labels is supplied */
11866 if (no_security_labels)
11869 /* SecLabel are SCHEMA not data */
11873 /* Search for comments associated with relation, using table */
11874 nlabels = findSecLabels(fout,
11875 tbinfo->dobj.catId.tableoid,
11876 tbinfo->dobj.catId.oid,
11879 /* If security labels exist, build SECURITY LABEL statements */
11883 query = createPQExpBuffer();
11884 target = createPQExpBuffer();
11886 for (i = 0; i < nlabels; i++)
11888 const char *colname;
11889 const char *provider = labels[i].provider;
11890 const char *label = labels[i].label;
11891 int objsubid = labels[i].objsubid;
11893 resetPQExpBuffer(target);
11896 appendPQExpBuffer(target, "%s %s", reltypename,
11897 fmtId(tbinfo->dobj.name));
11901 colname = getAttrName(objsubid, tbinfo);
11902 /* first fmtId result must be consumed before calling it again */
11903 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11904 appendPQExpBuffer(target, ".%s", fmtId(colname));
11906 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11907 fmtId(provider), target->data);
11908 appendStringLiteralAH(query, label, fout);
11909 appendPQExpBuffer(query, ";\n");
11911 if (query->len > 0)
11913 resetPQExpBuffer(target);
11914 appendPQExpBuffer(target, "%s %s", reltypename,
11915 fmtId(tbinfo->dobj.name));
11916 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11918 tbinfo->dobj.namespace->dobj.name,
11919 NULL, tbinfo->rolname,
11920 false, "SECURITY LABEL", SECTION_NONE,
11921 query->data, "", NULL,
11922 &(tbinfo->dobj.dumpId), 1,
11925 destroyPQExpBuffer(query);
11926 destroyPQExpBuffer(target);
11932 * Find the security label(s), if any, associated with the given object.
11933 * All the objsubid values associated with the given classoid/objoid are
11934 * found with one search.
11937 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11939 /* static storage for table of security labels */
11940 static SecLabelItem *labels = NULL;
11941 static int nlabels = -1;
11943 SecLabelItem *middle = NULL;
11945 SecLabelItem *high;
11948 /* Get security labels if we didn't already */
11950 nlabels = collectSecLabels(fout, &labels);
11952 if (nlabels <= 0) /* no labels, so no match is possible */
11959 * Do binary search to find some item matching the object.
11962 high = &labels[nlabels - 1];
11963 while (low <= high)
11965 middle = low + (high - low) / 2;
11967 if (classoid < middle->classoid)
11969 else if (classoid > middle->classoid)
11971 else if (objoid < middle->objoid)
11973 else if (objoid > middle->objoid)
11976 break; /* found a match */
11979 if (low > high) /* no matches */
11986 * Now determine how many items match the object. The search loop
11987 * invariant still holds: only items between low and high inclusive could
11991 while (middle > low)
11993 if (classoid != middle[-1].classoid ||
11994 objoid != middle[-1].objoid)
12003 while (middle <= high)
12005 if (classoid != middle->classoid ||
12006 objoid != middle->objoid)
12018 * Construct a table of all security labels available for database objects.
12019 * It's much faster to pull them all at once.
12021 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12024 collectSecLabels(Archive *fout, SecLabelItem **items)
12035 SecLabelItem *labels;
12037 query = createPQExpBuffer();
12039 appendPQExpBuffer(query,
12040 "SELECT label, provider, classoid, objoid, objsubid "
12041 "FROM pg_catalog.pg_seclabel "
12042 "ORDER BY classoid, objoid, objsubid");
12044 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12046 /* Construct lookup table containing OIDs in numeric form */
12047 i_label = PQfnumber(res, "label");
12048 i_provider = PQfnumber(res, "provider");
12049 i_classoid = PQfnumber(res, "classoid");
12050 i_objoid = PQfnumber(res, "objoid");
12051 i_objsubid = PQfnumber(res, "objsubid");
12053 ntups = PQntuples(res);
12055 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12057 for (i = 0; i < ntups; i++)
12059 labels[i].label = PQgetvalue(res, i, i_label);
12060 labels[i].provider = PQgetvalue(res, i, i_provider);
12061 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12062 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12063 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12066 /* Do NOT free the PGresult since we are keeping pointers into it */
12067 destroyPQExpBuffer(query);
12075 * write out to fout the declarations (not data) of a user-defined table
12078 dumpTable(Archive *fout, TableInfo *tbinfo)
12080 if (tbinfo->dobj.dump)
12084 if (tbinfo->relkind == RELKIND_SEQUENCE)
12085 dumpSequence(fout, tbinfo);
12086 else if (!dataOnly)
12087 dumpTableSchema(fout, tbinfo);
12089 /* Handle the ACL here */
12090 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12091 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12092 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12094 namecopy, NULL, tbinfo->dobj.name,
12095 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12099 * Handle column ACLs, if any. Note: we pull these with a separate
12100 * query rather than trying to fetch them during getTableAttrs, so
12101 * that we won't miss ACLs on system columns.
12103 if (fout->remoteVersion >= 80400)
12105 PQExpBuffer query = createPQExpBuffer();
12109 appendPQExpBuffer(query,
12110 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12111 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12113 tbinfo->dobj.catId.oid);
12114 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12116 for (i = 0; i < PQntuples(res); i++)
12118 char *attname = PQgetvalue(res, i, 0);
12119 char *attacl = PQgetvalue(res, i, 1);
12123 attnamecopy = pg_strdup(fmtId(attname));
12124 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12125 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12126 /* Column's GRANT type is always TABLE */
12127 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12128 namecopy, attnamecopy, acltag,
12129 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12135 destroyPQExpBuffer(query);
12144 * write the declaration (not data) of one user-defined table or view
12147 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12149 PQExpBuffer query = createPQExpBuffer();
12150 PQExpBuffer q = createPQExpBuffer();
12151 PQExpBuffer delq = createPQExpBuffer();
12152 PQExpBuffer labelq = createPQExpBuffer();
12155 TableInfo **parents;
12156 int actual_atts; /* number of attrs in this CREATE statement */
12157 const char *reltypename;
12164 /* Make sure we are in proper schema */
12165 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12167 if (binary_upgrade)
12168 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12169 tbinfo->dobj.catId.oid);
12171 /* Is it a table or a view? */
12172 if (tbinfo->relkind == RELKIND_VIEW)
12176 reltypename = "VIEW";
12178 /* Fetch the view definition */
12179 if (fout->remoteVersion >= 70300)
12181 /* Beginning in 7.3, viewname is not unique; rely on OID */
12182 appendPQExpBuffer(query,
12183 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12184 tbinfo->dobj.catId.oid);
12188 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12189 "FROM pg_views WHERE viewname = ");
12190 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12191 appendPQExpBuffer(query, ";");
12194 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12196 if (PQntuples(res) != 1)
12198 if (PQntuples(res) < 1)
12199 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12200 tbinfo->dobj.name);
12202 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12203 tbinfo->dobj.name);
12206 viewdef = PQgetvalue(res, 0, 0);
12208 if (strlen(viewdef) == 0)
12209 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12210 tbinfo->dobj.name);
12213 * DROP must be fully qualified in case same name appears in
12216 appendPQExpBuffer(delq, "DROP VIEW %s.",
12217 fmtId(tbinfo->dobj.namespace->dobj.name));
12218 appendPQExpBuffer(delq, "%s;\n",
12219 fmtId(tbinfo->dobj.name));
12221 if (binary_upgrade)
12222 binary_upgrade_set_pg_class_oids(fout, q,
12223 tbinfo->dobj.catId.oid, false);
12225 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12226 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12227 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12228 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12230 appendPQExpBuffer(labelq, "VIEW %s",
12231 fmtId(tbinfo->dobj.name));
12237 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12242 reltypename = "FOREIGN TABLE";
12244 /* retrieve name of foreign server and generic options */
12245 appendPQExpBuffer(query,
12246 "SELECT fs.srvname, "
12247 "pg_catalog.array_to_string(ARRAY("
12248 "SELECT pg_catalog.quote_ident(option_name) || "
12249 "' ' || pg_catalog.quote_literal(option_value) "
12250 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12251 "ORDER BY option_name"
12252 "), E',\n ') AS ftoptions "
12253 "FROM pg_catalog.pg_foreign_table ft "
12254 "JOIN pg_catalog.pg_foreign_server fs "
12255 "ON (fs.oid = ft.ftserver) "
12256 "WHERE ft.ftrelid = '%u'",
12257 tbinfo->dobj.catId.oid);
12258 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12259 i_srvname = PQfnumber(res, "srvname");
12260 i_ftoptions = PQfnumber(res, "ftoptions");
12261 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12262 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12267 reltypename = "TABLE";
12271 numParents = tbinfo->numParents;
12272 parents = tbinfo->parents;
12275 * DROP must be fully qualified in case same name appears in
12278 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12279 fmtId(tbinfo->dobj.namespace->dobj.name));
12280 appendPQExpBuffer(delq, "%s;\n",
12281 fmtId(tbinfo->dobj.name));
12283 appendPQExpBuffer(labelq, "%s %s", reltypename,
12284 fmtId(tbinfo->dobj.name));
12286 if (binary_upgrade)
12287 binary_upgrade_set_pg_class_oids(fout, q,
12288 tbinfo->dobj.catId.oid, false);
12290 appendPQExpBuffer(q, "CREATE %s%s %s",
12291 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12294 fmtId(tbinfo->dobj.name));
12297 * Attach to type, if reloftype; except in case of a binary upgrade,
12298 * we dump the table normally and attach it to the type afterward.
12300 if (tbinfo->reloftype && !binary_upgrade)
12301 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12303 /* Dump the attributes */
12305 for (j = 0; j < tbinfo->numatts; j++)
12308 * Normally, dump if it's locally defined in this table, and not
12309 * dropped. But for binary upgrade, we'll dump all the columns,
12310 * and then fix up the dropped and nonlocal cases below.
12312 if (shouldPrintColumn(tbinfo, j))
12315 * Default value --- suppress if to be printed separately.
12317 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12318 !tbinfo->attrdefs[j]->separate);
12321 * Not Null constraint --- suppress if inherited, except in
12322 * binary-upgrade case where that won't work.
12324 bool has_notnull = (tbinfo->notnull[j] &&
12325 (!tbinfo->inhNotNull[j] ||
12328 /* Skip column if fully defined by reloftype */
12329 if (tbinfo->reloftype &&
12330 !has_default && !has_notnull && !binary_upgrade)
12333 /* Format properly if not first attr */
12334 if (actual_atts == 0)
12335 appendPQExpBuffer(q, " (");
12337 appendPQExpBuffer(q, ",");
12338 appendPQExpBuffer(q, "\n ");
12341 /* Attribute name */
12342 appendPQExpBuffer(q, "%s ",
12343 fmtId(tbinfo->attnames[j]));
12345 if (tbinfo->attisdropped[j])
12348 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12349 * so we will not have gotten a valid type name; insert
12350 * INTEGER as a stopgap. We'll clean things up later.
12352 appendPQExpBuffer(q, "INTEGER /* dummy */");
12353 /* Skip all the rest, too */
12357 /* Attribute type */
12358 if (tbinfo->reloftype && !binary_upgrade)
12360 appendPQExpBuffer(q, "WITH OPTIONS");
12362 else if (fout->remoteVersion >= 70100)
12364 appendPQExpBuffer(q, "%s",
12365 tbinfo->atttypnames[j]);
12369 /* If no format_type, fake it */
12370 appendPQExpBuffer(q, "%s",
12371 myFormatType(tbinfo->atttypnames[j],
12372 tbinfo->atttypmod[j]));
12375 /* Add collation if not default for the type */
12376 if (OidIsValid(tbinfo->attcollation[j]))
12380 coll = findCollationByOid(tbinfo->attcollation[j]);
12383 /* always schema-qualify, don't try to be smart */
12384 appendPQExpBuffer(q, " COLLATE %s.",
12385 fmtId(coll->dobj.namespace->dobj.name));
12386 appendPQExpBuffer(q, "%s",
12387 fmtId(coll->dobj.name));
12392 appendPQExpBuffer(q, " DEFAULT %s",
12393 tbinfo->attrdefs[j]->adef_expr);
12396 appendPQExpBuffer(q, " NOT NULL");
12401 * Add non-inherited CHECK constraints, if any.
12403 for (j = 0; j < tbinfo->ncheck; j++)
12405 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12407 if (constr->separate || !constr->conislocal)
12410 if (actual_atts == 0)
12411 appendPQExpBuffer(q, " (\n ");
12413 appendPQExpBuffer(q, ",\n ");
12415 appendPQExpBuffer(q, "CONSTRAINT %s ",
12416 fmtId(constr->dobj.name));
12417 appendPQExpBuffer(q, "%s", constr->condef);
12423 appendPQExpBuffer(q, "\n)");
12424 else if (!(tbinfo->reloftype && !binary_upgrade))
12427 * We must have a parenthesized attribute list, even though empty,
12428 * when not using the OF TYPE syntax.
12430 appendPQExpBuffer(q, " (\n)");
12433 if (numParents > 0 && !binary_upgrade)
12435 appendPQExpBuffer(q, "\nINHERITS (");
12436 for (k = 0; k < numParents; k++)
12438 TableInfo *parentRel = parents[k];
12441 appendPQExpBuffer(q, ", ");
12442 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12443 appendPQExpBuffer(q, "%s.",
12444 fmtId(parentRel->dobj.namespace->dobj.name));
12445 appendPQExpBuffer(q, "%s",
12446 fmtId(parentRel->dobj.name));
12448 appendPQExpBuffer(q, ")");
12451 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12452 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12454 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12455 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12457 bool addcomma = false;
12459 appendPQExpBuffer(q, "\nWITH (");
12460 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12463 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12465 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12467 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12468 tbinfo->toast_reloptions);
12470 appendPQExpBuffer(q, ")");
12473 /* Dump generic options if any */
12474 if (ftoptions && ftoptions[0])
12475 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12477 appendPQExpBuffer(q, ";\n");
12480 * To create binary-compatible heap files, we have to ensure the same
12481 * physical column order, including dropped columns, as in the
12482 * original. Therefore, we create dropped columns above and drop them
12483 * here, also updating their attlen/attalign values so that the
12484 * dropped column can be skipped properly. (We do not bother with
12485 * restoring the original attbyval setting.) Also, inheritance
12486 * relationships are set up by doing ALTER INHERIT rather than using
12487 * an INHERITS clause --- the latter would possibly mess up the column
12488 * order. That also means we have to take care about setting
12489 * attislocal correctly, plus fix up any inherited CHECK constraints.
12490 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12492 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12494 for (j = 0; j < tbinfo->numatts; j++)
12496 if (tbinfo->attisdropped[j])
12498 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12499 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12500 "SET attlen = %d, "
12501 "attalign = '%c', attbyval = false\n"
12502 "WHERE attname = ",
12504 tbinfo->attalign[j]);
12505 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12506 appendPQExpBuffer(q, "\n AND attrelid = ");
12507 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12508 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12510 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12511 fmtId(tbinfo->dobj.name));
12512 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12513 fmtId(tbinfo->attnames[j]));
12515 else if (!tbinfo->attislocal[j])
12517 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12518 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12519 "SET attislocal = false\n"
12520 "WHERE attname = ");
12521 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12522 appendPQExpBuffer(q, "\n AND attrelid = ");
12523 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12524 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12528 for (k = 0; k < tbinfo->ncheck; k++)
12530 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12532 if (constr->separate || constr->conislocal)
12535 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12536 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12537 fmtId(tbinfo->dobj.name));
12538 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12539 fmtId(constr->dobj.name));
12540 appendPQExpBuffer(q, "%s;\n", constr->condef);
12541 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12542 "SET conislocal = false\n"
12543 "WHERE contype = 'c' AND conname = ");
12544 appendStringLiteralAH(q, constr->dobj.name, fout);
12545 appendPQExpBuffer(q, "\n AND conrelid = ");
12546 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12547 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12550 if (numParents > 0)
12552 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12553 for (k = 0; k < numParents; k++)
12555 TableInfo *parentRel = parents[k];
12557 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12558 fmtId(tbinfo->dobj.name));
12559 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12560 appendPQExpBuffer(q, "%s.",
12561 fmtId(parentRel->dobj.namespace->dobj.name));
12562 appendPQExpBuffer(q, "%s;\n",
12563 fmtId(parentRel->dobj.name));
12567 if (tbinfo->reloftype)
12569 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12570 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12571 fmtId(tbinfo->dobj.name),
12572 tbinfo->reloftype);
12575 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12576 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12577 "SET relfrozenxid = '%u'\n"
12579 tbinfo->frozenxid);
12580 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12581 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12583 if (tbinfo->toast_oid)
12585 /* We preserve the toast oids, so we can use it during restore */
12586 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12587 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12588 "SET relfrozenxid = '%u'\n"
12589 "WHERE oid = '%u';\n",
12590 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12595 * Dump additional per-column properties that we can't handle in the
12596 * main CREATE TABLE command.
12598 for (j = 0; j < tbinfo->numatts; j++)
12600 /* None of this applies to dropped columns */
12601 if (tbinfo->attisdropped[j])
12605 * If we didn't dump the column definition explicitly above, and
12606 * it is NOT NULL and did not inherit that property from a parent,
12607 * we have to mark it separately.
12609 if (!shouldPrintColumn(tbinfo, j) &&
12610 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12612 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12613 fmtId(tbinfo->dobj.name));
12614 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12615 fmtId(tbinfo->attnames[j]));
12619 * Dump per-column statistics information. We only issue an ALTER
12620 * TABLE statement if the attstattarget entry for this column is
12621 * non-negative (i.e. it's not the default value)
12623 if (tbinfo->attstattarget[j] >= 0)
12625 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12626 fmtId(tbinfo->dobj.name));
12627 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12628 fmtId(tbinfo->attnames[j]));
12629 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12630 tbinfo->attstattarget[j]);
12634 * Dump per-column storage information. The statement is only
12635 * dumped if the storage has been changed from the type's default.
12637 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12639 switch (tbinfo->attstorage[j])
12645 storage = "EXTERNAL";
12651 storage = "EXTENDED";
12658 * Only dump the statement if it's a storage type we recognize
12660 if (storage != NULL)
12662 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12663 fmtId(tbinfo->dobj.name));
12664 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12665 fmtId(tbinfo->attnames[j]));
12666 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12672 * Dump per-column attributes.
12674 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12676 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12677 fmtId(tbinfo->dobj.name));
12678 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12679 fmtId(tbinfo->attnames[j]));
12680 appendPQExpBuffer(q, "SET (%s);\n",
12681 tbinfo->attoptions[j]);
12685 * Dump per-column fdw options.
12687 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12688 tbinfo->attfdwoptions[j] &&
12689 tbinfo->attfdwoptions[j][0] != '\0')
12691 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12692 fmtId(tbinfo->dobj.name));
12693 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12694 fmtId(tbinfo->attnames[j]));
12695 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12696 tbinfo->attfdwoptions[j]);
12701 if (binary_upgrade)
12702 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12704 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12706 tbinfo->dobj.namespace->dobj.name,
12707 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12709 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12710 reltypename, SECTION_PRE_DATA,
12711 q->data, delq->data, NULL,
12716 /* Dump Table Comments */
12717 dumpTableComment(fout, tbinfo, reltypename);
12719 /* Dump Table Security Labels */
12720 dumpTableSecLabel(fout, tbinfo, reltypename);
12722 /* Dump comments on inlined table constraints */
12723 for (j = 0; j < tbinfo->ncheck; j++)
12725 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12727 if (constr->separate || !constr->conislocal)
12730 dumpTableConstraintComment(fout, constr);
12733 destroyPQExpBuffer(query);
12734 destroyPQExpBuffer(q);
12735 destroyPQExpBuffer(delq);
12736 destroyPQExpBuffer(labelq);
12740 * dumpAttrDef --- dump an attribute's default-value declaration
12743 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12745 TableInfo *tbinfo = adinfo->adtable;
12746 int adnum = adinfo->adnum;
12750 /* Skip if table definition not to be dumped */
12751 if (!tbinfo->dobj.dump || dataOnly)
12754 /* Skip if not "separate"; it was dumped in the table's definition */
12755 if (!adinfo->separate)
12758 q = createPQExpBuffer();
12759 delq = createPQExpBuffer();
12761 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12762 fmtId(tbinfo->dobj.name));
12763 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12764 fmtId(tbinfo->attnames[adnum - 1]),
12765 adinfo->adef_expr);
12768 * DROP must be fully qualified in case same name appears in pg_catalog
12770 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12771 fmtId(tbinfo->dobj.namespace->dobj.name));
12772 appendPQExpBuffer(delq, "%s ",
12773 fmtId(tbinfo->dobj.name));
12774 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12775 fmtId(tbinfo->attnames[adnum - 1]));
12777 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12778 tbinfo->attnames[adnum - 1],
12779 tbinfo->dobj.namespace->dobj.name,
12782 false, "DEFAULT", SECTION_PRE_DATA,
12783 q->data, delq->data, NULL,
12787 destroyPQExpBuffer(q);
12788 destroyPQExpBuffer(delq);
12792 * getAttrName: extract the correct name for an attribute
12794 * The array tblInfo->attnames[] only provides names of user attributes;
12795 * if a system attribute number is supplied, we have to fake it.
12796 * We also do a little bit of bounds checking for safety's sake.
12798 static const char *
12799 getAttrName(int attrnum, TableInfo *tblInfo)
12801 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12802 return tblInfo->attnames[attrnum - 1];
12805 case SelfItemPointerAttributeNumber:
12807 case ObjectIdAttributeNumber:
12809 case MinTransactionIdAttributeNumber:
12811 case MinCommandIdAttributeNumber:
12813 case MaxTransactionIdAttributeNumber:
12815 case MaxCommandIdAttributeNumber:
12817 case TableOidAttributeNumber:
12820 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12821 attrnum, tblInfo->dobj.name);
12822 return NULL; /* keep compiler quiet */
12827 * write out to fout a user-defined index
12830 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12832 TableInfo *tbinfo = indxinfo->indextable;
12835 PQExpBuffer labelq;
12840 q = createPQExpBuffer();
12841 delq = createPQExpBuffer();
12842 labelq = createPQExpBuffer();
12844 appendPQExpBuffer(labelq, "INDEX %s",
12845 fmtId(indxinfo->dobj.name));
12848 * If there's an associated constraint, don't dump the index per se, but
12849 * do dump any comment for it. (This is safe because dependency ordering
12850 * will have ensured the constraint is emitted first.)
12852 if (indxinfo->indexconstraint == 0)
12854 if (binary_upgrade)
12855 binary_upgrade_set_pg_class_oids(fout, q,
12856 indxinfo->dobj.catId.oid, true);
12858 /* Plain secondary index */
12859 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12861 /* If the index is clustered, we need to record that. */
12862 if (indxinfo->indisclustered)
12864 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12865 fmtId(tbinfo->dobj.name));
12866 appendPQExpBuffer(q, " ON %s;\n",
12867 fmtId(indxinfo->dobj.name));
12871 * DROP must be fully qualified in case same name appears in
12874 appendPQExpBuffer(delq, "DROP INDEX %s.",
12875 fmtId(tbinfo->dobj.namespace->dobj.name));
12876 appendPQExpBuffer(delq, "%s;\n",
12877 fmtId(indxinfo->dobj.name));
12879 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12880 indxinfo->dobj.name,
12881 tbinfo->dobj.namespace->dobj.name,
12882 indxinfo->tablespace,
12883 tbinfo->rolname, false,
12884 "INDEX", SECTION_POST_DATA,
12885 q->data, delq->data, NULL,
12890 /* Dump Index Comments */
12891 dumpComment(fout, labelq->data,
12892 tbinfo->dobj.namespace->dobj.name,
12894 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12896 destroyPQExpBuffer(q);
12897 destroyPQExpBuffer(delq);
12898 destroyPQExpBuffer(labelq);
12903 * write out to fout a user-defined constraint
12906 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12908 TableInfo *tbinfo = coninfo->contable;
12912 /* Skip if not to be dumped */
12913 if (!coninfo->dobj.dump || dataOnly)
12916 q = createPQExpBuffer();
12917 delq = createPQExpBuffer();
12919 if (coninfo->contype == 'p' ||
12920 coninfo->contype == 'u' ||
12921 coninfo->contype == 'x')
12923 /* Index-related constraint */
12924 IndxInfo *indxinfo;
12927 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12929 if (indxinfo == NULL)
12930 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12931 coninfo->dobj.name);
12933 if (binary_upgrade)
12934 binary_upgrade_set_pg_class_oids(fout, q,
12935 indxinfo->dobj.catId.oid, true);
12937 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12938 fmtId(tbinfo->dobj.name));
12939 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12940 fmtId(coninfo->dobj.name));
12942 if (coninfo->condef)
12944 /* pg_get_constraintdef should have provided everything */
12945 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12949 appendPQExpBuffer(q, "%s (",
12950 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12951 for (k = 0; k < indxinfo->indnkeys; k++)
12953 int indkey = (int) indxinfo->indkeys[k];
12954 const char *attname;
12956 if (indkey == InvalidAttrNumber)
12958 attname = getAttrName(indkey, tbinfo);
12960 appendPQExpBuffer(q, "%s%s",
12961 (k == 0) ? "" : ", ",
12965 appendPQExpBuffer(q, ")");
12967 if (indxinfo->options && strlen(indxinfo->options) > 0)
12968 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12970 if (coninfo->condeferrable)
12972 appendPQExpBuffer(q, " DEFERRABLE");
12973 if (coninfo->condeferred)
12974 appendPQExpBuffer(q, " INITIALLY DEFERRED");
12977 appendPQExpBuffer(q, ";\n");
12980 /* If the index is clustered, we need to record that. */
12981 if (indxinfo->indisclustered)
12983 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12984 fmtId(tbinfo->dobj.name));
12985 appendPQExpBuffer(q, " ON %s;\n",
12986 fmtId(indxinfo->dobj.name));
12990 * DROP must be fully qualified in case same name appears in
12993 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12994 fmtId(tbinfo->dobj.namespace->dobj.name));
12995 appendPQExpBuffer(delq, "%s ",
12996 fmtId(tbinfo->dobj.name));
12997 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12998 fmtId(coninfo->dobj.name));
13000 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13001 coninfo->dobj.name,
13002 tbinfo->dobj.namespace->dobj.name,
13003 indxinfo->tablespace,
13004 tbinfo->rolname, false,
13005 "CONSTRAINT", SECTION_POST_DATA,
13006 q->data, delq->data, NULL,
13010 else if (coninfo->contype == 'f')
13013 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13014 * current table data is not processed
13016 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13017 fmtId(tbinfo->dobj.name));
13018 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13019 fmtId(coninfo->dobj.name),
13023 * DROP must be fully qualified in case same name appears in
13026 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13027 fmtId(tbinfo->dobj.namespace->dobj.name));
13028 appendPQExpBuffer(delq, "%s ",
13029 fmtId(tbinfo->dobj.name));
13030 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13031 fmtId(coninfo->dobj.name));
13033 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13034 coninfo->dobj.name,
13035 tbinfo->dobj.namespace->dobj.name,
13037 tbinfo->rolname, false,
13038 "FK CONSTRAINT", SECTION_POST_DATA,
13039 q->data, delq->data, NULL,
13043 else if (coninfo->contype == 'c' && tbinfo)
13045 /* CHECK constraint on a table */
13047 /* Ignore if not to be dumped separately */
13048 if (coninfo->separate)
13050 /* not ONLY since we want it to propagate to children */
13051 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13052 fmtId(tbinfo->dobj.name));
13053 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13054 fmtId(coninfo->dobj.name),
13058 * DROP must be fully qualified in case same name appears in
13061 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13062 fmtId(tbinfo->dobj.namespace->dobj.name));
13063 appendPQExpBuffer(delq, "%s ",
13064 fmtId(tbinfo->dobj.name));
13065 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13066 fmtId(coninfo->dobj.name));
13068 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13069 coninfo->dobj.name,
13070 tbinfo->dobj.namespace->dobj.name,
13072 tbinfo->rolname, false,
13073 "CHECK CONSTRAINT", SECTION_POST_DATA,
13074 q->data, delq->data, NULL,
13079 else if (coninfo->contype == 'c' && tbinfo == NULL)
13081 /* CHECK constraint on a domain */
13082 TypeInfo *tyinfo = coninfo->condomain;
13084 /* Ignore if not to be dumped separately */
13085 if (coninfo->separate)
13087 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13088 fmtId(tyinfo->dobj.name));
13089 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13090 fmtId(coninfo->dobj.name),
13094 * DROP must be fully qualified in case same name appears in
13097 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13098 fmtId(tyinfo->dobj.namespace->dobj.name));
13099 appendPQExpBuffer(delq, "%s ",
13100 fmtId(tyinfo->dobj.name));
13101 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13102 fmtId(coninfo->dobj.name));
13104 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13105 coninfo->dobj.name,
13106 tyinfo->dobj.namespace->dobj.name,
13108 tyinfo->rolname, false,
13109 "CHECK CONSTRAINT", SECTION_POST_DATA,
13110 q->data, delq->data, NULL,
13117 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13121 /* Dump Constraint Comments --- only works for table constraints */
13122 if (tbinfo && coninfo->separate)
13123 dumpTableConstraintComment(fout, coninfo);
13125 destroyPQExpBuffer(q);
13126 destroyPQExpBuffer(delq);
13130 * dumpTableConstraintComment --- dump a constraint's comment if any
13132 * This is split out because we need the function in two different places
13133 * depending on whether the constraint is dumped as part of CREATE TABLE
13134 * or as a separate ALTER command.
13137 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13139 TableInfo *tbinfo = coninfo->contable;
13140 PQExpBuffer labelq = createPQExpBuffer();
13142 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13143 fmtId(coninfo->dobj.name));
13144 appendPQExpBuffer(labelq, "ON %s",
13145 fmtId(tbinfo->dobj.name));
13146 dumpComment(fout, labelq->data,
13147 tbinfo->dobj.namespace->dobj.name,
13149 coninfo->dobj.catId, 0,
13150 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13152 destroyPQExpBuffer(labelq);
13156 * findLastBuiltInOid -
13157 * find the last built in oid
13159 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13160 * pg_database entry for the current database
13163 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13167 PQExpBuffer query = createPQExpBuffer();
13169 resetPQExpBuffer(query);
13170 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13171 appendStringLiteralAH(query, dbname, fout);
13173 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13174 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13176 destroyPQExpBuffer(query);
13181 * findLastBuiltInOid -
13182 * find the last built in oid
13184 * For 7.0, we do this by assuming that the last thing that initdb does is to
13185 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13186 * initdb won't be changing anymore, it'll do.
13189 findLastBuiltinOid_V70(Archive *fout)
13194 res = ExecuteSqlQueryForSingleRow(fout,
13195 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13196 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13202 dumpSequence(Archive *fout, TableInfo *tbinfo)
13215 PQExpBuffer query = createPQExpBuffer();
13216 PQExpBuffer delqry = createPQExpBuffer();
13217 PQExpBuffer labelq = createPQExpBuffer();
13219 /* Make sure we are in proper schema */
13220 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13222 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13223 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13225 if (fout->remoteVersion >= 80400)
13227 appendPQExpBuffer(query,
13228 "SELECT sequence_name, "
13229 "start_value, last_value, increment_by, "
13230 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13231 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13233 "END AS max_value, "
13234 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13235 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13237 "END AS min_value, "
13238 "cache_value, is_cycled, is_called from %s",
13240 fmtId(tbinfo->dobj.name));
13244 appendPQExpBuffer(query,
13245 "SELECT sequence_name, "
13246 "0 AS start_value, last_value, increment_by, "
13247 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13248 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13250 "END AS max_value, "
13251 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13252 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13254 "END AS min_value, "
13255 "cache_value, is_cycled, is_called from %s",
13257 fmtId(tbinfo->dobj.name));
13260 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13262 if (PQntuples(res) != 1)
13264 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13265 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13267 tbinfo->dobj.name, PQntuples(res));
13271 /* Disable this check: it fails if sequence has been renamed */
13273 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13275 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13276 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13281 startv = PQgetvalue(res, 0, 1);
13282 last = PQgetvalue(res, 0, 2);
13283 incby = PQgetvalue(res, 0, 3);
13284 if (!PQgetisnull(res, 0, 4))
13285 maxv = PQgetvalue(res, 0, 4);
13286 if (!PQgetisnull(res, 0, 5))
13287 minv = PQgetvalue(res, 0, 5);
13288 cache = PQgetvalue(res, 0, 6);
13289 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13290 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13293 * The logic we use for restoring sequences is as follows:
13295 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13296 * last_val for start if called is false, else use min_val for start_val).
13297 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13298 * BY command for it.
13300 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13305 * DROP must be fully qualified in case same name appears in
13308 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13309 fmtId(tbinfo->dobj.namespace->dobj.name));
13310 appendPQExpBuffer(delqry, "%s;\n",
13311 fmtId(tbinfo->dobj.name));
13313 resetPQExpBuffer(query);
13315 if (binary_upgrade)
13317 binary_upgrade_set_pg_class_oids(fout, query,
13318 tbinfo->dobj.catId.oid, false);
13319 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13320 tbinfo->dobj.catId.oid);
13323 appendPQExpBuffer(query,
13324 "CREATE SEQUENCE %s\n",
13325 fmtId(tbinfo->dobj.name));
13327 if (fout->remoteVersion >= 80400)
13328 appendPQExpBuffer(query, " START WITH %s\n", startv);
13332 * Versions before 8.4 did not remember the true start value. If
13333 * is_called is false then the sequence has never been incremented
13334 * so we can use last_val. Otherwise punt and let it default.
13337 appendPQExpBuffer(query, " START WITH %s\n", last);
13340 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13343 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13345 appendPQExpBuffer(query, " NO MINVALUE\n");
13348 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13350 appendPQExpBuffer(query, " NO MAXVALUE\n");
13352 appendPQExpBuffer(query,
13354 cache, (cycled ? "\n CYCLE" : ""));
13356 appendPQExpBuffer(query, ";\n");
13358 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13360 /* binary_upgrade: no need to clear TOAST table oid */
13362 if (binary_upgrade)
13363 binary_upgrade_extension_member(query, &tbinfo->dobj,
13366 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13368 tbinfo->dobj.namespace->dobj.name,
13371 false, "SEQUENCE", SECTION_PRE_DATA,
13372 query->data, delqry->data, NULL,
13377 * If the sequence is owned by a table column, emit the ALTER for it
13378 * as a separate TOC entry immediately following the sequence's own
13379 * entry. It's OK to do this rather than using full sorting logic,
13380 * because the dependency that tells us it's owned will have forced
13381 * the table to be created first. We can't just include the ALTER in
13382 * the TOC entry because it will fail if we haven't reassigned the
13383 * sequence owner to match the table's owner.
13385 * We need not schema-qualify the table reference because both
13386 * sequence and table must be in the same schema.
13388 if (OidIsValid(tbinfo->owning_tab))
13390 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13392 if (owning_tab && owning_tab->dobj.dump)
13394 resetPQExpBuffer(query);
13395 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13396 fmtId(tbinfo->dobj.name));
13397 appendPQExpBuffer(query, " OWNED BY %s",
13398 fmtId(owning_tab->dobj.name));
13399 appendPQExpBuffer(query, ".%s;\n",
13400 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13402 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13404 tbinfo->dobj.namespace->dobj.name,
13407 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13408 query->data, "", NULL,
13409 &(tbinfo->dobj.dumpId), 1,
13414 /* Dump Sequence Comments and Security Labels */
13415 dumpComment(fout, labelq->data,
13416 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13417 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13418 dumpSecLabel(fout, labelq->data,
13419 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13420 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13425 resetPQExpBuffer(query);
13426 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13427 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13428 appendPQExpBuffer(query, ", %s, %s);\n",
13429 last, (called ? "true" : "false"));
13431 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13433 tbinfo->dobj.namespace->dobj.name,
13436 false, "SEQUENCE SET", SECTION_PRE_DATA,
13437 query->data, "", NULL,
13438 &(tbinfo->dobj.dumpId), 1,
13444 destroyPQExpBuffer(query);
13445 destroyPQExpBuffer(delqry);
13446 destroyPQExpBuffer(labelq);
13450 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13452 TableInfo *tbinfo = tginfo->tgtable;
13454 PQExpBuffer delqry;
13455 PQExpBuffer labelq;
13464 query = createPQExpBuffer();
13465 delqry = createPQExpBuffer();
13466 labelq = createPQExpBuffer();
13469 * DROP must be fully qualified in case same name appears in pg_catalog
13471 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13472 fmtId(tginfo->dobj.name));
13473 appendPQExpBuffer(delqry, "ON %s.",
13474 fmtId(tbinfo->dobj.namespace->dobj.name));
13475 appendPQExpBuffer(delqry, "%s;\n",
13476 fmtId(tbinfo->dobj.name));
13480 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13484 if (tginfo->tgisconstraint)
13486 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13487 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13491 appendPQExpBuffer(query, "CREATE TRIGGER ");
13492 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13494 appendPQExpBuffer(query, "\n ");
13497 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13498 appendPQExpBuffer(query, "BEFORE");
13499 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13500 appendPQExpBuffer(query, "AFTER");
13501 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13502 appendPQExpBuffer(query, "INSTEAD OF");
13505 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13510 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13512 appendPQExpBuffer(query, " INSERT");
13515 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13518 appendPQExpBuffer(query, " OR DELETE");
13520 appendPQExpBuffer(query, " DELETE");
13523 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13526 appendPQExpBuffer(query, " OR UPDATE");
13528 appendPQExpBuffer(query, " UPDATE");
13531 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13534 appendPQExpBuffer(query, " OR TRUNCATE");
13536 appendPQExpBuffer(query, " TRUNCATE");
13539 appendPQExpBuffer(query, " ON %s\n",
13540 fmtId(tbinfo->dobj.name));
13542 if (tginfo->tgisconstraint)
13544 if (OidIsValid(tginfo->tgconstrrelid))
13546 /* If we are using regclass, name is already quoted */
13547 if (fout->remoteVersion >= 70300)
13548 appendPQExpBuffer(query, " FROM %s\n ",
13549 tginfo->tgconstrrelname);
13551 appendPQExpBuffer(query, " FROM %s\n ",
13552 fmtId(tginfo->tgconstrrelname));
13554 if (!tginfo->tgdeferrable)
13555 appendPQExpBuffer(query, "NOT ");
13556 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13557 if (tginfo->tginitdeferred)
13558 appendPQExpBuffer(query, "DEFERRED\n");
13560 appendPQExpBuffer(query, "IMMEDIATE\n");
13563 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13564 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13566 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13568 /* In 7.3, result of regproc is already quoted */
13569 if (fout->remoteVersion >= 70300)
13570 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13573 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13574 fmtId(tginfo->tgfname));
13576 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13579 for (findx = 0; findx < tginfo->tgnargs; findx++)
13581 /* find the embedded null that terminates this trigger argument */
13582 size_t tlen = strlen(p);
13584 if (p + tlen >= tgargs + lentgargs)
13586 /* hm, not found before end of bytea value... */
13587 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13590 tbinfo->dobj.name);
13595 appendPQExpBuffer(query, ", ");
13596 appendStringLiteralAH(query, p, fout);
13600 appendPQExpBuffer(query, ");\n");
13603 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13605 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13606 fmtId(tbinfo->dobj.name));
13607 switch (tginfo->tgenabled)
13611 appendPQExpBuffer(query, "DISABLE");
13614 appendPQExpBuffer(query, "ENABLE ALWAYS");
13617 appendPQExpBuffer(query, "ENABLE REPLICA");
13620 appendPQExpBuffer(query, "ENABLE");
13623 appendPQExpBuffer(query, " TRIGGER %s;\n",
13624 fmtId(tginfo->dobj.name));
13627 appendPQExpBuffer(labelq, "TRIGGER %s ",
13628 fmtId(tginfo->dobj.name));
13629 appendPQExpBuffer(labelq, "ON %s",
13630 fmtId(tbinfo->dobj.name));
13632 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13634 tbinfo->dobj.namespace->dobj.name,
13636 tbinfo->rolname, false,
13637 "TRIGGER", SECTION_POST_DATA,
13638 query->data, delqry->data, NULL,
13642 dumpComment(fout, labelq->data,
13643 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13644 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13646 destroyPQExpBuffer(query);
13647 destroyPQExpBuffer(delqry);
13648 destroyPQExpBuffer(labelq);
13656 dumpRule(Archive *fout, RuleInfo *rinfo)
13658 TableInfo *tbinfo = rinfo->ruletable;
13661 PQExpBuffer delcmd;
13662 PQExpBuffer labelq;
13665 /* Skip if not to be dumped */
13666 if (!rinfo->dobj.dump || dataOnly)
13670 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13671 * we do not want to dump it as a separate object.
13673 if (!rinfo->separate)
13677 * Make sure we are in proper schema.
13679 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13681 query = createPQExpBuffer();
13682 cmd = createPQExpBuffer();
13683 delcmd = createPQExpBuffer();
13684 labelq = createPQExpBuffer();
13686 if (fout->remoteVersion >= 70300)
13688 appendPQExpBuffer(query,
13689 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13690 rinfo->dobj.catId.oid);
13694 /* Rule name was unique before 7.3 ... */
13695 appendPQExpBuffer(query,
13696 "SELECT pg_get_ruledef('%s') AS definition",
13700 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13702 if (PQntuples(res) != 1)
13704 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13705 rinfo->dobj.name, tbinfo->dobj.name);
13709 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13712 * Add the command to alter the rules replication firing semantics if it
13713 * differs from the default.
13715 if (rinfo->ev_enabled != 'O')
13717 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13718 fmtId(tbinfo->dobj.namespace->dobj.name));
13719 appendPQExpBuffer(cmd, "%s ",
13720 fmtId(tbinfo->dobj.name));
13721 switch (rinfo->ev_enabled)
13724 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13725 fmtId(rinfo->dobj.name));
13728 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13729 fmtId(rinfo->dobj.name));
13732 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13733 fmtId(rinfo->dobj.name));
13739 * DROP must be fully qualified in case same name appears in pg_catalog
13741 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13742 fmtId(rinfo->dobj.name));
13743 appendPQExpBuffer(delcmd, "ON %s.",
13744 fmtId(tbinfo->dobj.namespace->dobj.name));
13745 appendPQExpBuffer(delcmd, "%s;\n",
13746 fmtId(tbinfo->dobj.name));
13748 appendPQExpBuffer(labelq, "RULE %s",
13749 fmtId(rinfo->dobj.name));
13750 appendPQExpBuffer(labelq, " ON %s",
13751 fmtId(tbinfo->dobj.name));
13753 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13755 tbinfo->dobj.namespace->dobj.name,
13757 tbinfo->rolname, false,
13758 "RULE", SECTION_POST_DATA,
13759 cmd->data, delcmd->data, NULL,
13763 /* Dump rule comments */
13764 dumpComment(fout, labelq->data,
13765 tbinfo->dobj.namespace->dobj.name,
13767 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13771 destroyPQExpBuffer(query);
13772 destroyPQExpBuffer(cmd);
13773 destroyPQExpBuffer(delcmd);
13774 destroyPQExpBuffer(labelq);
13778 * getExtensionMembership --- obtain extension membership data
13781 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13792 DumpableObject *dobj,
13795 /* Nothing to do if no extensions */
13796 if (numExtensions == 0)
13799 /* Make sure we are in proper schema */
13800 selectSourceSchema(fout, "pg_catalog");
13802 query = createPQExpBuffer();
13804 /* refclassid constraint is redundant but may speed the search */
13805 appendPQExpBuffer(query, "SELECT "
13806 "classid, objid, refclassid, refobjid "
13808 "WHERE refclassid = 'pg_extension'::regclass "
13809 "AND deptype = 'e' "
13812 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13814 ntups = PQntuples(res);
13816 i_classid = PQfnumber(res, "classid");
13817 i_objid = PQfnumber(res, "objid");
13818 i_refclassid = PQfnumber(res, "refclassid");
13819 i_refobjid = PQfnumber(res, "refobjid");
13822 * Since we ordered the SELECT by referenced ID, we can expect that
13823 * multiple entries for the same extension will appear together; this
13824 * saves on searches.
13828 for (i = 0; i < ntups; i++)
13831 CatalogId refobjId;
13833 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13834 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13835 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13836 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13838 if (refdobj == NULL ||
13839 refdobj->catId.tableoid != refobjId.tableoid ||
13840 refdobj->catId.oid != refobjId.oid)
13841 refdobj = findObjectByCatalogId(refobjId);
13844 * Failure to find objects mentioned in pg_depend is not unexpected,
13845 * since for example we don't collect info about TOAST tables.
13847 if (refdobj == NULL)
13850 fprintf(stderr, "no referenced object %u %u\n",
13851 refobjId.tableoid, refobjId.oid);
13856 dobj = findObjectByCatalogId(objId);
13861 fprintf(stderr, "no referencing object %u %u\n",
13862 objId.tableoid, objId.oid);
13867 /* Record dependency so that getDependencies needn't repeat this */
13868 addObjectDependency(dobj, refdobj->dumpId);
13870 dobj->ext_member = true;
13873 * Normally, mark the member object as not to be dumped. But in
13874 * binary upgrades, we still dump the members individually, since the
13875 * idea is to exactly reproduce the database contents rather than
13876 * replace the extension contents with something different.
13878 if (!binary_upgrade)
13879 dobj->dump = false;
13881 dobj->dump = refdobj->dump;
13887 * Now identify extension configuration tables and create TableDataInfo
13888 * objects for them, ensuring their data will be dumped even though the
13889 * tables themselves won't be.
13891 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13892 * user data in a configuration table is treated like schema data. This
13893 * seems appropriate since system data in a config table would get
13894 * reloaded by CREATE EXTENSION.
13896 for (i = 0; i < numExtensions; i++)
13898 ExtensionInfo *curext = &(extinfo[i]);
13899 char *extconfig = curext->extconfig;
13900 char *extcondition = curext->extcondition;
13901 char **extconfigarray = NULL;
13902 char **extconditionarray = NULL;
13904 int nconditionitems;
13906 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13907 if (!curext->dobj.dump)
13910 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13911 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13912 nconfigitems == nconditionitems)
13916 for (j = 0; j < nconfigitems; j++)
13918 TableInfo *configtbl;
13920 configtbl = findTableByOid(atooid(extconfigarray[j]));
13921 if (configtbl == NULL)
13925 * Note: config tables are dumped without OIDs regardless of
13926 * the --oids setting. This is because row filtering
13927 * conditions aren't compatible with dumping OIDs.
13929 makeTableDataInfo(configtbl, false);
13930 if (configtbl->dataObj != NULL)
13932 if (strlen(extconditionarray[j]) > 0)
13933 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13937 if (extconfigarray)
13938 free(extconfigarray);
13939 if (extconditionarray)
13940 free(extconditionarray);
13943 destroyPQExpBuffer(query);
13947 * getDependencies --- obtain available dependency data
13950 getDependencies(Archive *fout)
13961 DumpableObject *dobj,
13964 /* No dependency info available before 7.3 */
13965 if (fout->remoteVersion < 70300)
13969 write_msg(NULL, "reading dependency data\n");
13971 /* Make sure we are in proper schema */
13972 selectSourceSchema(fout, "pg_catalog");
13974 query = createPQExpBuffer();
13977 * PIN dependencies aren't interesting, and EXTENSION dependencies were
13978 * already processed by getExtensionMembership.
13980 appendPQExpBuffer(query, "SELECT "
13981 "classid, objid, refclassid, refobjid, deptype "
13983 "WHERE deptype != 'p' AND deptype != 'e' "
13986 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13988 ntups = PQntuples(res);
13990 i_classid = PQfnumber(res, "classid");
13991 i_objid = PQfnumber(res, "objid");
13992 i_refclassid = PQfnumber(res, "refclassid");
13993 i_refobjid = PQfnumber(res, "refobjid");
13994 i_deptype = PQfnumber(res, "deptype");
13997 * Since we ordered the SELECT by referencing ID, we can expect that
13998 * multiple entries for the same object will appear together; this saves
14003 for (i = 0; i < ntups; i++)
14006 CatalogId refobjId;
14009 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14010 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14011 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14012 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14013 deptype = *(PQgetvalue(res, i, i_deptype));
14015 if (dobj == NULL ||
14016 dobj->catId.tableoid != objId.tableoid ||
14017 dobj->catId.oid != objId.oid)
14018 dobj = findObjectByCatalogId(objId);
14021 * Failure to find objects mentioned in pg_depend is not unexpected,
14022 * since for example we don't collect info about TOAST tables.
14027 fprintf(stderr, "no referencing object %u %u\n",
14028 objId.tableoid, objId.oid);
14033 refdobj = findObjectByCatalogId(refobjId);
14035 if (refdobj == NULL)
14038 fprintf(stderr, "no referenced object %u %u\n",
14039 refobjId.tableoid, refobjId.oid);
14045 * Ordinarily, table rowtypes have implicit dependencies on their
14046 * tables. However, for a composite type the implicit dependency goes
14047 * the other way in pg_depend; which is the right thing for DROP but
14048 * it doesn't produce the dependency ordering we need. So in that one
14049 * case, we reverse the direction of the dependency.
14051 if (deptype == 'i' &&
14052 dobj->objType == DO_TABLE &&
14053 refdobj->objType == DO_TYPE)
14054 addObjectDependency(refdobj, dobj->dumpId);
14057 addObjectDependency(dobj, refdobj->dumpId);
14062 destroyPQExpBuffer(query);
14067 * createBoundaryObjects - create dummy DumpableObjects to represent
14068 * dump section boundaries.
14070 static DumpableObject *
14071 createBoundaryObjects(void)
14073 DumpableObject *dobjs;
14075 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14077 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14078 dobjs[0].catId = nilCatalogId;
14079 AssignDumpId(dobjs + 0);
14080 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14082 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14083 dobjs[1].catId = nilCatalogId;
14084 AssignDumpId(dobjs + 1);
14085 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14091 * addBoundaryDependencies - add dependencies as needed to enforce the dump
14092 * section boundaries.
14095 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14096 DumpableObject *boundaryObjs)
14098 DumpableObject *preDataBound = boundaryObjs + 0;
14099 DumpableObject *postDataBound = boundaryObjs + 1;
14102 for (i = 0; i < numObjs; i++)
14104 DumpableObject *dobj = dobjs[i];
14107 * The classification of object types here must match the SECTION_xxx
14108 * values assigned during subsequent ArchiveEntry calls!
14110 switch (dobj->objType)
14115 case DO_SHELL_TYPE:
14122 case DO_CONVERSION:
14127 case DO_DUMMY_TYPE:
14130 case DO_TSTEMPLATE:
14133 case DO_FOREIGN_SERVER:
14135 /* Pre-data objects: must come before the pre-data boundary */
14136 addObjectDependency(preDataBound, dobj->dumpId);
14138 case DO_TABLE_DATA:
14140 /* Data objects: must come between the boundaries */
14141 addObjectDependency(dobj, preDataBound->dumpId);
14142 addObjectDependency(postDataBound, dobj->dumpId);
14146 case DO_DEFAULT_ACL:
14147 /* Post-data objects: must come after the post-data boundary */
14148 addObjectDependency(dobj, postDataBound->dumpId);
14151 /* Rules are post-data, but only if dumped separately */
14152 if (((RuleInfo *) dobj)->separate)
14153 addObjectDependency(dobj, postDataBound->dumpId);
14155 case DO_CONSTRAINT:
14156 case DO_FK_CONSTRAINT:
14157 /* Constraints are post-data, but only if dumped separately */
14158 if (((ConstraintInfo *) dobj)->separate)
14159 addObjectDependency(dobj, postDataBound->dumpId);
14161 case DO_PRE_DATA_BOUNDARY:
14162 /* nothing to do */
14164 case DO_POST_DATA_BOUNDARY:
14165 /* must come after the pre-data boundary */
14166 addObjectDependency(dobj, preDataBound->dumpId);
14174 * BuildArchiveDependencies - create dependency data for archive TOC entries
14176 * The raw dependency data obtained by getDependencies() is not terribly
14177 * useful in an archive dump, because in many cases there are dependency
14178 * chains linking through objects that don't appear explicitly in the dump.
14179 * For example, a view will depend on its _RETURN rule while the _RETURN rule
14180 * will depend on other objects --- but the rule will not appear as a separate
14181 * object in the dump. We need to adjust the view's dependencies to include
14182 * whatever the rule depends on that is included in the dump.
14184 * Just to make things more complicated, there are also "special" dependencies
14185 * such as the dependency of a TABLE DATA item on its TABLE, which we must
14186 * not rearrange because pg_restore knows that TABLE DATA only depends on
14187 * its table. In these cases we must leave the dependencies strictly as-is
14188 * even if they refer to not-to-be-dumped objects.
14190 * To handle this, the convention is that "special" dependencies are created
14191 * during ArchiveEntry calls, and an archive TOC item that has any such
14192 * entries will not be touched here. Otherwise, we recursively search the
14193 * DumpableObject data structures to build the correct dependencies for each
14194 * archive TOC item.
14197 BuildArchiveDependencies(Archive *fout)
14199 ArchiveHandle *AH = (ArchiveHandle *) fout;
14202 /* Scan all TOC entries in the archive */
14203 for (te = AH->toc->next; te != AH->toc; te = te->next)
14205 DumpableObject *dobj;
14206 DumpId *dependencies;
14210 /* No need to process entries that will not be dumped */
14213 /* Ignore entries that already have "special" dependencies */
14216 /* Otherwise, look up the item's original DumpableObject, if any */
14217 dobj = findObjectByDumpId(te->dumpId);
14220 /* No work if it has no dependencies */
14221 if (dobj->nDeps <= 0)
14223 /* Set up work array */
14225 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14227 /* Recursively find all dumpable dependencies */
14228 findDumpableDependencies(AH, dobj,
14229 &dependencies, &nDeps, &allocDeps);
14230 /* And save 'em ... */
14233 dependencies = (DumpId *) pg_realloc(dependencies,
14234 nDeps * sizeof(DumpId));
14235 te->dependencies = dependencies;
14239 free(dependencies);
14243 /* Recursive search subroutine for BuildArchiveDependencies */
14245 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14246 DumpId **dependencies, int *nDeps, int *allocDeps)
14251 * Ignore section boundary objects: if we search through them, we'll
14252 * report lots of bogus dependencies.
14254 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14255 dobj->objType == DO_POST_DATA_BOUNDARY)
14258 for (i = 0; i < dobj->nDeps; i++)
14260 DumpId depid = dobj->dependencies[i];
14262 if (TocIDRequired(AH, depid) != 0)
14264 /* Object will be dumped, so just reference it as a dependency */
14265 if (*nDeps >= *allocDeps)
14268 *dependencies = (DumpId *) pg_realloc(*dependencies,
14269 *allocDeps * sizeof(DumpId));
14271 (*dependencies)[*nDeps] = depid;
14277 * Object will not be dumped, so recursively consider its deps.
14278 * We rely on the assumption that sortDumpableObjects already
14279 * broke any dependency loops, else we might recurse infinitely.
14281 DumpableObject *otherdobj = findObjectByDumpId(depid);
14284 findDumpableDependencies(AH, otherdobj,
14285 dependencies, nDeps, allocDeps);
14292 * selectSourceSchema - make the specified schema the active search path
14293 * in the source database.
14295 * NB: pg_catalog is explicitly searched after the specified schema;
14296 * so user names are only qualified if they are cross-schema references,
14297 * and system names are only qualified if they conflict with a user name
14298 * in the current schema.
14300 * Whenever the selected schema is not pg_catalog, be careful to qualify
14301 * references to system catalogs and types in our emitted commands!
14304 selectSourceSchema(Archive *fout, const char *schemaName)
14306 static char *curSchemaName = NULL;
14309 /* Not relevant if fetching from pre-7.3 DB */
14310 if (fout->remoteVersion < 70300)
14312 /* Ignore null schema names */
14313 if (schemaName == NULL || *schemaName == '\0')
14315 /* Optimize away repeated selection of same schema */
14316 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14319 query = createPQExpBuffer();
14320 appendPQExpBuffer(query, "SET search_path = %s",
14321 fmtId(schemaName));
14322 if (strcmp(schemaName, "pg_catalog") != 0)
14323 appendPQExpBuffer(query, ", pg_catalog");
14325 ExecuteSqlStatement(fout, query->data);
14327 destroyPQExpBuffer(query);
14329 free(curSchemaName);
14330 curSchemaName = pg_strdup(schemaName);
14334 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14337 * NB: in 7.3 and up the result may depend on the currently-selected
14338 * schema; this is why we don't try to cache the names.
14341 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14349 if ((opts & zeroAsOpaque) != 0)
14350 return pg_strdup(g_opaque_type);
14351 else if ((opts & zeroAsAny) != 0)
14352 return pg_strdup("'any'");
14353 else if ((opts & zeroAsStar) != 0)
14354 return pg_strdup("*");
14355 else if ((opts & zeroAsNone) != 0)
14356 return pg_strdup("NONE");
14359 query = createPQExpBuffer();
14360 if (fout->remoteVersion >= 70300)
14362 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14365 else if (fout->remoteVersion >= 70100)
14367 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14372 appendPQExpBuffer(query, "SELECT typname "
14374 "WHERE oid = '%u'::oid",
14378 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14380 if (fout->remoteVersion >= 70100)
14382 /* already quoted */
14383 result = pg_strdup(PQgetvalue(res, 0, 0));
14387 /* may need to quote it */
14388 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14392 destroyPQExpBuffer(query);
14398 * myFormatType --- local implementation of format_type for use with 7.0.
14401 myFormatType(const char *typname, int32 typmod)
14404 bool isarray = false;
14405 PQExpBuffer buf = createPQExpBuffer();
14407 /* Handle array types */
14408 if (typname[0] == '_')
14414 /* Show lengths on bpchar and varchar */
14415 if (strcmp(typname, "bpchar") == 0)
14417 int len = (typmod - VARHDRSZ);
14419 appendPQExpBuffer(buf, "character");
14421 appendPQExpBuffer(buf, "(%d)",
14422 typmod - VARHDRSZ);
14424 else if (strcmp(typname, "varchar") == 0)
14426 appendPQExpBuffer(buf, "character varying");
14428 appendPQExpBuffer(buf, "(%d)",
14429 typmod - VARHDRSZ);
14431 else if (strcmp(typname, "numeric") == 0)
14433 appendPQExpBuffer(buf, "numeric");
14440 tmp_typmod = typmod - VARHDRSZ;
14441 precision = (tmp_typmod >> 16) & 0xffff;
14442 scale = tmp_typmod & 0xffff;
14443 appendPQExpBuffer(buf, "(%d,%d)",
14449 * char is an internal single-byte data type; Let's make sure we force it
14450 * through with quotes. - thomas 1998-12-13
14452 else if (strcmp(typname, "char") == 0)
14453 appendPQExpBuffer(buf, "\"char\"");
14455 appendPQExpBuffer(buf, "%s", fmtId(typname));
14457 /* Append array qualifier for array types */
14459 appendPQExpBuffer(buf, "[]");
14461 result = pg_strdup(buf->data);
14462 destroyPQExpBuffer(buf);
14468 * fmtQualifiedId - convert a qualified name to the proper format for
14469 * the source database.
14471 * Like fmtId, use the result before calling again.
14473 static const char *
14474 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14476 static PQExpBuffer id_return = NULL;
14478 if (id_return) /* first time through? */
14479 resetPQExpBuffer(id_return);
14481 id_return = createPQExpBuffer();
14483 /* Suppress schema name if fetching from pre-7.3 DB */
14484 if (fout->remoteVersion >= 70300 && schema && *schema)
14486 appendPQExpBuffer(id_return, "%s.",
14489 appendPQExpBuffer(id_return, "%s",
14492 return id_return->data;
14496 * Return a column list clause for the given relation.
14498 * Special case: if there are no undropped columns in the relation, return
14499 * "", not an invalid "()" column list.
14501 static const char *
14502 fmtCopyColumnList(const TableInfo *ti)
14504 static PQExpBuffer q = NULL;
14505 int numatts = ti->numatts;
14506 char **attnames = ti->attnames;
14507 bool *attisdropped = ti->attisdropped;
14511 if (q) /* first time through? */
14512 resetPQExpBuffer(q);
14514 q = createPQExpBuffer();
14516 appendPQExpBuffer(q, "(");
14518 for (i = 0; i < numatts; i++)
14520 if (attisdropped[i])
14523 appendPQExpBuffer(q, ", ");
14524 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14529 return ""; /* no undropped columns */
14531 appendPQExpBuffer(q, ")");
14536 * Execute an SQL query and verify that we got exactly one row back.
14539 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14544 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14546 /* Expecting a single result only */
14547 ntups = PQntuples(res);
14549 exit_horribly(NULL,
14550 ngettext("query returned %d row instead of one: %s\n",
14551 "query returned %d rows instead of one: %s\n",