1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2017, 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 look at
18 * the currently committed state. So it is possible to get 'cache
19 * lookup failed' error if someone performs DDL changes while a dump is
20 * happening. The window for this sort of thing is from the acquisition
21 * of the transaction snapshot to getSchemaData() (when pg_dump acquires
22 * AccessShareLock on every table it intends to dump). It isn't very large,
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
32 #include "postgres_fe.h"
40 #include "getopt_long.h"
42 #include "access/attnum.h"
43 #include "access/sysattr.h"
44 #include "access/transam.h"
45 #include "catalog/pg_am.h"
46 #include "catalog/pg_attribute.h"
47 #include "catalog/pg_cast.h"
48 #include "catalog/pg_class.h"
49 #include "catalog/pg_default_acl.h"
50 #include "catalog/pg_largeobject.h"
51 #include "catalog/pg_largeobject_metadata.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_trigger.h"
54 #include "catalog/pg_type.h"
55 #include "libpq/libpq-fs.h"
57 #include "dumputils.h"
59 #include "pg_backup_db.h"
60 #include "pg_backup_utils.h"
62 #include "fe_utils/string_utils.h"
67 const char *descr; /* comment for an object */
68 Oid classoid; /* object class (catalog OID) */
69 Oid objoid; /* object OID */
70 int objsubid; /* subobject (table column #) */
75 const char *provider; /* label provider of this security label */
76 const char *label; /* security label for an object */
77 Oid classoid; /* object class (catalog OID) */
78 Oid objoid; /* object OID */
79 int objsubid; /* subobject (table column #) */
82 typedef enum OidOptions
91 bool g_verbose; /* User wants verbose narration of our
93 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
95 /* subquery used to convert user ID (eg, datdba) to user name */
96 static const char *username_subquery;
99 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
100 * FirstNormalObjectId - 1.
102 static Oid g_last_builtin_oid; /* value of the last builtin oid */
104 /* The specified names/patterns should to match at least one entity */
105 static int strict_names = 0;
108 * Object inclusion/exclusion lists
110 * The string lists record the patterns given by command-line switches,
111 * which we then convert to lists of OIDs of matching objects.
113 static SimpleStringList schema_include_patterns = {NULL, NULL};
114 static SimpleOidList schema_include_oids = {NULL, NULL};
115 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
116 static SimpleOidList schema_exclude_oids = {NULL, NULL};
118 static SimpleStringList table_include_patterns = {NULL, NULL};
119 static SimpleOidList table_include_oids = {NULL, NULL};
120 static SimpleStringList table_exclude_patterns = {NULL, NULL};
121 static SimpleOidList table_exclude_oids = {NULL, NULL};
122 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
123 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
126 char g_opaque_type[10]; /* name for the opaque type */
128 /* placeholders for the delimiters for comments */
129 char g_comment_start[10];
130 char g_comment_end[10];
132 static const CatalogId nilCatalogId = {0, 0};
134 static void help(const char *progname);
135 static void setup_connection(Archive *AH,
136 const char *dumpencoding, const char *dumpsnapshot,
138 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
139 static void expand_schema_name_patterns(Archive *fout,
140 SimpleStringList *patterns,
143 static void expand_table_name_patterns(Archive *fout,
144 SimpleStringList *patterns,
147 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
148 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
149 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
150 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
151 static void dumpComment(Archive *fout, const char *target,
152 const char *namespace, const char *owner,
153 CatalogId catalogId, int subid, DumpId dumpId);
154 static int findComments(Archive *fout, Oid classoid, Oid objoid,
155 CommentItem **items);
156 static int collectComments(Archive *fout, CommentItem **items);
157 static void dumpSecLabel(Archive *fout, const char *target,
158 const char *namespace, const char *owner,
159 CatalogId catalogId, int subid, DumpId dumpId);
160 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
161 SecLabelItem **items);
162 static int collectSecLabels(Archive *fout, SecLabelItem **items);
163 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
164 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
165 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
166 static void dumpType(Archive *fout, TypeInfo *tyinfo);
167 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
168 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
169 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
170 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
172 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
174 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
175 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
176 static void dumpFunc(Archive *fout, FuncInfo *finfo);
177 static void dumpCast(Archive *fout, CastInfo *cast);
178 static void dumpTransform(Archive *fout, TransformInfo *transform);
179 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
180 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
181 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
182 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
183 static void dumpCollation(Archive *fout, CollInfo *collinfo);
184 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
185 static void dumpRule(Archive *fout, RuleInfo *rinfo);
186 static void dumpAgg(Archive *fout, AggInfo *agginfo);
187 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
188 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
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 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
194 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
195 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
196 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
197 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
198 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
199 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
200 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
201 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
202 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
203 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
204 static void dumpUserMappings(Archive *fout,
205 const char *servername, const char *namespace,
206 const char *owner, CatalogId catalogId, DumpId dumpId);
207 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
209 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
210 const char *type, const char *name, const char *subname,
211 const char *tag, const char *nspname, const char *owner,
212 const char *acls, const char *racls,
213 const char *initacls, const char *initracls);
215 static void getDependencies(Archive *fout);
216 static void BuildArchiveDependencies(Archive *fout);
217 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
218 DumpId **dependencies, int *nDeps, int *allocDeps);
220 static DumpableObject *createBoundaryObjects(void);
221 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
222 DumpableObject *boundaryObjs);
224 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
225 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
226 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
227 static void buildMatViewRefreshDependencies(Archive *fout);
228 static void getTableDataFKConstraints(void);
229 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
231 static char *format_function_arguments_old(Archive *fout,
232 FuncInfo *finfo, int nallargs,
236 static char *format_function_signature(Archive *fout,
237 FuncInfo *finfo, bool honor_quotes);
238 static char *convertRegProcReference(Archive *fout,
240 static char *convertOperatorReference(Archive *fout, const char *opr);
241 static char *convertTSFunction(Archive *fout, Oid funcOid);
242 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
243 static void selectSourceSchema(Archive *fout, const char *schemaName);
244 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
245 static void getBlobs(Archive *fout);
246 static void dumpBlob(Archive *fout, BlobInfo *binfo);
247 static int dumpBlobs(Archive *fout, void *arg);
248 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
249 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
250 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
251 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
252 static void dumpDatabase(Archive *AH);
253 static void dumpEncoding(Archive *AH);
254 static void dumpStdStrings(Archive *AH);
255 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
256 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
257 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
258 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
259 static void binary_upgrade_set_pg_class_oids(Archive *fout,
260 PQExpBuffer upgrade_buffer,
261 Oid pg_class_oid, bool is_index);
262 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
263 DumpableObject *dobj,
264 const char *objlabel);
265 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
266 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
267 static bool nonemptyReloptions(const char *reloptions);
268 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
269 const char *prefix, Archive *fout);
270 static char *get_synchronized_snapshot(Archive *fout);
271 static void setupDumpWorker(Archive *AHX);
275 main(int argc, char **argv)
278 const char *filename = NULL;
279 const char *format = "p";
282 DumpableObject **dobjs;
284 DumpableObject *boundaryObjs;
287 RestoreOptions *ropt;
288 Archive *fout; /* the script file */
289 const char *dumpencoding = NULL;
290 const char *dumpsnapshot = NULL;
291 char *use_role = NULL;
293 trivalue prompt_password = TRI_DEFAULT;
294 int compressLevel = -1;
296 ArchiveFormat archiveFormat = archUnknown;
297 ArchiveMode archiveMode;
299 static DumpOptions dopt;
301 static struct option long_options[] = {
302 {"data-only", no_argument, NULL, 'a'},
303 {"blobs", no_argument, NULL, 'b'},
304 {"no-blobs", no_argument, NULL, 'B'},
305 {"clean", no_argument, NULL, 'c'},
306 {"create", no_argument, NULL, 'C'},
307 {"dbname", required_argument, NULL, 'd'},
308 {"file", required_argument, NULL, 'f'},
309 {"format", required_argument, NULL, 'F'},
310 {"host", required_argument, NULL, 'h'},
311 {"jobs", 1, NULL, 'j'},
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, &dopt.column_inserts, 1},
337 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
338 {"column-inserts", no_argument, &dopt.column_inserts, 1},
339 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
340 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
341 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
342 {"exclude-table-data", required_argument, NULL, 4},
343 {"if-exists", no_argument, &dopt.if_exists, 1},
344 {"inserts", no_argument, &dopt.dump_inserts, 1},
345 {"lock-wait-timeout", required_argument, NULL, 2},
346 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
347 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
348 {"role", required_argument, NULL, 3},
349 {"section", required_argument, NULL, 5},
350 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
351 {"snapshot", required_argument, NULL, 6},
352 {"strict-names", no_argument, &strict_names, 1},
353 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
354 {"no-publications", no_argument, &dopt.no_publications, 1},
355 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
356 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
357 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
358 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
359 {"no-sync", no_argument, NULL, 7},
364 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
367 * Initialize what we need for parallel execution, especially for thread
368 * support on Windows.
370 init_parallel_dump_utils();
374 strcpy(g_comment_start, "-- ");
375 g_comment_end[0] = '\0';
376 strcpy(g_opaque_type, "opaque");
378 progname = get_progname(argv[0]);
382 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
387 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
389 puts("pg_dump (PostgreSQL) " PG_VERSION);
394 InitDumpOptions(&dopt);
396 while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
397 long_options, &optindex)) != -1)
401 case 'a': /* Dump data only */
402 dopt.dataOnly = true;
405 case 'b': /* Dump blobs */
406 dopt.outputBlobs = true;
409 case 'B': /* Don't dump blobs */
410 dopt.dontOutputBlobs = true;
413 case 'c': /* clean (i.e., drop) schema prior to create */
414 dopt.outputClean = 1;
417 case 'C': /* Create DB */
418 dopt.outputCreateDB = 1;
421 case 'd': /* database name */
422 dopt.dbname = pg_strdup(optarg);
425 case 'E': /* Dump encoding */
426 dumpencoding = pg_strdup(optarg);
430 filename = pg_strdup(optarg);
434 format = pg_strdup(optarg);
437 case 'h': /* server host */
438 dopt.pghost = pg_strdup(optarg);
441 case 'j': /* number of dump jobs */
442 numWorkers = atoi(optarg);
445 case 'n': /* include schema(s) */
446 simple_string_list_append(&schema_include_patterns, optarg);
447 dopt.include_everything = false;
450 case 'N': /* exclude schema(s) */
451 simple_string_list_append(&schema_exclude_patterns, optarg);
454 case 'o': /* Dump oids */
458 case 'O': /* Don't reconnect to match owner */
459 dopt.outputNoOwner = 1;
462 case 'p': /* server port */
463 dopt.pgport = pg_strdup(optarg);
467 /* no-op, still accepted for backwards compatibility */
470 case 's': /* dump schema only */
471 dopt.schemaOnly = true;
474 case 'S': /* Username for superuser in plain text output */
475 dopt.outputSuperuser = pg_strdup(optarg);
478 case 't': /* include table(s) */
479 simple_string_list_append(&table_include_patterns, optarg);
480 dopt.include_everything = false;
483 case 'T': /* exclude table(s) */
484 simple_string_list_append(&table_exclude_patterns, optarg);
488 dopt.username = pg_strdup(optarg);
491 case 'v': /* verbose */
496 prompt_password = TRI_NO;
500 prompt_password = TRI_YES;
503 case 'x': /* skip ACL dump */
504 dopt.aclsSkip = true;
507 case 'Z': /* Compression Level */
508 compressLevel = atoi(optarg);
509 if (compressLevel < 0 || compressLevel > 9)
511 write_msg(NULL, "compression level must be in range 0..9\n");
517 /* This covers the long options. */
520 case 2: /* lock-wait-timeout */
521 dopt.lockWaitTimeout = pg_strdup(optarg);
524 case 3: /* SET ROLE */
525 use_role = pg_strdup(optarg);
528 case 4: /* exclude table(s) data */
529 simple_string_list_append(&tabledata_exclude_patterns, optarg);
532 case 5: /* section */
533 set_dump_section(optarg, &dopt.dumpSections);
536 case 6: /* snapshot */
537 dumpsnapshot = pg_strdup(optarg);
540 case 7: /* no-sync */
545 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
551 * Non-option argument specifies database name as long as it wasn't
552 * already specified with -d / --dbname
554 if (optind < argc && dopt.dbname == NULL)
555 dopt.dbname = argv[optind++];
557 /* Complain if any arguments remain */
560 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
561 progname, argv[optind]);
562 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
567 /* --column-inserts implies --inserts */
568 if (dopt.column_inserts)
569 dopt.dump_inserts = 1;
572 * Binary upgrade mode implies dumping sequence data even in schema-only
573 * mode. This is not exposed as a separate option, but kept separate
574 * internally for clarity.
576 if (dopt.binary_upgrade)
577 dopt.sequence_data = 1;
579 if (dopt.dataOnly && dopt.schemaOnly)
581 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
585 if (dopt.dataOnly && dopt.outputClean)
587 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
591 if (dopt.dump_inserts && dopt.oids)
593 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
594 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
598 if (dopt.if_exists && !dopt.outputClean)
599 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
601 /* Identify archive format to emit */
602 archiveFormat = parseArchiveFormat(format, &archiveMode);
604 /* archiveFormat specific setup */
605 if (archiveFormat == archNull)
608 /* Custom and directory formats are compressed by default, others not */
609 if (compressLevel == -1)
612 if (archiveFormat == archCustom || archiveFormat == archDirectory)
613 compressLevel = Z_DEFAULT_COMPRESSION;
620 if (compressLevel != 0)
621 write_msg(NULL, "WARNING: requested compression not available in this "
622 "installation -- archive will be uncompressed\n");
627 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
628 * parallel jobs because that's the maximum limit for the
629 * WaitForMultipleObjects() call.
633 || numWorkers > MAXIMUM_WAIT_OBJECTS
636 exit_horribly(NULL, "invalid number of parallel jobs\n");
638 /* Parallel backup only in the directory archive format so far */
639 if (archiveFormat != archDirectory && numWorkers > 1)
640 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
642 /* Open the output file */
643 fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
644 archiveMode, setupDumpWorker);
646 /* Make dump options accessible right away */
647 SetArchiveOptions(fout, &dopt, NULL);
649 /* Register the cleanup hook */
650 on_exit_close_archive(fout);
652 /* Let the archiver know how noisy to be */
653 fout->verbose = g_verbose;
656 * We allow the server to be back to 8.0, and up to any minor release of
657 * our own major version. (See also version check in pg_dumpall.c.)
659 fout->minRemoteVersion = 80000;
660 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
662 fout->numWorkers = numWorkers;
665 * Open the database using the Archiver, so it knows about it. Errors mean
668 ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
669 setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
672 * Disable security label support if server version < v9.1.x (prevents
673 * access to nonexistent pg_seclabel catalog)
675 if (fout->remoteVersion < 90100)
676 dopt.no_security_labels = 1;
679 * On hot standby slaves, never try to dump unlogged table data, since it
680 * will just throw an error.
683 dopt.no_unlogged_table_data = true;
685 /* Select the appropriate subquery to convert user IDs to names */
686 if (fout->remoteVersion >= 80100)
687 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
689 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
691 /* check the version for the synchronized snapshots feature */
692 if (numWorkers > 1 && fout->remoteVersion < 90200
693 && !dopt.no_synchronized_snapshots)
695 "Synchronized snapshots are not supported by this server version.\n"
696 "Run with --no-synchronized-snapshots instead if you do not need\n"
697 "synchronized snapshots.\n");
699 /* check the version when a snapshot is explicitly specified by user */
700 if (dumpsnapshot && fout->remoteVersion < 90200)
702 "Exported snapshots are not supported by this server version.\n");
705 * Find the last built-in OID, if needed (prior to 8.1)
707 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
709 if (fout->remoteVersion < 80100)
710 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
711 PQdb(GetConnection(fout)));
713 g_last_builtin_oid = FirstNormalObjectId - 1;
716 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
718 /* Expand schema selection patterns into OID lists */
719 if (schema_include_patterns.head != NULL)
721 expand_schema_name_patterns(fout, &schema_include_patterns,
722 &schema_include_oids,
724 if (schema_include_oids.head == NULL)
725 exit_horribly(NULL, "no matching schemas were found\n");
727 expand_schema_name_patterns(fout, &schema_exclude_patterns,
728 &schema_exclude_oids,
730 /* non-matching exclusion patterns aren't an error */
732 /* Expand table selection patterns into OID lists */
733 if (table_include_patterns.head != NULL)
735 expand_table_name_patterns(fout, &table_include_patterns,
738 if (table_include_oids.head == NULL)
739 exit_horribly(NULL, "no matching tables were found\n");
741 expand_table_name_patterns(fout, &table_exclude_patterns,
745 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
746 &tabledata_exclude_oids,
749 /* non-matching exclusion patterns aren't an error */
752 * Dumping blobs is the default for dumps where an inclusion switch is not
753 * used (an "include everything" dump). -B can be used to exclude blobs
754 * from those dumps. -b can be used to include blobs even when an
755 * inclusion switch is used.
757 * -s means "schema only" and blobs are data, not schema, so we never
758 * include blobs when -s is used.
760 if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
761 dopt.outputBlobs = true;
764 * Now scan the database and create DumpableObject structs for all the
765 * objects we intend to dump.
767 tblinfo = getSchemaData(fout, &numTables);
769 if (fout->remoteVersion < 80400)
770 guessConstraintInheritance(tblinfo, numTables);
772 if (!dopt.schemaOnly)
774 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
775 buildMatViewRefreshDependencies(fout);
777 getTableDataFKConstraints();
780 if (dopt.schemaOnly && dopt.sequence_data)
781 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
784 * In binary-upgrade mode, we do not have to worry about the actual blob
785 * data or the associated metadata that resides in the pg_largeobject and
786 * pg_largeobject_metadata tables, respectivly.
788 * However, we do need to collect blob information as there may be
789 * comments or other information on blobs that we do need to dump out.
791 if (dopt.outputBlobs || dopt.binary_upgrade)
795 * Collect dependency data to assist in ordering the objects.
797 getDependencies(fout);
799 /* Lastly, create dummy objects to represent the section boundaries */
800 boundaryObjs = createBoundaryObjects();
802 /* Get pointers to all the known DumpableObjects */
803 getDumpableObjects(&dobjs, &numObjs);
806 * Add dummy dependencies to enforce the dump section ordering.
808 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
811 * Sort the objects into a safe dump order (no forward references).
813 * We rely on dependency information to help us determine a safe order, so
814 * the initial sort is mostly for cosmetic purposes: we sort by name to
815 * ensure that logically identical schemas will dump identically.
817 sortDumpableObjectsByTypeName(dobjs, numObjs);
819 /* If we do a parallel dump, we want the largest tables to go first */
820 if (archiveFormat == archDirectory && numWorkers > 1)
821 sortDataAndIndexObjectsBySize(dobjs, numObjs);
823 sortDumpableObjects(dobjs, numObjs,
824 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
827 * Create archive TOC entries for all the objects to be dumped, in a safe
831 /* First the special ENCODING and STDSTRINGS entries. */
833 dumpStdStrings(fout);
835 /* The database item is always next, unless we don't want it at all */
836 if (dopt.include_everything && !dopt.dataOnly)
839 /* Now the rearrangeable objects. */
840 for (i = 0; i < numObjs; i++)
841 dumpDumpableObject(fout, dobjs[i]);
844 * Set up options info to ensure we dump what we want.
846 ropt = NewRestoreOptions();
847 ropt->filename = filename;
849 /* if you change this list, see dumpOptionsFromRestoreOptions */
850 ropt->dropSchema = dopt.outputClean;
851 ropt->dataOnly = dopt.dataOnly;
852 ropt->schemaOnly = dopt.schemaOnly;
853 ropt->if_exists = dopt.if_exists;
854 ropt->column_inserts = dopt.column_inserts;
855 ropt->dumpSections = dopt.dumpSections;
856 ropt->aclsSkip = dopt.aclsSkip;
857 ropt->superuser = dopt.outputSuperuser;
858 ropt->createDB = dopt.outputCreateDB;
859 ropt->noOwner = dopt.outputNoOwner;
860 ropt->noTablespace = dopt.outputNoTablespaces;
861 ropt->disable_triggers = dopt.disable_triggers;
862 ropt->use_setsessauth = dopt.use_setsessauth;
863 ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
864 ropt->dump_inserts = dopt.dump_inserts;
865 ropt->no_publications = dopt.no_publications;
866 ropt->no_security_labels = dopt.no_security_labels;
867 ropt->no_subscriptions = dopt.no_subscriptions;
868 ropt->lockWaitTimeout = dopt.lockWaitTimeout;
869 ropt->include_everything = dopt.include_everything;
870 ropt->enable_row_security = dopt.enable_row_security;
871 ropt->sequence_data = dopt.sequence_data;
872 ropt->binary_upgrade = dopt.binary_upgrade;
874 if (compressLevel == -1)
875 ropt->compression = 0;
877 ropt->compression = compressLevel;
879 ropt->suppressDumpWarnings = true; /* We've already shown them */
881 SetArchiveOptions(fout, &dopt, ropt);
883 /* Mark which entries should be output */
884 ProcessArchiveRestoreOptions(fout);
887 * The archive's TOC entries are now marked as to which ones will actually
888 * be output, so we can set up their dependency lists properly. This isn't
889 * necessary for plain-text output, though.
892 BuildArchiveDependencies(fout);
895 * And finally we can do the actual output.
897 * Note: for non-plain-text output formats, the output file is written
898 * inside CloseArchive(). This is, um, bizarre; but not worth changing
902 RestoreArchive(fout);
911 help(const char *progname)
913 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
914 printf(_("Usage:\n"));
915 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
917 printf(_("\nGeneral options:\n"));
918 printf(_(" -f, --file=FILENAME output file or directory name\n"));
919 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
920 " plain text (default))\n"));
921 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
922 printf(_(" -v, --verbose verbose mode\n"));
923 printf(_(" -V, --version output version information, then exit\n"));
924 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
925 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
926 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
927 printf(_(" -?, --help show this help, then exit\n"));
929 printf(_("\nOptions controlling the output content:\n"));
930 printf(_(" -a, --data-only dump only the data, not the schema\n"));
931 printf(_(" -b, --blobs include large objects in dump\n"));
932 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
933 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
934 printf(_(" -C, --create include commands to create database in dump\n"));
935 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
936 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
937 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
938 printf(_(" -o, --oids include OIDs in dump\n"));
939 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
940 " plain-text format\n"));
941 printf(_(" -s, --schema-only dump only the schema, no data\n"));
942 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
943 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
944 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
945 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
946 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
947 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
948 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
949 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
950 printf(_(" --enable-row-security enable row security (dump only content user has\n"
952 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
953 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
954 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
955 printf(_(" --no-publications do not dump publications\n"));
956 printf(_(" --no-security-labels do not dump security label assignments\n"));
957 printf(_(" --no-subscriptions do not dump subscriptions\n"));
958 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
959 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
960 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
961 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
962 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
963 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
964 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
965 printf(_(" --strict-names require table and/or schema include patterns to\n"
966 " match at least one entity each\n"));
967 printf(_(" --use-set-session-authorization\n"
968 " use SET SESSION AUTHORIZATION commands instead of\n"
969 " ALTER OWNER commands to set ownership\n"));
971 printf(_("\nConnection options:\n"));
972 printf(_(" -d, --dbname=DBNAME database to dump\n"));
973 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
974 printf(_(" -p, --port=PORT database server port number\n"));
975 printf(_(" -U, --username=NAME connect as specified database user\n"));
976 printf(_(" -w, --no-password never prompt for password\n"));
977 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
978 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
980 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
981 "variable value is used.\n\n"));
982 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
986 setup_connection(Archive *AH, const char *dumpencoding,
987 const char *dumpsnapshot, char *use_role)
989 DumpOptions *dopt = AH->dopt;
990 PGconn *conn = GetConnection(AH);
991 const char *std_strings;
994 * Set the client encoding if requested.
998 if (PQsetClientEncoding(conn, dumpencoding) < 0)
999 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1004 * Get the active encoding and the standard_conforming_strings setting, so
1005 * we know how to escape strings.
1007 AH->encoding = PQclientEncoding(conn);
1009 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1010 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1013 * Set the role if requested. In a parallel dump worker, we'll be passed
1014 * use_role == NULL, but AH->use_role is already set (if user specified it
1015 * originally) and we should use that.
1017 if (!use_role && AH->use_role)
1018 use_role = AH->use_role;
1020 /* Set the role if requested */
1021 if (use_role && AH->remoteVersion >= 80100)
1023 PQExpBuffer query = createPQExpBuffer();
1025 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1026 ExecuteSqlStatement(AH, query->data);
1027 destroyPQExpBuffer(query);
1029 /* save it for possible later use by parallel workers */
1031 AH->use_role = pg_strdup(use_role);
1034 /* Set the datestyle to ISO to ensure the dump's portability */
1035 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1037 /* Likewise, avoid using sql_standard intervalstyle */
1038 if (AH->remoteVersion >= 80400)
1039 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1042 * Set extra_float_digits so that we can dump float data exactly (given
1043 * correctly implemented float I/O code, anyway)
1045 if (AH->remoteVersion >= 90000)
1046 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1048 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1051 * If synchronized scanning is supported, disable it, to prevent
1052 * unpredictable changes in row ordering across a dump and reload.
1054 if (AH->remoteVersion >= 80300)
1055 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1058 * Disable timeouts if supported.
1060 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1061 if (AH->remoteVersion >= 90300)
1062 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1063 if (AH->remoteVersion >= 90600)
1064 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1067 * Quote all identifiers, if requested.
1069 if (quote_all_identifiers && AH->remoteVersion >= 90100)
1070 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1073 * Adjust row-security mode, if supported.
1075 if (AH->remoteVersion >= 90500)
1077 if (dopt->enable_row_security)
1078 ExecuteSqlStatement(AH, "SET row_security = on");
1080 ExecuteSqlStatement(AH, "SET row_security = off");
1084 * Start transaction-snapshot mode transaction to dump consistent data.
1086 ExecuteSqlStatement(AH, "BEGIN");
1087 if (AH->remoteVersion >= 90100)
1090 * To support the combination of serializable_deferrable with the jobs
1091 * option we use REPEATABLE READ for the worker connections that are
1092 * passed a snapshot. As long as the snapshot is acquired in a
1093 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1094 * REPEATABLE READ transaction provides the appropriate integrity
1095 * guarantees. This is a kluge, but safe for back-patching.
1097 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1098 ExecuteSqlStatement(AH,
1099 "SET TRANSACTION ISOLATION LEVEL "
1100 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1102 ExecuteSqlStatement(AH,
1103 "SET TRANSACTION ISOLATION LEVEL "
1104 "REPEATABLE READ, READ ONLY");
1108 ExecuteSqlStatement(AH,
1109 "SET TRANSACTION ISOLATION LEVEL "
1110 "SERIALIZABLE, READ ONLY");
1114 * If user specified a snapshot to use, select that. In a parallel dump
1115 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1116 * is already set (if the server can handle it) and we should use that.
1119 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1121 if (AH->sync_snapshot_id)
1123 PQExpBuffer query = createPQExpBuffer();
1125 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1126 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1127 ExecuteSqlStatement(AH, query->data);
1128 destroyPQExpBuffer(query);
1130 else if (AH->numWorkers > 1 &&
1131 AH->remoteVersion >= 90200 &&
1132 !dopt->no_synchronized_snapshots)
1136 "Synchronized snapshots are not supported on standby servers.\n"
1137 "Run with --no-synchronized-snapshots instead if you do not need\n"
1138 "synchronized snapshots.\n");
1141 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1145 /* Set up connection for a parallel worker process */
1147 setupDumpWorker(Archive *AH)
1150 * We want to re-select all the same values the master connection is
1151 * using. We'll have inherited directly-usable values in
1152 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1153 * inherited encoding value back to a string to pass to setup_connection.
1155 setup_connection(AH,
1156 pg_encoding_to_char(AH->encoding),
1162 get_synchronized_snapshot(Archive *fout)
1164 char *query = "SELECT pg_catalog.pg_export_snapshot()";
1168 res = ExecuteSqlQueryForSingleRow(fout, query);
1169 result = pg_strdup(PQgetvalue(res, 0, 0));
1175 static ArchiveFormat
1176 parseArchiveFormat(const char *format, ArchiveMode *mode)
1178 ArchiveFormat archiveFormat;
1180 *mode = archModeWrite;
1182 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1184 /* This is used by pg_dumpall, and is not documented */
1185 archiveFormat = archNull;
1186 *mode = archModeAppend;
1188 else if (pg_strcasecmp(format, "c") == 0)
1189 archiveFormat = archCustom;
1190 else if (pg_strcasecmp(format, "custom") == 0)
1191 archiveFormat = archCustom;
1192 else if (pg_strcasecmp(format, "d") == 0)
1193 archiveFormat = archDirectory;
1194 else if (pg_strcasecmp(format, "directory") == 0)
1195 archiveFormat = archDirectory;
1196 else if (pg_strcasecmp(format, "p") == 0)
1197 archiveFormat = archNull;
1198 else if (pg_strcasecmp(format, "plain") == 0)
1199 archiveFormat = archNull;
1200 else if (pg_strcasecmp(format, "t") == 0)
1201 archiveFormat = archTar;
1202 else if (pg_strcasecmp(format, "tar") == 0)
1203 archiveFormat = archTar;
1205 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1206 return archiveFormat;
1210 * Find the OIDs of all schemas matching the given list of patterns,
1211 * and append them to the given OID list.
1214 expand_schema_name_patterns(Archive *fout,
1215 SimpleStringList *patterns,
1216 SimpleOidList *oids,
1221 SimpleStringListCell *cell;
1224 if (patterns->head == NULL)
1225 return; /* nothing to do */
1227 query = createPQExpBuffer();
1230 * The loop below runs multiple SELECTs might sometimes result in
1231 * duplicate entries in the OID list, but we don't care.
1234 for (cell = patterns->head; cell; cell = cell->next)
1236 appendPQExpBuffer(query,
1237 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1238 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1239 false, NULL, "n.nspname", NULL, NULL);
1241 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1242 if (strict_names && PQntuples(res) == 0)
1243 exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1245 for (i = 0; i < PQntuples(res); i++)
1247 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1251 resetPQExpBuffer(query);
1254 destroyPQExpBuffer(query);
1258 * Find the OIDs of all tables matching the given list of patterns,
1259 * and append them to the given OID list.
1262 expand_table_name_patterns(Archive *fout,
1263 SimpleStringList *patterns, SimpleOidList *oids,
1268 SimpleStringListCell *cell;
1271 if (patterns->head == NULL)
1272 return; /* nothing to do */
1274 query = createPQExpBuffer();
1277 * this might sometimes result in duplicate entries in the OID list, but
1281 for (cell = patterns->head; cell; cell = cell->next)
1283 appendPQExpBuffer(query,
1285 "\nFROM pg_catalog.pg_class c"
1286 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1287 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c')\n",
1288 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1289 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1290 RELKIND_PARTITIONED_TABLE);
1291 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1292 false, "n.nspname", "c.relname", NULL,
1293 "pg_catalog.pg_table_is_visible(c.oid)");
1295 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1296 if (strict_names && PQntuples(res) == 0)
1297 exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1299 for (i = 0; i < PQntuples(res); i++)
1301 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1305 resetPQExpBuffer(query);
1308 destroyPQExpBuffer(query);
1312 * checkExtensionMembership
1313 * Determine whether object is an extension member, and if so,
1314 * record an appropriate dependency and set the object's dump flag.
1316 * It's important to call this for each object that could be an extension
1317 * member. Generally, we integrate this with determining the object's
1318 * to-be-dumped-ness, since extension membership overrides other rules for that.
1320 * Returns true if object is an extension member, else false.
1323 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1325 ExtensionInfo *ext = findOwningExtension(dobj->catId);
1330 dobj->ext_member = true;
1332 /* Record dependency so that getDependencies needn't deal with that */
1333 addObjectDependency(dobj, ext->dobj.dumpId);
1336 * In 9.6 and above, mark the member object to have any non-initial ACL,
1337 * policies, and security labels dumped.
1339 * Note that any initial ACLs (see pg_init_privs) will be removed when we
1340 * extract the information about the object. We don't provide support for
1341 * initial policies and security labels and it seems unlikely for those to
1342 * ever exist, but we may have to revisit this later.
1344 * Prior to 9.6, we do not include any extension member components.
1346 * In binary upgrades, we still dump all components of the members
1347 * individually, since the idea is to exactly reproduce the database
1348 * contents rather than replace the extension contents with something
1351 if (fout->dopt->binary_upgrade)
1352 dobj->dump = ext->dobj.dump;
1355 if (fout->remoteVersion < 90600)
1356 dobj->dump = DUMP_COMPONENT_NONE;
1358 dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1359 DUMP_COMPONENT_SECLABEL |
1360 DUMP_COMPONENT_POLICY);
1367 * selectDumpableNamespace: policy-setting subroutine
1368 * Mark a namespace as to be dumped or not
1371 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1374 * If specific tables are being dumped, do not dump any complete
1375 * namespaces. If specific namespaces are being dumped, dump just those
1376 * namespaces. Otherwise, dump all non-system namespaces.
1378 if (table_include_oids.head != NULL)
1379 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1380 else if (schema_include_oids.head != NULL)
1381 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1382 simple_oid_list_member(&schema_include_oids,
1383 nsinfo->dobj.catId.oid) ?
1384 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1385 else if (fout->remoteVersion >= 90600 &&
1386 strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1389 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1390 * they are interesting (and not the original ACLs which were set at
1391 * initdb time, see pg_init_privs).
1393 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1395 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1396 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1398 /* Other system schemas don't get dumped */
1399 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1402 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1405 * In any case, a namespace can be excluded by an exclusion switch
1407 if (nsinfo->dobj.dump_contains &&
1408 simple_oid_list_member(&schema_exclude_oids,
1409 nsinfo->dobj.catId.oid))
1410 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1413 * If the schema belongs to an extension, allow extension membership to
1414 * override the dump decision for the schema itself. However, this does
1415 * not change dump_contains, so this won't change what we do with objects
1416 * within the schema. (If they belong to the extension, they'll get
1417 * suppressed by it, otherwise not.)
1419 (void) checkExtensionMembership(&nsinfo->dobj, fout);
1423 * selectDumpableTable: policy-setting subroutine
1424 * Mark a table as to be dumped or not
1427 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1429 if (checkExtensionMembership(&tbinfo->dobj, fout))
1430 return; /* extension membership overrides all else */
1433 * If specific tables are being dumped, dump just those tables; else, dump
1434 * according to the parent namespace's dump flag.
1436 if (table_include_oids.head != NULL)
1437 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1438 tbinfo->dobj.catId.oid) ?
1439 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1441 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1444 * In any case, a table can be excluded by an exclusion switch
1446 if (tbinfo->dobj.dump &&
1447 simple_oid_list_member(&table_exclude_oids,
1448 tbinfo->dobj.catId.oid))
1449 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1453 * selectDumpableType: policy-setting subroutine
1454 * Mark a type as to be dumped or not
1456 * If it's a table's rowtype or an autogenerated array type, we also apply a
1457 * special type code to facilitate sorting into the desired order. (We don't
1458 * want to consider those to be ordinary types because that would bring tables
1459 * up into the datatype part of the dump order.) We still set the object's
1460 * dump flag; that's not going to cause the dummy type to be dumped, but we
1461 * need it so that casts involving such types will be dumped correctly -- see
1462 * dumpCast. This means the flag should be set the same as for the underlying
1463 * object (the table or base type).
1466 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1468 /* skip complex types, except for standalone composite types */
1469 if (OidIsValid(tyinfo->typrelid) &&
1470 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1472 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1474 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1475 if (tytable != NULL)
1476 tyinfo->dobj.dump = tytable->dobj.dump;
1478 tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1482 /* skip auto-generated array types */
1483 if (tyinfo->isArray)
1485 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1488 * Fall through to set the dump flag; we assume that the subsequent
1489 * rules will do the same thing as they would for the array's base
1490 * type. (We cannot reliably look up the base type here, since
1491 * getTypes may not have processed it yet.)
1495 if (checkExtensionMembership(&tyinfo->dobj, fout))
1496 return; /* extension membership overrides all else */
1498 /* Dump based on if the contents of the namespace are being dumped */
1499 tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1503 * selectDumpableDefaultACL: policy-setting subroutine
1504 * Mark a default ACL as to be dumped or not
1506 * For per-schema default ACLs, dump if the schema is to be dumped.
1507 * Otherwise dump if we are dumping "everything". Note that dataOnly
1508 * and aclsSkip are checked separately.
1511 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1513 /* Default ACLs can't be extension members */
1515 if (dinfo->dobj.namespace)
1516 /* default ACLs are considered part of the namespace */
1517 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1519 dinfo->dobj.dump = dopt->include_everything ?
1520 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1524 * selectDumpableCast: policy-setting subroutine
1525 * Mark a cast as to be dumped or not
1527 * Casts do not belong to any particular namespace (since they haven't got
1528 * names), nor do they have identifiable owners. To distinguish user-defined
1529 * casts from built-in ones, we must resort to checking whether the cast's
1530 * OID is in the range reserved for initdb.
1533 selectDumpableCast(CastInfo *cast, Archive *fout)
1535 if (checkExtensionMembership(&cast->dobj, fout))
1536 return; /* extension membership overrides all else */
1539 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1540 * support ACLs currently.
1542 if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1543 cast->dobj.dump = DUMP_COMPONENT_NONE;
1545 cast->dobj.dump = fout->dopt->include_everything ?
1546 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1550 * selectDumpableProcLang: policy-setting subroutine
1551 * Mark a procedural language as to be dumped or not
1553 * Procedural languages do not belong to any particular namespace. To
1554 * identify built-in languages, we must resort to checking whether the
1555 * language's OID is in the range reserved for initdb.
1558 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1560 if (checkExtensionMembership(&plang->dobj, fout))
1561 return; /* extension membership overrides all else */
1564 * Only include procedural languages when we are dumping everything.
1566 * For from-initdb procedural languages, only include ACLs, as we do for
1567 * the pg_catalog namespace. We need this because procedural languages do
1568 * not live in any namespace.
1570 if (!fout->dopt->include_everything)
1571 plang->dobj.dump = DUMP_COMPONENT_NONE;
1574 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1575 plang->dobj.dump = fout->remoteVersion < 90600 ?
1576 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1578 plang->dobj.dump = DUMP_COMPONENT_ALL;
1583 * selectDumpableAccessMethod: policy-setting subroutine
1584 * Mark an access method as to be dumped or not
1586 * Access methods do not belong to any particular namespace. To identify
1587 * built-in access methods, we must resort to checking whether the
1588 * method's OID is in the range reserved for initdb.
1591 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1593 if (checkExtensionMembership(&method->dobj, fout))
1594 return; /* extension membership overrides all else */
1597 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1598 * they do not support ACLs currently.
1600 if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1601 method->dobj.dump = DUMP_COMPONENT_NONE;
1603 method->dobj.dump = fout->dopt->include_everything ?
1604 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1608 * selectDumpableExtension: policy-setting subroutine
1609 * Mark an extension as to be dumped or not
1611 * Normally, we dump all extensions, or none of them if include_everything
1612 * is false (i.e., a --schema or --table switch was given). However, in
1613 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1614 * assume those will already be installed in the target database. We identify
1615 * such extensions by their having OIDs in the range reserved for initdb.
1618 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1621 * Use DUMP_COMPONENT_ACL for from-initdb extensions, to allow users to
1622 * change permissions on those objects, if they wish to, and have those
1623 * changes preserved.
1625 if (dopt->binary_upgrade && extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1626 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1628 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1629 dopt->include_everything ? DUMP_COMPONENT_ALL :
1630 DUMP_COMPONENT_NONE;
1634 * selectDumpablePublicationTable: policy-setting subroutine
1635 * Mark a publication table as to be dumped or not
1637 * Publication tables have schemas, but those are ignored in decision making,
1638 * because publications are only dumped when we are dumping everything.
1641 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1643 if (checkExtensionMembership(dobj, fout))
1644 return; /* extension membership overrides all else */
1646 dobj->dump = fout->dopt->include_everything ?
1647 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1651 * selectDumpableObject: policy-setting subroutine
1652 * Mark a generic dumpable object as to be dumped or not
1654 * Use this only for object types without a special-case routine above.
1657 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1659 if (checkExtensionMembership(dobj, fout))
1660 return; /* extension membership overrides all else */
1663 * Default policy is to dump if parent namespace is dumpable, or for
1664 * non-namespace-associated items, dump if we're dumping "everything".
1666 if (dobj->namespace)
1667 dobj->dump = dobj->namespace->dobj.dump_contains;
1669 dobj->dump = fout->dopt->include_everything ?
1670 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1674 * Dump a table's contents for loading using the COPY command
1675 * - this routine is called by the Archiver when it wants the table
1680 dumpTableData_copy(Archive *fout, void *dcontext)
1682 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1683 TableInfo *tbinfo = tdinfo->tdtable;
1684 const char *classname = tbinfo->dobj.name;
1685 const bool hasoids = tbinfo->hasoids;
1686 const bool oids = tdinfo->oids;
1687 PQExpBuffer q = createPQExpBuffer();
1690 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1691 * which uses it already.
1693 PQExpBuffer clistBuf = createPQExpBuffer();
1694 PGconn *conn = GetConnection(fout);
1698 const char *column_list;
1701 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1702 tbinfo->dobj.namespace->dobj.name, classname);
1705 * Make sure we are in proper schema. We will qualify the table name
1706 * below anyway (in case its name conflicts with a pg_catalog table); but
1707 * this ensures reproducible results in case the table contains regproc,
1708 * regclass, etc columns.
1710 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1713 * Specify the column list explicitly so that we have no possibility of
1714 * retrieving data in the wrong column order. (The default column
1715 * ordering of COPY will not be what we want in certain corner cases
1716 * involving ADD COLUMN and inheritance.)
1718 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1720 if (oids && hasoids)
1722 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1723 fmtQualifiedId(fout->remoteVersion,
1724 tbinfo->dobj.namespace->dobj.name,
1728 else if (tdinfo->filtercond)
1730 /* Note: this syntax is only supported in 8.2 and up */
1731 appendPQExpBufferStr(q, "COPY (SELECT ");
1732 /* klugery to get rid of parens in column list */
1733 if (strlen(column_list) > 2)
1735 appendPQExpBufferStr(q, column_list + 1);
1736 q->data[q->len - 1] = ' ';
1739 appendPQExpBufferStr(q, "* ");
1740 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1741 fmtQualifiedId(fout->remoteVersion,
1742 tbinfo->dobj.namespace->dobj.name,
1744 tdinfo->filtercond);
1748 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1749 fmtQualifiedId(fout->remoteVersion,
1750 tbinfo->dobj.namespace->dobj.name,
1754 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1756 destroyPQExpBuffer(clistBuf);
1760 ret = PQgetCopyData(conn, ©buf, 0);
1763 break; /* done or error */
1767 WriteData(fout, copybuf, ret);
1774 * There was considerable discussion in late July, 2000 regarding
1775 * slowing down pg_dump when backing up large tables. Users with both
1776 * slow & fast (multi-processor) machines experienced performance
1777 * degradation when doing a backup.
1779 * Initial attempts based on sleeping for a number of ms for each ms
1780 * of work were deemed too complex, then a simple 'sleep in each loop'
1781 * implementation was suggested. The latter failed because the loop
1782 * was too tight. Finally, the following was implemented:
1784 * If throttle is non-zero, then
1785 * See how long since the last sleep.
1786 * Work out how long to sleep (based on ratio).
1787 * If sleep is more than 100ms, then
1793 * where the throttle value was the number of ms to sleep per ms of
1794 * work. The calculation was done in each loop.
1796 * Most of the hard work is done in the backend, and this solution
1797 * still did not work particularly well: on slow machines, the ratio
1798 * was 50:1, and on medium paced machines, 1:1, and on fast
1799 * multi-processor machines, it had little or no effect, for reasons
1800 * that were unclear.
1802 * Further discussion ensued, and the proposal was dropped.
1804 * For those people who want this feature, it can be implemented using
1805 * gettimeofday in each loop, calculating the time since last sleep,
1806 * multiplying that by the sleep ratio, then if the result is more
1807 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1808 * function to sleep for a subsecond period ie.
1810 * select(0, NULL, NULL, NULL, &tvi);
1812 * This will return after the interval specified in the structure tvi.
1813 * Finally, call gettimeofday again to save the 'last sleep time'.
1817 archprintf(fout, "\\.\n\n\n");
1821 /* copy data transfer failed */
1822 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1823 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1824 write_msg(NULL, "The command was: %s\n", q->data);
1828 /* Check command status and return to normal libpq state */
1829 res = PQgetResult(conn);
1830 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1832 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1833 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1834 write_msg(NULL, "The command was: %s\n", q->data);
1839 /* Do this to ensure we've pumped libpq back to idle state */
1840 if (PQgetResult(conn) != NULL)
1841 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1844 destroyPQExpBuffer(q);
1849 * Dump table data using INSERT commands.
1851 * Caution: when we restore from an archive file direct to database, the
1852 * INSERT commands emitted by this function have to be parsed by
1853 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1854 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1857 dumpTableData_insert(Archive *fout, void *dcontext)
1859 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1860 TableInfo *tbinfo = tdinfo->tdtable;
1861 const char *classname = tbinfo->dobj.name;
1862 DumpOptions *dopt = fout->dopt;
1863 PQExpBuffer q = createPQExpBuffer();
1864 PQExpBuffer insertStmt = NULL;
1871 * Make sure we are in proper schema. We will qualify the table name
1872 * below anyway (in case its name conflicts with a pg_catalog table); but
1873 * this ensures reproducible results in case the table contains regproc,
1874 * regclass, etc columns.
1876 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1878 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1879 "SELECT * FROM ONLY %s",
1880 fmtQualifiedId(fout->remoteVersion,
1881 tbinfo->dobj.namespace->dobj.name,
1883 if (tdinfo->filtercond)
1884 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1886 ExecuteSqlStatement(fout, q->data);
1890 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1892 nfields = PQnfields(res);
1893 for (tuple = 0; tuple < PQntuples(res); tuple++)
1896 * First time through, we build as much of the INSERT statement as
1897 * possible in "insertStmt", which we can then just print for each
1898 * line. If the table happens to have zero columns then this will
1899 * be a complete statement, otherwise it will end in "VALUES(" and
1900 * be ready to have the row's column values appended.
1902 if (insertStmt == NULL)
1904 insertStmt = createPQExpBuffer();
1905 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1908 /* corner case for zero-column table */
1911 appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1915 /* append the list of column names if required */
1916 if (dopt->column_inserts)
1918 appendPQExpBufferChar(insertStmt, '(');
1919 for (field = 0; field < nfields; field++)
1922 appendPQExpBufferStr(insertStmt, ", ");
1923 appendPQExpBufferStr(insertStmt,
1924 fmtId(PQfname(res, field)));
1926 appendPQExpBufferStr(insertStmt, ") ");
1929 if (tbinfo->needs_override)
1930 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1932 appendPQExpBufferStr(insertStmt, "VALUES (");
1936 archputs(insertStmt->data, fout);
1938 /* if it is zero-column table then we're done */
1942 for (field = 0; field < nfields; field++)
1945 archputs(", ", fout);
1946 if (PQgetisnull(res, tuple, field))
1948 archputs("NULL", fout);
1952 /* XXX This code is partially duplicated in ruleutils.c */
1953 switch (PQftype(res, field))
1964 * These types are printed without quotes unless
1965 * they contain values that aren't accepted by the
1966 * scanner unquoted (e.g., 'NaN'). Note that
1967 * strtod() and friends might accept NaN, so we
1968 * can't use that to test.
1970 * In reality we only need to defend against
1971 * infinity and NaN, so we need not get too crazy
1972 * about pattern matching here.
1974 const char *s = PQgetvalue(res, tuple, field);
1976 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1979 archprintf(fout, "'%s'", s);
1985 archprintf(fout, "B'%s'",
1986 PQgetvalue(res, tuple, field));
1990 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1991 archputs("true", fout);
1993 archputs("false", fout);
1997 /* All other types are printed as string literals. */
1998 resetPQExpBuffer(q);
1999 appendStringLiteralAH(q,
2000 PQgetvalue(res, tuple, field),
2002 archputs(q->data, fout);
2006 archputs(");\n", fout);
2009 if (PQntuples(res) <= 0)
2017 archputs("\n\n", fout);
2019 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2021 destroyPQExpBuffer(q);
2022 if (insertStmt != NULL)
2023 destroyPQExpBuffer(insertStmt);
2031 * dump the contents of a single table
2033 * Actually, this just makes an ArchiveEntry for the table contents.
2036 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2038 DumpOptions *dopt = fout->dopt;
2039 TableInfo *tbinfo = tdinfo->tdtable;
2040 PQExpBuffer copyBuf = createPQExpBuffer();
2041 PQExpBuffer clistBuf = createPQExpBuffer();
2042 DataDumperPtr dumpFn;
2045 if (!dopt->dump_inserts)
2047 /* Dump/restore using COPY */
2048 dumpFn = dumpTableData_copy;
2049 /* must use 2 steps here 'cause fmtId is nonreentrant */
2050 appendPQExpBuffer(copyBuf, "COPY %s ",
2051 fmtId(tbinfo->dobj.name));
2052 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2053 fmtCopyColumnList(tbinfo, clistBuf),
2054 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2055 copyStmt = copyBuf->data;
2059 /* Restore using INSERT */
2060 dumpFn = dumpTableData_insert;
2065 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2066 * dependency on its table as "special" and pass it to ArchiveEntry now.
2067 * See comments for BuildArchiveDependencies.
2069 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2070 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2071 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2072 NULL, tbinfo->rolname,
2073 false, "TABLE DATA", SECTION_DATA,
2075 &(tbinfo->dobj.dumpId), 1,
2078 destroyPQExpBuffer(copyBuf);
2079 destroyPQExpBuffer(clistBuf);
2083 * refreshMatViewData -
2084 * load or refresh the contents of a single materialized view
2086 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2090 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2092 TableInfo *tbinfo = tdinfo->tdtable;
2095 /* If the materialized view is not flagged as populated, skip this. */
2096 if (!tbinfo->relispopulated)
2099 q = createPQExpBuffer();
2101 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2102 fmtId(tbinfo->dobj.name));
2104 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2106 tdinfo->dobj.catId, /* catalog ID */
2107 tdinfo->dobj.dumpId, /* dump ID */
2108 tbinfo->dobj.name, /* Name */
2109 tbinfo->dobj.namespace->dobj.name, /* Namespace */
2110 NULL, /* Tablespace */
2111 tbinfo->rolname, /* Owner */
2112 false, /* with oids */
2113 "MATERIALIZED VIEW DATA", /* Desc */
2114 SECTION_POST_DATA, /* Section */
2115 q->data, /* Create */
2118 tdinfo->dobj.dependencies, /* Deps */
2119 tdinfo->dobj.nDeps, /* # Deps */
2121 NULL); /* Dumper Arg */
2123 destroyPQExpBuffer(q);
2128 * set up dumpable objects representing the contents of tables
2131 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2135 for (i = 0; i < numTables; i++)
2137 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2138 (!relkind || tblinfo[i].relkind == relkind))
2139 makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2144 * Make a dumpable object for the data of this specific table
2146 * Note: we make a TableDataInfo if and only if we are going to dump the
2147 * table data; the "dump" flag in such objects isn't used.
2150 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2152 TableDataInfo *tdinfo;
2155 * Nothing to do if we already decided to dump the table. This will
2156 * happen for "config" tables.
2158 if (tbinfo->dataObj != NULL)
2161 /* Skip VIEWs (no data to dump) */
2162 if (tbinfo->relkind == RELKIND_VIEW)
2164 /* Skip FOREIGN TABLEs (no data to dump) */
2165 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2167 /* Skip partitioned tables (data in partitions) */
2168 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2171 /* Don't dump data in unlogged tables, if so requested */
2172 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2173 dopt->no_unlogged_table_data)
2176 /* Check that the data is not explicitly excluded */
2177 if (simple_oid_list_member(&tabledata_exclude_oids,
2178 tbinfo->dobj.catId.oid))
2181 /* OK, let's dump it */
2182 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2184 if (tbinfo->relkind == RELKIND_MATVIEW)
2185 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2186 else if (tbinfo->relkind == RELKIND_SEQUENCE)
2187 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2189 tdinfo->dobj.objType = DO_TABLE_DATA;
2192 * Note: use tableoid 0 so that this object won't be mistaken for
2193 * something that pg_depend entries apply to.
2195 tdinfo->dobj.catId.tableoid = 0;
2196 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2197 AssignDumpId(&tdinfo->dobj);
2198 tdinfo->dobj.name = tbinfo->dobj.name;
2199 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2200 tdinfo->tdtable = tbinfo;
2201 tdinfo->oids = oids;
2202 tdinfo->filtercond = NULL; /* might get set later */
2203 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2205 tbinfo->dataObj = tdinfo;
2209 * The refresh for a materialized view must be dependent on the refresh for
2210 * any materialized view that this one is dependent on.
2212 * This must be called after all the objects are created, but before they are
2216 buildMatViewRefreshDependencies(Archive *fout)
2226 /* No Mat Views before 9.3. */
2227 if (fout->remoteVersion < 90300)
2230 /* Make sure we are in proper schema */
2231 selectSourceSchema(fout, "pg_catalog");
2233 query = createPQExpBuffer();
2235 appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2237 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2238 "FROM pg_depend d1 "
2239 "JOIN pg_class c1 ON c1.oid = d1.objid "
2240 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2241 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2242 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2243 "AND d2.objid = r1.oid "
2244 "AND d2.refobjid <> d1.objid "
2245 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2246 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2247 CppAsString2(RELKIND_VIEW) ") "
2248 "WHERE d1.classid = 'pg_class'::regclass "
2250 "SELECT w.objid, d3.refobjid, c3.relkind "
2252 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2253 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2254 "AND d3.objid = r3.oid "
2255 "AND d3.refobjid <> w.refobjid "
2256 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2257 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2258 CppAsString2(RELKIND_VIEW) ") "
2260 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2262 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2264 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2266 ntups = PQntuples(res);
2268 i_classid = PQfnumber(res, "classid");
2269 i_objid = PQfnumber(res, "objid");
2270 i_refobjid = PQfnumber(res, "refobjid");
2272 for (i = 0; i < ntups; i++)
2276 DumpableObject *dobj;
2277 DumpableObject *refdobj;
2279 TableInfo *reftbinfo;
2281 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2282 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2283 refobjId.tableoid = objId.tableoid;
2284 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2286 dobj = findObjectByCatalogId(objId);
2290 Assert(dobj->objType == DO_TABLE);
2291 tbinfo = (TableInfo *) dobj;
2292 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2293 dobj = (DumpableObject *) tbinfo->dataObj;
2296 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2298 refdobj = findObjectByCatalogId(refobjId);
2299 if (refdobj == NULL)
2302 Assert(refdobj->objType == DO_TABLE);
2303 reftbinfo = (TableInfo *) refdobj;
2304 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2305 refdobj = (DumpableObject *) reftbinfo->dataObj;
2306 if (refdobj == NULL)
2308 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2310 addObjectDependency(dobj, refdobj->dumpId);
2312 if (!reftbinfo->relispopulated)
2313 tbinfo->relispopulated = false;
2318 destroyPQExpBuffer(query);
2322 * getTableDataFKConstraints -
2323 * add dump-order dependencies reflecting foreign key constraints
2325 * This code is executed only in a data-only dump --- in schema+data dumps
2326 * we handle foreign key issues by not creating the FK constraints until
2327 * after the data is loaded. In a data-only dump, however, we want to
2328 * order the table data objects in such a way that a table's referenced
2329 * tables are restored first. (In the presence of circular references or
2330 * self-references this may be impossible; we'll detect and complain about
2331 * that during the dependency sorting step.)
2334 getTableDataFKConstraints(void)
2336 DumpableObject **dobjs;
2340 /* Search through all the dumpable objects for FK constraints */
2341 getDumpableObjects(&dobjs, &numObjs);
2342 for (i = 0; i < numObjs; i++)
2344 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2346 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2349 /* Not interesting unless both tables are to be dumped */
2350 if (cinfo->contable == NULL ||
2351 cinfo->contable->dataObj == NULL)
2353 ftable = findTableByOid(cinfo->confrelid);
2354 if (ftable == NULL ||
2355 ftable->dataObj == NULL)
2359 * Okay, make referencing table's TABLE_DATA object depend on the
2360 * referenced table's TABLE_DATA object.
2362 addObjectDependency(&cinfo->contable->dataObj->dobj,
2363 ftable->dataObj->dobj.dumpId);
2371 * guessConstraintInheritance:
2372 * In pre-8.4 databases, we can't tell for certain which constraints
2373 * are inherited. We assume a CHECK constraint is inherited if its name
2374 * matches the name of any constraint in the parent. Originally this code
2375 * tried to compare the expression texts, but that can fail for various
2376 * reasons --- for example, if the parent and child tables are in different
2377 * schemas, reverse-listing of function calls may produce different text
2378 * (schema-qualified or not) depending on search path.
2380 * In 8.4 and up we can rely on the conislocal field to decide which
2381 * constraints must be dumped; much safer.
2383 * This function assumes all conislocal flags were initialized to TRUE.
2384 * It clears the flag on anything that seems to be inherited.
2387 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2393 for (i = 0; i < numTables; i++)
2395 TableInfo *tbinfo = &(tblinfo[i]);
2397 TableInfo **parents;
2400 /* Sequences and views never have parents */
2401 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2402 tbinfo->relkind == RELKIND_VIEW)
2405 /* Don't bother computing anything for non-target tables, either */
2406 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2409 numParents = tbinfo->numParents;
2410 parents = tbinfo->parents;
2412 if (numParents == 0)
2413 continue; /* nothing to see here, move along */
2415 /* scan for inherited CHECK constraints */
2416 for (j = 0; j < tbinfo->ncheck; j++)
2418 ConstraintInfo *constr;
2420 constr = &(tbinfo->checkexprs[j]);
2422 for (k = 0; k < numParents; k++)
2426 parent = parents[k];
2427 for (l = 0; l < parent->ncheck; l++)
2429 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2431 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2433 constr->conislocal = false;
2437 if (!constr->conislocal)
2447 * dump the database definition
2450 dumpDatabase(Archive *fout)
2452 DumpOptions *dopt = fout->dopt;
2453 PQExpBuffer dbQry = createPQExpBuffer();
2454 PQExpBuffer delQry = createPQExpBuffer();
2455 PQExpBuffer creaQry = createPQExpBuffer();
2456 PGconn *conn = GetConnection(fout);
2469 const char *datname,
2478 datname = PQdb(conn);
2481 write_msg(NULL, "saving database definition\n");
2483 /* Make sure we are in proper schema */
2484 selectSourceSchema(fout, "pg_catalog");
2486 /* Get the database owner and parameters from pg_database */
2487 if (fout->remoteVersion >= 90300)
2489 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2490 "(%s datdba) AS dba, "
2491 "pg_encoding_to_char(encoding) AS encoding, "
2492 "datcollate, datctype, datfrozenxid, datminmxid, "
2493 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2494 "shobj_description(oid, 'pg_database') AS description "
2499 appendStringLiteralAH(dbQry, datname, fout);
2501 else if (fout->remoteVersion >= 80400)
2503 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2504 "(%s datdba) AS dba, "
2505 "pg_encoding_to_char(encoding) AS encoding, "
2506 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2507 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2508 "shobj_description(oid, 'pg_database') AS description "
2513 appendStringLiteralAH(dbQry, datname, fout);
2515 else if (fout->remoteVersion >= 80200)
2517 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2518 "(%s datdba) AS dba, "
2519 "pg_encoding_to_char(encoding) AS encoding, "
2520 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2521 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2522 "shobj_description(oid, 'pg_database') AS description "
2527 appendStringLiteralAH(dbQry, datname, fout);
2531 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2532 "(%s datdba) AS dba, "
2533 "pg_encoding_to_char(encoding) AS encoding, "
2534 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2535 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2539 appendStringLiteralAH(dbQry, datname, fout);
2542 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2544 i_tableoid = PQfnumber(res, "tableoid");
2545 i_oid = PQfnumber(res, "oid");
2546 i_dba = PQfnumber(res, "dba");
2547 i_encoding = PQfnumber(res, "encoding");
2548 i_collate = PQfnumber(res, "datcollate");
2549 i_ctype = PQfnumber(res, "datctype");
2550 i_frozenxid = PQfnumber(res, "datfrozenxid");
2551 i_minmxid = PQfnumber(res, "datminmxid");
2552 i_tablespace = PQfnumber(res, "tablespace");
2554 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2555 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2556 dba = PQgetvalue(res, 0, i_dba);
2557 encoding = PQgetvalue(res, 0, i_encoding);
2558 collate = PQgetvalue(res, 0, i_collate);
2559 ctype = PQgetvalue(res, 0, i_ctype);
2560 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2561 minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2562 tablespace = PQgetvalue(res, 0, i_tablespace);
2564 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2566 if (strlen(encoding) > 0)
2568 appendPQExpBufferStr(creaQry, " ENCODING = ");
2569 appendStringLiteralAH(creaQry, encoding, fout);
2571 if (strlen(collate) > 0)
2573 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2574 appendStringLiteralAH(creaQry, collate, fout);
2576 if (strlen(ctype) > 0)
2578 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2579 appendStringLiteralAH(creaQry, ctype, fout);
2581 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2582 !dopt->outputNoTablespaces)
2583 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2585 appendPQExpBufferStr(creaQry, ";\n");
2587 if (dopt->binary_upgrade)
2589 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2590 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2591 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2593 frozenxid, minmxid);
2594 appendStringLiteralAH(creaQry, datname, fout);
2595 appendPQExpBufferStr(creaQry, ";\n");
2599 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2602 dbDumpId = createDumpId();
2605 dbCatId, /* catalog ID */
2606 dbDumpId, /* dump ID */
2608 NULL, /* Namespace */
2609 NULL, /* Tablespace */
2611 false, /* with oids */
2612 "DATABASE", /* Desc */
2613 SECTION_PRE_DATA, /* Section */
2614 creaQry->data, /* Create */
2615 delQry->data, /* Del */
2620 NULL); /* Dumper Arg */
2623 * pg_largeobject and pg_largeobject_metadata come from the old system
2624 * intact, so set their relfrozenxids and relminmxids.
2626 if (dopt->binary_upgrade)
2629 PQExpBuffer loFrozenQry = createPQExpBuffer();
2630 PQExpBuffer loOutQry = createPQExpBuffer();
2637 if (fout->remoteVersion >= 90300)
2638 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2639 "FROM pg_catalog.pg_class\n"
2640 "WHERE oid = %u;\n",
2641 LargeObjectRelationId);
2643 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2644 "FROM pg_catalog.pg_class\n"
2645 "WHERE oid = %u;\n",
2646 LargeObjectRelationId);
2648 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2650 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2651 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2653 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2654 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2655 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2656 "WHERE oid = %u;\n",
2657 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2658 atoi(PQgetvalue(lo_res, 0, i_relminmxid)),
2659 LargeObjectRelationId);
2660 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2661 "pg_largeobject", NULL, NULL, "",
2662 false, "pg_largeobject", SECTION_PRE_DATA,
2663 loOutQry->data, "", NULL,
2670 * pg_largeobject_metadata
2672 if (fout->remoteVersion >= 90000)
2674 resetPQExpBuffer(loFrozenQry);
2675 resetPQExpBuffer(loOutQry);
2677 if (fout->remoteVersion >= 90300)
2678 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2679 "FROM pg_catalog.pg_class\n"
2680 "WHERE oid = %u;\n",
2681 LargeObjectMetadataRelationId);
2683 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2684 "FROM pg_catalog.pg_class\n"
2685 "WHERE oid = %u;\n",
2686 LargeObjectMetadataRelationId);
2688 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2690 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2691 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2693 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2694 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2695 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2696 "WHERE oid = %u;\n",
2697 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2698 atoi(PQgetvalue(lo_res, 0, i_relminmxid)),
2699 LargeObjectMetadataRelationId);
2700 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2701 "pg_largeobject_metadata", NULL, NULL, "",
2702 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2703 loOutQry->data, "", NULL,
2710 destroyPQExpBuffer(loFrozenQry);
2711 destroyPQExpBuffer(loOutQry);
2714 /* Dump DB comment if any */
2715 if (fout->remoteVersion >= 80200)
2718 * 8.2 keeps comments on shared objects in a shared table, so we
2719 * cannot use the dumpComment used for other database objects.
2721 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2723 if (comment && strlen(comment))
2725 resetPQExpBuffer(dbQry);
2728 * Generates warning when loaded into a differently-named
2731 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2732 appendStringLiteralAH(dbQry, comment, fout);
2733 appendPQExpBufferStr(dbQry, ";\n");
2735 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2736 dba, false, "COMMENT", SECTION_NONE,
2737 dbQry->data, "", NULL,
2738 &dbDumpId, 1, NULL, NULL);
2743 resetPQExpBuffer(dbQry);
2744 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2745 dumpComment(fout, dbQry->data, NULL, "",
2746 dbCatId, 0, dbDumpId);
2749 /* Dump shared security label. */
2750 if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2753 PQExpBuffer seclabelQry;
2755 seclabelQry = createPQExpBuffer();
2757 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2758 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2759 resetPQExpBuffer(seclabelQry);
2760 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2761 if (strlen(seclabelQry->data))
2762 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2763 dba, false, "SECURITY LABEL", SECTION_NONE,
2764 seclabelQry->data, "", NULL,
2765 &dbDumpId, 1, NULL, NULL);
2766 destroyPQExpBuffer(seclabelQry);
2772 destroyPQExpBuffer(dbQry);
2773 destroyPQExpBuffer(delQry);
2774 destroyPQExpBuffer(creaQry);
2778 * dumpEncoding: put the correct encoding into the archive
2781 dumpEncoding(Archive *AH)
2783 const char *encname = pg_encoding_to_char(AH->encoding);
2784 PQExpBuffer qry = createPQExpBuffer();
2787 write_msg(NULL, "saving encoding = %s\n", encname);
2789 appendPQExpBufferStr(qry, "SET client_encoding = ");
2790 appendStringLiteralAH(qry, encname, AH);
2791 appendPQExpBufferStr(qry, ";\n");
2793 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2794 "ENCODING", NULL, NULL, "",
2795 false, "ENCODING", SECTION_PRE_DATA,
2796 qry->data, "", NULL,
2800 destroyPQExpBuffer(qry);
2805 * dumpStdStrings: put the correct escape string behavior into the archive
2808 dumpStdStrings(Archive *AH)
2810 const char *stdstrings = AH->std_strings ? "on" : "off";
2811 PQExpBuffer qry = createPQExpBuffer();
2814 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2817 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2820 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2821 "STDSTRINGS", NULL, NULL, "",
2822 false, "STDSTRINGS", SECTION_PRE_DATA,
2823 qry->data, "", NULL,
2827 destroyPQExpBuffer(qry);
2833 * Collect schema-level data about large objects
2836 getBlobs(Archive *fout)
2838 DumpOptions *dopt = fout->dopt;
2839 PQExpBuffer blobQry = createPQExpBuffer();
2841 DumpableObject *bdata;
2852 /* Verbose message */
2854 write_msg(NULL, "reading large objects\n");
2856 /* Make sure we are in proper schema */
2857 selectSourceSchema(fout, "pg_catalog");
2859 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2860 if (fout->remoteVersion >= 90600)
2862 PQExpBuffer acl_subquery = createPQExpBuffer();
2863 PQExpBuffer racl_subquery = createPQExpBuffer();
2864 PQExpBuffer init_acl_subquery = createPQExpBuffer();
2865 PQExpBuffer init_racl_subquery = createPQExpBuffer();
2867 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
2868 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
2869 dopt->binary_upgrade);
2871 appendPQExpBuffer(blobQry,
2872 "SELECT l.oid, (%s l.lomowner) AS rolname, "
2875 "%s AS initlomacl, "
2876 "%s AS initrlomacl "
2877 "FROM pg_largeobject_metadata l "
2878 "LEFT JOIN pg_init_privs pip ON "
2879 "(l.oid = pip.objoid "
2880 "AND pip.classoid = 'pg_largeobject'::regclass "
2881 "AND pip.objsubid = 0) ",
2884 racl_subquery->data,
2885 init_acl_subquery->data,
2886 init_racl_subquery->data);
2888 destroyPQExpBuffer(acl_subquery);
2889 destroyPQExpBuffer(racl_subquery);
2890 destroyPQExpBuffer(init_acl_subquery);
2891 destroyPQExpBuffer(init_racl_subquery);
2893 else if (fout->remoteVersion >= 90000)
2894 appendPQExpBuffer(blobQry,
2895 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
2896 "NULL AS rlomacl, NULL AS initlomacl, "
2897 "NULL AS initrlomacl "
2898 " FROM pg_largeobject_metadata",
2901 appendPQExpBufferStr(blobQry,
2902 "SELECT DISTINCT loid AS oid, "
2903 "NULL::name AS rolname, NULL::oid AS lomacl, "
2904 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
2905 "NULL::oid AS initrlomacl "
2906 " FROM pg_largeobject");
2908 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2910 i_oid = PQfnumber(res, "oid");
2911 i_lomowner = PQfnumber(res, "rolname");
2912 i_lomacl = PQfnumber(res, "lomacl");
2913 i_rlomacl = PQfnumber(res, "rlomacl");
2914 i_initlomacl = PQfnumber(res, "initlomacl");
2915 i_initrlomacl = PQfnumber(res, "initrlomacl");
2917 ntups = PQntuples(res);
2920 * Each large object has its own BLOB archive entry.
2922 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2924 for (i = 0; i < ntups; i++)
2926 binfo[i].dobj.objType = DO_BLOB;
2927 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2928 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2929 AssignDumpId(&binfo[i].dobj);
2931 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
2932 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
2933 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
2934 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
2935 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
2936 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
2938 if (PQgetisnull(res, i, i_lomacl) &&
2939 PQgetisnull(res, i, i_rlomacl) &&
2940 PQgetisnull(res, i, i_initlomacl) &&
2941 PQgetisnull(res, i, i_initrlomacl))
2942 binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
2945 * In binary-upgrade mode for blobs, we do *not* dump out the data or
2946 * the ACLs, should any exist. The data and ACL (if any) will be
2947 * copied by pg_upgrade, which simply copies the pg_largeobject and
2948 * pg_largeobject_metadata tables.
2950 * We *do* dump out the definition of the blob because we need that to
2951 * make the restoration of the comments, and anything else, work since
2952 * pg_upgrade copies the files behind pg_largeobject and
2953 * pg_largeobject_metadata after the dump is restored.
2955 if (dopt->binary_upgrade)
2956 binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
2960 * If we have any large objects, a "BLOBS" archive entry is needed. This
2961 * is just a placeholder for sorting; it carries no data now.
2965 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2966 bdata->objType = DO_BLOB_DATA;
2967 bdata->catId = nilCatalogId;
2968 AssignDumpId(bdata);
2969 bdata->name = pg_strdup("BLOBS");
2973 destroyPQExpBuffer(blobQry);
2979 * dump the definition (metadata) of the given large object
2982 dumpBlob(Archive *fout, BlobInfo *binfo)
2984 PQExpBuffer cquery = createPQExpBuffer();
2985 PQExpBuffer dquery = createPQExpBuffer();
2987 appendPQExpBuffer(cquery,
2988 "SELECT pg_catalog.lo_create('%s');\n",
2991 appendPQExpBuffer(dquery,
2992 "SELECT pg_catalog.lo_unlink('%s');\n",
2995 if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
2996 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2999 binfo->rolname, false,
3000 "BLOB", SECTION_PRE_DATA,
3001 cquery->data, dquery->data, NULL,
3005 /* set up tag for comment and/or ACL */
3006 resetPQExpBuffer(cquery);
3007 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
3009 /* Dump comment if any */
3010 if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3011 dumpComment(fout, cquery->data,
3012 NULL, binfo->rolname,
3013 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3015 /* Dump security label if any */
3016 if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3017 dumpSecLabel(fout, cquery->data,
3018 NULL, binfo->rolname,
3019 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3021 /* Dump ACL if any */
3022 if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3023 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3024 binfo->dobj.name, NULL, cquery->data,
3025 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3026 binfo->initblobacl, binfo->initrblobacl);
3028 destroyPQExpBuffer(cquery);
3029 destroyPQExpBuffer(dquery);
3034 * dump the data contents of all large objects
3037 dumpBlobs(Archive *fout, void *arg)
3039 const char *blobQry;
3040 const char *blobFetchQry;
3041 PGconn *conn = GetConnection(fout);
3043 char buf[LOBBUFSIZE];
3049 write_msg(NULL, "saving large objects\n");
3051 /* Make sure we are in proper schema */
3052 selectSourceSchema(fout, "pg_catalog");
3055 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3056 * the already-in-memory dumpable objects instead...
3058 if (fout->remoteVersion >= 90000)
3059 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3061 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3063 ExecuteSqlStatement(fout, blobQry);
3065 /* Command to fetch from cursor */
3066 blobFetchQry = "FETCH 1000 IN bloboid";
3071 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3073 /* Process the tuples, if any */
3074 ntups = PQntuples(res);
3075 for (i = 0; i < ntups; i++)
3080 blobOid = atooid(PQgetvalue(res, i, 0));
3082 loFd = lo_open(conn, blobOid, INV_READ);
3084 exit_horribly(NULL, "could not open large object %u: %s",
3085 blobOid, PQerrorMessage(conn));
3087 StartBlob(fout, blobOid);
3089 /* Now read it in chunks, sending data to archive */
3092 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3094 exit_horribly(NULL, "error reading large object %u: %s",
3095 blobOid, PQerrorMessage(conn));
3097 WriteData(fout, buf, cnt);
3100 lo_close(conn, loFd);
3102 EndBlob(fout, blobOid);
3106 } while (ntups > 0);
3113 * get information about policies on a dumpable table.
3116 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3120 PolicyInfo *polinfo;
3125 int i_polpermissive;
3133 if (fout->remoteVersion < 90500)
3136 query = createPQExpBuffer();
3138 for (i = 0; i < numTables; i++)
3140 TableInfo *tbinfo = &tblinfo[i];
3142 /* Ignore row security on tables not to be dumped */
3143 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3147 write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3148 tbinfo->dobj.namespace->dobj.name,
3152 * Get row security enabled information for the table. We represent
3153 * RLS enabled on a table by creating PolicyInfo object with an empty
3159 * Note: use tableoid 0 so that this object won't be mistaken for
3160 * something that pg_depend entries apply to.
3162 polinfo = pg_malloc(sizeof(PolicyInfo));
3163 polinfo->dobj.objType = DO_POLICY;
3164 polinfo->dobj.catId.tableoid = 0;
3165 polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3166 AssignDumpId(&polinfo->dobj);
3167 polinfo->dobj.namespace = tbinfo->dobj.namespace;
3168 polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3169 polinfo->poltable = tbinfo;
3170 polinfo->polname = NULL;
3171 polinfo->polcmd = '\0';
3172 polinfo->polpermissive = 0;
3173 polinfo->polroles = NULL;
3174 polinfo->polqual = NULL;
3175 polinfo->polwithcheck = NULL;
3179 write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3180 tbinfo->dobj.namespace->dobj.name,
3184 * select table schema to ensure regproc name is qualified if needed
3186 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
3188 resetPQExpBuffer(query);
3190 /* Get the policies for the table. */
3191 if (fout->remoteVersion >= 100000)
3192 appendPQExpBuffer(query,
3193 "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3194 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3195 " pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3196 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3197 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3198 "FROM pg_catalog.pg_policy pol "
3199 "WHERE polrelid = '%u'",
3200 tbinfo->dobj.catId.oid);
3202 appendPQExpBuffer(query,
3203 "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3204 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3205 " pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3206 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3207 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3208 "FROM pg_catalog.pg_policy pol "
3209 "WHERE polrelid = '%u'",
3210 tbinfo->dobj.catId.oid);
3211 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3213 ntups = PQntuples(res);
3218 * No explicit policies to handle (only the default-deny policy,
3219 * which is handled as part of the table definition). Clean up
3226 i_oid = PQfnumber(res, "oid");
3227 i_tableoid = PQfnumber(res, "tableoid");
3228 i_polname = PQfnumber(res, "polname");
3229 i_polcmd = PQfnumber(res, "polcmd");
3230 i_polpermissive = PQfnumber(res, "polpermissive");
3231 i_polroles = PQfnumber(res, "polroles");
3232 i_polqual = PQfnumber(res, "polqual");
3233 i_polwithcheck = PQfnumber(res, "polwithcheck");
3235 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3237 for (j = 0; j < ntups; j++)
3239 polinfo[j].dobj.objType = DO_POLICY;
3240 polinfo[j].dobj.catId.tableoid =
3241 atooid(PQgetvalue(res, j, i_tableoid));
3242 polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3243 AssignDumpId(&polinfo[j].dobj);
3244 polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3245 polinfo[j].poltable = tbinfo;
3246 polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3247 polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3249 polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3250 polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3252 if (PQgetisnull(res, j, i_polroles))
3253 polinfo[j].polroles = NULL;
3255 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3257 if (PQgetisnull(res, j, i_polqual))
3258 polinfo[j].polqual = NULL;
3260 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3262 if (PQgetisnull(res, j, i_polwithcheck))
3263 polinfo[j].polwithcheck = NULL;
3265 polinfo[j].polwithcheck
3266 = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3270 destroyPQExpBuffer(query);
3275 * dump the definition of the given policy
3278 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3280 DumpOptions *dopt = fout->dopt;
3281 TableInfo *tbinfo = polinfo->poltable;
3291 * If polname is NULL, then this record is just indicating that ROW LEVEL
3292 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3293 * ROW LEVEL SECURITY.
3295 if (polinfo->polname == NULL)
3297 query = createPQExpBuffer();
3299 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3300 fmtId(polinfo->dobj.name));
3302 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3303 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3305 polinfo->dobj.namespace->dobj.name,
3307 tbinfo->rolname, false,
3308 "ROW SECURITY", SECTION_POST_DATA,
3309 query->data, "", NULL,
3313 destroyPQExpBuffer(query);
3317 if (polinfo->polcmd == '*')
3319 else if (polinfo->polcmd == 'r')
3320 cmd = " FOR SELECT";
3321 else if (polinfo->polcmd == 'a')
3322 cmd = " FOR INSERT";
3323 else if (polinfo->polcmd == 'w')
3324 cmd = " FOR UPDATE";
3325 else if (polinfo->polcmd == 'd')
3326 cmd = " FOR DELETE";
3329 write_msg(NULL, "unexpected policy command type: %c\n",
3334 query = createPQExpBuffer();
3335 delqry = createPQExpBuffer();
3337 appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3339 appendPQExpBuffer(query, " ON %s%s%s", fmtId(tbinfo->dobj.name),
3340 !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3342 if (polinfo->polroles != NULL)
3343 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3345 if (polinfo->polqual != NULL)
3346 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3348 if (polinfo->polwithcheck != NULL)
3349 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3351 appendPQExpBuffer(query, ";\n");
3353 appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3354 appendPQExpBuffer(delqry, " ON %s;\n", fmtId(tbinfo->dobj.name));
3356 tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3358 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3359 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3361 polinfo->dobj.namespace->dobj.name,
3363 tbinfo->rolname, false,
3364 "POLICY", SECTION_POST_DATA,
3365 query->data, delqry->data, NULL,
3370 destroyPQExpBuffer(query);
3371 destroyPQExpBuffer(delqry);
3376 * get information about publications
3379 getPublications(Archive *fout)
3381 DumpOptions *dopt = fout->dopt;
3384 PublicationInfo *pubinfo;
3396 if (dopt->no_publications || fout->remoteVersion < 100000)
3399 query = createPQExpBuffer();
3401 resetPQExpBuffer(query);
3403 /* Get the publications. */
3404 appendPQExpBuffer(query,
3405 "SELECT p.tableoid, p.oid, p.pubname, "
3406 "(%s p.pubowner) AS rolname, "
3407 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete "
3408 "FROM pg_catalog.pg_publication p",
3411 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3413 ntups = PQntuples(res);
3415 i_tableoid = PQfnumber(res, "tableoid");
3416 i_oid = PQfnumber(res, "oid");
3417 i_pubname = PQfnumber(res, "pubname");
3418 i_rolname = PQfnumber(res, "rolname");
3419 i_puballtables = PQfnumber(res, "puballtables");
3420 i_pubinsert = PQfnumber(res, "pubinsert");
3421 i_pubupdate = PQfnumber(res, "pubupdate");
3422 i_pubdelete = PQfnumber(res, "pubdelete");
3424 pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3426 for (i = 0; i < ntups; i++)
3428 pubinfo[i].dobj.objType = DO_PUBLICATION;
3429 pubinfo[i].dobj.catId.tableoid =
3430 atooid(PQgetvalue(res, i, i_tableoid));
3431 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3432 AssignDumpId(&pubinfo[i].dobj);
3433 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3434 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3435 pubinfo[i].puballtables =
3436 (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3437 pubinfo[i].pubinsert =
3438 (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3439 pubinfo[i].pubupdate =
3440 (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3441 pubinfo[i].pubdelete =
3442 (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3444 if (strlen(pubinfo[i].rolname) == 0)
3445 write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3446 pubinfo[i].dobj.name);
3448 /* Decide whether we want to dump it */
3449 selectDumpableObject(&(pubinfo[i].dobj), fout);
3453 destroyPQExpBuffer(query);
3458 * dump the definition of the given publication
3461 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3468 if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3471 delq = createPQExpBuffer();
3472 query = createPQExpBuffer();
3473 labelq = createPQExpBuffer();
3475 appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3476 fmtId(pubinfo->dobj.name));
3478 appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3479 fmtId(pubinfo->dobj.name));
3481 appendPQExpBuffer(labelq, "PUBLICATION %s", fmtId(pubinfo->dobj.name));
3483 if (pubinfo->puballtables)
3484 appendPQExpBufferStr(query, " FOR ALL TABLES");
3486 appendPQExpBufferStr(query, " WITH (publish = '");
3487 if (pubinfo->pubinsert)
3489 appendPQExpBufferStr(query, "insert");
3493 if (pubinfo->pubupdate)
3496 appendPQExpBufferStr(query, ", ");
3498 appendPQExpBufferStr(query, "update");
3502 if (pubinfo->pubdelete)
3505 appendPQExpBufferStr(query, ", ");
3507 appendPQExpBufferStr(query, "delete");
3511 appendPQExpBufferStr(query, "');\n");
3513 ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3517 pubinfo->rolname, false,
3518 "PUBLICATION", SECTION_POST_DATA,
3519 query->data, delq->data, NULL,
3523 if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3524 dumpComment(fout, labelq->data,
3525 NULL, pubinfo->rolname,
3526 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3528 if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3529 dumpSecLabel(fout, labelq->data,
3530 NULL, pubinfo->rolname,
3531 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3533 destroyPQExpBuffer(delq);
3534 destroyPQExpBuffer(query);
3538 * getPublicationTables
3539 * get information about publication membership for dumpable tables.
3542 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3546 PublicationRelInfo *pubrinfo;
3554 if (fout->remoteVersion < 100000)
3557 query = createPQExpBuffer();
3559 for (i = 0; i < numTables; i++)
3561 TableInfo *tbinfo = &tblinfo[i];
3563 /* Only plain tables can be aded to publications. */
3564 if (tbinfo->relkind != RELKIND_RELATION)
3568 * Ignore publication membership of tables whose definitions are not
3571 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3575 write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3576 tbinfo->dobj.namespace->dobj.name,
3579 resetPQExpBuffer(query);
3581 /* Get the publication membership for the table. */
3582 appendPQExpBuffer(query,
3583 "SELECT pr.tableoid, pr.oid, p.pubname "
3584 "FROM pg_catalog.pg_publication_rel pr,"
3585 " pg_catalog.pg_publication p "
3586 "WHERE pr.prrelid = '%u'"
3587 " AND p.oid = pr.prpubid",
3588 tbinfo->dobj.catId.oid);
3589 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3591 ntups = PQntuples(res);
3596 * Table is not member of any publications. Clean up and return.
3602 i_tableoid = PQfnumber(res, "tableoid");
3603 i_oid = PQfnumber(res, "oid");
3604 i_pubname = PQfnumber(res, "pubname");
3606 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3608 for (j = 0; j < ntups; j++)
3610 pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3611 pubrinfo[j].dobj.catId.tableoid =
3612 atooid(PQgetvalue(res, j, i_tableoid));
3613 pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3614 AssignDumpId(&pubrinfo[j].dobj);
3615 pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3616 pubrinfo[j].dobj.name = tbinfo->dobj.name;
3617 pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3618 pubrinfo[j].pubtable = tbinfo;
3620 /* Decide whether we want to dump it */
3621 selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3625 destroyPQExpBuffer(query);
3629 * dumpPublicationTable
3630 * dump the definition of the given publication table mapping
3633 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3635 TableInfo *tbinfo = pubrinfo->pubtable;
3639 if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3642 tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3644 query = createPQExpBuffer();
3646 appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3647 fmtId(pubrinfo->pubname));
3648 appendPQExpBuffer(query, " %s;",
3649 fmtId(tbinfo->dobj.name));
3652 * There is no point in creating drop query as drop query as the drop is
3653 * done by table drop.
3655 ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3657 tbinfo->dobj.namespace->dobj.name,
3660 "PUBLICATION TABLE", SECTION_POST_DATA,
3661 query->data, "", NULL,
3666 destroyPQExpBuffer(query);
3670 * Is the currently connected user a superuser?
3673 is_superuser(Archive *fout)
3675 ArchiveHandle *AH = (ArchiveHandle *) fout;
3678 val = PQparameterStatus(AH->connection, "is_superuser");
3680 if (val && strcmp(val, "on") == 0)
3688 * get information about subscriptions
3691 getSubscriptions(Archive *fout)
3693 DumpOptions *dopt = fout->dopt;
3696 SubscriptionInfo *subinfo;
3703 int i_subsynccommit;
3704 int i_subpublications;
3708 if (dopt->no_subscriptions || fout->remoteVersion < 100000)
3711 if (!is_superuser(fout))
3715 res = ExecuteSqlQuery(fout,
3716 "SELECT count(*) FROM pg_subscription "
3717 "WHERE subdbid = (SELECT oid FROM pg_catalog.pg_database"
3718 " WHERE datname = current_database())",
3720 n = atoi(PQgetvalue(res, 0, 0));
3722 write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
3727 query = createPQExpBuffer();
3729 resetPQExpBuffer(query);
3731 /* Get the subscriptions in current database. */
3732 appendPQExpBuffer(query,
3733 "SELECT s.tableoid, s.oid, s.subname,"
3734 "(%s s.subowner) AS rolname, "
3735 " s.subconninfo, s.subslotname, s.subsynccommit, "
3736 " s.subpublications "
3737 "FROM pg_catalog.pg_subscription s "
3738 "WHERE s.subdbid = (SELECT oid FROM pg_catalog.pg_database"
3739 " WHERE datname = current_database())",
3741 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3743 ntups = PQntuples(res);
3745 i_tableoid = PQfnumber(res, "tableoid");
3746 i_oid = PQfnumber(res, "oid");
3747 i_subname = PQfnumber(res, "subname");
3748 i_rolname = PQfnumber(res, "rolname");
3749 i_subconninfo = PQfnumber(res, "subconninfo");
3750 i_subslotname = PQfnumber(res, "subslotname");
3751 i_subsynccommit = PQfnumber(res, "subsynccommit");
3752 i_subpublications = PQfnumber(res, "subpublications");
3754 subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
3756 for (i = 0; i < ntups; i++)
3758 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
3759 subinfo[i].dobj.catId.tableoid =
3760 atooid(PQgetvalue(res, i, i_tableoid));
3761 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3762 AssignDumpId(&subinfo[i].dobj);
3763 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
3764 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3765 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
3766 if (PQgetisnull(res, i, i_subslotname))
3767 subinfo[i].subslotname = NULL;
3769 subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
3770 subinfo[i].subsynccommit =
3771 pg_strdup(PQgetvalue(res, i, i_subsynccommit));
3772 subinfo[i].subpublications =
3773 pg_strdup(PQgetvalue(res, i, i_subpublications));
3775 if (strlen(subinfo[i].rolname) == 0)
3776 write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
3777 subinfo[i].dobj.name);
3779 /* Decide whether we want to dump it */
3780 selectDumpableObject(&(subinfo[i].dobj), fout);
3784 destroyPQExpBuffer(query);
3789 * dump the definition of the given subscription
3792 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
3797 PQExpBuffer publications;
3798 char **pubnames = NULL;
3802 if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3805 delq = createPQExpBuffer();
3806 query = createPQExpBuffer();
3807 labelq = createPQExpBuffer();
3809 appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
3810 fmtId(subinfo->dobj.name));
3812 appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
3813 fmtId(subinfo->dobj.name));
3814 appendStringLiteralAH(query, subinfo->subconninfo, fout);
3816 /* Build list of quoted publications and append them to query. */
3817 if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
3820 "WARNING: could not parse subpublications array\n");
3827 publications = createPQExpBuffer();
3828 for (i = 0; i < npubnames; i++)
3831 appendPQExpBufferStr(publications, ", ");
3833 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
3836 appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
3837 if (subinfo->subslotname)
3838 appendStringLiteralAH(query, subinfo->subslotname, fout);
3840 appendPQExpBufferStr(query, "NONE");
3842 if (strcmp(subinfo->subsynccommit, "off") != 0)
3843 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
3845 appendPQExpBufferStr(query, ");\n");
3847 appendPQExpBuffer(labelq, "SUBSCRIPTION %s", fmtId(subinfo->dobj.name));
3849 ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
3853 subinfo->rolname, false,
3854 "SUBSCRIPTION", SECTION_POST_DATA,
3855 query->data, delq->data, NULL,
3859 if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3860 dumpComment(fout, labelq->data,
3861 NULL, subinfo->rolname,
3862 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
3864 if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3865 dumpSecLabel(fout, labelq->data,
3866 NULL, subinfo->rolname,
3867 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
3869 destroyPQExpBuffer(publications);
3873 destroyPQExpBuffer(delq);
3874 destroyPQExpBuffer(query);
3878 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
3879 PQExpBuffer upgrade_buffer,
3882 PQExpBuffer upgrade_query = createPQExpBuffer();
3883 PGresult *upgrade_res;
3884 Oid pg_type_array_oid;
3886 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
3887 appendPQExpBuffer(upgrade_buffer,
3888 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
3891 /* we only support old >= 8.3 for binary upgrades */
3892 appendPQExpBuffer(upgrade_query,
3894 "FROM pg_catalog.pg_type "
3895 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
3898 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
3900 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
3902 if (OidIsValid(pg_type_array_oid))
3904 appendPQExpBufferStr(upgrade_buffer,
3905 "\n-- For binary upgrade, must preserve pg_type array oid\n");
3906 appendPQExpBuffer(upgrade_buffer,
3907 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
3911 PQclear(upgrade_res);
3912 destroyPQExpBuffer(upgrade_query);
3916 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
3917 PQExpBuffer upgrade_buffer,
3920 PQExpBuffer upgrade_query = createPQExpBuffer();
3921 PGresult *upgrade_res;
3923 bool toast_set = false;
3925 /* we only support old >= 8.3 for binary upgrades */
3926 appendPQExpBuffer(upgrade_query,
3927 "SELECT c.reltype AS crel, t.reltype AS trel "
3928 "FROM pg_catalog.pg_class c "
3929 "LEFT JOIN pg_catalog.pg_class t ON "
3930 " (c.reltoastrelid = t.oid) "
3931 "WHERE c.oid = '%u'::pg_catalog.oid;",
3934 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
3936 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
3938 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
3941 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
3943 /* Toast tables do not have pg_type array rows */
3944 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
3945 PQfnumber(upgrade_res, "trel")));
3947 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
3948 appendPQExpBuffer(upgrade_buffer,
3949 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
3955 PQclear(upgrade_res);
3956 destroyPQExpBuffer(upgrade_query);
3962 binary_upgrade_set_pg_class_oids(Archive *fout,
3963 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
3966 PQExpBuffer upgrade_query = createPQExpBuffer();
3967 PGresult *upgrade_res;
3968 Oid pg_class_reltoastrelid;
3969 Oid pg_index_indexrelid;
3971 appendPQExpBuffer(upgrade_query,
3972 "SELECT c.reltoastrelid, i.indexrelid "
3973 "FROM pg_catalog.pg_class c LEFT JOIN "
3974 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
3975 "WHERE c.oid = '%u'::pg_catalog.oid;",
3978 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
3980 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
3981 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
3983 appendPQExpBufferStr(upgrade_buffer,
3984 "\n-- For binary upgrade, must preserve pg_class oids\n");
3988 appendPQExpBuffer(upgrade_buffer,
3989 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
3991 /* only tables have toast tables, not indexes */
3992 if (OidIsValid(pg_class_reltoastrelid))
3995 * One complexity is that the table definition might not require
3996 * the creation of a TOAST table, and the TOAST table might have
3997 * been created long after table creation, when the table was
3998 * loaded with wide data. By setting the TOAST oid we force
3999 * creation of the TOAST heap and TOAST index by the backend so we
4000 * can cleanly copy the files during binary upgrade.
4003 appendPQExpBuffer(upgrade_buffer,
4004 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4005 pg_class_reltoastrelid);
4007 /* every toast table has an index */
4008 appendPQExpBuffer(upgrade_buffer,
4009 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4010 pg_index_indexrelid);
4014 appendPQExpBuffer(upgrade_buffer,
4015 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4018 appendPQExpBufferChar(upgrade_buffer, '\n');
4020 PQclear(upgrade_res);
4021 destroyPQExpBuffer(upgrade_query);
4025 * If the DumpableObject is a member of an extension, add a suitable
4026 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4029 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4030 DumpableObject *dobj,
4031 const char *objlabel)
4033 DumpableObject *extobj = NULL;
4036 if (!dobj->ext_member)
4040 * Find the parent extension. We could avoid this search if we wanted to
4041 * add a link field to DumpableObject, but the space costs of that would
4042 * be considerable. We assume that member objects could only have a
4043 * direct dependency on their own extension, not any others.
4045 for (i = 0; i < dobj->nDeps; i++)
4047 extobj = findObjectByDumpId(dobj->dependencies[i]);
4048 if (extobj && extobj->objType == DO_EXTENSION)
4053 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
4055 appendPQExpBufferStr(upgrade_buffer,
4056 "\n-- For binary upgrade, handle extension membership the hard way\n");
4057 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
4058 fmtId(extobj->name),
4064 * read all namespaces in the system catalogs and return them in the
4065 * NamespaceInfo* structure
4067 * numNamespaces is set to the number of namespaces read in
4070 getNamespaces(Archive *fout, int *numNamespaces)
4072 DumpOptions *dopt = fout->dopt;
4077 NamespaceInfo *nsinfo;
4087 query = createPQExpBuffer();
4089 /* Make sure we are in proper schema */
4090 selectSourceSchema(fout, "pg_catalog");
4093 * we fetch all namespaces including system ones, so that every object we
4094 * read in can be linked to a containing namespace.
4096 if (fout->remoteVersion >= 90600)
4098 PQExpBuffer acl_subquery = createPQExpBuffer();
4099 PQExpBuffer racl_subquery = createPQExpBuffer();
4100 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4101 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4103 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4104 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4105 dopt->binary_upgrade);
4107 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4108 "(%s nspowner) AS rolname, "
4111 "%s as initnspacl, "
4112 "%s as initrnspacl "
4113 "FROM pg_namespace n "
4114 "LEFT JOIN pg_init_privs pip "
4115 "ON (n.oid = pip.objoid "
4116 "AND pip.classoid = 'pg_namespace'::regclass "
4117 "AND pip.objsubid = 0",
4120 racl_subquery->data,
4121 init_acl_subquery->data,
4122 init_racl_subquery->data);
4125 * When we are doing a 'clean' run, we will be dropping and recreating
4126 * the 'public' schema (the only object which has that kind of
4127 * treatment in the backend and which has an entry in pg_init_privs)
4128 * and therefore we should not consider any initial privileges in
4129 * pg_init_privs in that case.
4131 * See pg_backup_archiver.c:_printTocEntry() for the details on why
4132 * the public schema is special in this regard.
4134 * Note that if the public schema is dropped and re-created, this is
4135 * essentially a no-op because the new public schema won't have an
4136 * entry in pg_init_privs anyway, as the entry will be removed when
4137 * the public schema is dropped.
4139 * Further, we have to handle the case where the public schema does
4142 if (dopt->outputClean)
4143 appendPQExpBuffer(query, " AND pip.objoid <> "
4144 "coalesce((select oid from pg_namespace "
4145 "where nspname = 'public'),0)");
4147 appendPQExpBuffer(query, ") ");
4149 destroyPQExpBuffer(acl_subquery);
4150 destroyPQExpBuffer(racl_subquery);
4151 destroyPQExpBuffer(init_acl_subquery);
4152 destroyPQExpBuffer(init_racl_subquery);
4155 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4156 "(%s nspowner) AS rolname, "
4157 "nspacl, NULL as rnspacl, "
4158 "NULL AS initnspacl, NULL as initrnspacl "
4159 "FROM pg_namespace",
4162 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4164 ntups = PQntuples(res);
4166 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4168 i_tableoid = PQfnumber(res, "tableoid");
4169 i_oid = PQfnumber(res, "oid");
4170 i_nspname = PQfnumber(res, "nspname");
4171 i_rolname = PQfnumber(res, "rolname");
4172 i_nspacl = PQfnumber(res, "nspacl");
4173 i_rnspacl = PQfnumber(res, "rnspacl");
4174 i_initnspacl = PQfnumber(res, "initnspacl");
4175 i_initrnspacl = PQfnumber(res, "initrnspacl");
4177 for (i = 0; i < ntups; i++)
4179 nsinfo[i].dobj.objType = DO_NAMESPACE;
4180 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4181 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4182 AssignDumpId(&nsinfo[i].dobj);
4183 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4184 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4185 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4186 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4187 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4188 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4190 /* Decide whether to dump this namespace */
4191 selectDumpableNamespace(&nsinfo[i], fout);
4194 * Do not try to dump ACL if the ACL is empty or the default.
4196 * This is useful because, for some schemas/objects, the only
4197 * component we are going to try and dump is the ACL and if we can
4198 * remove that then 'dump' goes to zero/false and we don't consider
4199 * this object for dumping at all later on.
4201 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4202 PQgetisnull(res, i, i_initnspacl) &&
4203 PQgetisnull(res, i, i_initrnspacl))
4204 nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4206 if (strlen(nsinfo[i].rolname) == 0)
4207 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4208 nsinfo[i].dobj.name);
4212 destroyPQExpBuffer(query);
4214 *numNamespaces = ntups;
4221 * given a namespace OID, look up the info read by getNamespaces
4223 static NamespaceInfo *
4224 findNamespace(Archive *fout, Oid nsoid)
4226 NamespaceInfo *nsinfo;
4228 nsinfo = findNamespaceByOid(nsoid);
4230 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4236 * read all extensions in the system catalogs and return them in the
4237 * ExtensionInfo* structure
4239 * numExtensions is set to the number of extensions read in
4242 getExtensions(Archive *fout, int *numExtensions)
4244 DumpOptions *dopt = fout->dopt;
4249 ExtensionInfo *extinfo;
4254 int i_extrelocatable;
4260 * Before 9.1, there are no extensions.
4262 if (fout->remoteVersion < 90100)
4268 query = createPQExpBuffer();
4270 /* Make sure we are in proper schema */
4271 selectSourceSchema(fout, "pg_catalog");
4273 appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4274 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4275 "FROM pg_extension x "
4276 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4278 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4280 ntups = PQntuples(res);
4282 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4284 i_tableoid = PQfnumber(res, "tableoid");
4285 i_oid = PQfnumber(res, "oid");
4286 i_extname = PQfnumber(res, "extname");
4287 i_nspname = PQfnumber(res, "nspname");
4288 i_extrelocatable = PQfnumber(res, "extrelocatable");
4289 i_extversion = PQfnumber(res, "extversion");
4290 i_extconfig = PQfnumber(res, "extconfig");
4291 i_extcondition = PQfnumber(res, "extcondition");
4293 for (i = 0; i < ntups; i++)
4295 extinfo[i].dobj.objType = DO_EXTENSION;
4296 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4297 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4298 AssignDumpId(&extinfo[i].dobj);
4299 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4300 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4301 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4302 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4303 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4304 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4306 /* Decide whether we want to dump it */
4307 selectDumpableExtension(&(extinfo[i]), dopt);
4311 destroyPQExpBuffer(query);
4313 *numExtensions = ntups;
4320 * read all types in the system catalogs and return them in the
4321 * TypeInfo* structure
4323 * numTypes is set to the number of types read in
4325 * NB: this must run after getFuncs() because we assume we can do
4329 getTypes(Archive *fout, int *numTypes)
4331 DumpOptions *dopt = fout->dopt;
4335 PQExpBuffer query = createPQExpBuffer();
4337 ShellTypeInfo *stinfo;
4355 * we include even the built-in types because those may be used as array
4356 * elements by user-defined types
4358 * we filter out the built-in types when we dump out the types
4360 * same approach for undefined (shell) types and array types
4362 * Note: as of 8.3 we can reliably detect whether a type is an
4363 * auto-generated array type by checking the element type's typarray.
4364 * (Before that the test is capable of generating false positives.) We
4365 * still check for name beginning with '_', though, so as to avoid the
4366 * cost of the subselect probe for all standard types. This would have to
4367 * be revisited if the backend ever allows renaming of array types.
4370 /* Make sure we are in proper schema */
4371 selectSourceSchema(fout, "pg_catalog");
4373 if (fout->remoteVersion >= 90600)
4375 PQExpBuffer acl_subquery = createPQExpBuffer();
4376 PQExpBuffer racl_subquery = createPQExpBuffer();
4377 PQExpBuffer initacl_subquery = createPQExpBuffer();
4378 PQExpBuffer initracl_subquery = createPQExpBuffer();
4380 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4381 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4382 dopt->binary_upgrade);
4384 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4388 "%s AS inittypacl, "
4389 "%s AS initrtypacl, "
4390 "(%s t.typowner) AS rolname, "
4391 "t.typelem, t.typrelid, "
4392 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4393 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4394 "t.typtype, t.typisdefined, "
4395 "t.typname[0] = '_' AND t.typelem != 0 AND "
4396 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4398 "LEFT JOIN pg_init_privs pip ON "
4399 "(t.oid = pip.objoid "
4400 "AND pip.classoid = 'pg_type'::regclass "
4401 "AND pip.objsubid = 0) ",
4403 racl_subquery->data,
4404 initacl_subquery->data,
4405 initracl_subquery->data,
4408 destroyPQExpBuffer(acl_subquery);
4409 destroyPQExpBuffer(racl_subquery);
4410 destroyPQExpBuffer(initacl_subquery);
4411 destroyPQExpBuffer(initracl_subquery);
4413 else if (fout->remoteVersion >= 90200)
4415 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4416 "typnamespace, typacl, NULL as rtypacl, "
4417 "NULL AS inittypacl, NULL AS initrtypacl, "
4418 "(%s typowner) AS rolname, "
4419 "typelem, typrelid, "
4420 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4421 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4422 "typtype, typisdefined, "
4423 "typname[0] = '_' AND typelem != 0 AND "
4424 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4428 else if (fout->remoteVersion >= 80300)
4430 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4431 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4432 "NULL AS inittypacl, NULL AS initrtypacl, "
4433 "(%s typowner) AS rolname, "
4434 "typelem, typrelid, "
4435 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4436 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4437 "typtype, typisdefined, "
4438 "typname[0] = '_' AND typelem != 0 AND "
4439 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4445 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4446 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4447 "NULL AS inittypacl, NULL AS initrtypacl, "
4448 "(%s typowner) AS rolname, "
4449 "typelem, typrelid, "
4450 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4451 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4452 "typtype, typisdefined, "
4453 "typname[0] = '_' AND typelem != 0 AS isarray "
4458 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4460 ntups = PQntuples(res);
4462 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4464 i_tableoid = PQfnumber(res, "tableoid");
4465 i_oid = PQfnumber(res, "oid");
4466 i_typname = PQfnumber(res, "typname");
4467 i_typnamespace = PQfnumber(res, "typnamespace");
4468 i_typacl = PQfnumber(res, "typacl");
4469 i_rtypacl = PQfnumber(res, "rtypacl");
4470 i_inittypacl = PQfnumber(res, "inittypacl");
4471 i_initrtypacl = PQfnumber(res, "initrtypacl");
4472 i_rolname = PQfnumber(res, "rolname");
4473 i_typelem = PQfnumber(res, "typelem");
4474 i_typrelid = PQfnumber(res, "typrelid");
4475 i_typrelkind = PQfnumber(res, "typrelkind");
4476 i_typtype = PQfnumber(res, "typtype");
4477 i_typisdefined = PQfnumber(res, "typisdefined");
4478 i_isarray = PQfnumber(res, "isarray");
4480 for (i = 0; i < ntups; i++)
4482 tyinfo[i].dobj.objType = DO_TYPE;
4483 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4484 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4485 AssignDumpId(&tyinfo[i].dobj);
4486 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4487 tyinfo[i].dobj.namespace =
4489 atooid(PQgetvalue(res, i, i_typnamespace)));
4490 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4491 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4492 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4493 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4494 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4495 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4496 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4497 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4498 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4499 tyinfo[i].shellType = NULL;
4501 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4502 tyinfo[i].isDefined = true;
4504 tyinfo[i].isDefined = false;
4506 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4507 tyinfo[i].isArray = true;
4509 tyinfo[i].isArray = false;
4511 /* Decide whether we want to dump it */
4512 selectDumpableType(&tyinfo[i], fout);
4514 /* Do not try to dump ACL if no ACL exists. */
4515 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4516 PQgetisnull(res, i, i_inittypacl) &&
4517 PQgetisnull(res, i, i_initrtypacl))
4518 tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4521 * If it's a domain, fetch info about its constraints, if any
4523 tyinfo[i].nDomChecks = 0;
4524 tyinfo[i].domChecks = NULL;
4525 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4526 tyinfo[i].typtype == TYPTYPE_DOMAIN)
4527 getDomainConstraints(fout, &(tyinfo[i]));
4530 * If it's a base type, make a DumpableObject representing a shell
4531 * definition of the type. We will need to dump that ahead of the I/O
4532 * functions for the type. Similarly, range types need a shell
4533 * definition in case they have a canonicalize function.
4535 * Note: the shell type doesn't have a catId. You might think it
4536 * should copy the base type's catId, but then it might capture the
4537 * pg_depend entries for the type, which we don't want.
4539 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4540 (tyinfo[i].typtype == TYPTYPE_BASE ||
4541 tyinfo[i].typtype == TYPTYPE_RANGE))
4543 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4544 stinfo->dobj.objType = DO_SHELL_TYPE;
4545 stinfo->dobj.catId = nilCatalogId;
4546 AssignDumpId(&stinfo->dobj);
4547 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4548 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4549 stinfo->baseType = &(tyinfo[i]);
4550 tyinfo[i].shellType = stinfo;
4553 * Initially mark the shell type as not to be dumped. We'll only
4554 * dump it if the I/O or canonicalize functions need to be dumped;
4555 * this is taken care of while sorting dependencies.
4557 stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4560 if (strlen(tyinfo[i].rolname) == 0)
4561 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4562 tyinfo[i].dobj.name);
4569 destroyPQExpBuffer(query);
4576 * read all operators in the system catalogs and return them in the
4577 * OprInfo* structure
4579 * numOprs is set to the number of operators read in
4582 getOperators(Archive *fout, int *numOprs)
4587 PQExpBuffer query = createPQExpBuffer();
4598 * find all operators, including builtin operators; we filter out
4599 * system-defined operators at dump-out time.
4602 /* Make sure we are in proper schema */
4603 selectSourceSchema(fout, "pg_catalog");
4605 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4607 "(%s oprowner) AS rolname, "
4609 "oprcode::oid AS oprcode "
4613 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4615 ntups = PQntuples(res);
4618 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4620 i_tableoid = PQfnumber(res, "tableoid");
4621 i_oid = PQfnumber(res, "oid");
4622 i_oprname = PQfnumber(res, "oprname");
4623 i_oprnamespace = PQfnumber(res, "oprnamespace");
4624 i_rolname = PQfnumber(res, "rolname");
4625 i_oprkind = PQfnumber(res, "oprkind");
4626 i_oprcode = PQfnumber(res, "oprcode");
4628 for (i = 0; i < ntups; i++)
4630 oprinfo[i].dobj.objType = DO_OPERATOR;
4631 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4632 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4633 AssignDumpId(&oprinfo[i].dobj);
4634 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4635 oprinfo[i].dobj.namespace =
4637 atooid(PQgetvalue(res, i, i_oprnamespace)));
4638 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4639 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4640 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4642 /* Decide whether we want to dump it */
4643 selectDumpableObject(&(oprinfo[i].dobj), fout);
4645 /* Operators do not currently have ACLs. */
4646 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4648 if (strlen(oprinfo[i].rolname) == 0)
4649 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4650 oprinfo[i].dobj.name);
4655 destroyPQExpBuffer(query);
4662 * read all collations in the system catalogs and return them in the
4663 * CollInfo* structure
4665 * numCollations is set to the number of collations read in
4668 getCollations(Archive *fout, int *numCollations)
4678 int i_collnamespace;
4681 /* Collations didn't exist pre-9.1 */
4682 if (fout->remoteVersion < 90100)
4688 query = createPQExpBuffer();
4691 * find all collations, including builtin collations; we filter out
4692 * system-defined collations at dump-out time.
4695 /* Make sure we are in proper schema */
4696 selectSourceSchema(fout, "pg_catalog");
4698 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
4700 "(%s collowner) AS rolname "
4701 "FROM pg_collation",
4704 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4706 ntups = PQntuples(res);
4707 *numCollations = ntups;
4709 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
4711 i_tableoid = PQfnumber(res, "tableoid");
4712 i_oid = PQfnumber(res, "oid");
4713 i_collname = PQfnumber(res, "collname");
4714 i_collnamespace = PQfnumber(res, "collnamespace");
4715 i_rolname = PQfnumber(res, "rolname");
4717 for (i = 0; i < ntups; i++)
4719 collinfo[i].dobj.objType = DO_COLLATION;
4720 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4721 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4722 AssignDumpId(&collinfo[i].dobj);
4723 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
4724 collinfo[i].dobj.namespace =
4726 atooid(PQgetvalue(res, i, i_collnamespace)));
4727 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4729 /* Decide whether we want to dump it */
4730 selectDumpableObject(&(collinfo[i].dobj), fout);
4732 /* Collations do not currently have ACLs. */
4733 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4738 destroyPQExpBuffer(query);
4745 * read all conversions in the system catalogs and return them in the
4746 * ConvInfo* structure
4748 * numConversions is set to the number of conversions read in
4751 getConversions(Archive *fout, int *numConversions)
4764 query = createPQExpBuffer();
4767 * find all conversions, including builtin conversions; we filter out
4768 * system-defined conversions at dump-out time.
4771 /* Make sure we are in proper schema */
4772 selectSourceSchema(fout, "pg_catalog");
4774 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4776 "(%s conowner) AS rolname "
4777 "FROM pg_conversion",
4780 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4782 ntups = PQntuples(res);
4783 *numConversions = ntups;
4785 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
4787 i_tableoid = PQfnumber(res, "tableoid");
4788 i_oid = PQfnumber(res, "oid");
4789 i_conname = PQfnumber(res, "conname");
4790 i_connamespace = PQfnumber(res, "connamespace");
4791 i_rolname = PQfnumber(res, "rolname");
4793 for (i = 0; i < ntups; i++)
4795 convinfo[i].dobj.objType = DO_CONVERSION;
4796 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4797 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4798 AssignDumpId(&convinfo[i].dobj);
4799 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4800 convinfo[i].dobj.namespace =
4802 atooid(PQgetvalue(res, i, i_connamespace)));
4803 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4805 /* Decide whether we want to dump it */
4806 selectDumpableObject(&(convinfo[i].dobj), fout);
4808 /* Conversions do not currently have ACLs. */
4809 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4814 destroyPQExpBuffer(query);
4821 * read all user-defined access methods in the system catalogs and return
4822 * them in the AccessMethodInfo* structure
4824 * numAccessMethods is set to the number of access methods read in
4827 getAccessMethods(Archive *fout, int *numAccessMethods)
4833 AccessMethodInfo *aminfo;
4840 /* Before 9.6, there are no user-defined access methods */
4841 if (fout->remoteVersion < 90600)
4843 *numAccessMethods = 0;
4847 query = createPQExpBuffer();
4849 /* Make sure we are in proper schema */
4850 selectSourceSchema(fout, "pg_catalog");
4852 /* Select all access methods from pg_am table */
4853 appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
4854 "amhandler::pg_catalog.regproc AS amhandler "
4857 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4859 ntups = PQntuples(res);
4860 *numAccessMethods = ntups;
4862 aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
4864 i_tableoid = PQfnumber(res, "tableoid");
4865 i_oid = PQfnumber(res, "oid");
4866 i_amname = PQfnumber(res, "amname");
4867 i_amhandler = PQfnumber(res, "amhandler");
4868 i_amtype = PQfnumber(res, "amtype");
4870 for (i = 0; i < ntups; i++)
4872 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
4873 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4874 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4875 AssignDumpId(&aminfo[i].dobj);
4876 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
4877 aminfo[i].dobj.namespace = NULL;
4878 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
4879 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
4881 /* Decide whether we want to dump it */
4882 selectDumpableAccessMethod(&(aminfo[i]), fout);
4884 /* Access methods do not currently have ACLs. */
4885 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4890 destroyPQExpBuffer(query);
4898 * read all opclasses in the system catalogs and return them in the
4899 * OpclassInfo* structure
4901 * numOpclasses is set to the number of opclasses read in
4904 getOpclasses(Archive *fout, int *numOpclasses)
4909 PQExpBuffer query = createPQExpBuffer();
4910 OpclassInfo *opcinfo;
4918 * find all opclasses, including builtin opclasses; we filter out
4919 * system-defined opclasses at dump-out time.
4922 /* Make sure we are in proper schema */
4923 selectSourceSchema(fout, "pg_catalog");
4925 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
4927 "(%s opcowner) AS rolname "
4931 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4933 ntups = PQntuples(res);
4934 *numOpclasses = ntups;
4936 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
4938 i_tableoid = PQfnumber(res, "tableoid");
4939 i_oid = PQfnumber(res, "oid");
4940 i_opcname = PQfnumber(res, "opcname");
4941 i_opcnamespace = PQfnumber(res, "opcnamespace");
4942 i_rolname = PQfnumber(res, "rolname");
4944 for (i = 0; i < ntups; i++)
4946 opcinfo[i].dobj.objType = DO_OPCLASS;
4947 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4948 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4949 AssignDumpId(&opcinfo[i].dobj);
4950 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
4951 opcinfo[i].dobj.namespace =
4953 atooid(PQgetvalue(res, i, i_opcnamespace)));
4954 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4956 /* Decide whether we want to dump it */
4957 selectDumpableObject(&(opcinfo[i].dobj), fout);
4959 /* Op Classes do not currently have ACLs. */
4960 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4962 if (strlen(opcinfo[i].rolname) == 0)
4963 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
4964 opcinfo[i].dobj.name);
4969 destroyPQExpBuffer(query);
4976 * read all opfamilies in the system catalogs and return them in the
4977 * OpfamilyInfo* structure
4979 * numOpfamilies is set to the number of opfamilies read in
4982 getOpfamilies(Archive *fout, int *numOpfamilies)
4988 OpfamilyInfo *opfinfo;
4995 /* Before 8.3, there is no separate concept of opfamilies */
4996 if (fout->remoteVersion < 80300)
5002 query = createPQExpBuffer();
5005 * find all opfamilies, including builtin opfamilies; we filter out
5006 * system-defined opfamilies at dump-out time.
5009 /* Make sure we are in proper schema */
5010 selectSourceSchema(fout, "pg_catalog");
5012 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5014 "(%s opfowner) AS rolname "
5018 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5020 ntups = PQntuples(res);
5021 *numOpfamilies = ntups;
5023 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5025 i_tableoid = PQfnumber(res, "tableoid");
5026 i_oid = PQfnumber(res, "oid");
5027 i_opfname = PQfnumber(res, "opfname");
5028 i_opfnamespace = PQfnumber(res, "opfnamespace");
5029 i_rolname = PQfnumber(res, "rolname");
5031 for (i = 0; i < ntups; i++)
5033 opfinfo[i].dobj.objType = DO_OPFAMILY;
5034 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5035 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5036 AssignDumpId(&opfinfo[i].dobj);
5037 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5038 opfinfo[i].dobj.namespace =
5040 atooid(PQgetvalue(res, i, i_opfnamespace)));
5041 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5043 /* Decide whether we want to dump it */
5044 selectDumpableObject(&(opfinfo[i].dobj), fout);
5046 /* Extensions do not currently have ACLs. */
5047 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5049 if (strlen(opfinfo[i].rolname) == 0)
5050 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5051 opfinfo[i].dobj.name);
5056 destroyPQExpBuffer(query);
5063 * read all the user-defined aggregates in the system catalogs and
5064 * return them in the AggInfo* structure
5066 * numAggs is set to the number of aggregates read in
5069 getAggregates(Archive *fout, int *numAggs)
5071 DumpOptions *dopt = fout->dopt;
5075 PQExpBuffer query = createPQExpBuffer();
5089 /* Make sure we are in proper schema */
5090 selectSourceSchema(fout, "pg_catalog");
5093 * Find all interesting aggregates. See comment in getFuncs() for the
5094 * rationale behind the filtering logic.
5096 if (fout->remoteVersion >= 90600)
5098 PQExpBuffer acl_subquery = createPQExpBuffer();
5099 PQExpBuffer racl_subquery = createPQExpBuffer();
5100 PQExpBuffer initacl_subquery = createPQExpBuffer();
5101 PQExpBuffer initracl_subquery = createPQExpBuffer();
5103 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5104 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5105 dopt->binary_upgrade);
5107 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5108 "p.proname AS aggname, "
5109 "p.pronamespace AS aggnamespace, "
5110 "p.pronargs, p.proargtypes, "
5111 "(%s p.proowner) AS rolname, "
5114 "%s AS initaggacl, "
5115 "%s AS initraggacl "
5117 "LEFT JOIN pg_init_privs pip ON "
5118 "(p.oid = pip.objoid "
5119 "AND pip.classoid = 'pg_proc'::regclass "
5120 "AND pip.objsubid = 0) "
5121 "WHERE p.proisagg AND ("
5122 "p.pronamespace != "
5123 "(SELECT oid FROM pg_namespace "
5124 "WHERE nspname = 'pg_catalog') OR "
5125 "p.proacl IS DISTINCT FROM pip.initprivs",
5128 racl_subquery->data,
5129 initacl_subquery->data,
5130 initracl_subquery->data);
5131 if (dopt->binary_upgrade)
5132 appendPQExpBufferStr(query,
5133 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5134 "classid = 'pg_proc'::regclass AND "
5135 "objid = p.oid AND "
5136 "refclassid = 'pg_extension'::regclass AND "
5138 appendPQExpBufferChar(query, ')');
5140 destroyPQExpBuffer(acl_subquery);
5141 destroyPQExpBuffer(racl_subquery);
5142 destroyPQExpBuffer(initacl_subquery);
5143 destroyPQExpBuffer(initracl_subquery);
5145 else if (fout->remoteVersion >= 80200)
5147 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5148 "pronamespace AS aggnamespace, "
5149 "pronargs, proargtypes, "
5150 "(%s proowner) AS rolname, "
5151 "proacl AS aggacl, "
5153 "NULL AS initaggacl, NULL AS initraggacl "
5155 "WHERE proisagg AND ("
5157 "(SELECT oid FROM pg_namespace "
5158 "WHERE nspname = 'pg_catalog')",
5160 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5161 appendPQExpBufferStr(query,
5162 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5163 "classid = 'pg_proc'::regclass AND "
5164 "objid = p.oid AND "
5165 "refclassid = 'pg_extension'::regclass AND "
5167 appendPQExpBufferChar(query, ')');
5171 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5172 "pronamespace AS aggnamespace, "
5173 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5175 "(%s proowner) AS rolname, "
5176 "proacl AS aggacl, "
5178 "NULL AS initaggacl, NULL AS initraggacl "
5181 "AND pronamespace != "
5182 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5186 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5188 ntups = PQntuples(res);
5191 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5193 i_tableoid = PQfnumber(res, "tableoid");
5194 i_oid = PQfnumber(res, "oid");
5195 i_aggname = PQfnumber(res, "aggname");
5196 i_aggnamespace = PQfnumber(res, "aggnamespace");
5197 i_pronargs = PQfnumber(res, "pronargs");
5198 i_proargtypes = PQfnumber(res, "proargtypes");
5199 i_rolname = PQfnumber(res, "rolname");
5200 i_aggacl = PQfnumber(res, "aggacl");
5201 i_raggacl = PQfnumber(res, "raggacl");
5202 i_initaggacl = PQfnumber(res, "initaggacl");
5203 i_initraggacl = PQfnumber(res, "initraggacl");
5205 for (i = 0; i < ntups; i++)
5207 agginfo[i].aggfn.dobj.objType = DO_AGG;
5208 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5209 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5210 AssignDumpId(&agginfo[i].aggfn.dobj);
5211 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5212 agginfo[i].aggfn.dobj.namespace =
5214 atooid(PQgetvalue(res, i, i_aggnamespace)));
5215 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5216 if (strlen(agginfo[i].aggfn.rolname) == 0)
5217 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5218 agginfo[i].aggfn.dobj.name);
5219 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5220 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
5221 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5222 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5223 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5224 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5225 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5226 if (agginfo[i].aggfn.nargs == 0)
5227 agginfo[i].aggfn.argtypes = NULL;
5230 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5231 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5232 agginfo[i].aggfn.argtypes,
5233 agginfo[i].aggfn.nargs);
5236 /* Decide whether we want to dump it */
5237 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5239 /* Do not try to dump ACL if no ACL exists. */
5240 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5241 PQgetisnull(res, i, i_initaggacl) &&
5242 PQgetisnull(res, i, i_initraggacl))
5243 agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5248 destroyPQExpBuffer(query);
5255 * read all the user-defined functions in the system catalogs and
5256 * return them in the FuncInfo* structure
5258 * numFuncs is set to the number of functions read in
5261 getFuncs(Archive *fout, int *numFuncs)
5263 DumpOptions *dopt = fout->dopt;
5267 PQExpBuffer query = createPQExpBuffer();
5283 /* Make sure we are in proper schema */
5284 selectSourceSchema(fout, "pg_catalog");
5287 * Find all interesting functions. This is a bit complicated:
5289 * 1. Always exclude aggregates; those are handled elsewhere.
5291 * 2. Always exclude functions that are internally dependent on something
5292 * else, since presumably those will be created as a result of creating
5293 * the something else. This currently acts only to suppress constructor
5294 * functions for range types (so we only need it in 9.2 and up). Note
5295 * this is OK only because the constructors don't have any dependencies
5296 * the range type doesn't have; otherwise we might not get creation
5299 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5300 * they're members of extensions and we are in binary-upgrade mode then
5301 * include them, since we want to dump extension members individually in
5302 * that mode. Also, if they are used by casts or transforms then we need
5303 * to gather the information about them, though they won't be dumped if
5304 * they are built-in. Also, in 9.6 and up, include functions in
5305 * pg_catalog if they have an ACL different from what's shown in
5308 if (fout->remoteVersion >= 90600)
5310 PQExpBuffer acl_subquery = createPQExpBuffer();
5311 PQExpBuffer racl_subquery = createPQExpBuffer();
5312 PQExpBuffer initacl_subquery = createPQExpBuffer();
5313 PQExpBuffer initracl_subquery = createPQExpBuffer();
5315 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5316 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5317 dopt->binary_upgrade);
5319 appendPQExpBuffer(query,
5320 "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5321 "p.pronargs, p.proargtypes, p.prorettype, "
5324 "%s AS initproacl, "
5325 "%s AS initrproacl, "
5327 "(%s p.proowner) AS rolname "
5329 "LEFT JOIN pg_init_privs pip ON "
5330 "(p.oid = pip.objoid "
5331 "AND pip.classoid = 'pg_proc'::regclass "
5332 "AND pip.objsubid = 0) "
5333 "WHERE NOT proisagg"
5334 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5335 "WHERE classid = 'pg_proc'::regclass AND "
5336 "objid = p.oid AND deptype = 'i')"
5338 "\n pronamespace != "
5339 "(SELECT oid FROM pg_namespace "
5340 "WHERE nspname = 'pg_catalog')"
5341 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5342 "\n WHERE pg_cast.oid > %u "
5343 "\n AND p.oid = pg_cast.castfunc)"
5344 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5345 "\n WHERE pg_transform.oid > %u AND "
5346 "\n (p.oid = pg_transform.trffromsql"
5347 "\n OR p.oid = pg_transform.trftosql))",
5349 racl_subquery->data,
5350 initacl_subquery->data,
5351 initracl_subquery->data,
5354 g_last_builtin_oid);
5355 if (dopt->binary_upgrade)
5356 appendPQExpBufferStr(query,
5357 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5358 "classid = 'pg_proc'::regclass AND "
5359 "objid = p.oid AND "
5360 "refclassid = 'pg_extension'::regclass AND "
5362 appendPQExpBufferStr(query,
5363 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5364 appendPQExpBufferChar(query, ')');
5366 destroyPQExpBuffer(acl_subquery);
5367 destroyPQExpBuffer(racl_subquery);
5368 destroyPQExpBuffer(initacl_subquery);
5369 destroyPQExpBuffer(initracl_subquery);
5373 appendPQExpBuffer(query,
5374 "SELECT tableoid, oid, proname, prolang, "
5375 "pronargs, proargtypes, prorettype, proacl, "
5377 "NULL as initproacl, NULL AS initrproacl, "
5379 "(%s proowner) AS rolname "
5381 "WHERE NOT proisagg",
5383 if (fout->remoteVersion >= 90200)
5384 appendPQExpBufferStr(query,
5385 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5386 "WHERE classid = 'pg_proc'::regclass AND "
5387 "objid = p.oid AND deptype = 'i')");
5388 appendPQExpBuffer(query,
5390 "\n pronamespace != "
5391 "(SELECT oid FROM pg_namespace "
5392 "WHERE nspname = 'pg_catalog')"
5393 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5394 "\n WHERE pg_cast.oid > '%u'::oid"
5395 "\n AND p.oid = pg_cast.castfunc)",
5396 g_last_builtin_oid);
5398 if (fout->remoteVersion >= 90500)
5399 appendPQExpBuffer(query,
5400 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5401 "\n WHERE pg_transform.oid > '%u'::oid"
5402 "\n AND (p.oid = pg_transform.trffromsql"
5403 "\n OR p.oid = pg_transform.trftosql))",
5404 g_last_builtin_oid);
5406 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5407 appendPQExpBufferStr(query,
5408 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5409 "classid = 'pg_proc'::regclass AND "
5410 "objid = p.oid AND "
5411 "refclassid = 'pg_extension'::regclass AND "
5413 appendPQExpBufferChar(query, ')');
5416 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5418 ntups = PQntuples(res);
5422 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5424 i_tableoid = PQfnumber(res, "tableoid");
5425 i_oid = PQfnumber(res, "oid");
5426 i_proname = PQfnumber(res, "proname");
5427 i_pronamespace = PQfnumber(res, "pronamespace");
5428 i_rolname = PQfnumber(res, "rolname");
5429 i_prolang = PQfnumber(res, "prolang");
5430 i_pronargs = PQfnumber(res, "pronargs");
5431 i_proargtypes = PQfnumber(res, "proargtypes");
5432 i_prorettype = PQfnumber(res, "prorettype");
5433 i_proacl = PQfnumber(res, "proacl");
5434 i_rproacl = PQfnumber(res, "rproacl");
5435 i_initproacl = PQfnumber(res, "initproacl");
5436 i_initrproacl = PQfnumber(res, "initrproacl");
5438 for (i = 0; i < ntups; i++)
5440 finfo[i].dobj.objType = DO_FUNC;
5441 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5442 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5443 AssignDumpId(&finfo[i].dobj);
5444 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5445 finfo[i].dobj.namespace =
5447 atooid(PQgetvalue(res, i, i_pronamespace)));
5448 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5449 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5450 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5451 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5452 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5453 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5454 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5455 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5456 if (finfo[i].nargs == 0)
5457 finfo[i].argtypes = NULL;
5460 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5461 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5462 finfo[i].argtypes, finfo[i].nargs);
5465 /* Decide whether we want to dump it */
5466 selectDumpableObject(&(finfo[i].dobj), fout);
5468 /* Do not try to dump ACL if no ACL exists. */
5469 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5470 PQgetisnull(res, i, i_initproacl) &&
5471 PQgetisnull(res, i, i_initrproacl))
5472 finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5474 if (strlen(finfo[i].rolname) == 0)
5476 "WARNING: owner of function \"%s\" appears to be invalid\n",
5477 finfo[i].dobj.name);
5482 destroyPQExpBuffer(query);
5489 * read all the tables (no indexes)
5490 * in the system catalogs return them in the TableInfo* structure
5492 * numTables is set to the number of tables read in
5495 getTables(Archive *fout, int *numTables)
5497 DumpOptions *dopt = fout->dopt;
5501 PQExpBuffer query = createPQExpBuffer();
5514 int i_relhastriggers;
5518 int i_relforcerowsec;
5523 int i_toastfrozenxid;
5525 int i_relpersistence;
5526 int i_relispopulated;
5530 int i_reltablespace;
5533 int i_toastreloptions;
5536 int i_is_identity_sequence;
5542 /* Make sure we are in proper schema */
5543 selectSourceSchema(fout, "pg_catalog");
5546 * Find all the tables and table-like objects.
5548 * We include system catalogs, so that we can work if a user table is
5549 * defined to inherit from a system catalog (pretty weird, but...)
5551 * We ignore relations that are not ordinary tables, sequences, views,
5552 * materialized views, composite types, or foreign tables.
5554 * Composite-type table entries won't be dumped as such, but we have to
5555 * make a DumpableObject for them so that we can track dependencies of the
5556 * composite type (pg_depend entries for columns of the composite type
5557 * link to the pg_class entry not the pg_type entry).
5559 * Note: in this phase we should collect only a minimal amount of
5560 * information about each table, basically just enough to decide if it is
5561 * interesting. We must fetch all tables in this phase because otherwise
5562 * we cannot correctly identify inherited columns, owned sequences, etc.
5565 if (fout->remoteVersion >= 90600)
5567 char *partkeydef = "NULL";
5568 char *ispartition = "false";
5569 char *partbound = "NULL";
5571 PQExpBuffer acl_subquery = createPQExpBuffer();
5572 PQExpBuffer racl_subquery = createPQExpBuffer();
5573 PQExpBuffer initacl_subquery = createPQExpBuffer();
5574 PQExpBuffer initracl_subquery = createPQExpBuffer();
5576 PQExpBuffer attacl_subquery = createPQExpBuffer();
5577 PQExpBuffer attracl_subquery = createPQExpBuffer();
5578 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5579 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5582 * Collect the information about any partitioned tables, which were
5586 if (fout->remoteVersion >= 100000)
5588 partkeydef = "pg_get_partkeydef(c.oid)";
5589 ispartition = "c.relispartition";
5590 partbound = "pg_get_expr(c.relpartbound, c.oid)";
5594 * Left join to pick up dependency info linking sequences to their
5595 * owning column, if any (note this dependency is AUTO as of 8.2)
5597 * Left join to detect if any privileges are still as-set-at-init, in
5598 * which case we won't dump out ACL commands for those.
5601 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5602 initracl_subquery, "c.relacl", "c.relowner",
5603 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5604 " THEN 's' ELSE 'r' END::\"char\"",
5605 dopt->binary_upgrade);
5607 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5608 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5609 dopt->binary_upgrade);
5611 appendPQExpBuffer(query,
5612 "SELECT c.tableoid, c.oid, c.relname, "
5613 "%s AS relacl, %s as rrelacl, "
5614 "%s AS initrelacl, %s as initrrelacl, "
5615 "c.relkind, c.relnamespace, "
5616 "(%s c.relowner) AS rolname, "
5617 "c.relchecks, c.relhastriggers, "
5618 "c.relhasindex, c.relhasrules, c.relhasoids, "
5619 "c.relrowsecurity, c.relforcerowsecurity, "
5620 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5621 "tc.relfrozenxid AS tfrozenxid, "
5622 "tc.relminmxid AS tminmxid, "
5623 "c.relpersistence, c.relispopulated, "
5624 "c.relreplident, c.relpages, "
5625 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5626 "d.refobjid AS owning_tab, "
5627 "d.refobjsubid AS owning_col, "
5628 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5629 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5630 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5631 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5632 "tc.reloptions AS toast_reloptions, "
5633 "c.relkind = '%c' AND EXISTS (SELECT 1 FROM pg_depend WHERE classid = 'pg_class'::regclass AND objid = c.oid AND objsubid = 0 AND refclassid = 'pg_class'::regclass AND deptype = 'i') AS is_identity_sequence, "
5634 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5635 "(c.oid = pip.objoid "
5636 "AND pip.classoid = 'pg_class'::regclass "
5637 "AND pip.objsubid = at.attnum)"
5638 "WHERE at.attrelid = c.oid AND ("
5640 "OR %s IS NOT NULL "
5641 "OR %s IS NOT NULL "
5645 "%s AS partkeydef, "
5646 "%s AS ispartition, "
5649 "LEFT JOIN pg_depend d ON "
5650 "(c.relkind = '%c' AND "
5651 "d.classid = c.tableoid AND d.objid = c.oid AND "
5652 "d.objsubid = 0 AND "
5653 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5654 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5655 "LEFT JOIN pg_init_privs pip ON "
5656 "(c.oid = pip.objoid "
5657 "AND pip.classoid = 'pg_class'::regclass "
5658 "AND pip.objsubid = 0) "
5659 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5662 racl_subquery->data,
5663 initacl_subquery->data,
5664 initracl_subquery->data,
5667 attacl_subquery->data,
5668 attracl_subquery->data,
5669 attinitacl_subquery->data,
5670 attinitracl_subquery->data,
5675 RELKIND_RELATION, RELKIND_SEQUENCE,
5676 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5677 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5678 RELKIND_PARTITIONED_TABLE);
5680 destroyPQExpBuffer(acl_subquery);
5681 destroyPQExpBuffer(racl_subquery);
5682 destroyPQExpBuffer(initacl_subquery);
5683 destroyPQExpBuffer(initracl_subquery);
5685 destroyPQExpBuffer(attacl_subquery);
5686 destroyPQExpBuffer(attracl_subquery);
5687 destroyPQExpBuffer(attinitacl_subquery);
5688 destroyPQExpBuffer(attinitracl_subquery);
5690 else if (fout->remoteVersion >= 90500)
5693 * Left join to pick up dependency info linking sequences to their
5694 * owning column, if any (note this dependency is AUTO as of 8.2)
5696 appendPQExpBuffer(query,
5697 "SELECT c.tableoid, c.oid, c.relname, "
5698 "c.relacl, NULL as rrelacl, "
5699 "NULL AS initrelacl, NULL AS initrrelacl, "
5702 "(%s c.relowner) AS rolname, "
5703 "c.relchecks, c.relhastriggers, "
5704 "c.relhasindex, c.relhasrules, c.relhasoids, "
5705 "c.relrowsecurity, c.relforcerowsecurity, "
5706 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5707 "tc.relfrozenxid AS tfrozenxid, "
5708 "tc.relminmxid AS tminmxid, "
5709 "c.relpersistence, c.relispopulated, "
5710 "c.relreplident, c.relpages, "
5711 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5712 "d.refobjid AS owning_tab, "
5713 "d.refobjsubid AS owning_col, "
5714 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5715 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5716 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5717 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5718 "tc.reloptions AS toast_reloptions, "
5719 "NULL AS changed_acl, "
5720 "NULL AS partkeydef, "
5721 "false AS ispartition, "
5722 "NULL AS partbound "
5724 "LEFT JOIN pg_depend d ON "
5725 "(c.relkind = '%c' AND "
5726 "d.classid = c.tableoid AND d.objid = c.oid AND "
5727 "d.objsubid = 0 AND "
5728 "d.refclassid = c.tableoid AND d.deptype = 'a') "
5729 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5730 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5734 RELKIND_RELATION, RELKIND_SEQUENCE,
5735 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5736 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5738 else if (fout->remoteVersion >= 90400)
5741 * Left join to pick up dependency info linking sequences to their
5742 * owning column, if any (note this dependency is AUTO as of 8.2)
5744 appendPQExpBuffer(query,
5745 "SELECT c.tableoid, c.oid, c.relname, "
5746 "c.relacl, NULL as rrelacl, "
5747 "NULL AS initrelacl, NULL AS initrrelacl, "
5750 "(%s c.relowner) AS rolname, "
5751 "c.relchecks, c.relhastriggers, "
5752 "c.relhasindex, c.relhasrules, c.relhasoids, "
5753 "'f'::bool AS relrowsecurity, "
5754 "'f'::bool AS relforcerowsecurity, "
5755 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5756 "tc.relfrozenxid AS tfrozenxid, "
5757 "tc.relminmxid AS tminmxid, "
5758 "c.relpersistence, c.relispopulated, "
5759 "c.relreplident, c.relpages, "
5760 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5761 "d.refobjid AS owning_tab, "
5762 "d.refobjsubid AS owning_col, "
5763 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5764 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5765 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5766 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5767 "tc.reloptions AS toast_reloptions, "
5768 "NULL AS changed_acl, "
5769 "NULL AS partkeydef, "
5770 "false AS ispartition, "
5771 "NULL AS partbound "
5773 "LEFT JOIN pg_depend d ON "
5774 "(c.relkind = '%c' AND "
5775 "d.classid = c.tableoid AND d.objid = c.oid AND "
5776 "d.objsubid = 0 AND "
5777 "d.refclassid = c.tableoid AND d.deptype = 'a') "
5778 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5779 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5783 RELKIND_RELATION, RELKIND_SEQUENCE,
5784 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5785 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5787 else if (fout->remoteVersion >= 90300)
5790 * Left join to pick up dependency info linking sequences to their
5791 * owning column, if any (note this dependency is AUTO as of 8.2)
5793 appendPQExpBuffer(query,
5794 "SELECT c.tableoid, c.oid, c.relname, "
5795 "c.relacl, NULL as rrelacl, "
5796 "NULL AS initrelacl, NULL AS initrrelacl, "
5799 "(%s c.relowner) AS rolname, "
5800 "c.relchecks, c.relhastriggers, "
5801 "c.relhasindex, c.relhasrules, c.relhasoids, "
5802 "'f'::bool AS relrowsecurity, "
5803 "'f'::bool AS relforcerowsecurity, "
5804 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5805 "tc.relfrozenxid AS tfrozenxid, "
5806 "tc.relminmxid AS tminmxid, "
5807 "c.relpersistence, c.relispopulated, "
5808 "'d' AS relreplident, c.relpages, "
5809 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5810 "d.refobjid AS owning_tab, "
5811 "d.refobjsubid AS owning_col, "
5812 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5813 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5814 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5815 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5816 "tc.reloptions AS toast_reloptions, "
5817 "NULL AS changed_acl, "
5818 "NULL AS partkeydef, "
5819 "false AS ispartition, "
5820 "NULL AS partbound "
5822 "LEFT JOIN pg_depend d ON "
5823 "(c.relkind = '%c' AND "
5824 "d.classid = c.tableoid AND d.objid = c.oid AND "
5825 "d.objsubid = 0 AND "
5826 "d.refclassid = c.tableoid AND d.deptype = 'a') "
5827 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5828 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5832 RELKIND_RELATION, RELKIND_SEQUENCE,
5833 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5834 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5836 else if (fout->remoteVersion >= 90100)
5839 * Left join to pick up dependency info linking sequences to their
5840 * owning column, if any (note this dependency is AUTO as of 8.2)
5842 appendPQExpBuffer(query,
5843 "SELECT c.tableoid, c.oid, c.relname, "
5844 "c.relacl, NULL as rrelacl, "
5845 "NULL AS initrelacl, NULL AS initrrelacl, "
5848 "(%s c.relowner) AS rolname, "
5849 "c.relchecks, c.relhastriggers, "
5850 "c.relhasindex, c.relhasrules, c.relhasoids, "
5851 "'f'::bool AS relrowsecurity, "
5852 "'f'::bool AS relforcerowsecurity, "
5853 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5854 "tc.relfrozenxid AS tfrozenxid, "
5856 "c.relpersistence, 't' as relispopulated, "
5857 "'d' AS relreplident, c.relpages, "
5858 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5859 "d.refobjid AS owning_tab, "
5860 "d.refobjsubid AS owning_col, "
5861 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5862 "c.reloptions AS reloptions, "
5863 "tc.reloptions AS toast_reloptions, "
5864 "NULL AS changed_acl, "
5865 "NULL AS partkeydef, "
5866 "false AS ispartition, "
5867 "NULL AS partbound "
5869 "LEFT JOIN pg_depend d ON "
5870 "(c.relkind = '%c' AND "
5871 "d.classid = c.tableoid AND d.objid = c.oid AND "
5872 "d.objsubid = 0 AND "
5873 "d.refclassid = c.tableoid AND d.deptype = 'a') "
5874 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5875 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5879 RELKIND_RELATION, RELKIND_SEQUENCE,
5880 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5881 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5883 else if (fout->remoteVersion >= 90000)
5886 * Left join to pick up dependency info linking sequences to their
5887 * owning column, if any (note this dependency is AUTO as of 8.2)
5889 appendPQExpBuffer(query,
5890 "SELECT c.tableoid, c.oid, c.relname, "
5891 "c.relacl, NULL as rrelacl, "
5892 "NULL AS initrelacl, NULL AS initrrelacl, "
5895 "(%s c.relowner) AS rolname, "
5896 "c.relchecks, c.relhastriggers, "
5897 "c.relhasindex, c.relhasrules, c.relhasoids, "
5898 "'f'::bool AS relrowsecurity, "
5899 "'f'::bool AS relforcerowsecurity, "
5900 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5901 "tc.relfrozenxid AS tfrozenxid, "
5903 "'p' AS relpersistence, 't' as relispopulated, "
5904 "'d' AS relreplident, c.relpages, "
5905 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5906 "d.refobjid AS owning_tab, "
5907 "d.refobjsubid AS owning_col, "
5908 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5909 "c.reloptions AS reloptions, "
5910 "tc.reloptions AS toast_reloptions, "
5911 "NULL AS changed_acl, "
5912 "NULL AS partkeydef, "
5913 "false AS ispartition, "
5914 "NULL AS partbound "
5916 "LEFT JOIN pg_depend d ON "
5917 "(c.relkind = '%c' AND "
5918 "d.classid = c.tableoid AND d.objid = c.oid AND "
5919 "d.objsubid = 0 AND "
5920 "d.refclassid = c.tableoid AND d.deptype = 'a') "
5921 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5922 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
5926 RELKIND_RELATION, RELKIND_SEQUENCE,
5927 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
5929 else if (fout->remoteVersion >= 80400)
5932 * Left join to pick up dependency info linking sequences to their
5933 * owning column, if any (note this dependency is AUTO as of 8.2)
5935 appendPQExpBuffer(query,
5936 "SELECT c.tableoid, c.oid, c.relname, "
5937 "c.relacl, NULL as rrelacl, "
5938 "NULL AS initrelacl, NULL AS initrrelacl, "
5941 "(%s c.relowner) AS rolname, "
5942 "c.relchecks, c.relhastriggers, "
5943 "c.relhasindex, c.relhasrules, c.relhasoids, "
5944 "'f'::bool AS relrowsecurity, "
5945 "'f'::bool AS relforcerowsecurity, "
5946 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5947 "tc.relfrozenxid AS tfrozenxid, "
5949 "'p' AS relpersistence, 't' as relispopulated, "
5950 "'d' AS relreplident, c.relpages, "
5951 "NULL AS reloftype, "
5952 "d.refobjid AS owning_tab, "
5953 "d.refobjsubid AS owning_col, "
5954 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5955 "c.reloptions AS reloptions, "
5956 "tc.reloptions AS toast_reloptions, "
5957 "NULL AS changed_acl, "
5958 "NULL AS partkeydef, "
5959 "false AS ispartition, "
5960 "NULL AS partbound "
5962 "LEFT JOIN pg_depend d ON "
5963 "(c.relkind = '%c' AND "
5964 "d.classid = c.tableoid AND d.objid = c.oid AND "
5965 "d.objsubid = 0 AND "
5966 "d.refclassid = c.tableoid AND d.deptype = 'a') "
5967 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5968 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
5972 RELKIND_RELATION, RELKIND_SEQUENCE,
5973 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
5975 else if (fout->remoteVersion >= 80200)
5978 * Left join to pick up dependency info linking sequences to their
5979 * owning column, if any (note this dependency is AUTO as of 8.2)
5981 appendPQExpBuffer(query,
5982 "SELECT c.tableoid, c.oid, c.relname, "
5983 "c.relacl, NULL as rrelacl, "
5984 "NULL AS initrelacl, NULL AS initrrelacl, "
5987 "(%s c.relowner) AS rolname, "
5988 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
5989 "c.relhasindex, c.relhasrules, c.relhasoids, "
5990 "'f'::bool AS relrowsecurity, "
5991 "'f'::bool AS relforcerowsecurity, "
5992 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5993 "tc.relfrozenxid AS tfrozenxid, "
5995 "'p' AS relpersistence, 't' as relispopulated, "
5996 "'d' AS relreplident, c.relpages, "
5997 "NULL AS reloftype, "
5998 "d.refobjid AS owning_tab, "
5999 "d.refobjsubid AS owning_col, "
6000 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6001 "c.reloptions AS reloptions, "
6002 "NULL AS toast_reloptions, "
6003 "NULL AS changed_acl, "
6004 "NULL AS partkeydef, "
6005 "false AS ispartition, "
6006 "NULL AS partbound "
6008 "LEFT JOIN pg_depend d ON "
6009 "(c.relkind = '%c' AND "
6010 "d.classid = c.tableoid AND d.objid = c.oid AND "
6011 "d.objsubid = 0 AND "
6012 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6013 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6014 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6018 RELKIND_RELATION, RELKIND_SEQUENCE,
6019 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6024 * Left join to pick up dependency info linking sequences to their
6025 * owning column, if any
6027 appendPQExpBuffer(query,
6028 "SELECT c.tableoid, c.oid, relname, "
6029 "relacl, NULL as rrelacl, "
6030 "NULL AS initrelacl, NULL AS initrrelacl, "
6031 "relkind, relnamespace, "
6032 "(%s relowner) AS rolname, "
6033 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6034 "relhasindex, relhasrules, relhasoids, "
6035 "'f'::bool AS relrowsecurity, "
6036 "'f'::bool AS relforcerowsecurity, "
6037 "0 AS relfrozenxid, 0 AS relminmxid,"
6039 "0 AS tfrozenxid, 0 AS tminmxid,"
6040 "'p' AS relpersistence, 't' as relispopulated, "
6041 "'d' AS relreplident, relpages, "
6042 "NULL AS reloftype, "
6043 "d.refobjid AS owning_tab, "
6044 "d.refobjsubid AS owning_col, "
6045 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6046 "NULL AS reloptions, "
6047 "NULL AS toast_reloptions, "
6048 "NULL AS changed_acl, "
6049 "NULL AS partkeydef, "
6050 "false AS ispartition, "
6051 "NULL AS partbound "
6053 "LEFT JOIN pg_depend d ON "
6054 "(c.relkind = '%c' AND "
6055 "d.classid = c.tableoid AND d.objid = c.oid AND "
6056 "d.objsubid = 0 AND "
6057 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6058 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6062 RELKIND_RELATION, RELKIND_SEQUENCE,
6063 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6066 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6068 ntups = PQntuples(res);
6073 * Extract data from result and lock dumpable tables. We do the locking
6074 * before anything else, to minimize the window wherein a table could
6075 * disappear under us.
6077 * Note that we have to save info about all tables here, even when dumping
6078 * only one, because we don't yet know which tables might be inheritance
6079 * ancestors of the target table.
6081 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6083 i_reltableoid = PQfnumber(res, "tableoid");
6084 i_reloid = PQfnumber(res, "oid");
6085 i_relname = PQfnumber(res, "relname");
6086 i_relnamespace = PQfnumber(res, "relnamespace");
6087 i_relacl = PQfnumber(res, "relacl");
6088 i_rrelacl = PQfnumber(res, "rrelacl");
6089 i_initrelacl = PQfnumber(res, "initrelacl");
6090 i_initrrelacl = PQfnumber(res, "initrrelacl");
6091 i_relkind = PQfnumber(res, "relkind");
6092 i_rolname = PQfnumber(res, "rolname");
6093 i_relchecks = PQfnumber(res, "relchecks");
6094 i_relhastriggers = PQfnumber(res, "relhastriggers");
6095 i_relhasindex = PQfnumber(res, "relhasindex");
6096 i_relhasrules = PQfnumber(res, "relhasrules");
6097 i_relrowsec = PQfnumber(res, "relrowsecurity");
6098 i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6099 i_relhasoids = PQfnumber(res, "relhasoids");
6100 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6101 i_relminmxid = PQfnumber(res, "relminmxid");
6102 i_toastoid = PQfnumber(res, "toid");
6103 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6104 i_toastminmxid = PQfnumber(res, "tminmxid");
6105 i_relpersistence = PQfnumber(res, "relpersistence");
6106 i_relispopulated = PQfnumber(res, "relispopulated");
6107 i_relreplident = PQfnumber(res, "relreplident");
6108 i_relpages = PQfnumber(res, "relpages");
6109 i_owning_tab = PQfnumber(res, "owning_tab");
6110 i_owning_col = PQfnumber(res, "owning_col");
6111 i_reltablespace = PQfnumber(res, "reltablespace");
6112 i_reloptions = PQfnumber(res, "reloptions");
6113 i_checkoption = PQfnumber(res, "checkoption");
6114 i_toastreloptions = PQfnumber(res, "toast_reloptions");
6115 i_reloftype = PQfnumber(res, "reloftype");
6116 i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6117 i_changed_acl = PQfnumber(res, "changed_acl");
6118 i_partkeydef = PQfnumber(res, "partkeydef");
6119 i_ispartition = PQfnumber(res, "ispartition");
6120 i_partbound = PQfnumber(res, "partbound");
6122 if (dopt->lockWaitTimeout)
6125 * Arrange to fail instead of waiting forever for a table lock.
6127 * NB: this coding assumes that the only queries issued within the
6128 * following loop are LOCK TABLEs; else the timeout may be undesirably
6129 * applied to other things too.
6131 resetPQExpBuffer(query);
6132 appendPQExpBufferStr(query, "SET statement_timeout = ");
6133 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6134 ExecuteSqlStatement(fout, query->data);
6137 for (i = 0; i < ntups; i++)
6139 tblinfo[i].dobj.objType = DO_TABLE;
6140 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6141 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6142 AssignDumpId(&tblinfo[i].dobj);
6143 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6144 tblinfo[i].dobj.namespace =
6146 atooid(PQgetvalue(res, i, i_relnamespace)));
6147 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6148 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6149 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6150 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6151 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6152 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6153 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6154 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6155 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6156 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6157 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6158 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6159 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6160 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6161 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6162 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6163 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6164 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6165 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6166 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6167 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6168 if (PQgetisnull(res, i, i_reloftype))
6169 tblinfo[i].reloftype = NULL;
6171 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6172 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6173 if (PQgetisnull(res, i, i_owning_tab))
6175 tblinfo[i].owning_tab = InvalidOid;
6176 tblinfo[i].owning_col = 0;
6180 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6181 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6183 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6184 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6185 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6186 tblinfo[i].checkoption = NULL;
6188 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6189 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6191 /* other fields were zeroed above */
6194 * Decide whether we want to dump this table.
6196 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6197 tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6199 selectDumpableTable(&tblinfo[i], fout);
6202 * If the table-level and all column-level ACLs for this table are
6203 * unchanged, then we don't need to worry about including the ACLs for
6204 * this table. If any column-level ACLs have been changed, the
6205 * 'changed_acl' column from the query will indicate that.
6207 * This can result in a significant performance improvement in cases
6208 * where we are only looking to dump out the ACL (eg: pg_catalog).
6210 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6211 PQgetisnull(res, i, i_initrelacl) &&
6212 PQgetisnull(res, i, i_initrrelacl) &&
6213 strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6214 tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6216 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6217 tblinfo[i].dummy_view = false; /* might get set during sort */
6218 tblinfo[i].postponed_def = false; /* might get set during sort */
6220 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6221 strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6223 /* Partition key string or NULL */
6224 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6225 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6226 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6229 * Read-lock target tables to make sure they aren't DROPPED or altered
6230 * in schema before we get around to dumping them.
6232 * Note that we don't explicitly lock parents of the target tables; we
6233 * assume our lock on the child is enough to prevent schema
6234 * alterations to parent tables.
6236 * NOTE: it'd be kinda nice to lock other relations too, not only
6237 * plain tables, but the backend doesn't presently allow that.
6239 * We only need to lock the table for certain components; see
6242 if (tblinfo[i].dobj.dump &&
6243 (tblinfo[i].relkind == RELKIND_RELATION ||
6244 tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6245 (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6247 resetPQExpBuffer(query);
6248 appendPQExpBuffer(query,
6249 "LOCK TABLE %s IN ACCESS SHARE MODE",
6250 fmtQualifiedId(fout->remoteVersion,
6251 tblinfo[i].dobj.namespace->dobj.name,
6252 tblinfo[i].dobj.name));
6253 ExecuteSqlStatement(fout, query->data);
6256 /* Emit notice if join for owner failed */
6257 if (strlen(tblinfo[i].rolname) == 0)
6258 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6259 tblinfo[i].dobj.name);
6262 if (dopt->lockWaitTimeout)
6264 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6269 destroyPQExpBuffer(query);
6276 * identify owned sequences and mark them as dumpable if owning table is
6278 * We used to do this in getTables(), but it's better to do it after the
6279 * index used by findTableByOid() has been set up.
6282 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6287 * Force sequences that are "owned" by table columns to be dumped whenever
6288 * their owning table is being dumped.
6290 for (i = 0; i < numTables; i++)
6292 TableInfo *seqinfo = &tblinfo[i];
6293 TableInfo *owning_tab;
6295 if (!OidIsValid(seqinfo->owning_tab))
6296 continue; /* not an owned sequence */
6298 owning_tab = findTableByOid(seqinfo->owning_tab);
6299 if (owning_tab == NULL)
6300 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6301 seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6304 * We need to dump the components that are being dumped for the table
6305 * and any components which the sequence is explicitly marked with.
6307 * We can't simply use the set of components which are being dumped
6308 * for the table as the table might be in an extension (and only the
6309 * non-extension components, eg: ACLs if changed, security labels, and
6310 * policies, are being dumped) while the sequence is not (and
6311 * therefore the definition and other components should also be
6314 * If the sequence is part of the extension then it should be properly
6315 * marked by checkExtensionMembership() and this will be a no-op as
6316 * the table will be equivalently marked.
6318 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6320 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6321 seqinfo->interesting = true;
6327 * read all the inheritance information
6328 * from the system catalogs return them in the InhInfo* structure
6330 * numInherits is set to the number of pairs read in
6333 getInherits(Archive *fout, int *numInherits)
6338 PQExpBuffer query = createPQExpBuffer();
6344 /* Make sure we are in proper schema */
6345 selectSourceSchema(fout, "pg_catalog");
6348 * Find all the inheritance information, excluding implicit inheritance
6349 * via partitioning. We handle that case using getPartitions(), because
6350 * we want more information about partitions than just the parent-child
6353 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6355 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6357 ntups = PQntuples(res);
6359 *numInherits = ntups;
6361 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6363 i_inhrelid = PQfnumber(res, "inhrelid");
6364 i_inhparent = PQfnumber(res, "inhparent");
6366 for (i = 0; i < ntups; i++)
6368 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6369 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6374 destroyPQExpBuffer(query);
6381 * get information about every index on a dumpable table
6383 * Note: index data is not returned directly to the caller, but it
6384 * does get entered into the DumpableObject tables.
6387 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6391 PQExpBuffer query = createPQExpBuffer();
6394 ConstraintInfo *constrinfo;
6415 for (i = 0; i < numTables; i++)
6417 TableInfo *tbinfo = &tblinfo[i];
6419 /* Only plain tables and materialized views have indexes. */
6420 if (tbinfo->relkind != RELKIND_RELATION &&
6421 tbinfo->relkind != RELKIND_MATVIEW)
6423 if (!tbinfo->hasindex)
6426 /* Ignore indexes of tables whose definitions are not to be dumped */
6427 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
6431 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6432 tbinfo->dobj.namespace->dobj.name,
6435 /* Make sure we are in proper schema so indexdef is right */
6436 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6439 * The point of the messy-looking outer join is to find a constraint
6440 * that is related by an internal dependency link to the index. If we
6441 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6442 * assume an index won't have more than one internal dependency.
6444 * As of 9.0 we don't need to look at pg_depend but can check for a
6445 * match to pg_constraint.conindid. The check on conrelid is
6446 * redundant but useful because that column is indexed while conindid
6449 resetPQExpBuffer(query);
6450 if (fout->remoteVersion >= 90400)
6453 * the test on indisready is necessary in 9.2, and harmless in
6454 * earlier/later versions
6456 appendPQExpBuffer(query,
6457 "SELECT t.tableoid, t.oid, "
6458 "t.relname AS indexname, "
6459 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6460 "t.relnatts AS indnkeys, "
6461 "i.indkey, i.indisclustered, "
6462 "i.indisreplident, t.relpages, "
6463 "c.contype, c.conname, "
6464 "c.condeferrable, c.condeferred, "
6465 "c.tableoid AS contableoid, "
6467 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6468 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6469 "t.reloptions AS indreloptions "
6470 "FROM pg_catalog.pg_index i "
6471 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6472 "LEFT JOIN pg_catalog.pg_constraint c "
6473 "ON (i.indrelid = c.conrelid AND "
6474 "i.indexrelid = c.conindid AND "
6475 "c.contype IN ('p','u','x')) "
6476 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6477 "AND i.indisvalid AND i.indisready "
6478 "ORDER BY indexname",
6479 tbinfo->dobj.catId.oid);
6481 else if (fout->remoteVersion >= 90000)
6484 * the test on indisready is necessary in 9.2, and harmless in
6485 * earlier/later versions
6487 appendPQExpBuffer(query,
6488 "SELECT t.tableoid, t.oid, "
6489 "t.relname AS indexname, "
6490 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6491 "t.relnatts AS indnkeys, "
6492 "i.indkey, i.indisclustered, "
6493 "false AS indisreplident, t.relpages, "
6494 "c.contype, c.conname, "
6495 "c.condeferrable, c.condeferred, "
6496 "c.tableoid AS contableoid, "
6498 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6499 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6500 "t.reloptions AS indreloptions "
6501 "FROM pg_catalog.pg_index i "
6502 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6503 "LEFT JOIN pg_catalog.pg_constraint c "
6504 "ON (i.indrelid = c.conrelid AND "
6505 "i.indexrelid = c.conindid AND "
6506 "c.contype IN ('p','u','x')) "
6507 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6508 "AND i.indisvalid AND i.indisready "
6509 "ORDER BY indexname",
6510 tbinfo->dobj.catId.oid);
6512 else if (fout->remoteVersion >= 80200)
6514 appendPQExpBuffer(query,
6515 "SELECT t.tableoid, t.oid, "
6516 "t.relname AS indexname, "
6517 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6518 "t.relnatts AS indnkeys, "
6519 "i.indkey, i.indisclustered, "
6520 "false AS indisreplident, t.relpages, "
6521 "c.contype, c.conname, "
6522 "c.condeferrable, c.condeferred, "
6523 "c.tableoid AS contableoid, "
6526 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6527 "t.reloptions AS indreloptions "
6528 "FROM pg_catalog.pg_index i "
6529 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6530 "LEFT JOIN pg_catalog.pg_depend d "
6531 "ON (d.classid = t.tableoid "
6532 "AND d.objid = t.oid "
6533 "AND d.deptype = 'i') "
6534 "LEFT JOIN pg_catalog.pg_constraint c "
6535 "ON (d.refclassid = c.tableoid "
6536 "AND d.refobjid = c.oid) "
6537 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6539 "ORDER BY indexname",
6540 tbinfo->dobj.catId.oid);
6544 appendPQExpBuffer(query,
6545 "SELECT t.tableoid, t.oid, "
6546 "t.relname AS indexname, "
6547 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6548 "t.relnatts AS indnkeys, "
6549 "i.indkey, i.indisclustered, "
6550 "false AS indisreplident, t.relpages, "
6551 "c.contype, c.conname, "
6552 "c.condeferrable, c.condeferred, "
6553 "c.tableoid AS contableoid, "
6556 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6557 "null AS indreloptions "
6558 "FROM pg_catalog.pg_index i "
6559 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6560 "LEFT JOIN pg_catalog.pg_depend d "
6561 "ON (d.classid = t.tableoid "
6562 "AND d.objid = t.oid "
6563 "AND d.deptype = 'i') "
6564 "LEFT JOIN pg_catalog.pg_constraint c "
6565 "ON (d.refclassid = c.tableoid "
6566 "AND d.refobjid = c.oid) "
6567 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6568 "ORDER BY indexname",
6569 tbinfo->dobj.catId.oid);
6572 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6574 ntups = PQntuples(res);
6576 i_tableoid = PQfnumber(res, "tableoid");
6577 i_oid = PQfnumber(res, "oid");
6578 i_indexname = PQfnumber(res, "indexname");
6579 i_indexdef = PQfnumber(res, "indexdef");
6580 i_indnkeys = PQfnumber(res, "indnkeys");
6581 i_indkey = PQfnumber(res, "indkey");
6582 i_indisclustered = PQfnumber(res, "indisclustered");
6583 i_indisreplident = PQfnumber(res, "indisreplident");
6584 i_relpages = PQfnumber(res, "relpages");
6585 i_contype = PQfnumber(res, "contype");
6586 i_conname = PQfnumber(res, "conname");
6587 i_condeferrable = PQfnumber(res, "condeferrable");
6588 i_condeferred = PQfnumber(res, "condeferred");
6589 i_contableoid = PQfnumber(res, "contableoid");
6590 i_conoid = PQfnumber(res, "conoid");
6591 i_condef = PQfnumber(res, "condef");
6592 i_tablespace = PQfnumber(res, "tablespace");
6593 i_indreloptions = PQfnumber(res, "indreloptions");
6595 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6596 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6598 for (j = 0; j < ntups; j++)
6602 indxinfo[j].dobj.objType = DO_INDEX;
6603 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6604 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6605 AssignDumpId(&indxinfo[j].dobj);
6606 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6607 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6608 indxinfo[j].indextable = tbinfo;
6609 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6610 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
6611 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6612 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6613 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnkeys * sizeof(Oid));
6614 parseOidArray(PQgetvalue(res, j, i_indkey),
6615 indxinfo[j].indkeys, indxinfo[j].indnkeys);
6616 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6617 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6618 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
6619 contype = *(PQgetvalue(res, j, i_contype));
6621 if (contype == 'p' || contype == 'u' || contype == 'x')
6624 * If we found a constraint matching the index, create an
6627 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6628 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6629 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6630 AssignDumpId(&constrinfo[j].dobj);
6631 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6632 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6633 constrinfo[j].contable = tbinfo;
6634 constrinfo[j].condomain = NULL;
6635 constrinfo[j].contype = contype;
6637 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6639 constrinfo[j].condef = NULL;
6640 constrinfo[j].confrelid = InvalidOid;
6641 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
6642 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
6643 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
6644 constrinfo[j].conislocal = true;
6645 constrinfo[j].separate = true;
6647 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
6651 /* Plain secondary index */
6652 indxinfo[j].indexconstraint = 0;
6659 destroyPQExpBuffer(query);
6663 * getExtendedStatistics
6664 * get information about extended statistics on a dumpable table
6665 * or materialized view.
6667 * Note: extended statistics data is not returned directly to the caller, but
6668 * it does get entered into the DumpableObject tables.
6671 getExtendedStatistics(Archive *fout, TableInfo tblinfo[], int numTables)
6677 StatsExtInfo *statsextinfo;
6684 /* Extended statistics were new in v10 */
6685 if (fout->remoteVersion < 100000)
6688 query = createPQExpBuffer();
6690 for (i = 0; i < numTables; i++)
6692 TableInfo *tbinfo = &tblinfo[i];
6695 * Only plain tables, materialized views, foreign tables and
6696 * partitioned tables can have extended statistics.
6698 if (tbinfo->relkind != RELKIND_RELATION &&
6699 tbinfo->relkind != RELKIND_MATVIEW &&
6700 tbinfo->relkind != RELKIND_FOREIGN_TABLE &&
6701 tbinfo->relkind != RELKIND_PARTITIONED_TABLE)
6705 * Ignore extended statistics of tables whose definitions are not to
6708 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
6712 write_msg(NULL, "reading extended statistics for table \"%s.%s\"\n",
6713 tbinfo->dobj.namespace->dobj.name,
6716 /* Make sure we are in proper schema so stadef is right */
6717 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6719 resetPQExpBuffer(query);
6721 appendPQExpBuffer(query,
6726 "pg_catalog.pg_get_statisticsobjdef(oid) AS stxdef "
6727 "FROM pg_statistic_ext "
6728 "WHERE stxrelid = '%u' "
6729 "ORDER BY stxname", tbinfo->dobj.catId.oid);
6731 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6733 ntups = PQntuples(res);
6735 i_tableoid = PQfnumber(res, "tableoid");
6736 i_oid = PQfnumber(res, "oid");
6737 i_stxname = PQfnumber(res, "stxname");
6738 i_stxdef = PQfnumber(res, "stxdef");
6740 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
6742 for (j = 0; j < ntups; j++)
6744 statsextinfo[j].dobj.objType = DO_STATSEXT;
6745 statsextinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6746 statsextinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6747 AssignDumpId(&statsextinfo[j].dobj);
6748 statsextinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_stxname));
6749 statsextinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6750 statsextinfo[j].statsexttable = tbinfo;
6751 statsextinfo[j].statsextdef = pg_strdup(PQgetvalue(res, j, i_stxdef));
6757 destroyPQExpBuffer(query);
6763 * Get info about constraints on dumpable tables.
6765 * Currently handles foreign keys only.
6766 * Unique and primary key constraints are handled with indexes,
6767 * while check constraints are processed in getTableAttrs().
6770 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
6774 ConstraintInfo *constrinfo;
6784 query = createPQExpBuffer();
6786 for (i = 0; i < numTables; i++)
6788 TableInfo *tbinfo = &tblinfo[i];
6790 if (!tbinfo->hastriggers ||
6791 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
6795 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
6796 tbinfo->dobj.namespace->dobj.name,
6800 * select table schema to ensure constraint expr is qualified if
6803 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6805 resetPQExpBuffer(query);
6806 appendPQExpBuffer(query,
6807 "SELECT tableoid, oid, conname, confrelid, "
6808 "pg_catalog.pg_get_constraintdef(oid) AS condef "
6809 "FROM pg_catalog.pg_constraint "
6810 "WHERE conrelid = '%u'::pg_catalog.oid "
6811 "AND contype = 'f'",
6812 tbinfo->dobj.catId.oid);
6813 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6815 ntups = PQntuples(res);
6817 i_contableoid = PQfnumber(res, "tableoid");
6818 i_conoid = PQfnumber(res, "oid");
6819 i_conname = PQfnumber(res, "conname");
6820 i_confrelid = PQfnumber(res, "confrelid");
6821 i_condef = PQfnumber(res, "condef");
6823 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6825 for (j = 0; j < ntups; j++)
6827 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
6828 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6829 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6830 AssignDumpId(&constrinfo[j].dobj);
6831 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6832 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6833 constrinfo[j].contable = tbinfo;
6834 constrinfo[j].condomain = NULL;
6835 constrinfo[j].contype = 'f';
6836 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6837 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
6838 constrinfo[j].conindex = 0;
6839 constrinfo[j].condeferrable = false;
6840 constrinfo[j].condeferred = false;
6841 constrinfo[j].conislocal = true;
6842 constrinfo[j].separate = true;
6848 destroyPQExpBuffer(query);
6852 * getDomainConstraints
6854 * Get info about constraints on a domain.
6857 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
6860 ConstraintInfo *constrinfo;
6870 * select appropriate schema to ensure names in constraint are properly
6873 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
6875 query = createPQExpBuffer();
6877 if (fout->remoteVersion >= 90100)
6878 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
6879 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6881 "FROM pg_catalog.pg_constraint "
6882 "WHERE contypid = '%u'::pg_catalog.oid "
6884 tyinfo->dobj.catId.oid);
6887 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
6888 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6889 "true as convalidated "
6890 "FROM pg_catalog.pg_constraint "
6891 "WHERE contypid = '%u'::pg_catalog.oid "
6893 tyinfo->dobj.catId.oid);
6895 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6897 ntups = PQntuples(res);
6899 i_tableoid = PQfnumber(res, "tableoid");
6900 i_oid = PQfnumber(res, "oid");
6901 i_conname = PQfnumber(res, "conname");
6902 i_consrc = PQfnumber(res, "consrc");
6904 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6906 tyinfo->nDomChecks = ntups;
6907 tyinfo->domChecks = constrinfo;
6909 for (i = 0; i < ntups; i++)
6911 bool validated = PQgetvalue(res, i, 4)[0] == 't';
6913 constrinfo[i].dobj.objType = DO_CONSTRAINT;
6914 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6915 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6916 AssignDumpId(&constrinfo[i].dobj);
6917 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
6918 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
6919 constrinfo[i].contable = NULL;
6920 constrinfo[i].condomain = tyinfo;
6921 constrinfo[i].contype = 'c';
6922 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
6923 constrinfo[i].confrelid = InvalidOid;
6924 constrinfo[i].conindex = 0;
6925 constrinfo[i].condeferrable = false;
6926 constrinfo[i].condeferred = false;
6927 constrinfo[i].conislocal = true;
6929 constrinfo[i].separate = !validated;
6932 * Make the domain depend on the constraint, ensuring it won't be
6933 * output till any constraint dependencies are OK. If the constraint
6934 * has not been validated, it's going to be dumped after the domain
6935 * anyway, so this doesn't matter.
6938 addObjectDependency(&tyinfo->dobj,
6939 constrinfo[i].dobj.dumpId);
6944 destroyPQExpBuffer(query);
6949 * get basic information about every rule in the system
6951 * numRules is set to the number of rules read in
6954 getRules(Archive *fout, int *numRules)
6959 PQExpBuffer query = createPQExpBuffer();
6969 /* Make sure we are in proper schema */
6970 selectSourceSchema(fout, "pg_catalog");
6972 if (fout->remoteVersion >= 80300)
6974 appendPQExpBufferStr(query, "SELECT "
6975 "tableoid, oid, rulename, "
6976 "ev_class AS ruletable, ev_type, is_instead, "
6983 appendPQExpBufferStr(query, "SELECT "
6984 "tableoid, oid, rulename, "
6985 "ev_class AS ruletable, ev_type, is_instead, "
6986 "'O'::char AS ev_enabled "
6991 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6993 ntups = PQntuples(res);
6997 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
6999 i_tableoid = PQfnumber(res, "tableoid");
7000 i_oid = PQfnumber(res, "oid");
7001 i_rulename = PQfnumber(res, "rulename");
7002 i_ruletable = PQfnumber(res, "ruletable");
7003 i_ev_type = PQfnumber(res, "ev_type");
7004 i_is_instead = PQfnumber(res, "is_instead");
7005 i_ev_enabled = PQfnumber(res, "ev_enabled");
7007 for (i = 0; i < ntups; i++)
7011 ruleinfo[i].dobj.objType = DO_RULE;
7012 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7013 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7014 AssignDumpId(&ruleinfo[i].dobj);
7015 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7016 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7017 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7018 if (ruleinfo[i].ruletable == NULL)
7019 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7020 ruletableoid, ruleinfo[i].dobj.catId.oid);
7021 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7022 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7023 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7024 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7025 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7026 if (ruleinfo[i].ruletable)
7029 * If the table is a view or materialized view, force its ON
7030 * SELECT rule to be sorted before the view itself --- this
7031 * ensures that any dependencies for the rule affect the table's
7032 * positioning. Other rules are forced to appear after their
7035 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7036 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7037 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7039 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7040 ruleinfo[i].dobj.dumpId);
7041 /* We'll merge the rule into CREATE VIEW, if possible */
7042 ruleinfo[i].separate = false;
7046 addObjectDependency(&ruleinfo[i].dobj,
7047 ruleinfo[i].ruletable->dobj.dumpId);
7048 ruleinfo[i].separate = true;
7052 ruleinfo[i].separate = true;
7057 destroyPQExpBuffer(query);
7064 * get information about every trigger on a dumpable table
7066 * Note: trigger data is not returned directly to the caller, but it
7067 * does get entered into the DumpableObject tables.
7070 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7074 PQExpBuffer query = createPQExpBuffer();
7076 TriggerInfo *tginfo;
7094 for (i = 0; i < numTables; i++)
7096 TableInfo *tbinfo = &tblinfo[i];
7098 if (!tbinfo->hastriggers ||
7099 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7103 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7104 tbinfo->dobj.namespace->dobj.name,
7108 * select table schema to ensure regproc name is qualified if needed
7110 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7112 resetPQExpBuffer(query);
7113 if (fout->remoteVersion >= 90000)
7116 * NB: think not to use pretty=true in pg_get_triggerdef. It
7117 * could result in non-forward-compatible dumps of WHEN clauses
7118 * due to under-parenthesization.
7120 appendPQExpBuffer(query,
7122 "tgfoid::pg_catalog.regproc AS tgfname, "
7123 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7124 "tgenabled, tableoid, oid "
7125 "FROM pg_catalog.pg_trigger t "
7126 "WHERE tgrelid = '%u'::pg_catalog.oid "
7127 "AND NOT tgisinternal",
7128 tbinfo->dobj.catId.oid);
7130 else if (fout->remoteVersion >= 80300)
7133 * We ignore triggers that are tied to a foreign-key constraint
7135 appendPQExpBuffer(query,
7137 "tgfoid::pg_catalog.regproc AS tgfname, "
7138 "tgtype, tgnargs, tgargs, tgenabled, "
7139 "tgisconstraint, tgconstrname, tgdeferrable, "
7140 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7141 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7142 "FROM pg_catalog.pg_trigger t "
7143 "WHERE tgrelid = '%u'::pg_catalog.oid "
7144 "AND tgconstraint = 0",
7145 tbinfo->dobj.catId.oid);
7150 * We ignore triggers that are tied to a foreign-key constraint,
7151 * but in these versions we have to grovel through pg_constraint
7154 appendPQExpBuffer(query,
7156 "tgfoid::pg_catalog.regproc AS tgfname, "
7157 "tgtype, tgnargs, tgargs, tgenabled, "
7158 "tgisconstraint, tgconstrname, tgdeferrable, "
7159 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7160 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7161 "FROM pg_catalog.pg_trigger t "
7162 "WHERE tgrelid = '%u'::pg_catalog.oid "
7163 "AND (NOT tgisconstraint "
7165 " (SELECT 1 FROM pg_catalog.pg_depend d "
7166 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7167 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7168 tbinfo->dobj.catId.oid);
7171 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7173 ntups = PQntuples(res);
7175 i_tableoid = PQfnumber(res, "tableoid");
7176 i_oid = PQfnumber(res, "oid");
7177 i_tgname = PQfnumber(res, "tgname");
7178 i_tgfname = PQfnumber(res, "tgfname");
7179 i_tgtype = PQfnumber(res, "tgtype");
7180 i_tgnargs = PQfnumber(res, "tgnargs");
7181 i_tgargs = PQfnumber(res, "tgargs");
7182 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7183 i_tgconstrname = PQfnumber(res, "tgconstrname");
7184 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7185 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7186 i_tgenabled = PQfnumber(res, "tgenabled");
7187 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7188 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7189 i_tgdef = PQfnumber(res, "tgdef");
7191 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7193 tbinfo->numTriggers = ntups;
7194 tbinfo->triggers = tginfo;
7196 for (j = 0; j < ntups; j++)
7198 tginfo[j].dobj.objType = DO_TRIGGER;
7199 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7200 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7201 AssignDumpId(&tginfo[j].dobj);
7202 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7203 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7204 tginfo[j].tgtable = tbinfo;
7205 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7208 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7210 /* remaining fields are not valid if we have tgdef */
7211 tginfo[j].tgfname = NULL;
7212 tginfo[j].tgtype = 0;
7213 tginfo[j].tgnargs = 0;
7214 tginfo[j].tgargs = NULL;
7215 tginfo[j].tgisconstraint = false;
7216 tginfo[j].tgdeferrable = false;
7217 tginfo[j].tginitdeferred = false;
7218 tginfo[j].tgconstrname = NULL;
7219 tginfo[j].tgconstrrelid = InvalidOid;
7220 tginfo[j].tgconstrrelname = NULL;
7224 tginfo[j].tgdef = NULL;
7226 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7227 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7228 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7229 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7230 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7231 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7232 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7234 if (tginfo[j].tgisconstraint)
7236 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7237 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7238 if (OidIsValid(tginfo[j].tgconstrrelid))
7240 if (PQgetisnull(res, j, i_tgconstrrelname))
7241 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7242 tginfo[j].dobj.name,
7244 tginfo[j].tgconstrrelid);
7245 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7248 tginfo[j].tgconstrrelname = NULL;
7252 tginfo[j].tgconstrname = NULL;
7253 tginfo[j].tgconstrrelid = InvalidOid;
7254 tginfo[j].tgconstrrelname = NULL;
7262 destroyPQExpBuffer(query);
7267 * get information about event triggers
7270 getEventTriggers(Archive *fout, int *numEventTriggers)
7275 EventTriggerInfo *evtinfo;
7286 /* Before 9.3, there are no event triggers */
7287 if (fout->remoteVersion < 90300)
7289 *numEventTriggers = 0;
7293 query = createPQExpBuffer();
7295 /* Make sure we are in proper schema */
7296 selectSourceSchema(fout, "pg_catalog");
7298 appendPQExpBuffer(query,
7299 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7300 "evtevent, (%s evtowner) AS evtowner, "
7301 "array_to_string(array("
7302 "select quote_literal(x) "
7303 " from unnest(evttags) as t(x)), ', ') as evttags, "
7304 "e.evtfoid::regproc as evtfname "
7305 "FROM pg_event_trigger e "
7309 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7311 ntups = PQntuples(res);
7313 *numEventTriggers = ntups;
7315 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7317 i_tableoid = PQfnumber(res, "tableoid");
7318 i_oid = PQfnumber(res, "oid");
7319 i_evtname = PQfnumber(res, "evtname");
7320 i_evtevent = PQfnumber(res, "evtevent");
7321 i_evtowner = PQfnumber(res, "evtowner");
7322 i_evttags = PQfnumber(res, "evttags");
7323 i_evtfname = PQfnumber(res, "evtfname");
7324 i_evtenabled = PQfnumber(res, "evtenabled");
7326 for (i = 0; i < ntups; i++)
7328 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7329 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7330 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7331 AssignDumpId(&evtinfo[i].dobj);
7332 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7333 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7334 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7335 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7336 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7337 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7338 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7340 /* Decide whether we want to dump it */
7341 selectDumpableObject(&(evtinfo[i].dobj), fout);
7343 /* Event Triggers do not currently have ACLs. */
7344 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7349 destroyPQExpBuffer(query);
7356 * get basic information about every procedural language in the system
7358 * numProcLangs is set to the number of langs read in
7360 * NB: this must run after getFuncs() because we assume we can do
7364 getProcLangs(Archive *fout, int *numProcLangs)
7366 DumpOptions *dopt = fout->dopt;
7370 PQExpBuffer query = createPQExpBuffer();
7371 ProcLangInfo *planginfo;
7376 int i_lanplcallfoid;
7385 /* Make sure we are in proper schema */
7386 selectSourceSchema(fout, "pg_catalog");
7388 if (fout->remoteVersion >= 90600)
7390 PQExpBuffer acl_subquery = createPQExpBuffer();
7391 PQExpBuffer racl_subquery = createPQExpBuffer();
7392 PQExpBuffer initacl_subquery = createPQExpBuffer();
7393 PQExpBuffer initracl_subquery = createPQExpBuffer();
7395 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7396 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7397 dopt->binary_upgrade);
7399 /* pg_language has a laninline column */
7400 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7401 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7402 "l.laninline, l.lanvalidator, "
7405 "%s AS initlanacl, "
7406 "%s AS initrlanacl, "
7407 "(%s l.lanowner) AS lanowner "
7408 "FROM pg_language l "
7409 "LEFT JOIN pg_init_privs pip ON "
7410 "(l.oid = pip.objoid "
7411 "AND pip.classoid = 'pg_language'::regclass "
7412 "AND pip.objsubid = 0) "
7416 racl_subquery->data,
7417 initacl_subquery->data,
7418 initracl_subquery->data,
7421 destroyPQExpBuffer(acl_subquery);
7422 destroyPQExpBuffer(racl_subquery);
7423 destroyPQExpBuffer(initacl_subquery);
7424 destroyPQExpBuffer(initracl_subquery);
7426 else if (fout->remoteVersion >= 90000)
7428 /* pg_language has a laninline column */
7429 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7430 "lanname, lanpltrusted, lanplcallfoid, "
7431 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7432 "NULL AS initlanacl, NULL AS initrlanacl, "
7433 "(%s lanowner) AS lanowner "
7439 else if (fout->remoteVersion >= 80300)
7441 /* pg_language has a lanowner column */
7442 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7443 "lanname, lanpltrusted, lanplcallfoid, "
7444 "0 AS laninline, lanvalidator, lanacl, "
7446 "NULL AS initlanacl, NULL AS initrlanacl, "
7447 "(%s lanowner) AS lanowner "
7453 else if (fout->remoteVersion >= 80100)
7455 /* Languages are owned by the bootstrap superuser, OID 10 */
7456 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7457 "lanname, lanpltrusted, lanplcallfoid, "
7458 "0 AS laninline, lanvalidator, lanacl, "
7460 "NULL AS initlanacl, NULL AS initrlanacl, "
7461 "(%s '10') AS lanowner "
7469 /* Languages are owned by the bootstrap superuser, sysid 1 */
7470 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7471 "lanname, lanpltrusted, lanplcallfoid, "
7472 "0 AS laninline, lanvalidator, lanacl, "
7474 "NULL AS initlanacl, NULL AS initrlanacl, "
7475 "(%s '1') AS lanowner "
7482 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7484 ntups = PQntuples(res);
7486 *numProcLangs = ntups;
7488 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7490 i_tableoid = PQfnumber(res, "tableoid");
7491 i_oid = PQfnumber(res, "oid");
7492 i_lanname = PQfnumber(res, "lanname");
7493 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7494 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7495 i_laninline = PQfnumber(res, "laninline");
7496 i_lanvalidator = PQfnumber(res, "lanvalidator");
7497 i_lanacl = PQfnumber(res, "lanacl");
7498 i_rlanacl = PQfnumber(res, "rlanacl");
7499 i_initlanacl = PQfnumber(res, "initlanacl");
7500 i_initrlanacl = PQfnumber(res, "initrlanacl");
7501 i_lanowner = PQfnumber(res, "lanowner");
7503 for (i = 0; i < ntups; i++)
7505 planginfo[i].dobj.objType = DO_PROCLANG;
7506 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7507 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7508 AssignDumpId(&planginfo[i].dobj);
7510 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7511 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7512 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7513 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7514 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7515 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7516 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7517 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7518 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7519 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7521 /* Decide whether we want to dump it */
7522 selectDumpableProcLang(&(planginfo[i]), fout);
7524 /* Do not try to dump ACL if no ACL exists. */
7525 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7526 PQgetisnull(res, i, i_initlanacl) &&
7527 PQgetisnull(res, i, i_initrlanacl))
7528 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7533 destroyPQExpBuffer(query);
7540 * get basic information about every cast in the system
7542 * numCasts is set to the number of casts read in
7545 getCasts(Archive *fout, int *numCasts)
7550 PQExpBuffer query = createPQExpBuffer();
7560 /* Make sure we are in proper schema */
7561 selectSourceSchema(fout, "pg_catalog");
7563 if (fout->remoteVersion >= 80400)
7565 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7566 "castsource, casttarget, castfunc, castcontext, "
7568 "FROM pg_cast ORDER BY 3,4");
7572 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7573 "castsource, casttarget, castfunc, castcontext, "
7574 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7575 "FROM pg_cast ORDER BY 3,4");
7578 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7580 ntups = PQntuples(res);
7584 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7586 i_tableoid = PQfnumber(res, "tableoid");
7587 i_oid = PQfnumber(res, "oid");
7588 i_castsource = PQfnumber(res, "castsource");
7589 i_casttarget = PQfnumber(res, "casttarget");
7590 i_castfunc = PQfnumber(res, "castfunc");
7591 i_castcontext = PQfnumber(res, "castcontext");
7592 i_castmethod = PQfnumber(res, "castmethod");
7594 for (i = 0; i < ntups; i++)
7596 PQExpBufferData namebuf;
7597 TypeInfo *sTypeInfo;
7598 TypeInfo *tTypeInfo;
7600 castinfo[i].dobj.objType = DO_CAST;
7601 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7602 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7603 AssignDumpId(&castinfo[i].dobj);
7604 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7605 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7606 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7607 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7608 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7611 * Try to name cast as concatenation of typnames. This is only used
7612 * for purposes of sorting. If we fail to find either type, the name
7613 * will be an empty string.
7615 initPQExpBuffer(&namebuf);
7616 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7617 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7618 if (sTypeInfo && tTypeInfo)
7619 appendPQExpBuffer(&namebuf, "%s %s",
7620 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7621 castinfo[i].dobj.name = namebuf.data;
7623 /* Decide whether we want to dump it */
7624 selectDumpableCast(&(castinfo[i]), fout);
7626 /* Casts do not currently have ACLs. */
7627 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7632 destroyPQExpBuffer(query);
7638 get_language_name(Archive *fout, Oid langid)
7644 query = createPQExpBuffer();
7645 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7646 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7647 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7648 destroyPQExpBuffer(query);
7656 * get basic information about every transform in the system
7658 * numTransforms is set to the number of transforms read in
7661 getTransforms(Archive *fout, int *numTransforms)
7667 TransformInfo *transforminfo;
7675 /* Transforms didn't exist pre-9.5 */
7676 if (fout->remoteVersion < 90500)
7682 query = createPQExpBuffer();
7684 /* Make sure we are in proper schema */
7685 selectSourceSchema(fout, "pg_catalog");
7687 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7688 "trftype, trflang, trffromsql::oid, trftosql::oid "
7689 "FROM pg_transform "
7692 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7694 ntups = PQntuples(res);
7696 *numTransforms = ntups;
7698 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
7700 i_tableoid = PQfnumber(res, "tableoid");
7701 i_oid = PQfnumber(res, "oid");
7702 i_trftype = PQfnumber(res, "trftype");
7703 i_trflang = PQfnumber(res, "trflang");
7704 i_trffromsql = PQfnumber(res, "trffromsql");
7705 i_trftosql = PQfnumber(res, "trftosql");
7707 for (i = 0; i < ntups; i++)
7709 PQExpBufferData namebuf;
7713 transforminfo[i].dobj.objType = DO_TRANSFORM;
7714 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7715 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7716 AssignDumpId(&transforminfo[i].dobj);
7717 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
7718 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
7719 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
7720 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
7723 * Try to name transform as concatenation of type and language name.
7724 * This is only used for purposes of sorting. If we fail to find
7725 * either, the name will be an empty string.
7727 initPQExpBuffer(&namebuf);
7728 typeInfo = findTypeByOid(transforminfo[i].trftype);
7729 lanname = get_language_name(fout, transforminfo[i].trflang);
7730 if (typeInfo && lanname)
7731 appendPQExpBuffer(&namebuf, "%s %s",
7732 typeInfo->dobj.name, lanname);
7733 transforminfo[i].dobj.name = namebuf.data;
7736 /* Decide whether we want to dump it */
7737 selectDumpableObject(&(transforminfo[i].dobj), fout);
7742 destroyPQExpBuffer(query);
7744 return transforminfo;
7749 * for each interesting table, read info about its attributes
7750 * (names, types, default values, CHECK constraints, etc)
7752 * This is implemented in a very inefficient way right now, looping
7753 * through the tblinfo and doing a join per table to find the attrs and their
7754 * types. However, because we want type names and so forth to be named
7755 * relative to the schema of each table, we couldn't do it in just one
7756 * query. (Maybe one query per schema?)
7761 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
7763 DumpOptions *dopt = fout->dopt;
7766 PQExpBuffer q = createPQExpBuffer();
7771 int i_attstattarget;
7783 int i_attfdwoptions;
7788 for (i = 0; i < numTables; i++)
7790 TableInfo *tbinfo = &tblinfo[i];
7792 /* Don't bother to collect info for sequences */
7793 if (tbinfo->relkind == RELKIND_SEQUENCE)
7796 /* Don't bother with uninteresting tables, either */
7797 if (!tbinfo->interesting)
7801 * Make sure we are in proper schema for this table; this allows
7802 * correct retrieval of formatted type names and default exprs
7804 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7806 /* find all the user attributes and their types */
7809 * we must read the attribute names in attribute number order! because
7810 * we will use the attnum to index into the attnames array later.
7813 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
7814 tbinfo->dobj.namespace->dobj.name,
7817 resetPQExpBuffer(q);
7819 if (fout->remoteVersion >= 100000)
7822 * attidentity is new in version 10.
7824 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7825 "a.attstattarget, a.attstorage, t.typstorage, "
7826 "a.attnotnull, a.atthasdef, a.attisdropped, "
7827 "a.attlen, a.attalign, a.attislocal, "
7828 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7829 "array_to_string(a.attoptions, ', ') AS attoptions, "
7830 "CASE WHEN a.attcollation <> t.typcollation "
7831 "THEN a.attcollation ELSE 0 END AS attcollation, "
7833 "pg_catalog.array_to_string(ARRAY("
7834 "SELECT pg_catalog.quote_ident(option_name) || "
7835 "' ' || pg_catalog.quote_literal(option_value) "
7836 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
7837 "ORDER BY option_name"
7838 "), E',\n ') AS attfdwoptions "
7839 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7840 "ON a.atttypid = t.oid "
7841 "WHERE a.attrelid = '%u'::pg_catalog.oid "
7842 "AND a.attnum > 0::pg_catalog.int2 "
7843 "ORDER BY a.attnum",
7844 tbinfo->dobj.catId.oid);
7846 else if (fout->remoteVersion >= 90200)
7849 * attfdwoptions is new in 9.2.
7851 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7852 "a.attstattarget, a.attstorage, t.typstorage, "
7853 "a.attnotnull, a.atthasdef, a.attisdropped, "
7854 "a.attlen, a.attalign, a.attislocal, "
7855 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7856 "array_to_string(a.attoptions, ', ') AS attoptions, "
7857 "CASE WHEN a.attcollation <> t.typcollation "
7858 "THEN a.attcollation ELSE 0 END AS attcollation, "
7859 "pg_catalog.array_to_string(ARRAY("
7860 "SELECT pg_catalog.quote_ident(option_name) || "
7861 "' ' || pg_catalog.quote_literal(option_value) "
7862 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
7863 "ORDER BY option_name"
7864 "), E',\n ') AS attfdwoptions "
7865 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7866 "ON a.atttypid = t.oid "
7867 "WHERE a.attrelid = '%u'::pg_catalog.oid "
7868 "AND a.attnum > 0::pg_catalog.int2 "
7869 "ORDER BY a.attnum",
7870 tbinfo->dobj.catId.oid);
7872 else if (fout->remoteVersion >= 90100)
7875 * attcollation is new in 9.1. Since we only want to dump COLLATE
7876 * clauses for attributes whose collation is different from their
7877 * type's default, we use a CASE here to suppress uninteresting
7878 * attcollations cheaply.
7880 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7881 "a.attstattarget, a.attstorage, t.typstorage, "
7882 "a.attnotnull, a.atthasdef, a.attisdropped, "
7883 "a.attlen, a.attalign, a.attislocal, "
7884 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7885 "array_to_string(a.attoptions, ', ') AS attoptions, "
7886 "CASE WHEN a.attcollation <> t.typcollation "
7887 "THEN a.attcollation ELSE 0 END AS attcollation, "
7888 "NULL AS attfdwoptions "
7889 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7890 "ON a.atttypid = t.oid "
7891 "WHERE a.attrelid = '%u'::pg_catalog.oid "
7892 "AND a.attnum > 0::pg_catalog.int2 "
7893 "ORDER BY a.attnum",
7894 tbinfo->dobj.catId.oid);
7896 else if (fout->remoteVersion >= 90000)
7898 /* attoptions is new in 9.0 */
7899 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7900 "a.attstattarget, a.attstorage, t.typstorage, "
7901 "a.attnotnull, a.atthasdef, a.attisdropped, "
7902 "a.attlen, a.attalign, a.attislocal, "
7903 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7904 "array_to_string(a.attoptions, ', ') AS attoptions, "
7905 "0 AS attcollation, "
7906 "NULL AS attfdwoptions "
7907 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7908 "ON a.atttypid = t.oid "
7909 "WHERE a.attrelid = '%u'::pg_catalog.oid "
7910 "AND a.attnum > 0::pg_catalog.int2 "
7911 "ORDER BY a.attnum",
7912 tbinfo->dobj.catId.oid);
7916 /* need left join here to not fail on dropped columns ... */
7917 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7918 "a.attstattarget, a.attstorage, t.typstorage, "
7919 "a.attnotnull, a.atthasdef, a.attisdropped, "
7920 "a.attlen, a.attalign, a.attislocal, "
7921 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7922 "'' AS attoptions, 0 AS attcollation, "
7923 "NULL AS attfdwoptions "
7924 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7925 "ON a.atttypid = t.oid "
7926 "WHERE a.attrelid = '%u'::pg_catalog.oid "
7927 "AND a.attnum > 0::pg_catalog.int2 "
7928 "ORDER BY a.attnum",
7929 tbinfo->dobj.catId.oid);
7932 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
7934 ntups = PQntuples(res);
7936 i_attnum = PQfnumber(res, "attnum");
7937 i_attname = PQfnumber(res, "attname");
7938 i_atttypname = PQfnumber(res, "atttypname");
7939 i_atttypmod = PQfnumber(res, "atttypmod");
7940 i_attstattarget = PQfnumber(res, "attstattarget");
7941 i_attstorage = PQfnumber(res, "attstorage");
7942 i_typstorage = PQfnumber(res, "typstorage");
7943 i_attnotnull = PQfnumber(res, "attnotnull");
7944 i_atthasdef = PQfnumber(res, "atthasdef");
7945 i_attidentity = PQfnumber(res, "attidentity");
7946 i_attisdropped = PQfnumber(res, "attisdropped");
7947 i_attlen = PQfnumber(res, "attlen");
7948 i_attalign = PQfnumber(res, "attalign");
7949 i_attislocal = PQfnumber(res, "attislocal");
7950 i_attoptions = PQfnumber(res, "attoptions");
7951 i_attcollation = PQfnumber(res, "attcollation");
7952 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
7954 tbinfo->numatts = ntups;
7955 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
7956 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
7957 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
7958 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
7959 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
7960 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
7961 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
7962 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
7963 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
7964 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
7965 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
7966 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
7967 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
7968 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
7969 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
7970 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
7971 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
7972 hasdefaults = false;
7974 for (j = 0; j < ntups; j++)
7976 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
7978 "invalid column numbering in table \"%s\"\n",
7980 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
7981 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
7982 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
7983 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
7984 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
7985 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
7986 tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
7987 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
7988 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
7989 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
7990 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
7991 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
7992 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
7993 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
7994 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
7995 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
7996 tbinfo->attrdefs[j] = NULL; /* fix below */
7997 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
7999 /* these flags will be set in flagInhAttrs() */
8000 tbinfo->inhNotNull[j] = false;
8006 * Get info about column defaults
8010 AttrDefInfo *attrdefs;
8014 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8015 tbinfo->dobj.namespace->dobj.name,
8018 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8019 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8020 "FROM pg_catalog.pg_attrdef "
8021 "WHERE adrelid = '%u'::pg_catalog.oid",
8022 tbinfo->dobj.catId.oid);
8024 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8026 numDefaults = PQntuples(res);
8027 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8029 for (j = 0; j < numDefaults; j++)
8033 adnum = atoi(PQgetvalue(res, j, 2));
8035 if (adnum <= 0 || adnum > ntups)
8037 "invalid adnum value %d for table \"%s\"\n",
8038 adnum, tbinfo->dobj.name);
8041 * dropped columns shouldn't have defaults, but just in case,
8044 if (tbinfo->attisdropped[adnum - 1])
8047 attrdefs[j].dobj.objType = DO_ATTRDEF;
8048 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8049 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8050 AssignDumpId(&attrdefs[j].dobj);
8051 attrdefs[j].adtable = tbinfo;
8052 attrdefs[j].adnum = adnum;
8053 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8055 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8056 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8058 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8061 * Defaults on a VIEW must always be dumped as separate ALTER
8062 * TABLE commands. Defaults on regular tables are dumped as
8063 * part of the CREATE TABLE if possible, which it won't be if
8064 * the column is not going to be emitted explicitly.
8066 if (tbinfo->relkind == RELKIND_VIEW)
8068 attrdefs[j].separate = true;
8070 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8072 /* column will be suppressed, print default separately */
8073 attrdefs[j].separate = true;
8077 attrdefs[j].separate = false;
8080 * Mark the default as needing to appear before the table,
8081 * so that any dependencies it has must be emitted before
8082 * the CREATE TABLE. If this is not possible, we'll
8083 * change to "separate" mode while sorting dependencies.
8085 addObjectDependency(&tbinfo->dobj,
8086 attrdefs[j].dobj.dumpId);
8089 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8095 * Get info about table CHECK constraints
8097 if (tbinfo->ncheck > 0)
8099 ConstraintInfo *constrs;
8103 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8104 tbinfo->dobj.namespace->dobj.name,
8107 resetPQExpBuffer(q);
8108 if (fout->remoteVersion >= 90200)
8111 * convalidated is new in 9.2 (actually, it is there in 9.1,
8112 * but it wasn't ever false for check constraints until 9.2).
8114 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8115 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8116 "conislocal, convalidated "
8117 "FROM pg_catalog.pg_constraint "
8118 "WHERE conrelid = '%u'::pg_catalog.oid "
8119 " AND contype = 'c' "
8121 tbinfo->dobj.catId.oid);
8123 else if (fout->remoteVersion >= 80400)
8125 /* conislocal is new in 8.4 */
8126 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8127 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8128 "conislocal, true AS convalidated "
8129 "FROM pg_catalog.pg_constraint "
8130 "WHERE conrelid = '%u'::pg_catalog.oid "
8131 " AND contype = 'c' "
8133 tbinfo->dobj.catId.oid);
8137 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8138 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8139 "true AS conislocal, true AS convalidated "
8140 "FROM pg_catalog.pg_constraint "
8141 "WHERE conrelid = '%u'::pg_catalog.oid "
8142 " AND contype = 'c' "
8144 tbinfo->dobj.catId.oid);
8147 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8149 numConstrs = PQntuples(res);
8150 if (numConstrs != tbinfo->ncheck)
8152 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8153 "expected %d check constraints on table \"%s\" but found %d\n",
8155 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8156 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8160 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8161 tbinfo->checkexprs = constrs;
8163 for (j = 0; j < numConstrs; j++)
8165 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8167 constrs[j].dobj.objType = DO_CONSTRAINT;
8168 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8169 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8170 AssignDumpId(&constrs[j].dobj);
8171 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8172 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8173 constrs[j].contable = tbinfo;
8174 constrs[j].condomain = NULL;
8175 constrs[j].contype = 'c';
8176 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8177 constrs[j].confrelid = InvalidOid;
8178 constrs[j].conindex = 0;
8179 constrs[j].condeferrable = false;
8180 constrs[j].condeferred = false;
8181 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8184 * An unvalidated constraint needs to be dumped separately, so
8185 * that potentially-violating existing data is loaded before
8188 constrs[j].separate = !validated;
8190 constrs[j].dobj.dump = tbinfo->dobj.dump;
8193 * Mark the constraint as needing to appear before the table
8194 * --- this is so that any other dependencies of the
8195 * constraint will be emitted before we try to create the
8196 * table. If the constraint is to be dumped separately, it
8197 * will be dumped after data is loaded anyway, so don't do it.
8198 * (There's an automatic dependency in the opposite direction
8199 * anyway, so don't need to add one manually here.)
8201 if (!constrs[j].separate)
8202 addObjectDependency(&tbinfo->dobj,
8203 constrs[j].dobj.dumpId);
8206 * If the constraint is inherited, this will be detected later
8207 * (in pre-8.4 databases). We also detect later if the
8208 * constraint must be split out from the table definition.
8215 destroyPQExpBuffer(q);
8219 * Test whether a column should be printed as part of table's CREATE TABLE.
8220 * Column number is zero-based.
8222 * Normally this is always true, but it's false for dropped columns, as well
8223 * as those that were inherited without any local definition. (If we print
8224 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8225 * However, in binary_upgrade mode, we must print all such columns anyway and
8226 * fix the attislocal/attisdropped state later, so as to keep control of the
8227 * physical column order.
8229 * This function exists because there are scattered nonobvious places that
8230 * must be kept in sync with this decision.
8233 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8235 if (dopt->binary_upgrade)
8237 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8243 * read all text search parsers in the system catalogs and return them
8244 * in the TSParserInfo* structure
8246 * numTSParsers is set to the number of parsers read in
8249 getTSParsers(Archive *fout, int *numTSParsers)
8255 TSParserInfo *prsinfo;
8266 /* Before 8.3, there is no built-in text search support */
8267 if (fout->remoteVersion < 80300)
8273 query = createPQExpBuffer();
8276 * find all text search objects, including builtin ones; we filter out
8277 * system-defined objects at dump-out time.
8280 /* Make sure we are in proper schema */
8281 selectSourceSchema(fout, "pg_catalog");
8283 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8284 "prsstart::oid, prstoken::oid, "
8285 "prsend::oid, prsheadline::oid, prslextype::oid "
8286 "FROM pg_ts_parser");
8288 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8290 ntups = PQntuples(res);
8291 *numTSParsers = ntups;
8293 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8295 i_tableoid = PQfnumber(res, "tableoid");
8296 i_oid = PQfnumber(res, "oid");
8297 i_prsname = PQfnumber(res, "prsname");
8298 i_prsnamespace = PQfnumber(res, "prsnamespace");
8299 i_prsstart = PQfnumber(res, "prsstart");
8300 i_prstoken = PQfnumber(res, "prstoken");
8301 i_prsend = PQfnumber(res, "prsend");
8302 i_prsheadline = PQfnumber(res, "prsheadline");
8303 i_prslextype = PQfnumber(res, "prslextype");
8305 for (i = 0; i < ntups; i++)
8307 prsinfo[i].dobj.objType = DO_TSPARSER;
8308 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8309 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8310 AssignDumpId(&prsinfo[i].dobj);
8311 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8312 prsinfo[i].dobj.namespace =
8314 atooid(PQgetvalue(res, i, i_prsnamespace)));
8315 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8316 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8317 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8318 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8319 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8321 /* Decide whether we want to dump it */
8322 selectDumpableObject(&(prsinfo[i].dobj), fout);
8324 /* Text Search Parsers do not currently have ACLs. */
8325 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8330 destroyPQExpBuffer(query);
8336 * getTSDictionaries:
8337 * read all text search dictionaries in the system catalogs and return them
8338 * in the TSDictInfo* structure
8340 * numTSDicts is set to the number of dictionaries read in
8343 getTSDictionaries(Archive *fout, int *numTSDicts)
8349 TSDictInfo *dictinfo;
8353 int i_dictnamespace;
8356 int i_dictinitoption;
8358 /* Before 8.3, there is no built-in text search support */
8359 if (fout->remoteVersion < 80300)
8365 query = createPQExpBuffer();
8367 /* Make sure we are in proper schema */
8368 selectSourceSchema(fout, "pg_catalog");
8370 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8371 "dictnamespace, (%s dictowner) AS rolname, "
8372 "dicttemplate, dictinitoption "
8376 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8378 ntups = PQntuples(res);
8379 *numTSDicts = ntups;
8381 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8383 i_tableoid = PQfnumber(res, "tableoid");
8384 i_oid = PQfnumber(res, "oid");
8385 i_dictname = PQfnumber(res, "dictname");
8386 i_dictnamespace = PQfnumber(res, "dictnamespace");
8387 i_rolname = PQfnumber(res, "rolname");
8388 i_dictinitoption = PQfnumber(res, "dictinitoption");
8389 i_dicttemplate = PQfnumber(res, "dicttemplate");
8391 for (i = 0; i < ntups; i++)
8393 dictinfo[i].dobj.objType = DO_TSDICT;
8394 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8395 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8396 AssignDumpId(&dictinfo[i].dobj);
8397 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8398 dictinfo[i].dobj.namespace =
8400 atooid(PQgetvalue(res, i, i_dictnamespace)));
8401 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8402 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8403 if (PQgetisnull(res, i, i_dictinitoption))
8404 dictinfo[i].dictinitoption = NULL;
8406 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8408 /* Decide whether we want to dump it */
8409 selectDumpableObject(&(dictinfo[i].dobj), fout);
8411 /* Text Search Dictionaries do not currently have ACLs. */
8412 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8417 destroyPQExpBuffer(query);
8424 * read all text search templates in the system catalogs and return them
8425 * in the TSTemplateInfo* structure
8427 * numTSTemplates is set to the number of templates read in
8430 getTSTemplates(Archive *fout, int *numTSTemplates)
8436 TSTemplateInfo *tmplinfo;
8440 int i_tmplnamespace;
8444 /* Before 8.3, there is no built-in text search support */
8445 if (fout->remoteVersion < 80300)
8447 *numTSTemplates = 0;
8451 query = createPQExpBuffer();
8453 /* Make sure we are in proper schema */
8454 selectSourceSchema(fout, "pg_catalog");
8456 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8457 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8458 "FROM pg_ts_template");
8460 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8462 ntups = PQntuples(res);
8463 *numTSTemplates = ntups;
8465 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8467 i_tableoid = PQfnumber(res, "tableoid");
8468 i_oid = PQfnumber(res, "oid");
8469 i_tmplname = PQfnumber(res, "tmplname");
8470 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8471 i_tmplinit = PQfnumber(res, "tmplinit");
8472 i_tmpllexize = PQfnumber(res, "tmpllexize");
8474 for (i = 0; i < ntups; i++)
8476 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8477 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8478 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8479 AssignDumpId(&tmplinfo[i].dobj);
8480 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8481 tmplinfo[i].dobj.namespace =
8483 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8484 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8485 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8487 /* Decide whether we want to dump it */
8488 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8490 /* Text Search Templates do not currently have ACLs. */
8491 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8496 destroyPQExpBuffer(query);
8502 * getTSConfigurations:
8503 * read all text search configurations in the system catalogs and return
8504 * them in the TSConfigInfo* structure
8506 * numTSConfigs is set to the number of configurations read in
8509 getTSConfigurations(Archive *fout, int *numTSConfigs)
8515 TSConfigInfo *cfginfo;
8523 /* Before 8.3, there is no built-in text search support */
8524 if (fout->remoteVersion < 80300)
8530 query = createPQExpBuffer();
8532 /* Make sure we are in proper schema */
8533 selectSourceSchema(fout, "pg_catalog");
8535 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8536 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8537 "FROM pg_ts_config",
8540 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8542 ntups = PQntuples(res);
8543 *numTSConfigs = ntups;
8545 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8547 i_tableoid = PQfnumber(res, "tableoid");
8548 i_oid = PQfnumber(res, "oid");
8549 i_cfgname = PQfnumber(res, "cfgname");
8550 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8551 i_rolname = PQfnumber(res, "rolname");
8552 i_cfgparser = PQfnumber(res, "cfgparser");
8554 for (i = 0; i < ntups; i++)
8556 cfginfo[i].dobj.objType = DO_TSCONFIG;
8557 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8558 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8559 AssignDumpId(&cfginfo[i].dobj);
8560 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8561 cfginfo[i].dobj.namespace =
8563 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8564 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8565 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8567 /* Decide whether we want to dump it */
8568 selectDumpableObject(&(cfginfo[i].dobj), fout);
8570 /* Text Search Configurations do not currently have ACLs. */
8571 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8576 destroyPQExpBuffer(query);
8582 * getForeignDataWrappers:
8583 * read all foreign-data wrappers in the system catalogs and return
8584 * them in the FdwInfo* structure
8586 * numForeignDataWrappers is set to the number of fdws read in
8589 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8591 DumpOptions *dopt = fout->dopt;
8609 /* Before 8.4, there are no foreign-data wrappers */
8610 if (fout->remoteVersion < 80400)
8612 *numForeignDataWrappers = 0;
8616 query = createPQExpBuffer();
8618 /* Make sure we are in proper schema */
8619 selectSourceSchema(fout, "pg_catalog");
8621 if (fout->remoteVersion >= 90600)
8623 PQExpBuffer acl_subquery = createPQExpBuffer();
8624 PQExpBuffer racl_subquery = createPQExpBuffer();
8625 PQExpBuffer initacl_subquery = createPQExpBuffer();
8626 PQExpBuffer initracl_subquery = createPQExpBuffer();
8628 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8629 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8630 dopt->binary_upgrade);
8632 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8633 "(%s f.fdwowner) AS rolname, "
8634 "f.fdwhandler::pg_catalog.regproc, "
8635 "f.fdwvalidator::pg_catalog.regproc, "
8638 "%s AS initfdwacl, "
8639 "%s AS initrfdwacl, "
8640 "array_to_string(ARRAY("
8641 "SELECT quote_ident(option_name) || ' ' || "
8642 "quote_literal(option_value) "
8643 "FROM pg_options_to_table(f.fdwoptions) "
8644 "ORDER BY option_name"
8645 "), E',\n ') AS fdwoptions "
8646 "FROM pg_foreign_data_wrapper f "
8647 "LEFT JOIN pg_init_privs pip ON "
8648 "(f.oid = pip.objoid "
8649 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8650 "AND pip.objsubid = 0) ",
8653 racl_subquery->data,
8654 initacl_subquery->data,
8655 initracl_subquery->data);
8657 destroyPQExpBuffer(acl_subquery);
8658 destroyPQExpBuffer(racl_subquery);
8659 destroyPQExpBuffer(initacl_subquery);
8660 destroyPQExpBuffer(initracl_subquery);
8662 else if (fout->remoteVersion >= 90100)
8664 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8665 "(%s fdwowner) AS rolname, "
8666 "fdwhandler::pg_catalog.regproc, "
8667 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8669 "NULL as initfdwacl, NULL AS initrfdwacl, "
8670 "array_to_string(ARRAY("
8671 "SELECT quote_ident(option_name) || ' ' || "
8672 "quote_literal(option_value) "
8673 "FROM pg_options_to_table(fdwoptions) "
8674 "ORDER BY option_name"
8675 "), E',\n ') AS fdwoptions "
8676 "FROM pg_foreign_data_wrapper",
8681 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8682 "(%s fdwowner) AS rolname, "
8683 "'-' AS fdwhandler, "
8684 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8686 "NULL as initfdwacl, NULL AS initrfdwacl, "
8687 "array_to_string(ARRAY("
8688 "SELECT quote_ident(option_name) || ' ' || "
8689 "quote_literal(option_value) "
8690 "FROM pg_options_to_table(fdwoptions) "
8691 "ORDER BY option_name"
8692 "), E',\n ') AS fdwoptions "
8693 "FROM pg_foreign_data_wrapper",
8697 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8699 ntups = PQntuples(res);
8700 *numForeignDataWrappers = ntups;
8702 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
8704 i_tableoid = PQfnumber(res, "tableoid");
8705 i_oid = PQfnumber(res, "oid");
8706 i_fdwname = PQfnumber(res, "fdwname");
8707 i_rolname = PQfnumber(res, "rolname");
8708 i_fdwhandler = PQfnumber(res, "fdwhandler");
8709 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
8710 i_fdwacl = PQfnumber(res, "fdwacl");
8711 i_rfdwacl = PQfnumber(res, "rfdwacl");
8712 i_initfdwacl = PQfnumber(res, "initfdwacl");
8713 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
8714 i_fdwoptions = PQfnumber(res, "fdwoptions");
8716 for (i = 0; i < ntups; i++)
8718 fdwinfo[i].dobj.objType = DO_FDW;
8719 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8720 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8721 AssignDumpId(&fdwinfo[i].dobj);
8722 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
8723 fdwinfo[i].dobj.namespace = NULL;
8724 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8725 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
8726 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
8727 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
8728 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
8729 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
8730 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
8731 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
8733 /* Decide whether we want to dump it */
8734 selectDumpableObject(&(fdwinfo[i].dobj), fout);
8736 /* Do not try to dump ACL if no ACL exists. */
8737 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
8738 PQgetisnull(res, i, i_initfdwacl) &&
8739 PQgetisnull(res, i, i_initrfdwacl))
8740 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8745 destroyPQExpBuffer(query);
8751 * getForeignServers:
8752 * read all foreign servers in the system catalogs and return
8753 * them in the ForeignServerInfo * structure
8755 * numForeignServers is set to the number of servers read in
8758 getForeignServers(Archive *fout, int *numForeignServers)
8760 DumpOptions *dopt = fout->dopt;
8765 ForeignServerInfo *srvinfo;
8779 /* Before 8.4, there are no foreign servers */
8780 if (fout->remoteVersion < 80400)
8782 *numForeignServers = 0;
8786 query = createPQExpBuffer();
8788 /* Make sure we are in proper schema */
8789 selectSourceSchema(fout, "pg_catalog");
8791 if (fout->remoteVersion >= 90600)
8793 PQExpBuffer acl_subquery = createPQExpBuffer();
8794 PQExpBuffer racl_subquery = createPQExpBuffer();
8795 PQExpBuffer initacl_subquery = createPQExpBuffer();
8796 PQExpBuffer initracl_subquery = createPQExpBuffer();
8798 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8799 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
8800 dopt->binary_upgrade);
8802 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
8803 "(%s f.srvowner) AS rolname, "
8804 "f.srvfdw, f.srvtype, f.srvversion, "
8807 "%s AS initsrvacl, "
8808 "%s AS initrsrvacl, "
8809 "array_to_string(ARRAY("
8810 "SELECT quote_ident(option_name) || ' ' || "
8811 "quote_literal(option_value) "
8812 "FROM pg_options_to_table(f.srvoptions) "
8813 "ORDER BY option_name"
8814 "), E',\n ') AS srvoptions "
8815 "FROM pg_foreign_server f "
8816 "LEFT JOIN pg_init_privs pip "
8817 "ON (f.oid = pip.objoid "
8818 "AND pip.classoid = 'pg_foreign_server'::regclass "
8819 "AND pip.objsubid = 0) ",
8822 racl_subquery->data,
8823 initacl_subquery->data,
8824 initracl_subquery->data);
8826 destroyPQExpBuffer(acl_subquery);
8827 destroyPQExpBuffer(racl_subquery);
8828 destroyPQExpBuffer(initacl_subquery);
8829 destroyPQExpBuffer(initracl_subquery);
8833 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
8834 "(%s srvowner) AS rolname, "
8835 "srvfdw, srvtype, srvversion, srvacl, "
8837 "NULL AS initsrvacl, NULL AS initrsrvacl, "
8838 "array_to_string(ARRAY("
8839 "SELECT quote_ident(option_name) || ' ' || "
8840 "quote_literal(option_value) "
8841 "FROM pg_options_to_table(srvoptions) "
8842 "ORDER BY option_name"
8843 "), E',\n ') AS srvoptions "
8844 "FROM pg_foreign_server",
8848 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8850 ntups = PQntuples(res);
8851 *numForeignServers = ntups;
8853 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
8855 i_tableoid = PQfnumber(res, "tableoid");
8856 i_oid = PQfnumber(res, "oid");
8857 i_srvname = PQfnumber(res, "srvname");
8858 i_rolname = PQfnumber(res, "rolname");
8859 i_srvfdw = PQfnumber(res, "srvfdw");
8860 i_srvtype = PQfnumber(res, "srvtype");
8861 i_srvversion = PQfnumber(res, "srvversion");
8862 i_srvacl = PQfnumber(res, "srvacl");
8863 i_rsrvacl = PQfnumber(res, "rsrvacl");
8864 i_initsrvacl = PQfnumber(res, "initsrvacl");
8865 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
8866 i_srvoptions = PQfnumber(res, "srvoptions");
8868 for (i = 0; i < ntups; i++)
8870 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
8871 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8872 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8873 AssignDumpId(&srvinfo[i].dobj);
8874 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
8875 srvinfo[i].dobj.namespace = NULL;
8876 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8877 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
8878 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
8879 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
8880 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
8881 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
8882 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
8883 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
8884 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
8886 /* Decide whether we want to dump it */
8887 selectDumpableObject(&(srvinfo[i].dobj), fout);
8889 /* Do not try to dump ACL if no ACL exists. */
8890 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
8891 PQgetisnull(res, i, i_initsrvacl) &&
8892 PQgetisnull(res, i, i_initrsrvacl))
8893 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8898 destroyPQExpBuffer(query);
8905 * read all default ACL information in the system catalogs and return
8906 * them in the DefaultACLInfo structure
8908 * numDefaultACLs is set to the number of ACLs read in
8911 getDefaultACLs(Archive *fout, int *numDefaultACLs)
8913 DumpOptions *dopt = fout->dopt;
8914 DefaultACLInfo *daclinfo;
8920 int i_defaclnamespace;
8921 int i_defaclobjtype;
8924 int i_initdefaclacl;
8925 int i_initrdefaclacl;
8929 if (fout->remoteVersion < 90000)
8931 *numDefaultACLs = 0;
8935 query = createPQExpBuffer();
8937 /* Make sure we are in proper schema */
8938 selectSourceSchema(fout, "pg_catalog");
8940 if (fout->remoteVersion >= 90600)
8942 PQExpBuffer acl_subquery = createPQExpBuffer();
8943 PQExpBuffer racl_subquery = createPQExpBuffer();
8944 PQExpBuffer initacl_subquery = createPQExpBuffer();
8945 PQExpBuffer initracl_subquery = createPQExpBuffer();
8947 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8948 initracl_subquery, "defaclacl", "defaclrole",
8949 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
8950 dopt->binary_upgrade);
8952 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
8953 "(%s d.defaclrole) AS defaclrole, "
8954 "d.defaclnamespace, "
8957 "%s AS rdefaclacl, "
8958 "%s AS initdefaclacl, "
8959 "%s AS initrdefaclacl "
8960 "FROM pg_default_acl d "
8961 "LEFT JOIN pg_init_privs pip ON "
8962 "(d.oid = pip.objoid "
8963 "AND pip.classoid = 'pg_default_acl'::regclass "
8964 "AND pip.objsubid = 0) ",
8967 racl_subquery->data,
8968 initacl_subquery->data,
8969 initracl_subquery->data);
8973 appendPQExpBuffer(query, "SELECT oid, tableoid, "
8974 "(%s defaclrole) AS defaclrole, "
8978 "NULL AS rdefaclacl, "
8979 "NULL AS initdefaclacl, "
8980 "NULL AS initrdefaclacl "
8981 "FROM pg_default_acl",
8985 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8987 ntups = PQntuples(res);
8988 *numDefaultACLs = ntups;
8990 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
8992 i_oid = PQfnumber(res, "oid");
8993 i_tableoid = PQfnumber(res, "tableoid");
8994 i_defaclrole = PQfnumber(res, "defaclrole");
8995 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
8996 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
8997 i_defaclacl = PQfnumber(res, "defaclacl");
8998 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
8999 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9000 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9002 for (i = 0; i < ntups; i++)
9004 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9006 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9007 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9008 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9009 AssignDumpId(&daclinfo[i].dobj);
9010 /* cheesy ... is it worth coming up with a better object name? */
9011 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9013 if (nspid != InvalidOid)
9014 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9016 daclinfo[i].dobj.namespace = NULL;
9018 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9019 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9020 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9021 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9022 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9023 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9025 /* Decide whether we want to dump it */
9026 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9031 destroyPQExpBuffer(query);
9039 * This routine is used to dump any comments associated with the
9040 * object handed to this routine. The routine takes a constant character
9041 * string for the target part of the comment-creation command, plus
9042 * the namespace and owner of the object (for labeling the ArchiveEntry),
9043 * plus catalog ID and subid which are the lookup key for pg_description,
9044 * plus the dump ID for the object (for setting a dependency).
9045 * If a matching pg_description entry is found, it is dumped.
9047 * Note: although this routine takes a dumpId for dependency purposes,
9048 * that purpose is just to mark the dependency in the emitted dump file
9049 * for possible future use by pg_restore. We do NOT use it for determining
9050 * ordering of the comment in the dump file, because this routine is called
9051 * after dependency sorting occurs. This routine should be called just after
9052 * calling ArchiveEntry() for the specified object.
9055 dumpComment(Archive *fout, const char *target,
9056 const char *namespace, const char *owner,
9057 CatalogId catalogId, int subid, DumpId dumpId)
9059 DumpOptions *dopt = fout->dopt;
9060 CommentItem *comments;
9063 /* Comments are schema not data ... except blob comments are data */
9064 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
9071 /* We do dump blob comments in binary-upgrade mode */
9072 if (dopt->schemaOnly && !dopt->binary_upgrade)
9076 /* Search for comments associated with catalogId, using table */
9077 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9080 /* Is there one matching the subid? */
9081 while (ncomments > 0)
9083 if (comments->objsubid == subid)
9089 /* If a comment exists, build COMMENT ON statement */
9092 PQExpBuffer query = createPQExpBuffer();
9094 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
9095 appendStringLiteralAH(query, comments->descr, fout);
9096 appendPQExpBufferStr(query, ";\n");
9099 * We mark comments as SECTION_NONE because they really belong in the
9100 * same section as their parent, whether that is pre-data or
9103 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9104 target, namespace, NULL, owner,
9105 false, "COMMENT", SECTION_NONE,
9106 query->data, "", NULL,
9110 destroyPQExpBuffer(query);
9115 * dumpTableComment --
9117 * As above, but dump comments for both the specified table (or view)
9121 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9122 const char *reltypename)
9124 DumpOptions *dopt = fout->dopt;
9125 CommentItem *comments;
9130 /* Comments are SCHEMA not data */
9134 /* Search for comments associated with relation, using table */
9135 ncomments = findComments(fout,
9136 tbinfo->dobj.catId.tableoid,
9137 tbinfo->dobj.catId.oid,
9140 /* If comments exist, build COMMENT ON statements */
9144 query = createPQExpBuffer();
9145 target = createPQExpBuffer();
9147 while (ncomments > 0)
9149 const char *descr = comments->descr;
9150 int objsubid = comments->objsubid;
9154 resetPQExpBuffer(target);
9155 appendPQExpBuffer(target, "%s %s", reltypename,
9156 fmtId(tbinfo->dobj.name));
9158 resetPQExpBuffer(query);
9159 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9160 appendStringLiteralAH(query, descr, fout);
9161 appendPQExpBufferStr(query, ";\n");
9163 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9165 tbinfo->dobj.namespace->dobj.name,
9166 NULL, tbinfo->rolname,
9167 false, "COMMENT", SECTION_NONE,
9168 query->data, "", NULL,
9169 &(tbinfo->dobj.dumpId), 1,
9172 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9174 resetPQExpBuffer(target);
9175 appendPQExpBuffer(target, "COLUMN %s.",
9176 fmtId(tbinfo->dobj.name));
9177 appendPQExpBufferStr(target, fmtId(tbinfo->attnames[objsubid - 1]));
9179 resetPQExpBuffer(query);
9180 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9181 appendStringLiteralAH(query, descr, fout);
9182 appendPQExpBufferStr(query, ";\n");
9184 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9186 tbinfo->dobj.namespace->dobj.name,
9187 NULL, tbinfo->rolname,
9188 false, "COMMENT", SECTION_NONE,
9189 query->data, "", NULL,
9190 &(tbinfo->dobj.dumpId), 1,
9198 destroyPQExpBuffer(query);
9199 destroyPQExpBuffer(target);
9205 * Find the comment(s), if any, associated with the given object. All the
9206 * objsubid values associated with the given classoid/objoid are found with
9210 findComments(Archive *fout, Oid classoid, Oid objoid,
9211 CommentItem **items)
9213 /* static storage for table of comments */
9214 static CommentItem *comments = NULL;
9215 static int ncomments = -1;
9217 CommentItem *middle = NULL;
9222 /* Get comments if we didn't already */
9224 ncomments = collectComments(fout, &comments);
9227 * Do binary search to find some item matching the object.
9230 high = &comments[ncomments - 1];
9233 middle = low + (high - low) / 2;
9235 if (classoid < middle->classoid)
9237 else if (classoid > middle->classoid)
9239 else if (objoid < middle->objoid)
9241 else if (objoid > middle->objoid)
9244 break; /* found a match */
9247 if (low > high) /* no matches */
9254 * Now determine how many items match the object. The search loop
9255 * invariant still holds: only items between low and high inclusive could
9259 while (middle > low)
9261 if (classoid != middle[-1].classoid ||
9262 objoid != middle[-1].objoid)
9271 while (middle <= high)
9273 if (classoid != middle->classoid ||
9274 objoid != middle->objoid)
9284 * collectComments --
9286 * Construct a table of all comments available for database objects.
9287 * We used to do per-object queries for the comments, but it's much faster
9288 * to pull them all over at once, and on most databases the memory cost
9291 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9294 collectComments(Archive *fout, CommentItem **items)
9304 CommentItem *comments;
9307 * Note we do NOT change source schema here; preserve the caller's
9311 query = createPQExpBuffer();
9313 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9314 "FROM pg_catalog.pg_description "
9315 "ORDER BY classoid, objoid, objsubid");
9317 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9319 /* Construct lookup table containing OIDs in numeric form */
9321 i_description = PQfnumber(res, "description");
9322 i_classoid = PQfnumber(res, "classoid");
9323 i_objoid = PQfnumber(res, "objoid");
9324 i_objsubid = PQfnumber(res, "objsubid");
9326 ntups = PQntuples(res);
9328 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9330 for (i = 0; i < ntups; i++)
9332 comments[i].descr = PQgetvalue(res, i, i_description);
9333 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9334 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9335 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9338 /* Do NOT free the PGresult since we are keeping pointers into it */
9339 destroyPQExpBuffer(query);
9346 * dumpDumpableObject
9348 * This routine and its subsidiaries are responsible for creating
9349 * ArchiveEntries (TOC objects) for each object to be dumped.
9352 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9354 switch (dobj->objType)
9357 dumpNamespace(fout, (NamespaceInfo *) dobj);
9360 dumpExtension(fout, (ExtensionInfo *) dobj);
9363 dumpType(fout, (TypeInfo *) dobj);
9366 dumpShellType(fout, (ShellTypeInfo *) dobj);
9369 dumpFunc(fout, (FuncInfo *) dobj);
9372 dumpAgg(fout, (AggInfo *) dobj);
9375 dumpOpr(fout, (OprInfo *) dobj);
9377 case DO_ACCESS_METHOD:
9378 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9381 dumpOpclass(fout, (OpclassInfo *) dobj);
9384 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9387 dumpCollation(fout, (CollInfo *) dobj);
9390 dumpConversion(fout, (ConvInfo *) dobj);
9393 dumpTable(fout, (TableInfo *) dobj);
9396 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9399 dumpIndex(fout, (IndxInfo *) dobj);
9402 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9404 case DO_REFRESH_MATVIEW:
9405 refreshMatViewData(fout, (TableDataInfo *) dobj);
9408 dumpRule(fout, (RuleInfo *) dobj);
9411 dumpTrigger(fout, (TriggerInfo *) dobj);
9413 case DO_EVENT_TRIGGER:
9414 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9417 dumpConstraint(fout, (ConstraintInfo *) dobj);
9419 case DO_FK_CONSTRAINT:
9420 dumpConstraint(fout, (ConstraintInfo *) dobj);
9423 dumpProcLang(fout, (ProcLangInfo *) dobj);
9426 dumpCast(fout, (CastInfo *) dobj);
9429 dumpTransform(fout, (TransformInfo *) dobj);
9431 case DO_SEQUENCE_SET:
9432 dumpSequenceData(fout, (TableDataInfo *) dobj);
9435 dumpTableData(fout, (TableDataInfo *) dobj);
9438 /* table rowtypes and array types are never dumped separately */
9441 dumpTSParser(fout, (TSParserInfo *) dobj);
9444 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9447 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9450 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9453 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9455 case DO_FOREIGN_SERVER:
9456 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9458 case DO_DEFAULT_ACL:
9459 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9462 dumpBlob(fout, (BlobInfo *) dobj);
9465 if (dobj->dump & DUMP_COMPONENT_DATA)
9466 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9467 dobj->name, NULL, NULL, "",
9468 false, "BLOBS", SECTION_DATA,
9474 dumpPolicy(fout, (PolicyInfo *) dobj);
9476 case DO_PUBLICATION:
9477 dumpPublication(fout, (PublicationInfo *) dobj);
9479 case DO_PUBLICATION_REL:
9480 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9482 case DO_SUBSCRIPTION:
9483 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9485 case DO_PRE_DATA_BOUNDARY:
9486 case DO_POST_DATA_BOUNDARY:
9487 /* never dumped, nothing to do */
9494 * writes out to fout the queries to recreate a user-defined namespace
9497 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9499 DumpOptions *dopt = fout->dopt;
9505 /* Skip if not to be dumped */
9506 if (!nspinfo->dobj.dump || dopt->dataOnly)
9509 q = createPQExpBuffer();
9510 delq = createPQExpBuffer();
9511 labelq = createPQExpBuffer();
9513 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9515 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9517 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9519 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
9521 if (dopt->binary_upgrade)
9522 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
9524 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9525 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9529 false, "SCHEMA", SECTION_PRE_DATA,
9530 q->data, delq->data, NULL,
9534 /* Dump Schema Comments and Security Labels */
9535 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9536 dumpComment(fout, labelq->data,
9537 NULL, nspinfo->rolname,
9538 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9540 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9541 dumpSecLabel(fout, labelq->data,
9542 NULL, nspinfo->rolname,
9543 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9545 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9546 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9547 qnspname, NULL, nspinfo->dobj.name, NULL,
9548 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9549 nspinfo->initnspacl, nspinfo->initrnspacl);
9553 destroyPQExpBuffer(q);
9554 destroyPQExpBuffer(delq);
9555 destroyPQExpBuffer(labelq);
9560 * writes out to fout the queries to recreate an extension
9563 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9565 DumpOptions *dopt = fout->dopt;
9571 /* Skip if not to be dumped */
9572 if (!extinfo->dobj.dump || dopt->dataOnly)
9575 q = createPQExpBuffer();
9576 delq = createPQExpBuffer();
9577 labelq = createPQExpBuffer();
9579 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9581 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9583 if (!dopt->binary_upgrade)
9586 * In a regular dump, we use IF NOT EXISTS so that there isn't a
9587 * problem if the extension already exists in the target database;
9588 * this is essential for installed-by-default extensions such as
9591 * In binary-upgrade mode, that doesn't work well, so instead we skip
9592 * built-in extensions based on their OIDs; see
9593 * selectDumpableExtension.
9595 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9596 qextname, fmtId(extinfo->namespace));
9603 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9606 * We unconditionally create the extension, so we must drop it if it
9607 * exists. This could happen if the user deleted 'plpgsql' and then
9608 * readded it, causing its oid to be greater than g_last_builtin_oid.
9609 * The g_last_builtin_oid test was kept to avoid repeatedly dropping
9610 * and recreating extensions like 'plpgsql'.
9612 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9614 appendPQExpBufferStr(q,
9615 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9616 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9617 appendPQExpBufferStr(q, ", ");
9618 appendStringLiteralAH(q, extinfo->namespace, fout);
9619 appendPQExpBufferStr(q, ", ");
9620 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9621 appendStringLiteralAH(q, extinfo->extversion, fout);
9622 appendPQExpBufferStr(q, ", ");
9625 * Note that we're pushing extconfig (an OID array) back into
9626 * pg_extension exactly as-is. This is OK because pg_class OIDs are
9627 * preserved in binary upgrade.
9629 if (strlen(extinfo->extconfig) > 2)
9630 appendStringLiteralAH(q, extinfo->extconfig, fout);
9632 appendPQExpBufferStr(q, "NULL");
9633 appendPQExpBufferStr(q, ", ");
9634 if (strlen(extinfo->extcondition) > 2)
9635 appendStringLiteralAH(q, extinfo->extcondition, fout);
9637 appendPQExpBufferStr(q, "NULL");
9638 appendPQExpBufferStr(q, ", ");
9639 appendPQExpBufferStr(q, "ARRAY[");
9641 for (i = 0; i < extinfo->dobj.nDeps; i++)
9643 DumpableObject *extobj;
9645 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9646 if (extobj && extobj->objType == DO_EXTENSION)
9649 appendPQExpBufferChar(q, ',');
9650 appendStringLiteralAH(q, extobj->name, fout);
9653 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
9654 appendPQExpBufferStr(q, ");\n");
9657 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
9659 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9660 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
9664 false, "EXTENSION", SECTION_PRE_DATA,
9665 q->data, delq->data, NULL,
9669 /* Dump Extension Comments and Security Labels */
9670 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9671 dumpComment(fout, labelq->data,
9673 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9675 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9676 dumpSecLabel(fout, labelq->data,
9678 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9682 destroyPQExpBuffer(q);
9683 destroyPQExpBuffer(delq);
9684 destroyPQExpBuffer(labelq);
9689 * writes out to fout the queries to recreate a user-defined type
9692 dumpType(Archive *fout, TypeInfo *tyinfo)
9694 DumpOptions *dopt = fout->dopt;
9696 /* Skip if not to be dumped */
9697 if (!tyinfo->dobj.dump || dopt->dataOnly)
9700 /* Dump out in proper style */
9701 if (tyinfo->typtype == TYPTYPE_BASE)
9702 dumpBaseType(fout, tyinfo);
9703 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
9704 dumpDomain(fout, tyinfo);
9705 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
9706 dumpCompositeType(fout, tyinfo);
9707 else if (tyinfo->typtype == TYPTYPE_ENUM)
9708 dumpEnumType(fout, tyinfo);
9709 else if (tyinfo->typtype == TYPTYPE_RANGE)
9710 dumpRangeType(fout, tyinfo);
9711 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
9712 dumpUndefinedType(fout, tyinfo);
9714 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
9720 * writes out to fout the queries to recreate a user-defined enum type
9723 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
9725 DumpOptions *dopt = fout->dopt;
9726 PQExpBuffer q = createPQExpBuffer();
9727 PQExpBuffer delq = createPQExpBuffer();
9728 PQExpBuffer labelq = createPQExpBuffer();
9729 PQExpBuffer query = createPQExpBuffer();
9737 /* Set proper schema search path */
9738 selectSourceSchema(fout, "pg_catalog");
9740 if (fout->remoteVersion >= 90100)
9741 appendPQExpBuffer(query, "SELECT oid, enumlabel "
9742 "FROM pg_catalog.pg_enum "
9743 "WHERE enumtypid = '%u'"
9744 "ORDER BY enumsortorder",
9745 tyinfo->dobj.catId.oid);
9747 appendPQExpBuffer(query, "SELECT oid, enumlabel "
9748 "FROM pg_catalog.pg_enum "
9749 "WHERE enumtypid = '%u'"
9751 tyinfo->dobj.catId.oid);
9753 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9755 num = PQntuples(res);
9757 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
9760 * DROP must be fully qualified in case same name appears in pg_catalog.
9761 * CASCADE shouldn't be required here as for normal types since the I/O
9762 * functions are generic and do not get dropped.
9764 appendPQExpBuffer(delq, "DROP TYPE %s.",
9765 fmtId(tyinfo->dobj.namespace->dobj.name));
9766 appendPQExpBuffer(delq, "%s;\n",
9769 if (dopt->binary_upgrade)
9770 binary_upgrade_set_type_oids_by_type_oid(fout, q,
9771 tyinfo->dobj.catId.oid);
9773 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
9776 if (!dopt->binary_upgrade)
9778 /* Labels with server-assigned oids */
9779 for (i = 0; i < num; i++)
9781 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
9783 appendPQExpBufferChar(q, ',');
9784 appendPQExpBufferStr(q, "\n ");
9785 appendStringLiteralAH(q, label, fout);
9789 appendPQExpBufferStr(q, "\n);\n");
9791 if (dopt->binary_upgrade)
9793 /* Labels with dump-assigned (preserved) oids */
9794 for (i = 0; i < num; i++)
9796 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
9797 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
9800 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
9801 appendPQExpBuffer(q,
9802 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
9804 appendPQExpBuffer(q, "ALTER TYPE %s.",
9805 fmtId(tyinfo->dobj.namespace->dobj.name));
9806 appendPQExpBuffer(q, "%s ADD VALUE ",
9808 appendStringLiteralAH(q, label, fout);
9809 appendPQExpBufferStr(q, ";\n\n");
9813 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
9815 if (dopt->binary_upgrade)
9816 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
9818 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9819 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
9821 tyinfo->dobj.namespace->dobj.name,
9823 tyinfo->rolname, false,
9824 "TYPE", SECTION_PRE_DATA,
9825 q->data, delq->data, NULL,
9829 /* Dump Type Comments and Security Labels */
9830 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9831 dumpComment(fout, labelq->data,
9832 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9833 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9835 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9836 dumpSecLabel(fout, labelq->data,
9837 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9838 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9840 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
9841 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
9842 qtypname, NULL, tyinfo->dobj.name,
9843 tyinfo->dobj.namespace->dobj.name,
9844 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
9845 tyinfo->inittypacl, tyinfo->initrtypacl);
9848 destroyPQExpBuffer(q);
9849 destroyPQExpBuffer(delq);
9850 destroyPQExpBuffer(labelq);
9851 destroyPQExpBuffer(query);
9856 * writes out to fout the queries to recreate a user-defined range type
9859 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
9861 DumpOptions *dopt = fout->dopt;
9862 PQExpBuffer q = createPQExpBuffer();
9863 PQExpBuffer delq = createPQExpBuffer();
9864 PQExpBuffer labelq = createPQExpBuffer();
9865 PQExpBuffer query = createPQExpBuffer();
9872 * select appropriate schema to ensure names in CREATE are properly
9875 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
9877 appendPQExpBuffer(query,
9878 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
9879 "opc.opcname AS opcname, "
9880 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
9881 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
9883 "CASE WHEN rngcollation = st.typcollation THEN 0 "
9884 " ELSE rngcollation END AS collation, "
9885 "rngcanonical, rngsubdiff "
9886 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
9887 " pg_catalog.pg_opclass opc "
9888 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
9890 tyinfo->dobj.catId.oid);
9892 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9894 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
9897 * DROP must be fully qualified in case same name appears in pg_catalog.
9898 * CASCADE shouldn't be required here as for normal types since the I/O
9899 * functions are generic and do not get dropped.
9901 appendPQExpBuffer(delq, "DROP TYPE %s.",
9902 fmtId(tyinfo->dobj.namespace->dobj.name));
9903 appendPQExpBuffer(delq, "%s;\n",
9906 if (dopt->binary_upgrade)
9907 binary_upgrade_set_type_oids_by_type_oid(fout,
9908 q, tyinfo->dobj.catId.oid);
9910 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
9913 appendPQExpBuffer(q, "\n subtype = %s",
9914 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
9916 /* print subtype_opclass only if not default for subtype */
9917 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
9919 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
9920 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
9922 /* always schema-qualify, don't try to be smart */
9923 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
9925 appendPQExpBufferStr(q, fmtId(opcname));
9928 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
9929 if (OidIsValid(collationOid))
9931 CollInfo *coll = findCollationByOid(collationOid);
9935 /* always schema-qualify, don't try to be smart */
9936 appendPQExpBuffer(q, ",\n collation = %s.",
9937 fmtId(coll->dobj.namespace->dobj.name));
9938 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
9942 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
9943 if (strcmp(procname, "-") != 0)
9944 appendPQExpBuffer(q, ",\n canonical = %s", procname);
9946 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
9947 if (strcmp(procname, "-") != 0)
9948 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
9950 appendPQExpBufferStr(q, "\n);\n");
9952 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
9954 if (dopt->binary_upgrade)
9955 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
9957 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9958 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
9960 tyinfo->dobj.namespace->dobj.name,
9962 tyinfo->rolname, false,
9963 "TYPE", SECTION_PRE_DATA,
9964 q->data, delq->data, NULL,
9968 /* Dump Type Comments and Security Labels */
9969 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9970 dumpComment(fout, labelq->data,
9971 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9972 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9974 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9975 dumpSecLabel(fout, labelq->data,
9976 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9977 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9979 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
9980 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
9981 qtypname, NULL, tyinfo->dobj.name,
9982 tyinfo->dobj.namespace->dobj.name,
9983 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
9984 tyinfo->inittypacl, tyinfo->initrtypacl);
9987 destroyPQExpBuffer(q);
9988 destroyPQExpBuffer(delq);
9989 destroyPQExpBuffer(labelq);
9990 destroyPQExpBuffer(query);
9995 * writes out to fout the queries to recreate a !typisdefined type
9997 * This is a shell type, but we use different terminology to distinguish
9998 * this case from where we have to emit a shell type definition to break
9999 * circular dependencies. An undefined type shouldn't ever have anything
10003 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10005 DumpOptions *dopt = fout->dopt;
10006 PQExpBuffer q = createPQExpBuffer();
10007 PQExpBuffer delq = createPQExpBuffer();
10008 PQExpBuffer labelq = createPQExpBuffer();
10011 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10014 * DROP must be fully qualified in case same name appears in pg_catalog.
10016 appendPQExpBuffer(delq, "DROP TYPE %s.",
10017 fmtId(tyinfo->dobj.namespace->dobj.name));
10018 appendPQExpBuffer(delq, "%s;\n",
10021 if (dopt->binary_upgrade)
10022 binary_upgrade_set_type_oids_by_type_oid(fout,
10023 q, tyinfo->dobj.catId.oid);
10025 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10028 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10030 if (dopt->binary_upgrade)
10031 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10033 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10034 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10036 tyinfo->dobj.namespace->dobj.name,
10038 tyinfo->rolname, false,
10039 "TYPE", SECTION_PRE_DATA,
10040 q->data, delq->data, NULL,
10044 /* Dump Type Comments and Security Labels */
10045 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10046 dumpComment(fout, labelq->data,
10047 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10048 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10050 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10051 dumpSecLabel(fout, labelq->data,
10052 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10053 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10055 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10056 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10057 qtypname, NULL, tyinfo->dobj.name,
10058 tyinfo->dobj.namespace->dobj.name,
10059 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10060 tyinfo->inittypacl, tyinfo->initrtypacl);
10062 destroyPQExpBuffer(q);
10063 destroyPQExpBuffer(delq);
10064 destroyPQExpBuffer(labelq);
10069 * writes out to fout the queries to recreate a user-defined base type
10072 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10074 DumpOptions *dopt = fout->dopt;
10075 PQExpBuffer q = createPQExpBuffer();
10076 PQExpBuffer delq = createPQExpBuffer();
10077 PQExpBuffer labelq = createPQExpBuffer();
10078 PQExpBuffer query = createPQExpBuffer();
10095 char *typispreferred;
10100 char *typcollatable;
10102 bool typdefault_is_literal = false;
10104 /* Set proper schema search path so regproc references list correctly */
10105 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10107 /* Fetch type-specific details */
10108 if (fout->remoteVersion >= 90100)
10110 appendPQExpBuffer(query, "SELECT typlen, "
10111 "typinput, typoutput, typreceive, typsend, "
10112 "typmodin, typmodout, typanalyze, "
10113 "typreceive::pg_catalog.oid AS typreceiveoid, "
10114 "typsend::pg_catalog.oid AS typsendoid, "
10115 "typmodin::pg_catalog.oid AS typmodinoid, "
10116 "typmodout::pg_catalog.oid AS typmodoutoid, "
10117 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10118 "typcategory, typispreferred, "
10119 "typdelim, typbyval, typalign, typstorage, "
10120 "(typcollation <> 0) AS typcollatable, "
10121 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10122 "FROM pg_catalog.pg_type "
10123 "WHERE oid = '%u'::pg_catalog.oid",
10124 tyinfo->dobj.catId.oid);
10126 else if (fout->remoteVersion >= 80400)
10128 appendPQExpBuffer(query, "SELECT typlen, "
10129 "typinput, typoutput, typreceive, typsend, "
10130 "typmodin, typmodout, typanalyze, "
10131 "typreceive::pg_catalog.oid AS typreceiveoid, "
10132 "typsend::pg_catalog.oid AS typsendoid, "
10133 "typmodin::pg_catalog.oid AS typmodinoid, "
10134 "typmodout::pg_catalog.oid AS typmodoutoid, "
10135 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10136 "typcategory, typispreferred, "
10137 "typdelim, typbyval, typalign, typstorage, "
10138 "false AS typcollatable, "
10139 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10140 "FROM pg_catalog.pg_type "
10141 "WHERE oid = '%u'::pg_catalog.oid",
10142 tyinfo->dobj.catId.oid);
10144 else if (fout->remoteVersion >= 80300)
10146 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10147 appendPQExpBuffer(query, "SELECT typlen, "
10148 "typinput, typoutput, typreceive, typsend, "
10149 "typmodin, typmodout, typanalyze, "
10150 "typreceive::pg_catalog.oid AS typreceiveoid, "
10151 "typsend::pg_catalog.oid AS typsendoid, "
10152 "typmodin::pg_catalog.oid AS typmodinoid, "
10153 "typmodout::pg_catalog.oid AS typmodoutoid, "
10154 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10155 "'U' AS typcategory, false AS typispreferred, "
10156 "typdelim, typbyval, typalign, typstorage, "
10157 "false AS typcollatable, "
10158 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10159 "FROM pg_catalog.pg_type "
10160 "WHERE oid = '%u'::pg_catalog.oid",
10161 tyinfo->dobj.catId.oid);
10165 appendPQExpBuffer(query, "SELECT typlen, "
10166 "typinput, typoutput, typreceive, typsend, "
10167 "'-' AS typmodin, '-' AS typmodout, "
10169 "typreceive::pg_catalog.oid AS typreceiveoid, "
10170 "typsend::pg_catalog.oid AS typsendoid, "
10171 "0 AS typmodinoid, 0 AS typmodoutoid, "
10172 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10173 "'U' AS typcategory, false AS typispreferred, "
10174 "typdelim, typbyval, typalign, typstorage, "
10175 "false AS typcollatable, "
10176 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10177 "FROM pg_catalog.pg_type "
10178 "WHERE oid = '%u'::pg_catalog.oid",
10179 tyinfo->dobj.catId.oid);
10182 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10184 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10185 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10186 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10187 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10188 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10189 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10190 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10191 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10192 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10193 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10194 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10195 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10196 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10197 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10198 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10199 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10200 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10201 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10202 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10203 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10204 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10205 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10206 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10208 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10209 typdefault_is_literal = true; /* it needs quotes */
10214 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10217 * DROP must be fully qualified in case same name appears in pg_catalog.
10218 * The reason we include CASCADE is that the circular dependency between
10219 * the type and its I/O functions makes it impossible to drop the type any
10222 appendPQExpBuffer(delq, "DROP TYPE %s.",
10223 fmtId(tyinfo->dobj.namespace->dobj.name));
10224 appendPQExpBuffer(delq, "%s CASCADE;\n",
10227 /* We might already have a shell type, but setting pg_type_oid is harmless */
10228 if (dopt->binary_upgrade)
10229 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10230 tyinfo->dobj.catId.oid);
10232 appendPQExpBuffer(q,
10233 "CREATE TYPE %s (\n"
10234 " INTERNALLENGTH = %s",
10236 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10238 /* regproc result is sufficiently quoted already */
10239 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10240 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10241 if (OidIsValid(typreceiveoid))
10242 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10243 if (OidIsValid(typsendoid))
10244 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10245 if (OidIsValid(typmodinoid))
10246 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10247 if (OidIsValid(typmodoutoid))
10248 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10249 if (OidIsValid(typanalyzeoid))
10250 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10252 if (strcmp(typcollatable, "t") == 0)
10253 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10255 if (typdefault != NULL)
10257 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10258 if (typdefault_is_literal)
10259 appendStringLiteralAH(q, typdefault, fout);
10261 appendPQExpBufferStr(q, typdefault);
10264 if (OidIsValid(tyinfo->typelem))
10268 /* reselect schema in case changed by function dump */
10269 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10270 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10271 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10275 if (strcmp(typcategory, "U") != 0)
10277 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10278 appendStringLiteralAH(q, typcategory, fout);
10281 if (strcmp(typispreferred, "t") == 0)
10282 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10284 if (typdelim && strcmp(typdelim, ",") != 0)
10286 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10287 appendStringLiteralAH(q, typdelim, fout);
10290 if (strcmp(typalign, "c") == 0)
10291 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10292 else if (strcmp(typalign, "s") == 0)
10293 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10294 else if (strcmp(typalign, "i") == 0)
10295 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10296 else if (strcmp(typalign, "d") == 0)
10297 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10299 if (strcmp(typstorage, "p") == 0)
10300 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10301 else if (strcmp(typstorage, "e") == 0)
10302 appendPQExpBufferStr(q, ",\n STORAGE = external");
10303 else if (strcmp(typstorage, "x") == 0)
10304 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10305 else if (strcmp(typstorage, "m") == 0)
10306 appendPQExpBufferStr(q, ",\n STORAGE = main");
10308 if (strcmp(typbyval, "t") == 0)
10309 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10311 appendPQExpBufferStr(q, "\n);\n");
10313 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10315 if (dopt->binary_upgrade)
10316 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10318 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10319 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10321 tyinfo->dobj.namespace->dobj.name,
10323 tyinfo->rolname, false,
10324 "TYPE", SECTION_PRE_DATA,
10325 q->data, delq->data, NULL,
10329 /* Dump Type Comments and Security Labels */
10330 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10331 dumpComment(fout, labelq->data,
10332 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10333 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10335 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10336 dumpSecLabel(fout, labelq->data,
10337 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10338 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10340 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10341 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10342 qtypname, NULL, tyinfo->dobj.name,
10343 tyinfo->dobj.namespace->dobj.name,
10344 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10345 tyinfo->inittypacl, tyinfo->initrtypacl);
10348 destroyPQExpBuffer(q);
10349 destroyPQExpBuffer(delq);
10350 destroyPQExpBuffer(labelq);
10351 destroyPQExpBuffer(query);
10356 * writes out to fout the queries to recreate a user-defined domain
10359 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10361 DumpOptions *dopt = fout->dopt;
10362 PQExpBuffer q = createPQExpBuffer();
10363 PQExpBuffer delq = createPQExpBuffer();
10364 PQExpBuffer labelq = createPQExpBuffer();
10365 PQExpBuffer query = createPQExpBuffer();
10373 bool typdefault_is_literal = false;
10375 /* Set proper schema search path so type references list correctly */
10376 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10378 /* Fetch domain specific details */
10379 if (fout->remoteVersion >= 90100)
10381 /* typcollation is new in 9.1 */
10382 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10383 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10384 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10386 "CASE WHEN t.typcollation <> u.typcollation "
10387 "THEN t.typcollation ELSE 0 END AS typcollation "
10388 "FROM pg_catalog.pg_type t "
10389 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10390 "WHERE t.oid = '%u'::pg_catalog.oid",
10391 tyinfo->dobj.catId.oid);
10395 appendPQExpBuffer(query, "SELECT typnotnull, "
10396 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10397 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10398 "typdefault, 0 AS typcollation "
10399 "FROM pg_catalog.pg_type "
10400 "WHERE oid = '%u'::pg_catalog.oid",
10401 tyinfo->dobj.catId.oid);
10404 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10406 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10407 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10408 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10409 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10410 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10412 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10413 typdefault_is_literal = true; /* it needs quotes */
10417 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10419 if (dopt->binary_upgrade)
10420 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10421 tyinfo->dobj.catId.oid);
10423 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10425 appendPQExpBuffer(q,
10426 "CREATE DOMAIN %s AS %s",
10430 /* Print collation only if different from base type's collation */
10431 if (OidIsValid(typcollation))
10435 coll = findCollationByOid(typcollation);
10438 /* always schema-qualify, don't try to be smart */
10439 appendPQExpBuffer(q, " COLLATE %s.",
10440 fmtId(coll->dobj.namespace->dobj.name));
10441 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10445 if (typnotnull[0] == 't')
10446 appendPQExpBufferStr(q, " NOT NULL");
10448 if (typdefault != NULL)
10450 appendPQExpBufferStr(q, " DEFAULT ");
10451 if (typdefault_is_literal)
10452 appendStringLiteralAH(q, typdefault, fout);
10454 appendPQExpBufferStr(q, typdefault);
10460 * Add any CHECK constraints for the domain
10462 for (i = 0; i < tyinfo->nDomChecks; i++)
10464 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10466 if (!domcheck->separate)
10467 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10468 fmtId(domcheck->dobj.name), domcheck->condef);
10471 appendPQExpBufferStr(q, ";\n");
10474 * DROP must be fully qualified in case same name appears in pg_catalog
10476 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
10477 fmtId(tyinfo->dobj.namespace->dobj.name));
10478 appendPQExpBuffer(delq, "%s;\n",
10481 appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
10483 if (dopt->binary_upgrade)
10484 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10486 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10487 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10489 tyinfo->dobj.namespace->dobj.name,
10491 tyinfo->rolname, false,
10492 "DOMAIN", SECTION_PRE_DATA,
10493 q->data, delq->data, NULL,
10497 /* Dump Domain Comments and Security Labels */
10498 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10499 dumpComment(fout, labelq->data,
10500 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10501 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10503 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10504 dumpSecLabel(fout, labelq->data,
10505 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10506 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10508 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10509 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10510 qtypname, NULL, tyinfo->dobj.name,
10511 tyinfo->dobj.namespace->dobj.name,
10512 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10513 tyinfo->inittypacl, tyinfo->initrtypacl);
10515 /* Dump any per-constraint comments */
10516 for (i = 0; i < tyinfo->nDomChecks; i++)
10518 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10519 PQExpBuffer labelq = createPQExpBuffer();
10521 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
10522 fmtId(domcheck->dobj.name));
10523 appendPQExpBuffer(labelq, "ON DOMAIN %s",
10526 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10527 dumpComment(fout, labelq->data,
10528 tyinfo->dobj.namespace->dobj.name,
10530 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10532 destroyPQExpBuffer(labelq);
10535 destroyPQExpBuffer(q);
10536 destroyPQExpBuffer(delq);
10537 destroyPQExpBuffer(labelq);
10538 destroyPQExpBuffer(query);
10542 * dumpCompositeType
10543 * writes out to fout the queries to recreate a user-defined stand-alone
10547 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10549 DumpOptions *dopt = fout->dopt;
10550 PQExpBuffer q = createPQExpBuffer();
10551 PQExpBuffer dropped = createPQExpBuffer();
10552 PQExpBuffer delq = createPQExpBuffer();
10553 PQExpBuffer labelq = createPQExpBuffer();
10554 PQExpBuffer query = createPQExpBuffer();
10562 int i_attisdropped;
10563 int i_attcollation;
10567 /* Set proper schema search path so type references list correctly */
10568 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10570 /* Fetch type specific details */
10571 if (fout->remoteVersion >= 90100)
10574 * attcollation is new in 9.1. Since we only want to dump COLLATE
10575 * clauses for attributes whose collation is different from their
10576 * type's default, we use a CASE here to suppress uninteresting
10577 * attcollations cheaply. atttypid will be 0 for dropped columns;
10578 * collation does not matter for those.
10580 appendPQExpBuffer(query, "SELECT a.attname, "
10581 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10582 "a.attlen, a.attalign, a.attisdropped, "
10583 "CASE WHEN a.attcollation <> at.typcollation "
10584 "THEN a.attcollation ELSE 0 END AS attcollation "
10585 "FROM pg_catalog.pg_type ct "
10586 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10587 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10588 "WHERE ct.oid = '%u'::pg_catalog.oid "
10589 "ORDER BY a.attnum ",
10590 tyinfo->dobj.catId.oid);
10595 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10596 * should always be false.
10598 appendPQExpBuffer(query, "SELECT a.attname, "
10599 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10600 "a.attlen, a.attalign, a.attisdropped, "
10601 "0 AS attcollation "
10602 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10603 "WHERE ct.oid = '%u'::pg_catalog.oid "
10604 "AND a.attrelid = ct.typrelid "
10605 "ORDER BY a.attnum ",
10606 tyinfo->dobj.catId.oid);
10609 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10611 ntups = PQntuples(res);
10613 i_attname = PQfnumber(res, "attname");
10614 i_atttypdefn = PQfnumber(res, "atttypdefn");
10615 i_attlen = PQfnumber(res, "attlen");
10616 i_attalign = PQfnumber(res, "attalign");
10617 i_attisdropped = PQfnumber(res, "attisdropped");
10618 i_attcollation = PQfnumber(res, "attcollation");
10620 if (dopt->binary_upgrade)
10622 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10623 tyinfo->dobj.catId.oid);
10624 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10627 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10629 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10633 for (i = 0; i < ntups; i++)
10642 attname = PQgetvalue(res, i, i_attname);
10643 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10644 attlen = PQgetvalue(res, i, i_attlen);
10645 attalign = PQgetvalue(res, i, i_attalign);
10646 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10647 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10649 if (attisdropped && !dopt->binary_upgrade)
10652 /* Format properly if not first attr */
10653 if (actual_atts++ > 0)
10654 appendPQExpBufferChar(q, ',');
10655 appendPQExpBufferStr(q, "\n\t");
10659 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10661 /* Add collation if not default for the column type */
10662 if (OidIsValid(attcollation))
10666 coll = findCollationByOid(attcollation);
10669 /* always schema-qualify, don't try to be smart */
10670 appendPQExpBuffer(q, " COLLATE %s.",
10671 fmtId(coll->dobj.namespace->dobj.name));
10672 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10679 * This is a dropped attribute and we're in binary_upgrade mode.
10680 * Insert a placeholder for it in the CREATE TYPE command, and set
10681 * length and alignment with direct UPDATE to the catalogs
10682 * afterwards. See similar code in dumpTableSchema().
10684 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
10686 /* stash separately for insertion after the CREATE TYPE */
10687 appendPQExpBufferStr(dropped,
10688 "\n-- For binary upgrade, recreate dropped column.\n");
10689 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
10690 "SET attlen = %s, "
10691 "attalign = '%s', attbyval = false\n"
10692 "WHERE attname = ", attlen, attalign);
10693 appendStringLiteralAH(dropped, attname, fout);
10694 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
10695 appendStringLiteralAH(dropped, qtypname, fout);
10696 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
10698 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
10700 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
10704 appendPQExpBufferStr(q, "\n);\n");
10705 appendPQExpBufferStr(q, dropped->data);
10708 * DROP must be fully qualified in case same name appears in pg_catalog
10710 appendPQExpBuffer(delq, "DROP TYPE %s.",
10711 fmtId(tyinfo->dobj.namespace->dobj.name));
10712 appendPQExpBuffer(delq, "%s;\n",
10715 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10717 if (dopt->binary_upgrade)
10718 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10720 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10721 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10723 tyinfo->dobj.namespace->dobj.name,
10725 tyinfo->rolname, false,
10726 "TYPE", SECTION_PRE_DATA,
10727 q->data, delq->data, NULL,
10732 /* Dump Type Comments and Security Labels */
10733 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10734 dumpComment(fout, labelq->data,
10735 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10736 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10738 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10739 dumpSecLabel(fout, labelq->data,
10740 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10741 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10743 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10744 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10745 qtypname, NULL, tyinfo->dobj.name,
10746 tyinfo->dobj.namespace->dobj.name,
10747 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10748 tyinfo->inittypacl, tyinfo->initrtypacl);
10751 destroyPQExpBuffer(q);
10752 destroyPQExpBuffer(dropped);
10753 destroyPQExpBuffer(delq);
10754 destroyPQExpBuffer(labelq);
10755 destroyPQExpBuffer(query);
10757 /* Dump any per-column comments */
10758 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10759 dumpCompositeTypeColComments(fout, tyinfo);
10763 * dumpCompositeTypeColComments
10764 * writes out to fout the queries to recreate comments on the columns of
10765 * a user-defined stand-alone composite type
10768 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
10770 CommentItem *comments;
10774 PQExpBuffer target;
10781 query = createPQExpBuffer();
10783 appendPQExpBuffer(query,
10784 "SELECT c.tableoid, a.attname, a.attnum "
10785 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
10786 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
10787 " AND NOT a.attisdropped "
10788 "ORDER BY a.attnum ",
10791 /* Fetch column attnames */
10792 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10794 ntups = PQntuples(res);
10798 destroyPQExpBuffer(query);
10802 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
10804 /* Search for comments associated with type's pg_class OID */
10805 ncomments = findComments(fout,
10810 /* If no comments exist, we're done */
10811 if (ncomments <= 0)
10814 destroyPQExpBuffer(query);
10818 /* Build COMMENT ON statements */
10819 target = createPQExpBuffer();
10821 i_attnum = PQfnumber(res, "attnum");
10822 i_attname = PQfnumber(res, "attname");
10823 while (ncomments > 0)
10825 const char *attname;
10828 for (i = 0; i < ntups; i++)
10830 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
10832 attname = PQgetvalue(res, i, i_attname);
10836 if (attname) /* just in case we don't find it */
10838 const char *descr = comments->descr;
10840 resetPQExpBuffer(target);
10841 appendPQExpBuffer(target, "COLUMN %s.",
10842 fmtId(tyinfo->dobj.name));
10843 appendPQExpBufferStr(target, fmtId(attname));
10845 resetPQExpBuffer(query);
10846 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
10847 appendStringLiteralAH(query, descr, fout);
10848 appendPQExpBufferStr(query, ";\n");
10850 ArchiveEntry(fout, nilCatalogId, createDumpId(),
10852 tyinfo->dobj.namespace->dobj.name,
10853 NULL, tyinfo->rolname,
10854 false, "COMMENT", SECTION_NONE,
10855 query->data, "", NULL,
10856 &(tyinfo->dobj.dumpId), 1,
10865 destroyPQExpBuffer(query);
10866 destroyPQExpBuffer(target);
10871 * writes out to fout the queries to create a shell type
10873 * We dump a shell definition in advance of the I/O functions for the type.
10876 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
10878 DumpOptions *dopt = fout->dopt;
10881 /* Skip if not to be dumped */
10882 if (!stinfo->dobj.dump || dopt->dataOnly)
10885 q = createPQExpBuffer();
10888 * Note the lack of a DROP command for the shell type; any required DROP
10889 * is driven off the base type entry, instead. This interacts with
10890 * _printTocEntry()'s use of the presence of a DROP command to decide
10891 * whether an entry needs an ALTER OWNER command. We don't want to alter
10892 * the shell type's owner immediately on creation; that should happen only
10893 * after it's filled in, otherwise the backend complains.
10896 if (dopt->binary_upgrade)
10897 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10898 stinfo->baseType->dobj.catId.oid);
10900 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10901 fmtId(stinfo->dobj.name));
10903 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10904 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
10906 stinfo->dobj.namespace->dobj.name,
10908 stinfo->baseType->rolname, false,
10909 "SHELL TYPE", SECTION_PRE_DATA,
10914 destroyPQExpBuffer(q);
10919 * writes out to fout the queries to recreate a user-defined
10920 * procedural language
10923 dumpProcLang(Archive *fout, ProcLangInfo *plang)
10925 DumpOptions *dopt = fout->dopt;
10926 PQExpBuffer defqry;
10927 PQExpBuffer delqry;
10928 PQExpBuffer labelq;
10932 FuncInfo *funcInfo;
10933 FuncInfo *inlineInfo = NULL;
10934 FuncInfo *validatorInfo = NULL;
10936 /* Skip if not to be dumped */
10937 if (!plang->dobj.dump || dopt->dataOnly)
10941 * Try to find the support function(s). It is not an error if we don't
10942 * find them --- if the functions are in the pg_catalog schema, as is
10943 * standard in 8.1 and up, then we won't have loaded them. (In this case
10944 * we will emit a parameterless CREATE LANGUAGE command, which will
10945 * require PL template knowledge in the backend to reload.)
10948 funcInfo = findFuncByOid(plang->lanplcallfoid);
10949 if (funcInfo != NULL && !funcInfo->dobj.dump)
10950 funcInfo = NULL; /* treat not-dumped same as not-found */
10952 if (OidIsValid(plang->laninline))
10954 inlineInfo = findFuncByOid(plang->laninline);
10955 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
10959 if (OidIsValid(plang->lanvalidator))
10961 validatorInfo = findFuncByOid(plang->lanvalidator);
10962 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
10963 validatorInfo = NULL;
10967 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
10968 * with parameters. Otherwise, we'll write a parameterless command, which
10969 * will rely on data from pg_pltemplate.
10971 useParams = (funcInfo != NULL &&
10972 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
10973 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
10975 defqry = createPQExpBuffer();
10976 delqry = createPQExpBuffer();
10977 labelq = createPQExpBuffer();
10979 qlanname = pg_strdup(fmtId(plang->dobj.name));
10982 * If dumping a HANDLER clause, treat the language as being in the handler
10983 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
10984 * it doesn't really have a schema.
10987 lanschema = funcInfo->dobj.namespace->dobj.name;
10991 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
10996 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
10997 plang->lanpltrusted ? "TRUSTED " : "",
10999 appendPQExpBuffer(defqry, " HANDLER %s",
11000 fmtId(funcInfo->dobj.name));
11001 if (OidIsValid(plang->laninline))
11003 appendPQExpBufferStr(defqry, " INLINE ");
11004 /* Cope with possibility that inline is in different schema */
11005 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
11006 appendPQExpBuffer(defqry, "%s.",
11007 fmtId(inlineInfo->dobj.namespace->dobj.name));
11008 appendPQExpBufferStr(defqry, fmtId(inlineInfo->dobj.name));
11010 if (OidIsValid(plang->lanvalidator))
11012 appendPQExpBufferStr(defqry, " VALIDATOR ");
11013 /* Cope with possibility that validator is in different schema */
11014 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
11015 appendPQExpBuffer(defqry, "%s.",
11016 fmtId(validatorInfo->dobj.namespace->dobj.name));
11017 appendPQExpBufferStr(defqry, fmtId(validatorInfo->dobj.name));
11023 * If not dumping parameters, then use CREATE OR REPLACE so that the
11024 * command will not fail if the language is preinstalled in the target
11025 * database. We restrict the use of REPLACE to this case so as to
11026 * eliminate the risk of replacing a language with incompatible
11027 * parameter settings: this command will only succeed at all if there
11028 * is a pg_pltemplate entry, and if there is one, the existing entry
11029 * must match it too.
11031 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11034 appendPQExpBufferStr(defqry, ";\n");
11036 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
11038 if (dopt->binary_upgrade)
11039 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
11041 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11042 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11044 lanschema, NULL, plang->lanowner,
11045 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11046 defqry->data, delqry->data, NULL,
11050 /* Dump Proc Lang Comments and Security Labels */
11051 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11052 dumpComment(fout, labelq->data,
11053 lanschema, plang->lanowner,
11054 plang->dobj.catId, 0, plang->dobj.dumpId);
11056 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11057 dumpSecLabel(fout, labelq->data,
11058 lanschema, plang->lanowner,
11059 plang->dobj.catId, 0, plang->dobj.dumpId);
11061 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11062 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11063 qlanname, NULL, plang->dobj.name,
11065 plang->lanowner, plang->lanacl, plang->rlanacl,
11066 plang->initlanacl, plang->initrlanacl);
11070 destroyPQExpBuffer(defqry);
11071 destroyPQExpBuffer(delqry);
11072 destroyPQExpBuffer(labelq);
11076 * format_function_arguments: generate function name and argument list
11078 * This is used when we can rely on pg_get_function_arguments to format
11079 * the argument list. Note, however, that pg_get_function_arguments
11080 * does not special-case zero-argument aggregates.
11083 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11085 PQExpBufferData fn;
11087 initPQExpBuffer(&fn);
11088 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11089 if (is_agg && finfo->nargs == 0)
11090 appendPQExpBufferStr(&fn, "(*)");
11092 appendPQExpBuffer(&fn, "(%s)", funcargs);
11097 * format_function_arguments_old: generate function name and argument list
11099 * The argument type names are qualified if needed. The function name
11100 * is never qualified.
11102 * This is used only with pre-8.4 servers, so we aren't expecting to see
11103 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11105 * Any or all of allargtypes, argmodes, argnames may be NULL.
11108 format_function_arguments_old(Archive *fout,
11109 FuncInfo *finfo, int nallargs,
11110 char **allargtypes,
11114 PQExpBufferData fn;
11117 initPQExpBuffer(&fn);
11118 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11119 for (j = 0; j < nallargs; j++)
11123 const char *argmode;
11124 const char *argname;
11126 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11127 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11131 switch (argmodes[j][0])
11133 case PROARGMODE_IN:
11136 case PROARGMODE_OUT:
11139 case PROARGMODE_INOUT:
11140 argmode = "INOUT ";
11143 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11151 argname = argnames ? argnames[j] : (char *) NULL;
11152 if (argname && argname[0] == '\0')
11155 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11156 (j > 0) ? ", " : "",
11158 argname ? fmtId(argname) : "",
11159 argname ? " " : "",
11163 appendPQExpBufferChar(&fn, ')');
11168 * format_function_signature: generate function name and argument list
11170 * This is like format_function_arguments_old except that only a minimal
11171 * list of input argument types is generated; this is sufficient to
11172 * reference the function, but not to define it.
11174 * If honor_quotes is false then the function name is never quoted.
11175 * This is appropriate for use in TOC tags, but not in SQL commands.
11178 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11180 PQExpBufferData fn;
11183 initPQExpBuffer(&fn);
11185 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11187 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11188 for (j = 0; j < finfo->nargs; j++)
11193 appendPQExpBufferStr(&fn, ", ");
11195 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11197 appendPQExpBufferStr(&fn, typname);
11200 appendPQExpBufferChar(&fn, ')');
11207 * dump out one function
11210 dumpFunc(Archive *fout, FuncInfo *finfo)
11212 DumpOptions *dopt = fout->dopt;
11215 PQExpBuffer delqry;
11216 PQExpBuffer labelq;
11217 PQExpBuffer asPart;
11219 char *funcsig; /* identity signature */
11220 char *funcfullsig = NULL; /* full signature */
11228 char *proallargtypes;
11236 char *proleakproof;
11244 char **allargtypes = NULL;
11245 char **argmodes = NULL;
11246 char **argnames = NULL;
11247 char **configitems = NULL;
11248 int nconfigitems = 0;
11251 /* Skip if not to be dumped */
11252 if (!finfo->dobj.dump || dopt->dataOnly)
11255 query = createPQExpBuffer();
11256 q = createPQExpBuffer();
11257 delqry = createPQExpBuffer();
11258 labelq = createPQExpBuffer();
11259 asPart = createPQExpBuffer();
11261 /* Set proper schema search path so type references list correctly */
11262 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
11264 /* Fetch function-specific details */
11265 if (fout->remoteVersion >= 90600)
11268 * proparallel was added in 9.6
11270 appendPQExpBuffer(query,
11271 "SELECT proretset, prosrc, probin, "
11272 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11273 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11274 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11275 "array_to_string(protrftypes, ' ') AS protrftypes, "
11276 "proiswindow, provolatile, proisstrict, prosecdef, "
11277 "proleakproof, proconfig, procost, prorows, "
11279 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11280 "FROM pg_catalog.pg_proc "
11281 "WHERE oid = '%u'::pg_catalog.oid",
11282 finfo->dobj.catId.oid);
11284 else if (fout->remoteVersion >= 90500)
11287 * protrftypes was added in 9.5
11289 appendPQExpBuffer(query,
11290 "SELECT proretset, prosrc, probin, "
11291 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11292 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11293 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11294 "array_to_string(protrftypes, ' ') AS protrftypes, "
11295 "proiswindow, provolatile, proisstrict, prosecdef, "
11296 "proleakproof, proconfig, procost, prorows, "
11297 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11298 "FROM pg_catalog.pg_proc "
11299 "WHERE oid = '%u'::pg_catalog.oid",
11300 finfo->dobj.catId.oid);
11302 else if (fout->remoteVersion >= 90200)
11305 * proleakproof was added in 9.2
11307 appendPQExpBuffer(query,
11308 "SELECT proretset, prosrc, probin, "
11309 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11310 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11311 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11312 "proiswindow, provolatile, proisstrict, prosecdef, "
11313 "proleakproof, proconfig, procost, prorows, "
11314 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11315 "FROM pg_catalog.pg_proc "
11316 "WHERE oid = '%u'::pg_catalog.oid",
11317 finfo->dobj.catId.oid);
11319 else if (fout->remoteVersion >= 80400)
11322 * In 8.4 and up we rely on pg_get_function_arguments and
11323 * pg_get_function_result instead of examining proallargtypes etc.
11325 appendPQExpBuffer(query,
11326 "SELECT proretset, prosrc, probin, "
11327 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11328 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11329 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11330 "proiswindow, provolatile, proisstrict, prosecdef, "
11331 "false AS proleakproof, "
11332 " proconfig, procost, prorows, "
11333 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11334 "FROM pg_catalog.pg_proc "
11335 "WHERE oid = '%u'::pg_catalog.oid",
11336 finfo->dobj.catId.oid);
11338 else if (fout->remoteVersion >= 80300)
11340 appendPQExpBuffer(query,
11341 "SELECT proretset, prosrc, probin, "
11342 "proallargtypes, proargmodes, proargnames, "
11343 "false AS proiswindow, "
11344 "provolatile, proisstrict, prosecdef, "
11345 "false AS proleakproof, "
11346 "proconfig, procost, prorows, "
11347 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11348 "FROM pg_catalog.pg_proc "
11349 "WHERE oid = '%u'::pg_catalog.oid",
11350 finfo->dobj.catId.oid);
11352 else if (fout->remoteVersion >= 80100)
11354 appendPQExpBuffer(query,
11355 "SELECT proretset, prosrc, probin, "
11356 "proallargtypes, proargmodes, proargnames, "
11357 "false AS proiswindow, "
11358 "provolatile, proisstrict, prosecdef, "
11359 "false AS proleakproof, "
11360 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11361 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11362 "FROM pg_catalog.pg_proc "
11363 "WHERE oid = '%u'::pg_catalog.oid",
11364 finfo->dobj.catId.oid);
11368 appendPQExpBuffer(query,
11369 "SELECT proretset, prosrc, probin, "
11370 "null AS proallargtypes, "
11371 "null AS proargmodes, "
11373 "false AS proiswindow, "
11374 "provolatile, proisstrict, prosecdef, "
11375 "false AS proleakproof, "
11376 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11377 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11378 "FROM pg_catalog.pg_proc "
11379 "WHERE oid = '%u'::pg_catalog.oid",
11380 finfo->dobj.catId.oid);
11383 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11385 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11386 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11387 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11388 if (fout->remoteVersion >= 80400)
11390 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11391 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11392 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11393 proallargtypes = proargmodes = proargnames = NULL;
11397 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11398 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11399 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11400 funcargs = funciargs = funcresult = NULL;
11402 if (PQfnumber(res, "protrftypes") != -1)
11403 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11405 protrftypes = NULL;
11406 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
11407 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11408 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11409 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11410 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11411 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11412 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11413 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11415 if (PQfnumber(res, "proparallel") != -1)
11416 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11418 proparallel = NULL;
11420 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11423 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11424 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11425 * versions would set it to "-". There are no known cases in which prosrc
11426 * is unused, so the tests below for "-" are probably useless.
11428 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11430 appendPQExpBufferStr(asPart, "AS ");
11431 appendStringLiteralAH(asPart, probin, fout);
11432 if (strcmp(prosrc, "-") != 0)
11434 appendPQExpBufferStr(asPart, ", ");
11437 * where we have bin, use dollar quoting if allowed and src
11438 * contains quote or backslash; else use regular quoting.
11440 if (dopt->disable_dollar_quoting ||
11441 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11442 appendStringLiteralAH(asPart, prosrc, fout);
11444 appendStringLiteralDQ(asPart, prosrc, NULL);
11449 if (strcmp(prosrc, "-") != 0)
11451 appendPQExpBufferStr(asPart, "AS ");
11452 /* with no bin, dollar quote src unconditionally if allowed */
11453 if (dopt->disable_dollar_quoting)
11454 appendStringLiteralAH(asPart, prosrc, fout);
11456 appendStringLiteralDQ(asPart, prosrc, NULL);
11460 nallargs = finfo->nargs; /* unless we learn different from allargs */
11462 if (proallargtypes && *proallargtypes)
11466 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11467 nitems < finfo->nargs)
11469 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11472 allargtypes = NULL;
11478 if (proargmodes && *proargmodes)
11482 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11483 nitems != nallargs)
11485 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11492 if (proargnames && *proargnames)
11496 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11497 nitems != nallargs)
11499 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11506 if (proconfig && *proconfig)
11508 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11510 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11513 configitems = NULL;
11520 /* 8.4 or later; we rely on server-side code for most of the work */
11521 funcfullsig = format_function_arguments(finfo, funcargs, false);
11522 funcsig = format_function_arguments(finfo, funciargs, false);
11525 /* pre-8.4, do it ourselves */
11526 funcsig = format_function_arguments_old(fout,
11527 finfo, nallargs, allargtypes,
11528 argmodes, argnames);
11530 funcsig_tag = format_function_signature(fout, finfo, false);
11533 * DROP must be fully qualified in case same name appears in pg_catalog
11535 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
11536 fmtId(finfo->dobj.namespace->dobj.name),
11539 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig ? funcfullsig :
11542 appendPQExpBuffer(q, "RETURNS %s", funcresult);
11545 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11547 appendPQExpBuffer(q, "RETURNS %s%s",
11548 (proretset[0] == 't') ? "SETOF " : "",
11553 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11555 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11557 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11560 appendPQExpBufferStr(q, " TRANSFORM ");
11561 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11562 for (i = 0; typeids[i]; i++)
11565 appendPQExpBufferStr(q, ", ");
11566 appendPQExpBuffer(q, "FOR TYPE %s",
11567 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11571 if (proiswindow[0] == 't')
11572 appendPQExpBufferStr(q, " WINDOW");
11574 if (provolatile[0] != PROVOLATILE_VOLATILE)
11576 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11577 appendPQExpBufferStr(q, " IMMUTABLE");
11578 else if (provolatile[0] == PROVOLATILE_STABLE)
11579 appendPQExpBufferStr(q, " STABLE");
11580 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11581 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11585 if (proisstrict[0] == 't')
11586 appendPQExpBufferStr(q, " STRICT");
11588 if (prosecdef[0] == 't')
11589 appendPQExpBufferStr(q, " SECURITY DEFINER");
11591 if (proleakproof[0] == 't')
11592 appendPQExpBufferStr(q, " LEAKPROOF");
11595 * COST and ROWS are emitted only if present and not default, so as not to
11596 * break backwards-compatibility of the dump without need. Keep this code
11597 * in sync with the defaults in functioncmds.c.
11599 if (strcmp(procost, "0") != 0)
11601 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11603 /* default cost is 1 */
11604 if (strcmp(procost, "1") != 0)
11605 appendPQExpBuffer(q, " COST %s", procost);
11609 /* default cost is 100 */
11610 if (strcmp(procost, "100") != 0)
11611 appendPQExpBuffer(q, " COST %s", procost);
11614 if (proretset[0] == 't' &&
11615 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11616 appendPQExpBuffer(q, " ROWS %s", prorows);
11618 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11620 if (proparallel[0] == PROPARALLEL_SAFE)
11621 appendPQExpBufferStr(q, " PARALLEL SAFE");
11622 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11623 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11624 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11625 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11629 for (i = 0; i < nconfigitems; i++)
11631 /* we feel free to scribble on configitems[] here */
11632 char *configitem = configitems[i];
11635 pos = strchr(configitem, '=');
11639 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
11642 * Some GUC variable names are 'LIST' type and hence must not be
11645 if (pg_strcasecmp(configitem, "DateStyle") == 0
11646 || pg_strcasecmp(configitem, "search_path") == 0)
11647 appendPQExpBufferStr(q, pos);
11649 appendStringLiteralAH(q, pos, fout);
11652 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
11654 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
11656 if (dopt->binary_upgrade)
11657 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
11659 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11660 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
11662 finfo->dobj.namespace->dobj.name,
11664 finfo->rolname, false,
11665 "FUNCTION", SECTION_PRE_DATA,
11666 q->data, delqry->data, NULL,
11670 /* Dump Function Comments and Security Labels */
11671 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11672 dumpComment(fout, labelq->data,
11673 finfo->dobj.namespace->dobj.name, finfo->rolname,
11674 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11676 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11677 dumpSecLabel(fout, labelq->data,
11678 finfo->dobj.namespace->dobj.name, finfo->rolname,
11679 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11681 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
11682 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
11683 funcsig, NULL, funcsig_tag,
11684 finfo->dobj.namespace->dobj.name,
11685 finfo->rolname, finfo->proacl, finfo->rproacl,
11686 finfo->initproacl, finfo->initrproacl);
11690 destroyPQExpBuffer(query);
11691 destroyPQExpBuffer(q);
11692 destroyPQExpBuffer(delqry);
11693 destroyPQExpBuffer(labelq);
11694 destroyPQExpBuffer(asPart);
11711 * Dump a user-defined cast
11714 dumpCast(Archive *fout, CastInfo *cast)
11716 DumpOptions *dopt = fout->dopt;
11717 PQExpBuffer defqry;
11718 PQExpBuffer delqry;
11719 PQExpBuffer labelq;
11720 FuncInfo *funcInfo = NULL;
11724 /* Skip if not to be dumped */
11725 if (!cast->dobj.dump || dopt->dataOnly)
11728 /* Cannot dump if we don't have the cast function's info */
11729 if (OidIsValid(cast->castfunc))
11731 funcInfo = findFuncByOid(cast->castfunc);
11732 if (funcInfo == NULL)
11733 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11738 * Make sure we are in proper schema (needed for getFormattedTypeName).
11739 * Casts don't have a schema of their own, so use pg_catalog.
11741 selectSourceSchema(fout, "pg_catalog");
11743 defqry = createPQExpBuffer();
11744 delqry = createPQExpBuffer();
11745 labelq = createPQExpBuffer();
11747 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
11748 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
11749 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
11750 sourceType, targetType);
11752 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
11753 sourceType, targetType);
11755 switch (cast->castmethod)
11757 case COERCION_METHOD_BINARY:
11758 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
11760 case COERCION_METHOD_INOUT:
11761 appendPQExpBufferStr(defqry, "WITH INOUT");
11763 case COERCION_METHOD_FUNCTION:
11766 char *fsig = format_function_signature(fout, funcInfo, true);
11769 * Always qualify the function name, in case it is not in
11770 * pg_catalog schema (format_function_signature won't qualify
11773 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
11774 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
11778 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
11781 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
11784 if (cast->castcontext == 'a')
11785 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
11786 else if (cast->castcontext == 'i')
11787 appendPQExpBufferStr(defqry, " AS IMPLICIT");
11788 appendPQExpBufferStr(defqry, ";\n");
11790 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
11791 sourceType, targetType);
11793 if (dopt->binary_upgrade)
11794 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
11796 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
11797 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
11799 "pg_catalog", NULL, "",
11800 false, "CAST", SECTION_PRE_DATA,
11801 defqry->data, delqry->data, NULL,
11805 /* Dump Cast Comments */
11806 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
11807 dumpComment(fout, labelq->data,
11809 cast->dobj.catId, 0, cast->dobj.dumpId);
11814 destroyPQExpBuffer(defqry);
11815 destroyPQExpBuffer(delqry);
11816 destroyPQExpBuffer(labelq);
11823 dumpTransform(Archive *fout, TransformInfo *transform)
11825 DumpOptions *dopt = fout->dopt;
11826 PQExpBuffer defqry;
11827 PQExpBuffer delqry;
11828 PQExpBuffer labelq;
11829 FuncInfo *fromsqlFuncInfo = NULL;
11830 FuncInfo *tosqlFuncInfo = NULL;
11832 char *transformType;
11834 /* Skip if not to be dumped */
11835 if (!transform->dobj.dump || dopt->dataOnly)
11838 /* Cannot dump if we don't have the transform functions' info */
11839 if (OidIsValid(transform->trffromsql))
11841 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
11842 if (fromsqlFuncInfo == NULL)
11843 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11844 transform->trffromsql);
11846 if (OidIsValid(transform->trftosql))
11848 tosqlFuncInfo = findFuncByOid(transform->trftosql);
11849 if (tosqlFuncInfo == NULL)
11850 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11851 transform->trftosql);
11854 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
11855 selectSourceSchema(fout, "pg_catalog");
11857 defqry = createPQExpBuffer();
11858 delqry = createPQExpBuffer();
11859 labelq = createPQExpBuffer();
11861 lanname = get_language_name(fout, transform->trflang);
11862 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
11864 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
11865 transformType, lanname);
11867 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
11868 transformType, lanname);
11870 if (!transform->trffromsql && !transform->trftosql)
11871 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
11873 if (transform->trffromsql)
11875 if (fromsqlFuncInfo)
11877 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
11880 * Always qualify the function name, in case it is not in
11881 * pg_catalog schema (format_function_signature won't qualify it).
11883 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
11884 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
11888 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
11891 if (transform->trftosql)
11893 if (transform->trffromsql)
11894 appendPQExpBuffer(defqry, ", ");
11898 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
11901 * Always qualify the function name, in case it is not in
11902 * pg_catalog schema (format_function_signature won't qualify it).
11904 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
11905 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
11909 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
11912 appendPQExpBuffer(defqry, ");\n");
11914 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
11915 transformType, lanname);
11917 if (dopt->binary_upgrade)
11918 binary_upgrade_extension_member(defqry, &transform->dobj, labelq->data);
11920 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
11921 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
11923 "pg_catalog", NULL, "",
11924 false, "TRANSFORM", SECTION_PRE_DATA,
11925 defqry->data, delqry->data, NULL,
11926 transform->dobj.dependencies, transform->dobj.nDeps,
11929 /* Dump Transform Comments */
11930 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
11931 dumpComment(fout, labelq->data,
11933 transform->dobj.catId, 0, transform->dobj.dumpId);
11936 free(transformType);
11937 destroyPQExpBuffer(defqry);
11938 destroyPQExpBuffer(delqry);
11939 destroyPQExpBuffer(labelq);
11945 * write out a single operator definition
11948 dumpOpr(Archive *fout, OprInfo *oprinfo)
11950 DumpOptions *dopt = fout->dopt;
11954 PQExpBuffer labelq;
11956 PQExpBuffer details;
11981 /* Skip if not to be dumped */
11982 if (!oprinfo->dobj.dump || dopt->dataOnly)
11986 * some operators are invalid because they were the result of user
11987 * defining operators before commutators exist
11989 if (!OidIsValid(oprinfo->oprcode))
11992 query = createPQExpBuffer();
11993 q = createPQExpBuffer();
11994 delq = createPQExpBuffer();
11995 labelq = createPQExpBuffer();
11996 oprid = createPQExpBuffer();
11997 details = createPQExpBuffer();
11999 /* Make sure we are in proper schema so regoperator works correctly */
12000 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
12002 if (fout->remoteVersion >= 80300)
12004 appendPQExpBuffer(query, "SELECT oprkind, "
12005 "oprcode::pg_catalog.regprocedure, "
12006 "oprleft::pg_catalog.regtype, "
12007 "oprright::pg_catalog.regtype, "
12008 "oprcom::pg_catalog.regoperator, "
12009 "oprnegate::pg_catalog.regoperator, "
12010 "oprrest::pg_catalog.regprocedure, "
12011 "oprjoin::pg_catalog.regprocedure, "
12012 "oprcanmerge, oprcanhash "
12013 "FROM pg_catalog.pg_operator "
12014 "WHERE oid = '%u'::pg_catalog.oid",
12015 oprinfo->dobj.catId.oid);
12019 appendPQExpBuffer(query, "SELECT oprkind, "
12020 "oprcode::pg_catalog.regprocedure, "
12021 "oprleft::pg_catalog.regtype, "
12022 "oprright::pg_catalog.regtype, "
12023 "oprcom::pg_catalog.regoperator, "
12024 "oprnegate::pg_catalog.regoperator, "
12025 "oprrest::pg_catalog.regprocedure, "
12026 "oprjoin::pg_catalog.regprocedure, "
12027 "(oprlsortop != 0) AS oprcanmerge, "
12029 "FROM pg_catalog.pg_operator "
12030 "WHERE oid = '%u'::pg_catalog.oid",
12031 oprinfo->dobj.catId.oid);
12034 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12036 i_oprkind = PQfnumber(res, "oprkind");
12037 i_oprcode = PQfnumber(res, "oprcode");
12038 i_oprleft = PQfnumber(res, "oprleft");
12039 i_oprright = PQfnumber(res, "oprright");
12040 i_oprcom = PQfnumber(res, "oprcom");
12041 i_oprnegate = PQfnumber(res, "oprnegate");
12042 i_oprrest = PQfnumber(res, "oprrest");
12043 i_oprjoin = PQfnumber(res, "oprjoin");
12044 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12045 i_oprcanhash = PQfnumber(res, "oprcanhash");
12047 oprkind = PQgetvalue(res, 0, i_oprkind);
12048 oprcode = PQgetvalue(res, 0, i_oprcode);
12049 oprleft = PQgetvalue(res, 0, i_oprleft);
12050 oprright = PQgetvalue(res, 0, i_oprright);
12051 oprcom = PQgetvalue(res, 0, i_oprcom);
12052 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12053 oprrest = PQgetvalue(res, 0, i_oprrest);
12054 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12055 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12056 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12058 oprregproc = convertRegProcReference(fout, oprcode);
12061 appendPQExpBuffer(details, " PROCEDURE = %s", oprregproc);
12065 appendPQExpBuffer(oprid, "%s (",
12066 oprinfo->dobj.name);
12069 * right unary means there's a left arg and left unary means there's a
12072 if (strcmp(oprkind, "r") == 0 ||
12073 strcmp(oprkind, "b") == 0)
12075 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12076 appendPQExpBufferStr(oprid, oprleft);
12079 appendPQExpBufferStr(oprid, "NONE");
12081 if (strcmp(oprkind, "l") == 0 ||
12082 strcmp(oprkind, "b") == 0)
12084 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12085 appendPQExpBuffer(oprid, ", %s)", oprright);
12088 appendPQExpBufferStr(oprid, ", NONE)");
12090 oprref = convertOperatorReference(fout, oprcom);
12093 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12097 oprref = convertOperatorReference(fout, oprnegate);
12100 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12104 if (strcmp(oprcanmerge, "t") == 0)
12105 appendPQExpBufferStr(details, ",\n MERGES");
12107 if (strcmp(oprcanhash, "t") == 0)
12108 appendPQExpBufferStr(details, ",\n HASHES");
12110 oprregproc = convertRegProcReference(fout, oprrest);
12113 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12117 oprregproc = convertRegProcReference(fout, oprjoin);
12120 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12125 * DROP must be fully qualified in case same name appears in pg_catalog
12127 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12128 fmtId(oprinfo->dobj.namespace->dobj.name),
12131 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
12132 oprinfo->dobj.name, details->data);
12134 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
12136 if (dopt->binary_upgrade)
12137 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
12139 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12140 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12141 oprinfo->dobj.name,
12142 oprinfo->dobj.namespace->dobj.name,
12145 false, "OPERATOR", SECTION_PRE_DATA,
12146 q->data, delq->data, NULL,
12150 /* Dump Operator Comments */
12151 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12152 dumpComment(fout, labelq->data,
12153 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12154 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12158 destroyPQExpBuffer(query);
12159 destroyPQExpBuffer(q);
12160 destroyPQExpBuffer(delq);
12161 destroyPQExpBuffer(labelq);
12162 destroyPQExpBuffer(oprid);
12163 destroyPQExpBuffer(details);
12167 * Convert a function reference obtained from pg_operator
12169 * Returns allocated string of what to print, or NULL if function references
12170 * is InvalidOid. Returned string is expected to be free'd by the caller.
12172 * The input is a REGPROCEDURE display; we have to strip the argument-types
12176 convertRegProcReference(Archive *fout, const char *proc)
12182 /* In all cases "-" means a null reference */
12183 if (strcmp(proc, "-") == 0)
12186 name = pg_strdup(proc);
12187 /* find non-double-quoted left paren */
12189 for (paren = name; *paren; paren++)
12191 if (*paren == '(' && !inquote)
12197 inquote = !inquote;
12203 * Convert an operator cross-reference obtained from pg_operator
12205 * Returns an allocated string of what to print, or NULL to print nothing.
12206 * Caller is responsible for free'ing result string.
12208 * The input is a REGOPERATOR display; we have to strip the argument-types
12209 * part, and add OPERATOR() decoration if the name is schema-qualified.
12212 convertOperatorReference(Archive *fout, const char *opr)
12220 /* In all cases "0" means a null reference */
12221 if (strcmp(opr, "0") == 0)
12224 name = pg_strdup(opr);
12225 /* find non-double-quoted left paren, and check for non-quoted dot */
12228 for (ptr = name; *ptr; ptr++)
12231 inquote = !inquote;
12232 else if (*ptr == '.' && !inquote)
12234 else if (*ptr == '(' && !inquote)
12240 /* If not schema-qualified, don't need to add OPERATOR() */
12243 oname = psprintf("OPERATOR(%s)", name);
12249 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12251 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12252 * argument lists of these functions are predetermined. Note that the
12253 * caller should ensure we are in the proper schema, because the results
12254 * are search path dependent!
12257 convertTSFunction(Archive *fout, Oid funcOid)
12263 snprintf(query, sizeof(query),
12264 "SELECT '%u'::pg_catalog.regproc", funcOid);
12265 res = ExecuteSqlQueryForSingleRow(fout, query);
12267 result = pg_strdup(PQgetvalue(res, 0, 0));
12276 * write out a single access method definition
12279 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12281 DumpOptions *dopt = fout->dopt;
12284 PQExpBuffer labelq;
12287 /* Skip if not to be dumped */
12288 if (!aminfo->dobj.dump || dopt->dataOnly)
12291 q = createPQExpBuffer();
12292 delq = createPQExpBuffer();
12293 labelq = createPQExpBuffer();
12295 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12297 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12299 switch (aminfo->amtype)
12302 appendPQExpBuffer(q, "TYPE INDEX ");
12305 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12306 aminfo->amtype, qamname);
12308 destroyPQExpBuffer(q);
12309 destroyPQExpBuffer(delq);
12310 destroyPQExpBuffer(labelq);
12314 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12316 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12319 appendPQExpBuffer(labelq, "ACCESS METHOD %s",
12322 if (dopt->binary_upgrade)
12323 binary_upgrade_extension_member(q, &aminfo->dobj, labelq->data);
12325 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12326 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12331 false, "ACCESS METHOD", SECTION_PRE_DATA,
12332 q->data, delq->data, NULL,
12336 /* Dump Access Method Comments */
12337 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12338 dumpComment(fout, labelq->data,
12340 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12344 destroyPQExpBuffer(q);
12345 destroyPQExpBuffer(delq);
12346 destroyPQExpBuffer(labelq);
12351 * write out a single operator class definition
12354 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12356 DumpOptions *dopt = fout->dopt;
12360 PQExpBuffer labelq;
12367 int i_opcfamilyname;
12368 int i_opcfamilynsp;
12370 int i_amopstrategy;
12371 int i_amopreqcheck;
12374 int i_sortfamilynsp;
12377 int i_amproclefttype;
12378 int i_amprocrighttype;
12383 char *opcfamilyname;
12384 char *opcfamilynsp;
12386 char *amopstrategy;
12387 char *amopreqcheck;
12390 char *sortfamilynsp;
12393 char *amproclefttype;
12394 char *amprocrighttype;
12398 /* Skip if not to be dumped */
12399 if (!opcinfo->dobj.dump || dopt->dataOnly)
12402 query = createPQExpBuffer();
12403 q = createPQExpBuffer();
12404 delq = createPQExpBuffer();
12405 labelq = createPQExpBuffer();
12407 /* Make sure we are in proper schema so regoperator works correctly */
12408 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
12410 /* Get additional fields from the pg_opclass row */
12411 if (fout->remoteVersion >= 80300)
12413 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12414 "opckeytype::pg_catalog.regtype, "
12415 "opcdefault, opcfamily, "
12416 "opfname AS opcfamilyname, "
12417 "nspname AS opcfamilynsp, "
12418 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12419 "FROM pg_catalog.pg_opclass c "
12420 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12421 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12422 "WHERE c.oid = '%u'::pg_catalog.oid",
12423 opcinfo->dobj.catId.oid);
12427 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12428 "opckeytype::pg_catalog.regtype, "
12429 "opcdefault, NULL AS opcfamily, "
12430 "NULL AS opcfamilyname, "
12431 "NULL AS opcfamilynsp, "
12432 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12433 "FROM pg_catalog.pg_opclass "
12434 "WHERE oid = '%u'::pg_catalog.oid",
12435 opcinfo->dobj.catId.oid);
12438 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12440 i_opcintype = PQfnumber(res, "opcintype");
12441 i_opckeytype = PQfnumber(res, "opckeytype");
12442 i_opcdefault = PQfnumber(res, "opcdefault");
12443 i_opcfamily = PQfnumber(res, "opcfamily");
12444 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12445 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12446 i_amname = PQfnumber(res, "amname");
12448 /* opcintype may still be needed after we PQclear res */
12449 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12450 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12451 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12452 /* opcfamily will still be needed after we PQclear res */
12453 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12454 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12455 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12456 /* amname will still be needed after we PQclear res */
12457 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12460 * DROP must be fully qualified in case same name appears in pg_catalog
12462 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12463 fmtId(opcinfo->dobj.namespace->dobj.name));
12464 appendPQExpBuffer(delq, ".%s",
12465 fmtId(opcinfo->dobj.name));
12466 appendPQExpBuffer(delq, " USING %s;\n",
12469 /* Build the fixed portion of the CREATE command */
12470 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12471 fmtId(opcinfo->dobj.name));
12472 if (strcmp(opcdefault, "t") == 0)
12473 appendPQExpBufferStr(q, "DEFAULT ");
12474 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12477 if (strlen(opcfamilyname) > 0)
12479 appendPQExpBufferStr(q, " FAMILY ");
12480 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12481 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12482 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12484 appendPQExpBufferStr(q, " AS\n ");
12488 if (strcmp(opckeytype, "-") != 0)
12490 appendPQExpBuffer(q, "STORAGE %s",
12498 * Now fetch and print the OPERATOR entries (pg_amop rows).
12500 * Print only those opfamily members that are tied to the opclass by
12501 * pg_depend entries.
12503 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12504 * older server's opclass in which it is used. This is to avoid
12505 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12506 * older server and then reload into that old version. This can go away
12507 * once 8.3 is so old as to not be of interest to anyone.
12509 resetPQExpBuffer(query);
12511 if (fout->remoteVersion >= 90100)
12513 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12514 "amopopr::pg_catalog.regoperator, "
12515 "opfname AS sortfamily, "
12516 "nspname AS sortfamilynsp "
12517 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12518 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12519 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12520 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12521 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12522 "AND refobjid = '%u'::pg_catalog.oid "
12523 "AND amopfamily = '%s'::pg_catalog.oid "
12524 "ORDER BY amopstrategy",
12525 opcinfo->dobj.catId.oid,
12528 else if (fout->remoteVersion >= 80400)
12530 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12531 "amopopr::pg_catalog.regoperator, "
12532 "NULL AS sortfamily, "
12533 "NULL AS sortfamilynsp "
12534 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12535 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12536 "AND refobjid = '%u'::pg_catalog.oid "
12537 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12538 "AND objid = ao.oid "
12539 "ORDER BY amopstrategy",
12540 opcinfo->dobj.catId.oid);
12542 else if (fout->remoteVersion >= 80300)
12544 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12545 "amopopr::pg_catalog.regoperator, "
12546 "NULL AS sortfamily, "
12547 "NULL AS sortfamilynsp "
12548 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12549 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12550 "AND refobjid = '%u'::pg_catalog.oid "
12551 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12552 "AND objid = ao.oid "
12553 "ORDER BY amopstrategy",
12554 opcinfo->dobj.catId.oid);
12559 * Here, we print all entries since there are no opfamilies and hence
12560 * no loose operators to worry about.
12562 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12563 "amopopr::pg_catalog.regoperator, "
12564 "NULL AS sortfamily, "
12565 "NULL AS sortfamilynsp "
12566 "FROM pg_catalog.pg_amop "
12567 "WHERE amopclaid = '%u'::pg_catalog.oid "
12568 "ORDER BY amopstrategy",
12569 opcinfo->dobj.catId.oid);
12572 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12574 ntups = PQntuples(res);
12576 i_amopstrategy = PQfnumber(res, "amopstrategy");
12577 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12578 i_amopopr = PQfnumber(res, "amopopr");
12579 i_sortfamily = PQfnumber(res, "sortfamily");
12580 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12582 for (i = 0; i < ntups; i++)
12584 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12585 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12586 amopopr = PQgetvalue(res, i, i_amopopr);
12587 sortfamily = PQgetvalue(res, i, i_sortfamily);
12588 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12591 appendPQExpBufferStr(q, " ,\n ");
12593 appendPQExpBuffer(q, "OPERATOR %s %s",
12594 amopstrategy, amopopr);
12596 if (strlen(sortfamily) > 0)
12598 appendPQExpBufferStr(q, " FOR ORDER BY ");
12599 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12600 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12601 appendPQExpBufferStr(q, fmtId(sortfamily));
12604 if (strcmp(amopreqcheck, "t") == 0)
12605 appendPQExpBufferStr(q, " RECHECK");
12613 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12615 * Print only those opfamily members that are tied to the opclass by
12616 * pg_depend entries.
12618 * We print the amproclefttype/amprocrighttype even though in most cases
12619 * the backend could deduce the right values, because of the corner case
12620 * of a btree sort support function for a cross-type comparison. That's
12621 * only allowed in 9.2 and later, but for simplicity print them in all
12622 * versions that have the columns.
12624 resetPQExpBuffer(query);
12626 if (fout->remoteVersion >= 80300)
12628 appendPQExpBuffer(query, "SELECT amprocnum, "
12629 "amproc::pg_catalog.regprocedure, "
12630 "amproclefttype::pg_catalog.regtype, "
12631 "amprocrighttype::pg_catalog.regtype "
12632 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12633 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12634 "AND refobjid = '%u'::pg_catalog.oid "
12635 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12636 "AND objid = ap.oid "
12637 "ORDER BY amprocnum",
12638 opcinfo->dobj.catId.oid);
12642 appendPQExpBuffer(query, "SELECT amprocnum, "
12643 "amproc::pg_catalog.regprocedure, "
12644 "'' AS amproclefttype, "
12645 "'' AS amprocrighttype "
12646 "FROM pg_catalog.pg_amproc "
12647 "WHERE amopclaid = '%u'::pg_catalog.oid "
12648 "ORDER BY amprocnum",
12649 opcinfo->dobj.catId.oid);
12652 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12654 ntups = PQntuples(res);
12656 i_amprocnum = PQfnumber(res, "amprocnum");
12657 i_amproc = PQfnumber(res, "amproc");
12658 i_amproclefttype = PQfnumber(res, "amproclefttype");
12659 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12661 for (i = 0; i < ntups; i++)
12663 amprocnum = PQgetvalue(res, i, i_amprocnum);
12664 amproc = PQgetvalue(res, i, i_amproc);
12665 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12666 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12669 appendPQExpBufferStr(q, " ,\n ");
12671 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12673 if (*amproclefttype && *amprocrighttype)
12674 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12676 appendPQExpBuffer(q, " %s", amproc);
12684 * If needComma is still false it means we haven't added anything after
12685 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
12686 * clause with the same datatype. This isn't sanctioned by the
12687 * documentation, but actually DefineOpClass will treat it as a no-op.
12690 appendPQExpBuffer(q, "STORAGE %s", opcintype);
12692 appendPQExpBufferStr(q, ";\n");
12694 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
12695 fmtId(opcinfo->dobj.name));
12696 appendPQExpBuffer(labelq, " USING %s",
12699 if (dopt->binary_upgrade)
12700 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
12702 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12703 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
12704 opcinfo->dobj.name,
12705 opcinfo->dobj.namespace->dobj.name,
12708 false, "OPERATOR CLASS", SECTION_PRE_DATA,
12709 q->data, delq->data, NULL,
12713 /* Dump Operator Class Comments */
12714 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12715 dumpComment(fout, labelq->data,
12716 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
12717 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
12722 destroyPQExpBuffer(query);
12723 destroyPQExpBuffer(q);
12724 destroyPQExpBuffer(delq);
12725 destroyPQExpBuffer(labelq);
12730 * write out a single operator family definition
12732 * Note: this also dumps any "loose" operator members that aren't bound to a
12733 * specific opclass within the opfamily.
12736 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
12738 DumpOptions *dopt = fout->dopt;
12742 PQExpBuffer labelq;
12745 PGresult *res_procs;
12748 int i_amopstrategy;
12749 int i_amopreqcheck;
12752 int i_sortfamilynsp;
12755 int i_amproclefttype;
12756 int i_amprocrighttype;
12758 char *amopstrategy;
12759 char *amopreqcheck;
12762 char *sortfamilynsp;
12765 char *amproclefttype;
12766 char *amprocrighttype;
12770 /* Skip if not to be dumped */
12771 if (!opfinfo->dobj.dump || dopt->dataOnly)
12774 query = createPQExpBuffer();
12775 q = createPQExpBuffer();
12776 delq = createPQExpBuffer();
12777 labelq = createPQExpBuffer();
12779 /* Make sure we are in proper schema so regoperator works correctly */
12780 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
12783 * Fetch only those opfamily members that are tied directly to the
12784 * opfamily by pg_depend entries.
12786 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12787 * older server's opclass in which it is used. This is to avoid
12788 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12789 * older server and then reload into that old version. This can go away
12790 * once 8.3 is so old as to not be of interest to anyone.
12792 if (fout->remoteVersion >= 90100)
12794 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12795 "amopopr::pg_catalog.regoperator, "
12796 "opfname AS sortfamily, "
12797 "nspname AS sortfamilynsp "
12798 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12799 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12800 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12801 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12802 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12803 "AND refobjid = '%u'::pg_catalog.oid "
12804 "AND amopfamily = '%u'::pg_catalog.oid "
12805 "ORDER BY amopstrategy",
12806 opfinfo->dobj.catId.oid,
12807 opfinfo->dobj.catId.oid);
12809 else if (fout->remoteVersion >= 80400)
12811 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12812 "amopopr::pg_catalog.regoperator, "
12813 "NULL AS sortfamily, "
12814 "NULL AS sortfamilynsp "
12815 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12816 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12817 "AND refobjid = '%u'::pg_catalog.oid "
12818 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12819 "AND objid = ao.oid "
12820 "ORDER BY amopstrategy",
12821 opfinfo->dobj.catId.oid);
12825 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12826 "amopopr::pg_catalog.regoperator, "
12827 "NULL AS sortfamily, "
12828 "NULL AS sortfamilynsp "
12829 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12830 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12831 "AND refobjid = '%u'::pg_catalog.oid "
12832 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12833 "AND objid = ao.oid "
12834 "ORDER BY amopstrategy",
12835 opfinfo->dobj.catId.oid);
12838 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12840 resetPQExpBuffer(query);
12842 appendPQExpBuffer(query, "SELECT amprocnum, "
12843 "amproc::pg_catalog.regprocedure, "
12844 "amproclefttype::pg_catalog.regtype, "
12845 "amprocrighttype::pg_catalog.regtype "
12846 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12847 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12848 "AND refobjid = '%u'::pg_catalog.oid "
12849 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12850 "AND objid = ap.oid "
12851 "ORDER BY amprocnum",
12852 opfinfo->dobj.catId.oid);
12854 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12856 /* Get additional fields from the pg_opfamily row */
12857 resetPQExpBuffer(query);
12859 appendPQExpBuffer(query, "SELECT "
12860 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
12861 "FROM pg_catalog.pg_opfamily "
12862 "WHERE oid = '%u'::pg_catalog.oid",
12863 opfinfo->dobj.catId.oid);
12865 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12867 i_amname = PQfnumber(res, "amname");
12869 /* amname will still be needed after we PQclear res */
12870 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12873 * DROP must be fully qualified in case same name appears in pg_catalog
12875 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
12876 fmtId(opfinfo->dobj.namespace->dobj.name));
12877 appendPQExpBuffer(delq, ".%s",
12878 fmtId(opfinfo->dobj.name));
12879 appendPQExpBuffer(delq, " USING %s;\n",
12882 /* Build the fixed portion of the CREATE command */
12883 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
12884 fmtId(opfinfo->dobj.name));
12885 appendPQExpBuffer(q, " USING %s;\n",
12890 /* Do we need an ALTER to add loose members? */
12891 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
12893 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
12894 fmtId(opfinfo->dobj.name));
12895 appendPQExpBuffer(q, " USING %s ADD\n ",
12901 * Now fetch and print the OPERATOR entries (pg_amop rows).
12903 ntups = PQntuples(res_ops);
12905 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
12906 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
12907 i_amopopr = PQfnumber(res_ops, "amopopr");
12908 i_sortfamily = PQfnumber(res_ops, "sortfamily");
12909 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
12911 for (i = 0; i < ntups; i++)
12913 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
12914 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
12915 amopopr = PQgetvalue(res_ops, i, i_amopopr);
12916 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
12917 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
12920 appendPQExpBufferStr(q, " ,\n ");
12922 appendPQExpBuffer(q, "OPERATOR %s %s",
12923 amopstrategy, amopopr);
12925 if (strlen(sortfamily) > 0)
12927 appendPQExpBufferStr(q, " FOR ORDER BY ");
12928 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
12929 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12930 appendPQExpBufferStr(q, fmtId(sortfamily));
12933 if (strcmp(amopreqcheck, "t") == 0)
12934 appendPQExpBufferStr(q, " RECHECK");
12940 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12942 ntups = PQntuples(res_procs);
12944 i_amprocnum = PQfnumber(res_procs, "amprocnum");
12945 i_amproc = PQfnumber(res_procs, "amproc");
12946 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
12947 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
12949 for (i = 0; i < ntups; i++)
12951 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
12952 amproc = PQgetvalue(res_procs, i, i_amproc);
12953 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
12954 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
12957 appendPQExpBufferStr(q, " ,\n ");
12959 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
12960 amprocnum, amproclefttype, amprocrighttype,
12966 appendPQExpBufferStr(q, ";\n");
12969 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
12970 fmtId(opfinfo->dobj.name));
12971 appendPQExpBuffer(labelq, " USING %s",
12974 if (dopt->binary_upgrade)
12975 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
12977 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12978 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
12979 opfinfo->dobj.name,
12980 opfinfo->dobj.namespace->dobj.name,
12983 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
12984 q->data, delq->data, NULL,
12988 /* Dump Operator Family Comments */
12989 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12990 dumpComment(fout, labelq->data,
12991 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
12992 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
12996 PQclear(res_procs);
12997 destroyPQExpBuffer(query);
12998 destroyPQExpBuffer(q);
12999 destroyPQExpBuffer(delq);
13000 destroyPQExpBuffer(labelq);
13005 * write out a single collation definition
13008 dumpCollation(Archive *fout, CollInfo *collinfo)
13010 DumpOptions *dopt = fout->dopt;
13014 PQExpBuffer labelq;
13016 int i_collprovider;
13019 const char *collprovider;
13020 const char *collcollate;
13021 const char *collctype;
13023 /* Skip if not to be dumped */
13024 if (!collinfo->dobj.dump || dopt->dataOnly)
13027 query = createPQExpBuffer();
13028 q = createPQExpBuffer();
13029 delq = createPQExpBuffer();
13030 labelq = createPQExpBuffer();
13032 /* Make sure we are in proper schema */
13033 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
13035 /* Get collation-specific details */
13036 if (fout->remoteVersion >= 100000)
13037 appendPQExpBuffer(query, "SELECT "
13042 "FROM pg_catalog.pg_collation c "
13043 "WHERE c.oid = '%u'::pg_catalog.oid",
13044 collinfo->dobj.catId.oid);
13046 appendPQExpBuffer(query, "SELECT "
13047 "'c'::char AS collprovider, "
13050 "NULL AS collversion "
13051 "FROM pg_catalog.pg_collation c "
13052 "WHERE c.oid = '%u'::pg_catalog.oid",
13053 collinfo->dobj.catId.oid);
13055 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13057 i_collprovider = PQfnumber(res, "collprovider");
13058 i_collcollate = PQfnumber(res, "collcollate");
13059 i_collctype = PQfnumber(res, "collctype");
13061 collprovider = PQgetvalue(res, 0, i_collprovider);
13062 collcollate = PQgetvalue(res, 0, i_collcollate);
13063 collctype = PQgetvalue(res, 0, i_collctype);
13066 * DROP must be fully qualified in case same name appears in pg_catalog
13068 appendPQExpBuffer(delq, "DROP COLLATION %s",
13069 fmtId(collinfo->dobj.namespace->dobj.name));
13070 appendPQExpBuffer(delq, ".%s;\n",
13071 fmtId(collinfo->dobj.name));
13073 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13074 fmtId(collinfo->dobj.name));
13076 appendPQExpBufferStr(q, "provider = ");
13077 if (collprovider[0] == 'c')
13078 appendPQExpBufferStr(q, "libc");
13079 else if (collprovider[0] == 'i')
13080 appendPQExpBufferStr(q, "icu");
13081 else if (collprovider[0] == 'd')
13082 /* to allow dumping pg_catalog; not accepted on input */
13083 appendPQExpBufferStr(q, "default");
13085 exit_horribly(NULL,
13086 "unrecognized collation provider: %s\n",
13089 if (strcmp(collcollate, collctype) == 0)
13091 appendPQExpBufferStr(q, ", locale = ");
13092 appendStringLiteralAH(q, collcollate, fout);
13096 appendPQExpBufferStr(q, ", lc_collate = ");
13097 appendStringLiteralAH(q, collcollate, fout);
13098 appendPQExpBufferStr(q, ", lc_ctype = ");
13099 appendStringLiteralAH(q, collctype, fout);
13103 * For binary upgrade, carry over the collation version. For normal
13104 * dump/restore, omit the version, so that it is computed upon restore.
13106 if (dopt->binary_upgrade)
13110 i_collversion = PQfnumber(res, "collversion");
13111 if (!PQgetisnull(res, 0, i_collversion))
13113 appendPQExpBufferStr(q, ", version = ");
13114 appendStringLiteralAH(q,
13115 PQgetvalue(res, 0, i_collversion),
13120 appendPQExpBufferStr(q, ");\n");
13122 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
13124 if (dopt->binary_upgrade)
13125 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
13127 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13128 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13129 collinfo->dobj.name,
13130 collinfo->dobj.namespace->dobj.name,
13133 false, "COLLATION", SECTION_PRE_DATA,
13134 q->data, delq->data, NULL,
13138 /* Dump Collation Comments */
13139 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13140 dumpComment(fout, labelq->data,
13141 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13142 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13146 destroyPQExpBuffer(query);
13147 destroyPQExpBuffer(q);
13148 destroyPQExpBuffer(delq);
13149 destroyPQExpBuffer(labelq);
13154 * write out a single conversion definition
13157 dumpConversion(Archive *fout, ConvInfo *convinfo)
13159 DumpOptions *dopt = fout->dopt;
13163 PQExpBuffer labelq;
13165 int i_conforencoding;
13166 int i_contoencoding;
13169 const char *conforencoding;
13170 const char *contoencoding;
13171 const char *conproc;
13174 /* Skip if not to be dumped */
13175 if (!convinfo->dobj.dump || dopt->dataOnly)
13178 query = createPQExpBuffer();
13179 q = createPQExpBuffer();
13180 delq = createPQExpBuffer();
13181 labelq = createPQExpBuffer();
13183 /* Make sure we are in proper schema */
13184 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
13186 /* Get conversion-specific details */
13187 appendPQExpBuffer(query, "SELECT "
13188 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13189 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13190 "conproc, condefault "
13191 "FROM pg_catalog.pg_conversion c "
13192 "WHERE c.oid = '%u'::pg_catalog.oid",
13193 convinfo->dobj.catId.oid);
13195 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13197 i_conforencoding = PQfnumber(res, "conforencoding");
13198 i_contoencoding = PQfnumber(res, "contoencoding");
13199 i_conproc = PQfnumber(res, "conproc");
13200 i_condefault = PQfnumber(res, "condefault");
13202 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13203 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13204 conproc = PQgetvalue(res, 0, i_conproc);
13205 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13208 * DROP must be fully qualified in case same name appears in pg_catalog
13210 appendPQExpBuffer(delq, "DROP CONVERSION %s",
13211 fmtId(convinfo->dobj.namespace->dobj.name));
13212 appendPQExpBuffer(delq, ".%s;\n",
13213 fmtId(convinfo->dobj.name));
13215 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13216 (condefault) ? "DEFAULT " : "",
13217 fmtId(convinfo->dobj.name));
13218 appendStringLiteralAH(q, conforencoding, fout);
13219 appendPQExpBufferStr(q, " TO ");
13220 appendStringLiteralAH(q, contoencoding, fout);
13221 /* regproc output is already sufficiently quoted */
13222 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13224 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
13226 if (dopt->binary_upgrade)
13227 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
13229 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13230 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13231 convinfo->dobj.name,
13232 convinfo->dobj.namespace->dobj.name,
13235 false, "CONVERSION", SECTION_PRE_DATA,
13236 q->data, delq->data, NULL,
13240 /* Dump Conversion Comments */
13241 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13242 dumpComment(fout, labelq->data,
13243 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13244 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13248 destroyPQExpBuffer(query);
13249 destroyPQExpBuffer(q);
13250 destroyPQExpBuffer(delq);
13251 destroyPQExpBuffer(labelq);
13255 * format_aggregate_signature: generate aggregate name and argument list
13257 * The argument type names are qualified if needed. The aggregate name
13258 * is never qualified.
13261 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13263 PQExpBufferData buf;
13266 initPQExpBuffer(&buf);
13268 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13270 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13272 if (agginfo->aggfn.nargs == 0)
13273 appendPQExpBuffer(&buf, "(*)");
13276 appendPQExpBufferChar(&buf, '(');
13277 for (j = 0; j < agginfo->aggfn.nargs; j++)
13281 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13284 appendPQExpBuffer(&buf, "%s%s",
13285 (j > 0) ? ", " : "",
13289 appendPQExpBufferChar(&buf, ')');
13296 * write out a single aggregate definition
13299 dumpAgg(Archive *fout, AggInfo *agginfo)
13301 DumpOptions *dopt = fout->dopt;
13305 PQExpBuffer labelq;
13306 PQExpBuffer details;
13307 char *aggsig; /* identity signature */
13308 char *aggfullsig = NULL; /* full signature */
13313 int i_aggcombinefn;
13315 int i_aggdeserialfn;
13317 int i_aggminvtransfn;
13319 int i_aggfinalextra;
13320 int i_aggmfinalextra;
13322 int i_hypothetical;
13323 int i_aggtranstype;
13324 int i_aggtransspace;
13325 int i_aggmtranstype;
13326 int i_aggmtransspace;
13331 const char *aggtransfn;
13332 const char *aggfinalfn;
13333 const char *aggcombinefn;
13334 const char *aggserialfn;
13335 const char *aggdeserialfn;
13336 const char *aggmtransfn;
13337 const char *aggminvtransfn;
13338 const char *aggmfinalfn;
13339 bool aggfinalextra;
13340 bool aggmfinalextra;
13341 const char *aggsortop;
13342 char *aggsortconvop;
13344 const char *aggtranstype;
13345 const char *aggtransspace;
13346 const char *aggmtranstype;
13347 const char *aggmtransspace;
13348 const char *agginitval;
13349 const char *aggminitval;
13351 const char *proparallel;
13353 /* Skip if not to be dumped */
13354 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13357 query = createPQExpBuffer();
13358 q = createPQExpBuffer();
13359 delq = createPQExpBuffer();
13360 labelq = createPQExpBuffer();
13361 details = createPQExpBuffer();
13363 /* Make sure we are in proper schema */
13364 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
13366 /* Get aggregate-specific details */
13367 if (fout->remoteVersion >= 90600)
13369 appendPQExpBuffer(query, "SELECT aggtransfn, "
13370 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13371 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13372 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13373 "aggfinalextra, aggmfinalextra, "
13374 "aggsortop::pg_catalog.regoperator, "
13375 "(aggkind = 'h') AS hypothetical, "
13376 "aggtransspace, agginitval, "
13377 "aggmtransspace, aggminitval, "
13378 "true AS convertok, "
13379 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13380 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13382 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13383 "WHERE a.aggfnoid = p.oid "
13384 "AND p.oid = '%u'::pg_catalog.oid",
13385 agginfo->aggfn.dobj.catId.oid);
13387 else if (fout->remoteVersion >= 90400)
13389 appendPQExpBuffer(query, "SELECT aggtransfn, "
13390 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13391 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13392 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13393 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13394 "aggfinalextra, aggmfinalextra, "
13395 "aggsortop::pg_catalog.regoperator, "
13396 "(aggkind = 'h') AS hypothetical, "
13397 "aggtransspace, agginitval, "
13398 "aggmtransspace, aggminitval, "
13399 "true AS convertok, "
13400 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13401 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13402 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13403 "WHERE a.aggfnoid = p.oid "
13404 "AND p.oid = '%u'::pg_catalog.oid",
13405 agginfo->aggfn.dobj.catId.oid);
13407 else if (fout->remoteVersion >= 80400)
13409 appendPQExpBuffer(query, "SELECT aggtransfn, "
13410 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13411 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13412 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13413 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13414 "0 AS aggmtranstype, false AS aggfinalextra, "
13415 "false AS aggmfinalextra, "
13416 "aggsortop::pg_catalog.regoperator, "
13417 "false AS hypothetical, "
13418 "0 AS aggtransspace, agginitval, "
13419 "0 AS aggmtransspace, NULL AS aggminitval, "
13420 "true AS convertok, "
13421 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13422 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13423 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13424 "WHERE a.aggfnoid = p.oid "
13425 "AND p.oid = '%u'::pg_catalog.oid",
13426 agginfo->aggfn.dobj.catId.oid);
13428 else if (fout->remoteVersion >= 80100)
13430 appendPQExpBuffer(query, "SELECT aggtransfn, "
13431 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13432 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13433 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13434 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13435 "0 AS aggmtranstype, false AS aggfinalextra, "
13436 "false AS aggmfinalextra, "
13437 "aggsortop::pg_catalog.regoperator, "
13438 "false AS hypothetical, "
13439 "0 AS aggtransspace, agginitval, "
13440 "0 AS aggmtransspace, NULL AS aggminitval, "
13441 "true AS convertok "
13442 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13443 "WHERE a.aggfnoid = p.oid "
13444 "AND p.oid = '%u'::pg_catalog.oid",
13445 agginfo->aggfn.dobj.catId.oid);
13449 appendPQExpBuffer(query, "SELECT aggtransfn, "
13450 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13451 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13452 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13453 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13454 "0 AS aggmtranstype, false AS aggfinalextra, "
13455 "false AS aggmfinalextra, 0 AS aggsortop, "
13456 "false AS hypothetical, "
13457 "0 AS aggtransspace, agginitval, "
13458 "0 AS aggmtransspace, NULL AS aggminitval, "
13459 "true AS convertok "
13460 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13461 "WHERE a.aggfnoid = p.oid "
13462 "AND p.oid = '%u'::pg_catalog.oid",
13463 agginfo->aggfn.dobj.catId.oid);
13466 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13468 i_aggtransfn = PQfnumber(res, "aggtransfn");
13469 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13470 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13471 i_aggserialfn = PQfnumber(res, "aggserialfn");
13472 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13473 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13474 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13475 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13476 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13477 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13478 i_aggsortop = PQfnumber(res, "aggsortop");
13479 i_hypothetical = PQfnumber(res, "hypothetical");
13480 i_aggtranstype = PQfnumber(res, "aggtranstype");
13481 i_aggtransspace = PQfnumber(res, "aggtransspace");
13482 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13483 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13484 i_agginitval = PQfnumber(res, "agginitval");
13485 i_aggminitval = PQfnumber(res, "aggminitval");
13486 i_convertok = PQfnumber(res, "convertok");
13487 i_proparallel = PQfnumber(res, "proparallel");
13489 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13490 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13491 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13492 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13493 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13494 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13495 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13496 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13497 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13498 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13499 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13500 hypothetical = (PQgetvalue(res, 0, i_hypothetical)[0] == 't');
13501 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13502 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13503 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13504 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13505 agginitval = PQgetvalue(res, 0, i_agginitval);
13506 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13507 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13509 if (fout->remoteVersion >= 80400)
13511 /* 8.4 or later; we rely on server-side code for most of the work */
13515 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13516 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13517 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13518 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13521 /* pre-8.4, do it ourselves */
13522 aggsig = format_aggregate_signature(agginfo, fout, true);
13524 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13526 if (i_proparallel != -1)
13527 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13529 proparallel = NULL;
13533 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13544 /* regproc and regtype output is already sufficiently quoted */
13545 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13546 aggtransfn, aggtranstype);
13548 if (strcmp(aggtransspace, "0") != 0)
13550 appendPQExpBuffer(details, ",\n SSPACE = %s",
13554 if (!PQgetisnull(res, 0, i_agginitval))
13556 appendPQExpBufferStr(details, ",\n INITCOND = ");
13557 appendStringLiteralAH(details, agginitval, fout);
13560 if (strcmp(aggfinalfn, "-") != 0)
13562 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13565 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13568 if (strcmp(aggcombinefn, "-") != 0)
13569 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
13571 if (strcmp(aggserialfn, "-") != 0)
13572 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
13574 if (strcmp(aggdeserialfn, "-") != 0)
13575 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
13577 if (strcmp(aggmtransfn, "-") != 0)
13579 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
13585 if (strcmp(aggmtransspace, "0") != 0)
13587 appendPQExpBuffer(details, ",\n MSSPACE = %s",
13591 if (!PQgetisnull(res, 0, i_aggminitval))
13593 appendPQExpBufferStr(details, ",\n MINITCOND = ");
13594 appendStringLiteralAH(details, aggminitval, fout);
13597 if (strcmp(aggmfinalfn, "-") != 0)
13599 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
13601 if (aggmfinalextra)
13602 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
13605 aggsortconvop = convertOperatorReference(fout, aggsortop);
13608 appendPQExpBuffer(details, ",\n SORTOP = %s",
13610 free(aggsortconvop);
13614 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
13616 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13618 if (proparallel[0] == PROPARALLEL_SAFE)
13619 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
13620 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13621 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
13622 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13623 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13624 agginfo->aggfn.dobj.name);
13628 * DROP must be fully qualified in case same name appears in pg_catalog
13630 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13631 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13634 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
13635 aggfullsig ? aggfullsig : aggsig, details->data);
13637 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
13639 if (dopt->binary_upgrade)
13640 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
13642 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
13643 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
13644 agginfo->aggfn.dobj.dumpId,
13646 agginfo->aggfn.dobj.namespace->dobj.name,
13648 agginfo->aggfn.rolname,
13649 false, "AGGREGATE", SECTION_PRE_DATA,
13650 q->data, delq->data, NULL,
13654 /* Dump Aggregate Comments */
13655 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
13656 dumpComment(fout, labelq->data,
13657 agginfo->aggfn.dobj.namespace->dobj.name,
13658 agginfo->aggfn.rolname,
13659 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13661 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
13662 dumpSecLabel(fout, labelq->data,
13663 agginfo->aggfn.dobj.namespace->dobj.name,
13664 agginfo->aggfn.rolname,
13665 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13668 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
13669 * command look like a function's GRANT; in particular this affects the
13670 * syntax for zero-argument aggregates and ordered-set aggregates.
13675 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
13676 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
13678 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
13679 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
13681 aggsig, NULL, aggsig_tag,
13682 agginfo->aggfn.dobj.namespace->dobj.name,
13683 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
13684 agginfo->aggfn.rproacl,
13685 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
13694 destroyPQExpBuffer(query);
13695 destroyPQExpBuffer(q);
13696 destroyPQExpBuffer(delq);
13697 destroyPQExpBuffer(labelq);
13698 destroyPQExpBuffer(details);
13703 * write out a single text search parser
13706 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
13708 DumpOptions *dopt = fout->dopt;
13711 PQExpBuffer labelq;
13713 /* Skip if not to be dumped */
13714 if (!prsinfo->dobj.dump || dopt->dataOnly)
13717 q = createPQExpBuffer();
13718 delq = createPQExpBuffer();
13719 labelq = createPQExpBuffer();
13721 /* Make sure we are in proper schema */
13722 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
13724 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
13725 fmtId(prsinfo->dobj.name));
13727 appendPQExpBuffer(q, " START = %s,\n",
13728 convertTSFunction(fout, prsinfo->prsstart));
13729 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
13730 convertTSFunction(fout, prsinfo->prstoken));
13731 appendPQExpBuffer(q, " END = %s,\n",
13732 convertTSFunction(fout, prsinfo->prsend));
13733 if (prsinfo->prsheadline != InvalidOid)
13734 appendPQExpBuffer(q, " HEADLINE = %s,\n",
13735 convertTSFunction(fout, prsinfo->prsheadline));
13736 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
13737 convertTSFunction(fout, prsinfo->prslextype));
13740 * DROP must be fully qualified in case same name appears in pg_catalog
13742 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
13743 fmtId(prsinfo->dobj.namespace->dobj.name));
13744 appendPQExpBuffer(delq, ".%s;\n",
13745 fmtId(prsinfo->dobj.name));
13747 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
13748 fmtId(prsinfo->dobj.name));
13750 if (dopt->binary_upgrade)
13751 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
13753 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13754 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
13755 prsinfo->dobj.name,
13756 prsinfo->dobj.namespace->dobj.name,
13759 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
13760 q->data, delq->data, NULL,
13764 /* Dump Parser Comments */
13765 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13766 dumpComment(fout, labelq->data,
13767 prsinfo->dobj.namespace->dobj.name, "",
13768 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
13770 destroyPQExpBuffer(q);
13771 destroyPQExpBuffer(delq);
13772 destroyPQExpBuffer(labelq);
13777 * write out a single text search dictionary
13780 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
13782 DumpOptions *dopt = fout->dopt;
13785 PQExpBuffer labelq;
13791 /* Skip if not to be dumped */
13792 if (!dictinfo->dobj.dump || dopt->dataOnly)
13795 q = createPQExpBuffer();
13796 delq = createPQExpBuffer();
13797 labelq = createPQExpBuffer();
13798 query = createPQExpBuffer();
13800 /* Fetch name and namespace of the dictionary's template */
13801 selectSourceSchema(fout, "pg_catalog");
13802 appendPQExpBuffer(query, "SELECT nspname, tmplname "
13803 "FROM pg_ts_template p, pg_namespace n "
13804 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
13805 dictinfo->dicttemplate);
13806 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13807 nspname = PQgetvalue(res, 0, 0);
13808 tmplname = PQgetvalue(res, 0, 1);
13810 /* Make sure we are in proper schema */
13811 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
13813 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
13814 fmtId(dictinfo->dobj.name));
13816 appendPQExpBufferStr(q, " TEMPLATE = ");
13817 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
13818 appendPQExpBuffer(q, "%s.", fmtId(nspname));
13819 appendPQExpBufferStr(q, fmtId(tmplname));
13823 /* the dictinitoption can be dumped straight into the command */
13824 if (dictinfo->dictinitoption)
13825 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
13827 appendPQExpBufferStr(q, " );\n");
13830 * DROP must be fully qualified in case same name appears in pg_catalog
13832 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
13833 fmtId(dictinfo->dobj.namespace->dobj.name));
13834 appendPQExpBuffer(delq, ".%s;\n",
13835 fmtId(dictinfo->dobj.name));
13837 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
13838 fmtId(dictinfo->dobj.name));
13840 if (dopt->binary_upgrade)
13841 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
13843 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13844 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
13845 dictinfo->dobj.name,
13846 dictinfo->dobj.namespace->dobj.name,
13849 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
13850 q->data, delq->data, NULL,
13854 /* Dump Dictionary Comments */
13855 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13856 dumpComment(fout, labelq->data,
13857 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
13858 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
13860 destroyPQExpBuffer(q);
13861 destroyPQExpBuffer(delq);
13862 destroyPQExpBuffer(labelq);
13863 destroyPQExpBuffer(query);
13868 * write out a single text search template
13871 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
13873 DumpOptions *dopt = fout->dopt;
13876 PQExpBuffer labelq;
13878 /* Skip if not to be dumped */
13879 if (!tmplinfo->dobj.dump || dopt->dataOnly)
13882 q = createPQExpBuffer();
13883 delq = createPQExpBuffer();
13884 labelq = createPQExpBuffer();
13886 /* Make sure we are in proper schema */
13887 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
13889 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
13890 fmtId(tmplinfo->dobj.name));
13892 if (tmplinfo->tmplinit != InvalidOid)
13893 appendPQExpBuffer(q, " INIT = %s,\n",
13894 convertTSFunction(fout, tmplinfo->tmplinit));
13895 appendPQExpBuffer(q, " LEXIZE = %s );\n",
13896 convertTSFunction(fout, tmplinfo->tmpllexize));
13899 * DROP must be fully qualified in case same name appears in pg_catalog
13901 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
13902 fmtId(tmplinfo->dobj.namespace->dobj.name));
13903 appendPQExpBuffer(delq, ".%s;\n",
13904 fmtId(tmplinfo->dobj.name));
13906 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
13907 fmtId(tmplinfo->dobj.name));
13909 if (dopt->binary_upgrade)
13910 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
13912 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13913 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
13914 tmplinfo->dobj.name,
13915 tmplinfo->dobj.namespace->dobj.name,
13918 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
13919 q->data, delq->data, NULL,
13923 /* Dump Template Comments */
13924 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13925 dumpComment(fout, labelq->data,
13926 tmplinfo->dobj.namespace->dobj.name, "",
13927 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
13929 destroyPQExpBuffer(q);
13930 destroyPQExpBuffer(delq);
13931 destroyPQExpBuffer(labelq);
13936 * write out a single text search configuration
13939 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
13941 DumpOptions *dopt = fout->dopt;
13944 PQExpBuffer labelq;
13954 /* Skip if not to be dumped */
13955 if (!cfginfo->dobj.dump || dopt->dataOnly)
13958 q = createPQExpBuffer();
13959 delq = createPQExpBuffer();
13960 labelq = createPQExpBuffer();
13961 query = createPQExpBuffer();
13963 /* Fetch name and namespace of the config's parser */
13964 selectSourceSchema(fout, "pg_catalog");
13965 appendPQExpBuffer(query, "SELECT nspname, prsname "
13966 "FROM pg_ts_parser p, pg_namespace n "
13967 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
13968 cfginfo->cfgparser);
13969 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13970 nspname = PQgetvalue(res, 0, 0);
13971 prsname = PQgetvalue(res, 0, 1);
13973 /* Make sure we are in proper schema */
13974 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
13976 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
13977 fmtId(cfginfo->dobj.name));
13979 appendPQExpBufferStr(q, " PARSER = ");
13980 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
13981 appendPQExpBuffer(q, "%s.", fmtId(nspname));
13982 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
13986 resetPQExpBuffer(query);
13987 appendPQExpBuffer(query,
13989 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
13990 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
13991 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
13992 "FROM pg_catalog.pg_ts_config_map AS m\n"
13993 "WHERE m.mapcfg = '%u'\n"
13994 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
13995 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
13997 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13998 ntups = PQntuples(res);
14000 i_tokenname = PQfnumber(res, "tokenname");
14001 i_dictname = PQfnumber(res, "dictname");
14003 for (i = 0; i < ntups; i++)
14005 char *tokenname = PQgetvalue(res, i, i_tokenname);
14006 char *dictname = PQgetvalue(res, i, i_dictname);
14009 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14011 /* starting a new token type, so start a new command */
14013 appendPQExpBufferStr(q, ";\n");
14014 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14015 fmtId(cfginfo->dobj.name));
14016 /* tokenname needs quoting, dictname does NOT */
14017 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14018 fmtId(tokenname), dictname);
14021 appendPQExpBuffer(q, ", %s", dictname);
14025 appendPQExpBufferStr(q, ";\n");
14030 * DROP must be fully qualified in case same name appears in pg_catalog
14032 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
14033 fmtId(cfginfo->dobj.namespace->dobj.name));
14034 appendPQExpBuffer(delq, ".%s;\n",
14035 fmtId(cfginfo->dobj.name));
14037 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
14038 fmtId(cfginfo->dobj.name));
14040 if (dopt->binary_upgrade)
14041 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
14043 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14044 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14045 cfginfo->dobj.name,
14046 cfginfo->dobj.namespace->dobj.name,
14049 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14050 q->data, delq->data, NULL,
14054 /* Dump Configuration Comments */
14055 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14056 dumpComment(fout, labelq->data,
14057 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14058 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14060 destroyPQExpBuffer(q);
14061 destroyPQExpBuffer(delq);
14062 destroyPQExpBuffer(labelq);
14063 destroyPQExpBuffer(query);
14067 * dumpForeignDataWrapper
14068 * write out a single foreign-data wrapper definition
14071 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14073 DumpOptions *dopt = fout->dopt;
14076 PQExpBuffer labelq;
14079 /* Skip if not to be dumped */
14080 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14083 q = createPQExpBuffer();
14084 delq = createPQExpBuffer();
14085 labelq = createPQExpBuffer();
14087 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14089 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14092 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14093 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14095 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14096 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14098 if (strlen(fdwinfo->fdwoptions) > 0)
14099 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14101 appendPQExpBufferStr(q, ";\n");
14103 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14106 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
14109 if (dopt->binary_upgrade)
14110 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
14112 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14113 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14114 fdwinfo->dobj.name,
14118 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14119 q->data, delq->data, NULL,
14123 /* Handle the ACL */
14124 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14125 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14126 "FOREIGN DATA WRAPPER",
14127 qfdwname, NULL, fdwinfo->dobj.name,
14128 NULL, fdwinfo->rolname,
14129 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14130 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14132 /* Dump Foreign Data Wrapper Comments */
14133 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14134 dumpComment(fout, labelq->data,
14135 NULL, fdwinfo->rolname,
14136 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14140 destroyPQExpBuffer(q);
14141 destroyPQExpBuffer(delq);
14142 destroyPQExpBuffer(labelq);
14146 * dumpForeignServer
14147 * write out a foreign server definition
14150 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14152 DumpOptions *dopt = fout->dopt;
14155 PQExpBuffer labelq;
14161 /* Skip if not to be dumped */
14162 if (!srvinfo->dobj.dump || dopt->dataOnly)
14165 q = createPQExpBuffer();
14166 delq = createPQExpBuffer();
14167 labelq = createPQExpBuffer();
14168 query = createPQExpBuffer();
14170 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14172 /* look up the foreign-data wrapper */
14173 selectSourceSchema(fout, "pg_catalog");
14174 appendPQExpBuffer(query, "SELECT fdwname "
14175 "FROM pg_foreign_data_wrapper w "
14176 "WHERE w.oid = '%u'",
14178 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14179 fdwname = PQgetvalue(res, 0, 0);
14181 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14182 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14184 appendPQExpBufferStr(q, " TYPE ");
14185 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14187 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14189 appendPQExpBufferStr(q, " VERSION ");
14190 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14193 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14194 appendPQExpBufferStr(q, fmtId(fdwname));
14196 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14197 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14199 appendPQExpBufferStr(q, ";\n");
14201 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14204 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
14206 if (dopt->binary_upgrade)
14207 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
14209 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14210 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14211 srvinfo->dobj.name,
14215 false, "SERVER", SECTION_PRE_DATA,
14216 q->data, delq->data, NULL,
14220 /* Handle the ACL */
14221 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14222 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14224 qsrvname, NULL, srvinfo->dobj.name,
14225 NULL, srvinfo->rolname,
14226 srvinfo->srvacl, srvinfo->rsrvacl,
14227 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14229 /* Dump user mappings */
14230 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14231 dumpUserMappings(fout,
14232 srvinfo->dobj.name, NULL,
14234 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14236 /* Dump Foreign Server Comments */
14237 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14238 dumpComment(fout, labelq->data,
14239 NULL, srvinfo->rolname,
14240 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14244 destroyPQExpBuffer(q);
14245 destroyPQExpBuffer(delq);
14246 destroyPQExpBuffer(labelq);
14247 destroyPQExpBuffer(query);
14253 * This routine is used to dump any user mappings associated with the
14254 * server handed to this routine. Should be called after ArchiveEntry()
14258 dumpUserMappings(Archive *fout,
14259 const char *servername, const char *namespace,
14261 CatalogId catalogId, DumpId dumpId)
14273 q = createPQExpBuffer();
14274 tag = createPQExpBuffer();
14275 delq = createPQExpBuffer();
14276 query = createPQExpBuffer();
14279 * We read from the publicly accessible view pg_user_mappings, so as not
14280 * to fail if run by a non-superuser. Note that the view will show
14281 * umoptions as null if the user hasn't got privileges for the associated
14282 * server; this means that pg_dump will dump such a mapping, but with no
14283 * OPTIONS clause. A possible alternative is to skip such mappings
14284 * altogether, but it's not clear that that's an improvement.
14286 selectSourceSchema(fout, "pg_catalog");
14288 appendPQExpBuffer(query,
14290 "array_to_string(ARRAY("
14291 "SELECT quote_ident(option_name) || ' ' || "
14292 "quote_literal(option_value) "
14293 "FROM pg_options_to_table(umoptions) "
14294 "ORDER BY option_name"
14295 "), E',\n ') AS umoptions "
14296 "FROM pg_user_mappings "
14297 "WHERE srvid = '%u' "
14298 "ORDER BY usename",
14301 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14303 ntups = PQntuples(res);
14304 i_usename = PQfnumber(res, "usename");
14305 i_umoptions = PQfnumber(res, "umoptions");
14307 for (i = 0; i < ntups; i++)
14312 usename = PQgetvalue(res, i, i_usename);
14313 umoptions = PQgetvalue(res, i, i_umoptions);
14315 resetPQExpBuffer(q);
14316 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14317 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14319 if (umoptions && strlen(umoptions) > 0)
14320 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14322 appendPQExpBufferStr(q, ";\n");
14324 resetPQExpBuffer(delq);
14325 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14326 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14328 resetPQExpBuffer(tag);
14329 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14330 usename, servername);
14332 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14337 "USER MAPPING", SECTION_PRE_DATA,
14338 q->data, delq->data, NULL,
14345 destroyPQExpBuffer(query);
14346 destroyPQExpBuffer(delq);
14347 destroyPQExpBuffer(tag);
14348 destroyPQExpBuffer(q);
14352 * Write out default privileges information
14355 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14357 DumpOptions *dopt = fout->dopt;
14362 /* Skip if not to be dumped */
14363 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14366 q = createPQExpBuffer();
14367 tag = createPQExpBuffer();
14369 switch (daclinfo->defaclobjtype)
14371 case DEFACLOBJ_RELATION:
14374 case DEFACLOBJ_SEQUENCE:
14375 type = "SEQUENCES";
14377 case DEFACLOBJ_FUNCTION:
14378 type = "FUNCTIONS";
14380 case DEFACLOBJ_TYPE:
14383 case DEFACLOBJ_NAMESPACE:
14387 /* shouldn't get here */
14388 exit_horribly(NULL,
14389 "unrecognized object type in default privileges: %d\n",
14390 (int) daclinfo->defaclobjtype);
14391 type = ""; /* keep compiler quiet */
14394 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14396 /* build the actual command(s) for this tuple */
14397 if (!buildDefaultACLCommands(type,
14398 daclinfo->dobj.namespace != NULL ?
14399 daclinfo->dobj.namespace->dobj.name : NULL,
14400 daclinfo->defaclacl,
14401 daclinfo->rdefaclacl,
14402 daclinfo->initdefaclacl,
14403 daclinfo->initrdefaclacl,
14404 daclinfo->defaclrole,
14405 fout->remoteVersion,
14407 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14408 daclinfo->defaclacl);
14410 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14411 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14413 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14415 daclinfo->defaclrole,
14416 false, "DEFAULT ACL", SECTION_POST_DATA,
14421 destroyPQExpBuffer(tag);
14422 destroyPQExpBuffer(q);
14426 * Write out grant/revoke information
14428 * 'objCatId' is the catalog ID of the underlying object.
14429 * 'objDumpId' is the dump ID of the underlying object.
14430 * 'type' must be one of
14431 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14432 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14433 * 'name' is the formatted name of the object. Must be quoted etc. already.
14434 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14435 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
14436 * 'nspname' is the namespace the object is in (NULL if none).
14437 * 'owner' is the owner, NULL if there is no owner (for languages).
14438 * 'acls' contains the ACL string of the object from the appropriate system
14439 * catalog field; it will be passed to buildACLCommands for building the
14440 * appropriate GRANT commands.
14441 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14442 * object; it will be passed to buildACLCommands for building the
14443 * appropriate REVOKE commands.
14444 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14445 * privileges, to be recorded into pg_init_privs
14446 * 'initracls' In binary-upgrade mode, ACL string of the object's
14447 * revoked-from-default privileges, to be recorded into pg_init_privs
14449 * NB: initacls/initracls are needed because extensions can set privileges on
14450 * an object during the extension's script file and we record those into
14451 * pg_init_privs as that object's initial privileges.
14455 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14456 const char *type, const char *name, const char *subname,
14457 const char *tag, const char *nspname, const char *owner,
14458 const char *acls, const char *racls,
14459 const char *initacls, const char *initracls)
14461 DumpOptions *dopt = fout->dopt;
14464 /* Do nothing if ACL dump is not enabled */
14465 if (dopt->aclsSkip)
14468 /* --data-only skips ACLs *except* BLOB ACLs */
14469 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14472 sql = createPQExpBuffer();
14475 * Check to see if this object has had any initial ACLs included for it.
14476 * If so, we are in binary upgrade mode and these are the ACLs to turn
14477 * into GRANT and REVOKE statements to set and record the initial
14478 * privileges for an extension object. Let the backend know that these
14479 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14480 * before and after.
14482 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14484 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14485 if (!buildACLCommands(name, subname, type, initacls, initracls, owner,
14486 "", fout->remoteVersion, sql))
14487 exit_horribly(NULL,
14488 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14489 initacls, initracls, name, type);
14490 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14493 if (!buildACLCommands(name, subname, type, acls, racls, owner,
14494 "", fout->remoteVersion, sql))
14495 exit_horribly(NULL,
14496 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14497 acls, racls, name, type);
14500 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14503 owner ? owner : "",
14504 false, "ACL", SECTION_NONE,
14505 sql->data, "", NULL,
14509 destroyPQExpBuffer(sql);
14515 * This routine is used to dump any security labels associated with the
14516 * object handed to this routine. The routine takes a constant character
14517 * string for the target part of the security-label command, plus
14518 * the namespace and owner of the object (for labeling the ArchiveEntry),
14519 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14520 * plus the dump ID for the object (for setting a dependency).
14521 * If a matching pg_seclabel entry is found, it is dumped.
14523 * Note: although this routine takes a dumpId for dependency purposes,
14524 * that purpose is just to mark the dependency in the emitted dump file
14525 * for possible future use by pg_restore. We do NOT use it for determining
14526 * ordering of the label in the dump file, because this routine is called
14527 * after dependency sorting occurs. This routine should be called just after
14528 * calling ArchiveEntry() for the specified object.
14531 dumpSecLabel(Archive *fout, const char *target,
14532 const char *namespace, const char *owner,
14533 CatalogId catalogId, int subid, DumpId dumpId)
14535 DumpOptions *dopt = fout->dopt;
14536 SecLabelItem *labels;
14541 /* do nothing, if --no-security-labels is supplied */
14542 if (dopt->no_security_labels)
14545 /* Comments are schema not data ... except blob comments are data */
14546 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
14548 if (dopt->dataOnly)
14553 /* We do dump blob security labels in binary-upgrade mode */
14554 if (dopt->schemaOnly && !dopt->binary_upgrade)
14558 /* Search for security labels associated with catalogId, using table */
14559 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14561 query = createPQExpBuffer();
14563 for (i = 0; i < nlabels; i++)
14566 * Ignore label entries for which the subid doesn't match.
14568 if (labels[i].objsubid != subid)
14571 appendPQExpBuffer(query,
14572 "SECURITY LABEL FOR %s ON %s IS ",
14573 fmtId(labels[i].provider), target);
14574 appendStringLiteralAH(query, labels[i].label, fout);
14575 appendPQExpBufferStr(query, ";\n");
14578 if (query->len > 0)
14580 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14581 target, namespace, NULL, owner,
14582 false, "SECURITY LABEL", SECTION_NONE,
14583 query->data, "", NULL,
14587 destroyPQExpBuffer(query);
14591 * dumpTableSecLabel
14593 * As above, but dump security label for both the specified table (or view)
14597 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14599 DumpOptions *dopt = fout->dopt;
14600 SecLabelItem *labels;
14604 PQExpBuffer target;
14606 /* do nothing, if --no-security-labels is supplied */
14607 if (dopt->no_security_labels)
14610 /* SecLabel are SCHEMA not data */
14611 if (dopt->dataOnly)
14614 /* Search for comments associated with relation, using table */
14615 nlabels = findSecLabels(fout,
14616 tbinfo->dobj.catId.tableoid,
14617 tbinfo->dobj.catId.oid,
14620 /* If security labels exist, build SECURITY LABEL statements */
14624 query = createPQExpBuffer();
14625 target = createPQExpBuffer();
14627 for (i = 0; i < nlabels; i++)
14629 const char *colname;
14630 const char *provider = labels[i].provider;
14631 const char *label = labels[i].label;
14632 int objsubid = labels[i].objsubid;
14634 resetPQExpBuffer(target);
14637 appendPQExpBuffer(target, "%s %s", reltypename,
14638 fmtId(tbinfo->dobj.name));
14642 colname = getAttrName(objsubid, tbinfo);
14643 /* first fmtId result must be consumed before calling it again */
14644 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
14645 appendPQExpBuffer(target, ".%s", fmtId(colname));
14647 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14648 fmtId(provider), target->data);
14649 appendStringLiteralAH(query, label, fout);
14650 appendPQExpBufferStr(query, ";\n");
14652 if (query->len > 0)
14654 resetPQExpBuffer(target);
14655 appendPQExpBuffer(target, "%s %s", reltypename,
14656 fmtId(tbinfo->dobj.name));
14657 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14659 tbinfo->dobj.namespace->dobj.name,
14660 NULL, tbinfo->rolname,
14661 false, "SECURITY LABEL", SECTION_NONE,
14662 query->data, "", NULL,
14663 &(tbinfo->dobj.dumpId), 1,
14666 destroyPQExpBuffer(query);
14667 destroyPQExpBuffer(target);
14673 * Find the security label(s), if any, associated with the given object.
14674 * All the objsubid values associated with the given classoid/objoid are
14675 * found with one search.
14678 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
14680 /* static storage for table of security labels */
14681 static SecLabelItem *labels = NULL;
14682 static int nlabels = -1;
14684 SecLabelItem *middle = NULL;
14686 SecLabelItem *high;
14689 /* Get security labels if we didn't already */
14691 nlabels = collectSecLabels(fout, &labels);
14693 if (nlabels <= 0) /* no labels, so no match is possible */
14700 * Do binary search to find some item matching the object.
14703 high = &labels[nlabels - 1];
14704 while (low <= high)
14706 middle = low + (high - low) / 2;
14708 if (classoid < middle->classoid)
14710 else if (classoid > middle->classoid)
14712 else if (objoid < middle->objoid)
14714 else if (objoid > middle->objoid)
14717 break; /* found a match */
14720 if (low > high) /* no matches */
14727 * Now determine how many items match the object. The search loop
14728 * invariant still holds: only items between low and high inclusive could
14732 while (middle > low)
14734 if (classoid != middle[-1].classoid ||
14735 objoid != middle[-1].objoid)
14744 while (middle <= high)
14746 if (classoid != middle->classoid ||
14747 objoid != middle->objoid)
14759 * Construct a table of all security labels available for database objects.
14760 * It's much faster to pull them all at once.
14762 * The table is sorted by classoid/objid/objsubid for speed in lookup.
14765 collectSecLabels(Archive *fout, SecLabelItem **items)
14776 SecLabelItem *labels;
14778 query = createPQExpBuffer();
14780 appendPQExpBufferStr(query,
14781 "SELECT label, provider, classoid, objoid, objsubid "
14782 "FROM pg_catalog.pg_seclabel "
14783 "ORDER BY classoid, objoid, objsubid");
14785 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14787 /* Construct lookup table containing OIDs in numeric form */
14788 i_label = PQfnumber(res, "label");
14789 i_provider = PQfnumber(res, "provider");
14790 i_classoid = PQfnumber(res, "classoid");
14791 i_objoid = PQfnumber(res, "objoid");
14792 i_objsubid = PQfnumber(res, "objsubid");
14794 ntups = PQntuples(res);
14796 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
14798 for (i = 0; i < ntups; i++)
14800 labels[i].label = PQgetvalue(res, i, i_label);
14801 labels[i].provider = PQgetvalue(res, i, i_provider);
14802 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
14803 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
14804 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
14807 /* Do NOT free the PGresult since we are keeping pointers into it */
14808 destroyPQExpBuffer(query);
14816 * write out to fout the declarations (not data) of a user-defined table
14819 dumpTable(Archive *fout, TableInfo *tbinfo)
14821 DumpOptions *dopt = fout->dopt;
14825 * noop if we are not dumping anything about this table, or if we are
14826 * doing a data-only dump
14828 if (!tbinfo->dobj.dump || dopt->dataOnly)
14831 if (tbinfo->relkind == RELKIND_SEQUENCE)
14832 dumpSequence(fout, tbinfo);
14834 dumpTableSchema(fout, tbinfo);
14836 /* Handle the ACL here */
14837 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
14838 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
14839 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
14840 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
14842 namecopy, NULL, tbinfo->dobj.name,
14843 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14844 tbinfo->relacl, tbinfo->rrelacl,
14845 tbinfo->initrelacl, tbinfo->initrrelacl);
14848 * Handle column ACLs, if any. Note: we pull these with a separate query
14849 * rather than trying to fetch them during getTableAttrs, so that we won't
14850 * miss ACLs on system columns.
14852 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
14854 PQExpBuffer query = createPQExpBuffer();
14858 if (fout->remoteVersion >= 90600)
14860 PQExpBuffer acl_subquery = createPQExpBuffer();
14861 PQExpBuffer racl_subquery = createPQExpBuffer();
14862 PQExpBuffer initacl_subquery = createPQExpBuffer();
14863 PQExpBuffer initracl_subquery = createPQExpBuffer();
14865 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
14866 initracl_subquery, "at.attacl", "c.relowner", "'c'",
14867 dopt->binary_upgrade);
14869 appendPQExpBuffer(query,
14870 "SELECT at.attname, "
14873 "%s AS initattacl, "
14874 "%s AS initrattacl "
14875 "FROM pg_catalog.pg_attribute at "
14876 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
14877 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
14878 "(at.attrelid = pip.objoid "
14879 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
14880 "AND at.attnum = pip.objsubid) "
14881 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
14882 "NOT at.attisdropped "
14884 "%s IS NOT NULL OR "
14885 "%s IS NOT NULL OR "
14886 "%s IS NOT NULL OR "
14888 "ORDER BY at.attnum",
14889 acl_subquery->data,
14890 racl_subquery->data,
14891 initacl_subquery->data,
14892 initracl_subquery->data,
14893 tbinfo->dobj.catId.oid,
14894 acl_subquery->data,
14895 racl_subquery->data,
14896 initacl_subquery->data,
14897 initracl_subquery->data);
14899 destroyPQExpBuffer(acl_subquery);
14900 destroyPQExpBuffer(racl_subquery);
14901 destroyPQExpBuffer(initacl_subquery);
14902 destroyPQExpBuffer(initracl_subquery);
14906 appendPQExpBuffer(query,
14907 "SELECT attname, attacl, NULL as rattacl, "
14908 "NULL AS initattacl, NULL AS initrattacl "
14909 "FROM pg_catalog.pg_attribute "
14910 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
14911 "AND attacl IS NOT NULL "
14913 tbinfo->dobj.catId.oid);
14916 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14918 for (i = 0; i < PQntuples(res); i++)
14920 char *attname = PQgetvalue(res, i, 0);
14921 char *attacl = PQgetvalue(res, i, 1);
14922 char *rattacl = PQgetvalue(res, i, 2);
14923 char *initattacl = PQgetvalue(res, i, 3);
14924 char *initrattacl = PQgetvalue(res, i, 4);
14928 attnamecopy = pg_strdup(fmtId(attname));
14929 acltag = psprintf("%s.%s", tbinfo->dobj.name, attname);
14930 /* Column's GRANT type is always TABLE */
14931 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
14932 namecopy, attnamecopy, acltag,
14933 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14934 attacl, rattacl, initattacl, initrattacl);
14939 destroyPQExpBuffer(query);
14948 * Create the AS clause for a view or materialized view. The semicolon is
14949 * stripped because a materialized view must add a WITH NO DATA clause.
14951 * This returns a new buffer which must be freed by the caller.
14954 createViewAsClause(Archive *fout, TableInfo *tbinfo)
14956 PQExpBuffer query = createPQExpBuffer();
14957 PQExpBuffer result = createPQExpBuffer();
14961 /* Fetch the view definition */
14962 appendPQExpBuffer(query,
14963 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
14964 tbinfo->dobj.catId.oid);
14966 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14968 if (PQntuples(res) != 1)
14970 if (PQntuples(res) < 1)
14971 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
14972 tbinfo->dobj.name);
14974 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
14975 tbinfo->dobj.name);
14978 len = PQgetlength(res, 0, 0);
14981 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
14982 tbinfo->dobj.name);
14984 /* Strip off the trailing semicolon so that other things may follow. */
14985 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
14986 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
14989 destroyPQExpBuffer(query);
14995 * Create a dummy AS clause for a view. This is used when the real view
14996 * definition has to be postponed because of circular dependencies.
14997 * We must duplicate the view's external properties -- column names and types
14998 * (including collation) -- so that it works for subsequent references.
15000 * This returns a new buffer which must be freed by the caller.
15003 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15005 PQExpBuffer result = createPQExpBuffer();
15008 appendPQExpBufferStr(result, "SELECT");
15010 for (j = 0; j < tbinfo->numatts; j++)
15013 appendPQExpBufferChar(result, ',');
15014 appendPQExpBufferStr(result, "\n ");
15016 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15019 * Must add collation if not default for the type, because CREATE OR
15020 * REPLACE VIEW won't change it
15022 if (OidIsValid(tbinfo->attcollation[j]))
15026 coll = findCollationByOid(tbinfo->attcollation[j]);
15029 /* always schema-qualify, don't try to be smart */
15030 appendPQExpBuffer(result, " COLLATE %s.",
15031 fmtId(coll->dobj.namespace->dobj.name));
15032 appendPQExpBufferStr(result, fmtId(coll->dobj.name));
15036 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15044 * write the declaration (not data) of one user-defined table or view
15047 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15049 DumpOptions *dopt = fout->dopt;
15050 PQExpBuffer q = createPQExpBuffer();
15051 PQExpBuffer delq = createPQExpBuffer();
15052 PQExpBuffer labelq = createPQExpBuffer();
15054 TableInfo **parents;
15055 int actual_atts; /* number of attrs in this CREATE statement */
15056 const char *reltypename;
15063 /* Make sure we are in proper schema */
15064 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
15066 if (dopt->binary_upgrade)
15067 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15068 tbinfo->dobj.catId.oid);
15070 /* Is it a table or a view? */
15071 if (tbinfo->relkind == RELKIND_VIEW)
15073 PQExpBuffer result;
15076 * Note: keep this code in sync with the is_view case in dumpRule()
15079 reltypename = "VIEW";
15082 * DROP must be fully qualified in case same name appears in
15085 appendPQExpBuffer(delq, "DROP VIEW %s.",
15086 fmtId(tbinfo->dobj.namespace->dobj.name));
15087 appendPQExpBuffer(delq, "%s;\n",
15088 fmtId(tbinfo->dobj.name));
15090 if (dopt->binary_upgrade)
15091 binary_upgrade_set_pg_class_oids(fout, q,
15092 tbinfo->dobj.catId.oid, false);
15094 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
15095 if (tbinfo->dummy_view)
15096 result = createDummyViewAsClause(fout, tbinfo);
15099 if (nonemptyReloptions(tbinfo->reloptions))
15101 appendPQExpBufferStr(q, " WITH (");
15102 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15103 appendPQExpBufferChar(q, ')');
15105 result = createViewAsClause(fout, tbinfo);
15107 appendPQExpBuffer(q, " AS\n%s", result->data);
15108 destroyPQExpBuffer(result);
15110 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15111 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15112 appendPQExpBufferStr(q, ";\n");
15114 appendPQExpBuffer(labelq, "VIEW %s",
15115 fmtId(tbinfo->dobj.name));
15119 switch (tbinfo->relkind)
15121 case RELKIND_FOREIGN_TABLE:
15123 PQExpBuffer query = createPQExpBuffer();
15128 reltypename = "FOREIGN TABLE";
15130 /* retrieve name of foreign server and generic options */
15131 appendPQExpBuffer(query,
15132 "SELECT fs.srvname, "
15133 "pg_catalog.array_to_string(ARRAY("
15134 "SELECT pg_catalog.quote_ident(option_name) || "
15135 "' ' || pg_catalog.quote_literal(option_value) "
15136 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15137 "ORDER BY option_name"
15138 "), E',\n ') AS ftoptions "
15139 "FROM pg_catalog.pg_foreign_table ft "
15140 "JOIN pg_catalog.pg_foreign_server fs "
15141 "ON (fs.oid = ft.ftserver) "
15142 "WHERE ft.ftrelid = '%u'",
15143 tbinfo->dobj.catId.oid);
15144 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15145 i_srvname = PQfnumber(res, "srvname");
15146 i_ftoptions = PQfnumber(res, "ftoptions");
15147 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15148 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15150 destroyPQExpBuffer(query);
15153 case RELKIND_MATVIEW:
15154 reltypename = "MATERIALIZED VIEW";
15159 reltypename = "TABLE";
15164 numParents = tbinfo->numParents;
15165 parents = tbinfo->parents;
15168 * DROP must be fully qualified in case same name appears in
15171 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
15172 fmtId(tbinfo->dobj.namespace->dobj.name));
15173 appendPQExpBuffer(delq, "%s;\n",
15174 fmtId(tbinfo->dobj.name));
15176 appendPQExpBuffer(labelq, "%s %s", reltypename,
15177 fmtId(tbinfo->dobj.name));
15179 if (dopt->binary_upgrade)
15180 binary_upgrade_set_pg_class_oids(fout, q,
15181 tbinfo->dobj.catId.oid, false);
15183 appendPQExpBuffer(q, "CREATE %s%s %s",
15184 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15187 fmtId(tbinfo->dobj.name));
15190 * Attach to type, if reloftype; except in case of a binary upgrade,
15191 * we dump the table normally and attach it to the type afterward.
15193 if (tbinfo->reloftype && !dopt->binary_upgrade)
15194 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15197 * If the table is a partition, dump it as such; except in the case of
15198 * a binary upgrade, we dump the table normally and attach it to the
15199 * parent afterward.
15201 if (tbinfo->ispartition && !dopt->binary_upgrade)
15203 TableInfo *parentRel = tbinfo->parents[0];
15206 * With partitions, unlike inheritance, there can only be one
15209 if (tbinfo->numParents != 1)
15210 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15211 tbinfo->numParents, tbinfo->dobj.name);
15213 appendPQExpBuffer(q, " PARTITION OF ");
15214 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15215 appendPQExpBuffer(q, "%s.",
15216 fmtId(parentRel->dobj.namespace->dobj.name));
15217 appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15220 if (tbinfo->relkind != RELKIND_MATVIEW)
15222 /* Dump the attributes */
15224 for (j = 0; j < tbinfo->numatts; j++)
15227 * Normally, dump if it's locally defined in this table, and
15228 * not dropped. But for binary upgrade, we'll dump all the
15229 * columns, and then fix up the dropped and nonlocal cases
15232 if (shouldPrintColumn(dopt, tbinfo, j))
15235 * Default value --- suppress if to be printed separately.
15237 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15238 !tbinfo->attrdefs[j]->separate);
15241 * Not Null constraint --- suppress if inherited, except
15242 * in binary-upgrade case where that won't work.
15244 bool has_notnull = (tbinfo->notnull[j] &&
15245 (!tbinfo->inhNotNull[j] ||
15246 dopt->binary_upgrade));
15249 * Skip column if fully defined by reloftype or the
15250 * partition parent.
15252 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15253 !has_default && !has_notnull && !dopt->binary_upgrade)
15256 /* Format properly if not first attr */
15257 if (actual_atts == 0)
15258 appendPQExpBufferStr(q, " (");
15260 appendPQExpBufferChar(q, ',');
15261 appendPQExpBufferStr(q, "\n ");
15264 /* Attribute name */
15265 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15267 if (tbinfo->attisdropped[j])
15270 * ALTER TABLE DROP COLUMN clears
15271 * pg_attribute.atttypid, so we will not have gotten a
15272 * valid type name; insert INTEGER as a stopgap. We'll
15273 * clean things up later.
15275 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15276 /* Skip all the rest, too */
15283 * In binary-upgrade mode, we always include the type. If
15284 * we aren't in binary-upgrade mode, then we skip the type
15285 * when creating a typed table ('OF type_name') or a
15286 * partition ('PARTITION OF'), since the type comes from
15287 * the parent/partitioned table.
15289 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15291 appendPQExpBuffer(q, " %s",
15292 tbinfo->atttypnames[j]);
15295 /* Add collation if not default for the type */
15296 if (OidIsValid(tbinfo->attcollation[j]))
15300 coll = findCollationByOid(tbinfo->attcollation[j]);
15303 /* always schema-qualify, don't try to be smart */
15304 appendPQExpBuffer(q, " COLLATE %s.",
15305 fmtId(coll->dobj.namespace->dobj.name));
15306 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
15311 appendPQExpBuffer(q, " DEFAULT %s",
15312 tbinfo->attrdefs[j]->adef_expr);
15315 appendPQExpBufferStr(q, " NOT NULL");
15320 * Add non-inherited CHECK constraints, if any.
15322 for (j = 0; j < tbinfo->ncheck; j++)
15324 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15326 if (constr->separate || !constr->conislocal)
15329 if (actual_atts == 0)
15330 appendPQExpBufferStr(q, " (\n ");
15332 appendPQExpBufferStr(q, ",\n ");
15334 appendPQExpBuffer(q, "CONSTRAINT %s ",
15335 fmtId(constr->dobj.name));
15336 appendPQExpBufferStr(q, constr->condef);
15342 appendPQExpBufferStr(q, "\n)");
15343 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15344 !dopt->binary_upgrade))
15347 * We must have a parenthesized attribute list, even though
15348 * empty, when not using the OF TYPE or PARTITION OF syntax.
15350 appendPQExpBufferStr(q, " (\n)");
15353 if (tbinfo->ispartition && !dopt->binary_upgrade)
15355 appendPQExpBufferStr(q, "\n");
15356 appendPQExpBufferStr(q, tbinfo->partbound);
15359 /* Emit the INHERITS clause, except if this is a partition. */
15360 if (numParents > 0 &&
15361 !tbinfo->ispartition &&
15362 !dopt->binary_upgrade)
15364 appendPQExpBufferStr(q, "\nINHERITS (");
15365 for (k = 0; k < numParents; k++)
15367 TableInfo *parentRel = parents[k];
15370 appendPQExpBufferStr(q, ", ");
15371 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15372 appendPQExpBuffer(q, "%s.",
15373 fmtId(parentRel->dobj.namespace->dobj.name));
15374 appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15376 appendPQExpBufferChar(q, ')');
15379 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15380 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15382 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15383 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15386 if (nonemptyReloptions(tbinfo->reloptions) ||
15387 nonemptyReloptions(tbinfo->toast_reloptions))
15389 bool addcomma = false;
15391 appendPQExpBufferStr(q, "\nWITH (");
15392 if (nonemptyReloptions(tbinfo->reloptions))
15395 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15397 if (nonemptyReloptions(tbinfo->toast_reloptions))
15400 appendPQExpBufferStr(q, ", ");
15401 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15404 appendPQExpBufferChar(q, ')');
15407 /* Dump generic options if any */
15408 if (ftoptions && ftoptions[0])
15409 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15412 * For materialized views, create the AS clause just like a view. At
15413 * this point, we always mark the view as not populated.
15415 if (tbinfo->relkind == RELKIND_MATVIEW)
15417 PQExpBuffer result;
15419 result = createViewAsClause(fout, tbinfo);
15420 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15422 destroyPQExpBuffer(result);
15425 appendPQExpBufferStr(q, ";\n");
15428 * To create binary-compatible heap files, we have to ensure the same
15429 * physical column order, including dropped columns, as in the
15430 * original. Therefore, we create dropped columns above and drop them
15431 * here, also updating their attlen/attalign values so that the
15432 * dropped column can be skipped properly. (We do not bother with
15433 * restoring the original attbyval setting.) Also, inheritance
15434 * relationships are set up by doing ALTER TABLE INHERIT rather than
15435 * using an INHERITS clause --- the latter would possibly mess up the
15436 * column order. That also means we have to take care about setting
15437 * attislocal correctly, plus fix up any inherited CHECK constraints.
15438 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15440 if (dopt->binary_upgrade &&
15441 (tbinfo->relkind == RELKIND_RELATION ||
15442 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15443 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15445 for (j = 0; j < tbinfo->numatts; j++)
15447 if (tbinfo->attisdropped[j])
15449 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15450 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15451 "SET attlen = %d, "
15452 "attalign = '%c', attbyval = false\n"
15453 "WHERE attname = ",
15455 tbinfo->attalign[j]);
15456 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15457 appendPQExpBufferStr(q, "\n AND attrelid = ");
15458 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15459 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15461 if (tbinfo->relkind == RELKIND_RELATION ||
15462 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15463 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15464 fmtId(tbinfo->dobj.name));
15466 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15467 fmtId(tbinfo->dobj.name));
15468 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15469 fmtId(tbinfo->attnames[j]));
15471 else if (!tbinfo->attislocal[j])
15473 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15474 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15475 "SET attislocal = false\n"
15476 "WHERE attname = ");
15477 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15478 appendPQExpBufferStr(q, "\n AND attrelid = ");
15479 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15480 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15484 for (k = 0; k < tbinfo->ncheck; k++)
15486 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15488 if (constr->separate || constr->conislocal)
15491 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15492 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15493 fmtId(tbinfo->dobj.name));
15494 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15495 fmtId(constr->dobj.name));
15496 appendPQExpBuffer(q, "%s;\n", constr->condef);
15497 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15498 "SET conislocal = false\n"
15499 "WHERE contype = 'c' AND conname = ");
15500 appendStringLiteralAH(q, constr->dobj.name, fout);
15501 appendPQExpBufferStr(q, "\n AND conrelid = ");
15502 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15503 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15506 if (numParents > 0)
15508 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15509 for (k = 0; k < numParents; k++)
15511 TableInfo *parentRel = parents[k];
15512 PQExpBuffer parentname = createPQExpBuffer();
15514 /* Schema-qualify the parent table, if necessary */
15515 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15516 appendPQExpBuffer(parentname, "%s.",
15517 fmtId(parentRel->dobj.namespace->dobj.name));
15519 appendPQExpBuffer(parentname, "%s",
15520 fmtId(parentRel->dobj.name));
15522 /* In the partitioning case, we alter the parent */
15523 if (tbinfo->ispartition)
15524 appendPQExpBuffer(q,
15525 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15528 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15529 fmtId(tbinfo->dobj.name));
15531 /* Partition needs specifying the bounds */
15532 if (tbinfo->ispartition)
15533 appendPQExpBuffer(q, "%s %s;\n",
15534 fmtId(tbinfo->dobj.name),
15535 tbinfo->partbound);
15537 appendPQExpBuffer(q, "%s;\n", parentname->data);
15539 destroyPQExpBuffer(parentname);
15543 if (tbinfo->reloftype)
15545 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15546 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15547 fmtId(tbinfo->dobj.name),
15548 tbinfo->reloftype);
15551 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15552 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15553 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15555 tbinfo->frozenxid, tbinfo->minmxid);
15556 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15557 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15559 if (tbinfo->toast_oid)
15561 /* We preserve the toast oids, so we can use it during restore */
15562 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15563 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15564 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15565 "WHERE oid = '%u';\n",
15566 tbinfo->toast_frozenxid,
15567 tbinfo->toast_minmxid, tbinfo->toast_oid);
15572 * In binary_upgrade mode, restore matviews' populated status by
15573 * poking pg_class directly. This is pretty ugly, but we can't use
15574 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15575 * matview is not populated even though this matview is.
15577 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15578 tbinfo->relispopulated)
15580 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15581 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15582 "SET relispopulated = 't'\n"
15584 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15585 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15589 * Dump additional per-column properties that we can't handle in the
15590 * main CREATE TABLE command.
15592 for (j = 0; j < tbinfo->numatts; j++)
15594 /* None of this applies to dropped columns */
15595 if (tbinfo->attisdropped[j])
15599 * If we didn't dump the column definition explicitly above, and
15600 * it is NOT NULL and did not inherit that property from a parent,
15601 * we have to mark it separately.
15603 if (!shouldPrintColumn(dopt, tbinfo, j) &&
15604 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15606 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15607 fmtId(tbinfo->dobj.name));
15608 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15609 fmtId(tbinfo->attnames[j]));
15613 * Dump per-column statistics information. We only issue an ALTER
15614 * TABLE statement if the attstattarget entry for this column is
15615 * non-negative (i.e. it's not the default value)
15617 if (tbinfo->attstattarget[j] >= 0)
15619 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15620 fmtId(tbinfo->dobj.name));
15621 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15622 fmtId(tbinfo->attnames[j]));
15623 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15624 tbinfo->attstattarget[j]);
15628 * Dump per-column storage information. The statement is only
15629 * dumped if the storage has been changed from the type's default.
15631 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15633 switch (tbinfo->attstorage[j])
15639 storage = "EXTERNAL";
15645 storage = "EXTENDED";
15652 * Only dump the statement if it's a storage type we recognize
15654 if (storage != NULL)
15656 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15657 fmtId(tbinfo->dobj.name));
15658 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15659 fmtId(tbinfo->attnames[j]));
15660 appendPQExpBuffer(q, "SET STORAGE %s;\n",
15666 * Dump per-column attributes.
15668 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
15670 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15671 fmtId(tbinfo->dobj.name));
15672 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15673 fmtId(tbinfo->attnames[j]));
15674 appendPQExpBuffer(q, "SET (%s);\n",
15675 tbinfo->attoptions[j]);
15679 * Dump per-column fdw options.
15681 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
15682 tbinfo->attfdwoptions[j] &&
15683 tbinfo->attfdwoptions[j][0] != '\0')
15685 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
15686 fmtId(tbinfo->dobj.name));
15687 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15688 fmtId(tbinfo->attnames[j]));
15689 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
15690 tbinfo->attfdwoptions[j]);
15696 * dump properties we only have ALTER TABLE syntax for
15698 if ((tbinfo->relkind == RELKIND_RELATION ||
15699 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
15700 tbinfo->relkind == RELKIND_MATVIEW) &&
15701 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
15703 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
15705 /* nothing to do, will be set when the index is dumped */
15707 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
15709 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
15710 fmtId(tbinfo->dobj.name));
15712 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
15714 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
15715 fmtId(tbinfo->dobj.name));
15719 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
15720 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
15721 fmtId(tbinfo->dobj.name));
15723 if (tbinfo->forcerowsec)
15724 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
15725 fmtId(tbinfo->dobj.name));
15727 if (dopt->binary_upgrade)
15728 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
15730 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15731 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15733 tbinfo->dobj.namespace->dobj.name,
15734 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
15736 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
15738 tbinfo->postponed_def ?
15739 SECTION_POST_DATA : SECTION_PRE_DATA,
15740 q->data, delq->data, NULL,
15745 /* Dump Table Comments */
15746 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15747 dumpTableComment(fout, tbinfo, reltypename);
15749 /* Dump Table Security Labels */
15750 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
15751 dumpTableSecLabel(fout, tbinfo, reltypename);
15753 /* Dump comments on inlined table constraints */
15754 for (j = 0; j < tbinfo->ncheck; j++)
15756 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15758 if (constr->separate || !constr->conislocal)
15761 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15762 dumpTableConstraintComment(fout, constr);
15765 destroyPQExpBuffer(q);
15766 destroyPQExpBuffer(delq);
15767 destroyPQExpBuffer(labelq);
15771 * dumpAttrDef --- dump an attribute's default-value declaration
15774 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
15776 DumpOptions *dopt = fout->dopt;
15777 TableInfo *tbinfo = adinfo->adtable;
15778 int adnum = adinfo->adnum;
15783 /* Skip if table definition not to be dumped */
15784 if (!tbinfo->dobj.dump || dopt->dataOnly)
15787 /* Skip if not "separate"; it was dumped in the table's definition */
15788 if (!adinfo->separate)
15791 q = createPQExpBuffer();
15792 delq = createPQExpBuffer();
15794 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15795 fmtId(tbinfo->dobj.name));
15796 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
15797 fmtId(tbinfo->attnames[adnum - 1]),
15798 adinfo->adef_expr);
15801 * DROP must be fully qualified in case same name appears in pg_catalog
15803 appendPQExpBuffer(delq, "ALTER TABLE %s.",
15804 fmtId(tbinfo->dobj.namespace->dobj.name));
15805 appendPQExpBuffer(delq, "%s ",
15806 fmtId(tbinfo->dobj.name));
15807 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
15808 fmtId(tbinfo->attnames[adnum - 1]));
15810 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
15812 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15813 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
15815 tbinfo->dobj.namespace->dobj.name,
15818 false, "DEFAULT", SECTION_PRE_DATA,
15819 q->data, delq->data, NULL,
15824 destroyPQExpBuffer(q);
15825 destroyPQExpBuffer(delq);
15829 * getAttrName: extract the correct name for an attribute
15831 * The array tblInfo->attnames[] only provides names of user attributes;
15832 * if a system attribute number is supplied, we have to fake it.
15833 * We also do a little bit of bounds checking for safety's sake.
15835 static const char *
15836 getAttrName(int attrnum, TableInfo *tblInfo)
15838 if (attrnum > 0 && attrnum <= tblInfo->numatts)
15839 return tblInfo->attnames[attrnum - 1];
15842 case SelfItemPointerAttributeNumber:
15844 case ObjectIdAttributeNumber:
15846 case MinTransactionIdAttributeNumber:
15848 case MinCommandIdAttributeNumber:
15850 case MaxTransactionIdAttributeNumber:
15852 case MaxCommandIdAttributeNumber:
15854 case TableOidAttributeNumber:
15857 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
15858 attrnum, tblInfo->dobj.name);
15859 return NULL; /* keep compiler quiet */
15864 * write out to fout a user-defined index
15867 dumpIndex(Archive *fout, IndxInfo *indxinfo)
15869 DumpOptions *dopt = fout->dopt;
15870 TableInfo *tbinfo = indxinfo->indextable;
15871 bool is_constraint = (indxinfo->indexconstraint != 0);
15874 PQExpBuffer labelq;
15876 if (dopt->dataOnly)
15879 q = createPQExpBuffer();
15880 delq = createPQExpBuffer();
15881 labelq = createPQExpBuffer();
15883 appendPQExpBuffer(labelq, "INDEX %s",
15884 fmtId(indxinfo->dobj.name));
15887 * If there's an associated constraint, don't dump the index per se, but
15888 * do dump any comment for it. (This is safe because dependency ordering
15889 * will have ensured the constraint is emitted first.) Note that the
15890 * emitted comment has to be shown as depending on the constraint, not the
15891 * index, in such cases.
15893 if (!is_constraint)
15895 if (dopt->binary_upgrade)
15896 binary_upgrade_set_pg_class_oids(fout, q,
15897 indxinfo->dobj.catId.oid, true);
15899 /* Plain secondary index */
15900 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
15902 /* If the index is clustered, we need to record that. */
15903 if (indxinfo->indisclustered)
15905 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
15906 fmtId(tbinfo->dobj.name));
15907 appendPQExpBuffer(q, " ON %s;\n",
15908 fmtId(indxinfo->dobj.name));
15911 /* If the index defines identity, we need to record that. */
15912 if (indxinfo->indisreplident)
15914 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
15915 fmtId(tbinfo->dobj.name));
15916 appendPQExpBuffer(q, " INDEX %s;\n",
15917 fmtId(indxinfo->dobj.name));
15921 * DROP must be fully qualified in case same name appears in
15924 appendPQExpBuffer(delq, "DROP INDEX %s.",
15925 fmtId(tbinfo->dobj.namespace->dobj.name));
15926 appendPQExpBuffer(delq, "%s;\n",
15927 fmtId(indxinfo->dobj.name));
15929 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15930 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
15931 indxinfo->dobj.name,
15932 tbinfo->dobj.namespace->dobj.name,
15933 indxinfo->tablespace,
15934 tbinfo->rolname, false,
15935 "INDEX", SECTION_POST_DATA,
15936 q->data, delq->data, NULL,
15941 /* Dump Index Comments */
15942 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15943 dumpComment(fout, labelq->data,
15944 tbinfo->dobj.namespace->dobj.name,
15946 indxinfo->dobj.catId, 0,
15947 is_constraint ? indxinfo->indexconstraint :
15948 indxinfo->dobj.dumpId);
15950 destroyPQExpBuffer(q);
15951 destroyPQExpBuffer(delq);
15952 destroyPQExpBuffer(labelq);
15956 * dumpStatisticsExt
15957 * write out to fout an extended statistics object
15960 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
15962 DumpOptions *dopt = fout->dopt;
15963 TableInfo *tbinfo = statsextinfo->statsexttable;
15966 PQExpBuffer labelq;
15968 if (dopt->dataOnly)
15971 q = createPQExpBuffer();
15972 delq = createPQExpBuffer();
15973 labelq = createPQExpBuffer();
15975 appendPQExpBuffer(labelq, "STATISTICS %s",
15976 fmtId(statsextinfo->dobj.name));
15978 appendPQExpBuffer(q, "%s;\n", statsextinfo->statsextdef);
15980 appendPQExpBuffer(delq, "DROP STATISTICS %s.",
15981 fmtId(tbinfo->dobj.namespace->dobj.name));
15982 appendPQExpBuffer(delq, "%s;\n",
15983 fmtId(statsextinfo->dobj.name));
15985 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15986 ArchiveEntry(fout, statsextinfo->dobj.catId,
15987 statsextinfo->dobj.dumpId,
15988 statsextinfo->dobj.name,
15989 tbinfo->dobj.namespace->dobj.name,
15991 tbinfo->rolname, false,
15992 "STATISTICS", SECTION_POST_DATA,
15993 q->data, delq->data, NULL,
15997 /* Dump Statistics Comments */
15998 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15999 dumpComment(fout, labelq->data,
16000 tbinfo->dobj.namespace->dobj.name,
16002 statsextinfo->dobj.catId, 0,
16003 statsextinfo->dobj.dumpId);
16005 destroyPQExpBuffer(q);
16006 destroyPQExpBuffer(delq);
16007 destroyPQExpBuffer(labelq);
16012 * write out to fout a user-defined constraint
16015 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16017 DumpOptions *dopt = fout->dopt;
16018 TableInfo *tbinfo = coninfo->contable;
16023 /* Skip if not to be dumped */
16024 if (!coninfo->dobj.dump || dopt->dataOnly)
16027 q = createPQExpBuffer();
16028 delq = createPQExpBuffer();
16030 if (coninfo->contype == 'p' ||
16031 coninfo->contype == 'u' ||
16032 coninfo->contype == 'x')
16034 /* Index-related constraint */
16035 IndxInfo *indxinfo;
16038 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16040 if (indxinfo == NULL)
16041 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16042 coninfo->dobj.name);
16044 if (dopt->binary_upgrade)
16045 binary_upgrade_set_pg_class_oids(fout, q,
16046 indxinfo->dobj.catId.oid, true);
16048 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16049 fmtId(tbinfo->dobj.name));
16050 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16051 fmtId(coninfo->dobj.name));
16053 if (coninfo->condef)
16055 /* pg_get_constraintdef should have provided everything */
16056 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16060 appendPQExpBuffer(q, "%s (",
16061 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16062 for (k = 0; k < indxinfo->indnkeys; k++)
16064 int indkey = (int) indxinfo->indkeys[k];
16065 const char *attname;
16067 if (indkey == InvalidAttrNumber)
16069 attname = getAttrName(indkey, tbinfo);
16071 appendPQExpBuffer(q, "%s%s",
16072 (k == 0) ? "" : ", ",
16076 appendPQExpBufferChar(q, ')');
16078 if (nonemptyReloptions(indxinfo->indreloptions))
16080 appendPQExpBufferStr(q, " WITH (");
16081 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16082 appendPQExpBufferChar(q, ')');
16085 if (coninfo->condeferrable)
16087 appendPQExpBufferStr(q, " DEFERRABLE");
16088 if (coninfo->condeferred)
16089 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16092 appendPQExpBufferStr(q, ";\n");
16095 /* If the index is clustered, we need to record that. */
16096 if (indxinfo->indisclustered)
16098 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16099 fmtId(tbinfo->dobj.name));
16100 appendPQExpBuffer(q, " ON %s;\n",
16101 fmtId(indxinfo->dobj.name));
16105 * DROP must be fully qualified in case same name appears in
16108 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16109 fmtId(tbinfo->dobj.namespace->dobj.name));
16110 appendPQExpBuffer(delq, "%s ",
16111 fmtId(tbinfo->dobj.name));
16112 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16113 fmtId(coninfo->dobj.name));
16115 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16117 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16118 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16120 tbinfo->dobj.namespace->dobj.name,
16121 indxinfo->tablespace,
16122 tbinfo->rolname, false,
16123 "CONSTRAINT", SECTION_POST_DATA,
16124 q->data, delq->data, NULL,
16128 else if (coninfo->contype == 'f')
16131 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16132 * current table data is not processed
16134 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16135 fmtId(tbinfo->dobj.name));
16136 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16137 fmtId(coninfo->dobj.name),
16141 * DROP must be fully qualified in case same name appears in
16144 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16145 fmtId(tbinfo->dobj.namespace->dobj.name));
16146 appendPQExpBuffer(delq, "%s ",
16147 fmtId(tbinfo->dobj.name));
16148 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16149 fmtId(coninfo->dobj.name));
16151 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16153 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16154 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16156 tbinfo->dobj.namespace->dobj.name,
16158 tbinfo->rolname, false,
16159 "FK CONSTRAINT", SECTION_POST_DATA,
16160 q->data, delq->data, NULL,
16164 else if (coninfo->contype == 'c' && tbinfo)
16166 /* CHECK constraint on a table */
16168 /* Ignore if not to be dumped separately, or if it was inherited */
16169 if (coninfo->separate && coninfo->conislocal)
16171 /* not ONLY since we want it to propagate to children */
16172 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16173 fmtId(tbinfo->dobj.name));
16174 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16175 fmtId(coninfo->dobj.name),
16179 * DROP must be fully qualified in case same name appears in
16182 appendPQExpBuffer(delq, "ALTER TABLE %s.",
16183 fmtId(tbinfo->dobj.namespace->dobj.name));
16184 appendPQExpBuffer(delq, "%s ",
16185 fmtId(tbinfo->dobj.name));
16186 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16187 fmtId(coninfo->dobj.name));
16189 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16191 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16192 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16194 tbinfo->dobj.namespace->dobj.name,
16196 tbinfo->rolname, false,
16197 "CHECK CONSTRAINT", SECTION_POST_DATA,
16198 q->data, delq->data, NULL,
16203 else if (coninfo->contype == 'c' && tbinfo == NULL)
16205 /* CHECK constraint on a domain */
16206 TypeInfo *tyinfo = coninfo->condomain;
16208 /* Ignore if not to be dumped separately */
16209 if (coninfo->separate)
16211 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16212 fmtId(tyinfo->dobj.name));
16213 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16214 fmtId(coninfo->dobj.name),
16218 * DROP must be fully qualified in case same name appears in
16221 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
16222 fmtId(tyinfo->dobj.namespace->dobj.name));
16223 appendPQExpBuffer(delq, "%s ",
16224 fmtId(tyinfo->dobj.name));
16225 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16226 fmtId(coninfo->dobj.name));
16228 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16230 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16231 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16233 tyinfo->dobj.namespace->dobj.name,
16235 tyinfo->rolname, false,
16236 "CHECK CONSTRAINT", SECTION_POST_DATA,
16237 q->data, delq->data, NULL,
16244 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16248 /* Dump Constraint Comments --- only works for table constraints */
16249 if (tbinfo && coninfo->separate &&
16250 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16251 dumpTableConstraintComment(fout, coninfo);
16254 destroyPQExpBuffer(q);
16255 destroyPQExpBuffer(delq);
16259 * dumpTableConstraintComment --- dump a constraint's comment if any
16261 * This is split out because we need the function in two different places
16262 * depending on whether the constraint is dumped as part of CREATE TABLE
16263 * or as a separate ALTER command.
16266 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16268 TableInfo *tbinfo = coninfo->contable;
16269 PQExpBuffer labelq = createPQExpBuffer();
16271 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
16272 fmtId(coninfo->dobj.name));
16273 appendPQExpBuffer(labelq, "ON %s",
16274 fmtId(tbinfo->dobj.name));
16276 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16277 dumpComment(fout, labelq->data,
16278 tbinfo->dobj.namespace->dobj.name,
16280 coninfo->dobj.catId, 0,
16281 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16283 destroyPQExpBuffer(labelq);
16287 * findLastBuiltinOid_V71 -
16289 * find the last built in oid
16291 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16292 * pg_database entry for the current database.
16295 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
16299 PQExpBuffer query = createPQExpBuffer();
16301 resetPQExpBuffer(query);
16302 appendPQExpBufferStr(query, "SELECT datlastsysoid from pg_database where datname = ");
16303 appendStringLiteralAH(query, dbname, fout);
16305 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16306 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16308 destroyPQExpBuffer(query);
16315 * write the declaration (not data) of one user-defined sequence
16318 dumpSequence(Archive *fout, TableInfo *tbinfo)
16320 DumpOptions *dopt = fout->dopt;
16330 PQExpBuffer query = createPQExpBuffer();
16331 PQExpBuffer delqry = createPQExpBuffer();
16332 PQExpBuffer labelq = createPQExpBuffer();
16334 if (fout->remoteVersion >= 100000)
16336 /* Make sure we are in proper schema */
16337 selectSourceSchema(fout, "pg_catalog");
16339 appendPQExpBuffer(query,
16340 "SELECT format_type(seqtypid, NULL), "
16341 "seqstart, seqincrement, "
16343 "seqcache, seqcycle "
16345 "JOIN pg_sequence s ON (s.seqrelid = c.oid) "
16346 "WHERE c.oid = '%u'::oid",
16347 tbinfo->dobj.catId.oid);
16349 else if (fout->remoteVersion >= 80400)
16352 * Before PostgreSQL 10, sequence metadata is in the sequence itself,
16353 * so switch to the sequence's schema instead of pg_catalog.
16356 /* Make sure we are in proper schema */
16357 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16359 appendPQExpBuffer(query,
16360 "SELECT 'bigint'::name AS sequence_type, "
16361 "start_value, increment_by, max_value, min_value, "
16362 "cache_value, is_cycled FROM %s",
16363 fmtId(tbinfo->dobj.name));
16367 /* Make sure we are in proper schema */
16368 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16370 appendPQExpBuffer(query,
16371 "SELECT 'bigint'::name AS sequence_type, "
16372 "0 AS start_value, increment_by, max_value, min_value, "
16373 "cache_value, is_cycled FROM %s",
16374 fmtId(tbinfo->dobj.name));
16377 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16379 if (PQntuples(res) != 1)
16381 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16382 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16384 tbinfo->dobj.name, PQntuples(res));
16388 seqtype = PQgetvalue(res, 0, 0);
16389 startv = PQgetvalue(res, 0, 1);
16390 incby = PQgetvalue(res, 0, 2);
16391 maxv = PQgetvalue(res, 0, 3);
16392 minv = PQgetvalue(res, 0, 4);
16393 cache = PQgetvalue(res, 0, 5);
16394 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16396 is_ascending = incby[0] != '-';
16398 if (is_ascending && atoi(minv) == 1)
16400 if (!is_ascending && atoi(maxv) == -1)
16403 if (strcmp(seqtype, "smallint") == 0)
16405 if (!is_ascending && atoi(minv) == PG_INT16_MIN)
16407 if (is_ascending && atoi(maxv) == PG_INT16_MAX)
16410 else if (strcmp(seqtype, "integer") == 0)
16412 if (!is_ascending && atoi(minv) == PG_INT32_MIN)
16414 if (is_ascending && atoi(maxv) == PG_INT32_MAX)
16417 else if (strcmp(seqtype, "bigint") == 0)
16422 snprintf(bufm, sizeof(bufm), INT64_FORMAT, PG_INT64_MIN);
16423 snprintf(bufx, sizeof(bufx), INT64_FORMAT, PG_INT64_MAX);
16425 if (!is_ascending && strcmp(minv, bufm) == 0)
16427 if (is_ascending && strcmp(maxv, bufx) == 0)
16432 * DROP must be fully qualified in case same name appears in pg_catalog
16434 if (!tbinfo->is_identity_sequence)
16436 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
16437 fmtId(tbinfo->dobj.namespace->dobj.name));
16438 appendPQExpBuffer(delqry, "%s;\n",
16439 fmtId(tbinfo->dobj.name));
16442 resetPQExpBuffer(query);
16444 if (dopt->binary_upgrade)
16446 binary_upgrade_set_pg_class_oids(fout, query,
16447 tbinfo->dobj.catId.oid, false);
16448 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16449 tbinfo->dobj.catId.oid);
16452 if (tbinfo->is_identity_sequence)
16454 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16456 appendPQExpBuffer(query,
16458 fmtId(owning_tab->dobj.name));
16459 appendPQExpBuffer(query,
16460 "ALTER COLUMN %s ADD GENERATED ",
16461 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16462 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16463 appendPQExpBuffer(query, "ALWAYS");
16464 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16465 appendPQExpBuffer(query, "BY DEFAULT");
16466 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16467 fmtId(tbinfo->dobj.name));
16471 appendPQExpBuffer(query,
16472 "CREATE SEQUENCE %s\n",
16473 fmtId(tbinfo->dobj.name));
16475 if (strcmp(seqtype, "bigint") != 0)
16476 appendPQExpBuffer(query, " AS %s\n", seqtype);
16479 if (fout->remoteVersion >= 80400)
16480 appendPQExpBuffer(query, " START WITH %s\n", startv);
16482 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
16485 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
16487 appendPQExpBufferStr(query, " NO MINVALUE\n");
16490 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
16492 appendPQExpBufferStr(query, " NO MAXVALUE\n");
16494 appendPQExpBuffer(query,
16496 cache, (cycled ? "\n CYCLE" : ""));
16498 if (tbinfo->is_identity_sequence)
16499 appendPQExpBufferStr(query, "\n);\n");
16501 appendPQExpBufferStr(query, ";\n");
16503 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
16505 /* binary_upgrade: no need to clear TOAST table oid */
16507 if (dopt->binary_upgrade)
16508 binary_upgrade_extension_member(query, &tbinfo->dobj,
16511 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16512 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16514 tbinfo->dobj.namespace->dobj.name,
16517 false, "SEQUENCE", SECTION_PRE_DATA,
16518 query->data, delqry->data, NULL,
16523 * If the sequence is owned by a table column, emit the ALTER for it as a
16524 * separate TOC entry immediately following the sequence's own entry. It's
16525 * OK to do this rather than using full sorting logic, because the
16526 * dependency that tells us it's owned will have forced the table to be
16527 * created first. We can't just include the ALTER in the TOC entry
16528 * because it will fail if we haven't reassigned the sequence owner to
16529 * match the table's owner.
16531 * We need not schema-qualify the table reference because both sequence
16532 * and table must be in the same schema.
16534 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16536 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16538 if (owning_tab == NULL)
16539 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16540 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16542 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16544 resetPQExpBuffer(query);
16545 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16546 fmtId(tbinfo->dobj.name));
16547 appendPQExpBuffer(query, " OWNED BY %s",
16548 fmtId(owning_tab->dobj.name));
16549 appendPQExpBuffer(query, ".%s;\n",
16550 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16552 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16553 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16555 tbinfo->dobj.namespace->dobj.name,
16558 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16559 query->data, "", NULL,
16560 &(tbinfo->dobj.dumpId), 1,
16565 /* Dump Sequence Comments and Security Labels */
16566 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16567 dumpComment(fout, labelq->data,
16568 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16569 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16571 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16572 dumpSecLabel(fout, labelq->data,
16573 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16574 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16578 destroyPQExpBuffer(query);
16579 destroyPQExpBuffer(delqry);
16580 destroyPQExpBuffer(labelq);
16585 * write the data of one user-defined sequence
16588 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16590 TableInfo *tbinfo = tdinfo->tdtable;
16594 PQExpBuffer query = createPQExpBuffer();
16596 /* Make sure we are in proper schema */
16597 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16599 appendPQExpBuffer(query,
16600 "SELECT last_value, is_called FROM %s",
16601 fmtId(tbinfo->dobj.name));
16603 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16605 if (PQntuples(res) != 1)
16607 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16608 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16610 tbinfo->dobj.name, PQntuples(res));
16614 last = PQgetvalue(res, 0, 0);
16615 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
16617 resetPQExpBuffer(query);
16618 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
16619 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
16620 appendPQExpBuffer(query, ", %s, %s);\n",
16621 last, (called ? "true" : "false"));
16623 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
16624 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16626 tbinfo->dobj.namespace->dobj.name,
16629 false, "SEQUENCE SET", SECTION_DATA,
16630 query->data, "", NULL,
16631 &(tbinfo->dobj.dumpId), 1,
16636 destroyPQExpBuffer(query);
16641 * write the declaration of one user-defined table trigger
16644 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
16646 DumpOptions *dopt = fout->dopt;
16647 TableInfo *tbinfo = tginfo->tgtable;
16649 PQExpBuffer delqry;
16650 PQExpBuffer labelq;
16658 * we needn't check dobj.dump because TriggerInfo wouldn't have been
16659 * created in the first place for non-dumpable triggers
16661 if (dopt->dataOnly)
16664 query = createPQExpBuffer();
16665 delqry = createPQExpBuffer();
16666 labelq = createPQExpBuffer();
16669 * DROP must be fully qualified in case same name appears in pg_catalog
16671 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
16672 fmtId(tginfo->dobj.name));
16673 appendPQExpBuffer(delqry, "ON %s.",
16674 fmtId(tbinfo->dobj.namespace->dobj.name));
16675 appendPQExpBuffer(delqry, "%s;\n",
16676 fmtId(tbinfo->dobj.name));
16680 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
16684 if (tginfo->tgisconstraint)
16686 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
16687 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
16691 appendPQExpBufferStr(query, "CREATE TRIGGER ");
16692 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
16694 appendPQExpBufferStr(query, "\n ");
16697 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
16698 appendPQExpBufferStr(query, "BEFORE");
16699 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
16700 appendPQExpBufferStr(query, "AFTER");
16701 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
16702 appendPQExpBufferStr(query, "INSTEAD OF");
16705 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
16710 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
16712 appendPQExpBufferStr(query, " INSERT");
16715 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
16718 appendPQExpBufferStr(query, " OR DELETE");
16720 appendPQExpBufferStr(query, " DELETE");
16723 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
16726 appendPQExpBufferStr(query, " OR UPDATE");
16728 appendPQExpBufferStr(query, " UPDATE");
16731 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
16734 appendPQExpBufferStr(query, " OR TRUNCATE");
16736 appendPQExpBufferStr(query, " TRUNCATE");
16739 appendPQExpBuffer(query, " ON %s\n",
16740 fmtId(tbinfo->dobj.name));
16742 if (tginfo->tgisconstraint)
16744 if (OidIsValid(tginfo->tgconstrrelid))
16746 /* regclass output is already quoted */
16747 appendPQExpBuffer(query, " FROM %s\n ",
16748 tginfo->tgconstrrelname);
16750 if (!tginfo->tgdeferrable)
16751 appendPQExpBufferStr(query, "NOT ");
16752 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
16753 if (tginfo->tginitdeferred)
16754 appendPQExpBufferStr(query, "DEFERRED\n");
16756 appendPQExpBufferStr(query, "IMMEDIATE\n");
16759 if (TRIGGER_FOR_ROW(tginfo->tgtype))
16760 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
16762 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
16764 /* regproc output is already sufficiently quoted */
16765 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
16768 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
16771 for (findx = 0; findx < tginfo->tgnargs; findx++)
16773 /* find the embedded null that terminates this trigger argument */
16774 size_t tlen = strlen(p);
16776 if (p + tlen >= tgargs + lentgargs)
16778 /* hm, not found before end of bytea value... */
16779 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
16782 tbinfo->dobj.name);
16787 appendPQExpBufferStr(query, ", ");
16788 appendStringLiteralAH(query, p, fout);
16792 appendPQExpBufferStr(query, ");\n");
16795 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
16797 appendPQExpBuffer(query, "\nALTER TABLE %s ",
16798 fmtId(tbinfo->dobj.name));
16799 switch (tginfo->tgenabled)
16803 appendPQExpBufferStr(query, "DISABLE");
16806 appendPQExpBufferStr(query, "ENABLE ALWAYS");
16809 appendPQExpBufferStr(query, "ENABLE REPLICA");
16812 appendPQExpBufferStr(query, "ENABLE");
16815 appendPQExpBuffer(query, " TRIGGER %s;\n",
16816 fmtId(tginfo->dobj.name));
16819 appendPQExpBuffer(labelq, "TRIGGER %s ",
16820 fmtId(tginfo->dobj.name));
16821 appendPQExpBuffer(labelq, "ON %s",
16822 fmtId(tbinfo->dobj.name));
16824 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
16826 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16827 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
16829 tbinfo->dobj.namespace->dobj.name,
16831 tbinfo->rolname, false,
16832 "TRIGGER", SECTION_POST_DATA,
16833 query->data, delqry->data, NULL,
16837 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16838 dumpComment(fout, labelq->data,
16839 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16840 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
16843 destroyPQExpBuffer(query);
16844 destroyPQExpBuffer(delqry);
16845 destroyPQExpBuffer(labelq);
16850 * write the declaration of one user-defined event trigger
16853 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
16855 DumpOptions *dopt = fout->dopt;
16857 PQExpBuffer delqry;
16858 PQExpBuffer labelq;
16860 /* Skip if not to be dumped */
16861 if (!evtinfo->dobj.dump || dopt->dataOnly)
16864 query = createPQExpBuffer();
16865 delqry = createPQExpBuffer();
16866 labelq = createPQExpBuffer();
16868 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
16869 appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
16870 appendPQExpBufferStr(query, " ON ");
16871 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
16873 if (strcmp("", evtinfo->evttags) != 0)
16875 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
16876 appendPQExpBufferStr(query, evtinfo->evttags);
16877 appendPQExpBufferChar(query, ')');
16880 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
16881 appendPQExpBufferStr(query, evtinfo->evtfname);
16882 appendPQExpBufferStr(query, "();\n");
16884 if (evtinfo->evtenabled != 'O')
16886 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
16887 fmtId(evtinfo->dobj.name));
16888 switch (evtinfo->evtenabled)
16891 appendPQExpBufferStr(query, "DISABLE");
16894 appendPQExpBufferStr(query, "ENABLE ALWAYS");
16897 appendPQExpBufferStr(query, "ENABLE REPLICA");
16900 appendPQExpBufferStr(query, "ENABLE");
16903 appendPQExpBufferStr(query, ";\n");
16906 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
16907 fmtId(evtinfo->dobj.name));
16909 appendPQExpBuffer(labelq, "EVENT TRIGGER %s",
16910 fmtId(evtinfo->dobj.name));
16912 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16913 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
16914 evtinfo->dobj.name, NULL, NULL,
16915 evtinfo->evtowner, false,
16916 "EVENT TRIGGER", SECTION_POST_DATA,
16917 query->data, delqry->data, NULL,
16921 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16922 dumpComment(fout, labelq->data,
16923 NULL, evtinfo->evtowner,
16924 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
16926 destroyPQExpBuffer(query);
16927 destroyPQExpBuffer(delqry);
16928 destroyPQExpBuffer(labelq);
16936 dumpRule(Archive *fout, RuleInfo *rinfo)
16938 DumpOptions *dopt = fout->dopt;
16939 TableInfo *tbinfo = rinfo->ruletable;
16943 PQExpBuffer delcmd;
16944 PQExpBuffer labelq;
16948 /* Skip if not to be dumped */
16949 if (!rinfo->dobj.dump || dopt->dataOnly)
16953 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
16954 * we do not want to dump it as a separate object.
16956 if (!rinfo->separate)
16960 * If it's an ON SELECT rule, we want to print it as a view definition,
16961 * instead of a rule.
16963 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
16966 * Make sure we are in proper schema.
16968 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16970 query = createPQExpBuffer();
16971 cmd = createPQExpBuffer();
16972 delcmd = createPQExpBuffer();
16973 labelq = createPQExpBuffer();
16977 PQExpBuffer result;
16980 * We need OR REPLACE here because we'll be replacing a dummy view.
16981 * Otherwise this should look largely like the regular view dump code.
16983 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
16984 fmtId(tbinfo->dobj.name));
16985 if (nonemptyReloptions(tbinfo->reloptions))
16987 appendPQExpBufferStr(cmd, " WITH (");
16988 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
16989 appendPQExpBufferChar(cmd, ')');
16991 result = createViewAsClause(fout, tbinfo);
16992 appendPQExpBuffer(cmd, " AS\n%s", result->data);
16993 destroyPQExpBuffer(result);
16994 if (tbinfo->checkoption != NULL)
16995 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
16996 tbinfo->checkoption);
16997 appendPQExpBufferStr(cmd, ";\n");
17001 /* In the rule case, just print pg_get_ruledef's result verbatim */
17002 appendPQExpBuffer(query,
17003 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17004 rinfo->dobj.catId.oid);
17006 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17008 if (PQntuples(res) != 1)
17010 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17011 rinfo->dobj.name, tbinfo->dobj.name);
17015 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17021 * Add the command to alter the rules replication firing semantics if it
17022 * differs from the default.
17024 if (rinfo->ev_enabled != 'O')
17026 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
17027 switch (rinfo->ev_enabled)
17030 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17031 fmtId(rinfo->dobj.name));
17034 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17035 fmtId(rinfo->dobj.name));
17038 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17039 fmtId(rinfo->dobj.name));
17045 * DROP must be fully qualified in case same name appears in pg_catalog
17050 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17051 * REPLACE VIEW to replace the rule with something with minimal
17054 PQExpBuffer result;
17056 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s.",
17057 fmtId(tbinfo->dobj.namespace->dobj.name));
17058 appendPQExpBuffer(delcmd, "%s",
17059 fmtId(tbinfo->dobj.name));
17060 result = createDummyViewAsClause(fout, tbinfo);
17061 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17062 destroyPQExpBuffer(result);
17066 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17067 fmtId(rinfo->dobj.name));
17068 appendPQExpBuffer(delcmd, "ON %s.",
17069 fmtId(tbinfo->dobj.namespace->dobj.name));
17070 appendPQExpBuffer(delcmd, "%s;\n",
17071 fmtId(tbinfo->dobj.name));
17074 appendPQExpBuffer(labelq, "RULE %s",
17075 fmtId(rinfo->dobj.name));
17076 appendPQExpBuffer(labelq, " ON %s",
17077 fmtId(tbinfo->dobj.name));
17079 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17081 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17082 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17084 tbinfo->dobj.namespace->dobj.name,
17086 tbinfo->rolname, false,
17087 "RULE", SECTION_POST_DATA,
17088 cmd->data, delcmd->data, NULL,
17092 /* Dump rule comments */
17093 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17094 dumpComment(fout, labelq->data,
17095 tbinfo->dobj.namespace->dobj.name,
17097 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17100 destroyPQExpBuffer(query);
17101 destroyPQExpBuffer(cmd);
17102 destroyPQExpBuffer(delcmd);
17103 destroyPQExpBuffer(labelq);
17107 * getExtensionMembership --- obtain extension membership data
17109 * We need to identify objects that are extension members as soon as they're
17110 * loaded, so that we can correctly determine whether they need to be dumped.
17111 * Generally speaking, extension member objects will get marked as *not* to
17112 * be dumped, as they will be recreated by the single CREATE EXTENSION
17113 * command. However, in binary upgrade mode we still need to dump the members
17117 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17128 ExtensionMemberId *extmembers;
17129 ExtensionInfo *ext;
17131 /* Nothing to do if no extensions */
17132 if (numExtensions == 0)
17135 /* Make sure we are in proper schema */
17136 selectSourceSchema(fout, "pg_catalog");
17138 query = createPQExpBuffer();
17140 /* refclassid constraint is redundant but may speed the search */
17141 appendPQExpBufferStr(query, "SELECT "
17142 "classid, objid, refobjid "
17144 "WHERE refclassid = 'pg_extension'::regclass "
17145 "AND deptype = 'e' "
17148 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17150 ntups = PQntuples(res);
17152 i_classid = PQfnumber(res, "classid");
17153 i_objid = PQfnumber(res, "objid");
17154 i_refobjid = PQfnumber(res, "refobjid");
17156 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17160 * Accumulate data into extmembers[].
17162 * Since we ordered the SELECT by referenced ID, we can expect that
17163 * multiple entries for the same extension will appear together; this
17164 * saves on searches.
17168 for (i = 0; i < ntups; i++)
17173 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17174 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17175 extId = atooid(PQgetvalue(res, i, i_refobjid));
17178 ext->dobj.catId.oid != extId)
17179 ext = findExtensionByOid(extId);
17183 /* shouldn't happen */
17184 fprintf(stderr, "could not find referenced extension %u\n", extId);
17188 extmembers[nextmembers].catId = objId;
17189 extmembers[nextmembers].ext = ext;
17195 /* Remember the data for use later */
17196 setExtensionMembership(extmembers, nextmembers);
17198 destroyPQExpBuffer(query);
17202 * processExtensionTables --- deal with extension configuration tables
17204 * There are two parts to this process:
17206 * 1. Identify and create dump records for extension configuration tables.
17208 * Extensions can mark tables as "configuration", which means that the user
17209 * is able and expected to modify those tables after the extension has been
17210 * loaded. For these tables, we dump out only the data- the structure is
17211 * expected to be handled at CREATE EXTENSION time, including any indexes or
17212 * foreign keys, which brings us to-
17214 * 2. Record FK dependencies between configuration tables.
17216 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17217 * the data is loaded, we have to work out what the best order for reloading
17218 * the data is, to avoid FK violations when the tables are restored. This is
17219 * not perfect- we can't handle circular dependencies and if any exist they
17220 * will cause an invalid dump to be produced (though at least all of the data
17221 * is included for a user to manually restore). This is currently documented
17222 * but perhaps we can provide a better solution in the future.
17225 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17228 DumpOptions *dopt = fout->dopt;
17236 /* Nothing to do if no extensions */
17237 if (numExtensions == 0)
17241 * Identify extension configuration tables and create TableDataInfo
17242 * objects for them, ensuring their data will be dumped even though the
17243 * tables themselves won't be.
17245 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17246 * user data in a configuration table is treated like schema data. This
17247 * seems appropriate since system data in a config table would get
17248 * reloaded by CREATE EXTENSION.
17250 for (i = 0; i < numExtensions; i++)
17252 ExtensionInfo *curext = &(extinfo[i]);
17253 char *extconfig = curext->extconfig;
17254 char *extcondition = curext->extcondition;
17255 char **extconfigarray = NULL;
17256 char **extconditionarray = NULL;
17258 int nconditionitems;
17260 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17261 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17262 nconfigitems == nconditionitems)
17266 for (j = 0; j < nconfigitems; j++)
17268 TableInfo *configtbl;
17269 Oid configtbloid = atooid(extconfigarray[j]);
17271 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17273 configtbl = findTableByOid(configtbloid);
17274 if (configtbl == NULL)
17278 * Tables of not-to-be-dumped extensions shouldn't be dumped
17279 * unless the table or its schema is explicitly included
17281 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17283 /* check table explicitly requested */
17284 if (table_include_oids.head != NULL &&
17285 simple_oid_list_member(&table_include_oids,
17289 /* check table's schema explicitly requested */
17290 if (configtbl->dobj.namespace->dobj.dump &
17291 DUMP_COMPONENT_DATA)
17295 /* check table excluded by an exclusion switch */
17296 if (table_exclude_oids.head != NULL &&
17297 simple_oid_list_member(&table_exclude_oids,
17301 /* check schema excluded by an exclusion switch */
17302 if (simple_oid_list_member(&schema_exclude_oids,
17303 configtbl->dobj.namespace->dobj.catId.oid))
17309 * Note: config tables are dumped without OIDs regardless
17310 * of the --oids setting. This is because row filtering
17311 * conditions aren't compatible with dumping OIDs.
17313 makeTableDataInfo(dopt, configtbl, false);
17314 if (configtbl->dataObj != NULL)
17316 if (strlen(extconditionarray[j]) > 0)
17317 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17322 if (extconfigarray)
17323 free(extconfigarray);
17324 if (extconditionarray)
17325 free(extconditionarray);
17329 * Now that all the TableInfoData objects have been created for all the
17330 * extensions, check their FK dependencies and register them to try and
17331 * dump the data out in an order that they can be restored in.
17333 * Note that this is not a problem for user tables as their FKs are
17334 * recreated after the data has been loaded.
17337 /* Make sure we are in proper schema */
17338 selectSourceSchema(fout, "pg_catalog");
17340 query = createPQExpBuffer();
17342 printfPQExpBuffer(query,
17343 "SELECT conrelid, confrelid "
17344 "FROM pg_constraint "
17345 "JOIN pg_depend ON (objid = confrelid) "
17346 "WHERE contype = 'f' "
17347 "AND refclassid = 'pg_extension'::regclass "
17348 "AND classid = 'pg_class'::regclass;");
17350 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17351 ntups = PQntuples(res);
17353 i_conrelid = PQfnumber(res, "conrelid");
17354 i_confrelid = PQfnumber(res, "confrelid");
17356 /* Now get the dependencies and register them */
17357 for (i = 0; i < ntups; i++)
17361 TableInfo *reftable,
17364 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17365 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17366 contable = findTableByOid(conrelid);
17367 reftable = findTableByOid(confrelid);
17369 if (reftable == NULL ||
17370 reftable->dataObj == NULL ||
17371 contable == NULL ||
17372 contable->dataObj == NULL)
17376 * Make referencing TABLE_DATA object depend on the referenced table's
17377 * TABLE_DATA object.
17379 addObjectDependency(&contable->dataObj->dobj,
17380 reftable->dataObj->dobj.dumpId);
17383 destroyPQExpBuffer(query);
17387 * getDependencies --- obtain available dependency data
17390 getDependencies(Archive *fout)
17401 DumpableObject *dobj,
17405 write_msg(NULL, "reading dependency data\n");
17407 /* Make sure we are in proper schema */
17408 selectSourceSchema(fout, "pg_catalog");
17410 query = createPQExpBuffer();
17413 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17414 * already processed by getExtensionMembership.
17416 appendPQExpBufferStr(query, "SELECT "
17417 "classid, objid, refclassid, refobjid, deptype "
17419 "WHERE deptype != 'p' AND deptype != 'e' "
17422 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17424 ntups = PQntuples(res);
17426 i_classid = PQfnumber(res, "classid");
17427 i_objid = PQfnumber(res, "objid");
17428 i_refclassid = PQfnumber(res, "refclassid");
17429 i_refobjid = PQfnumber(res, "refobjid");
17430 i_deptype = PQfnumber(res, "deptype");
17433 * Since we ordered the SELECT by referencing ID, we can expect that
17434 * multiple entries for the same object will appear together; this saves
17439 for (i = 0; i < ntups; i++)
17442 CatalogId refobjId;
17445 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17446 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17447 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17448 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17449 deptype = *(PQgetvalue(res, i, i_deptype));
17451 if (dobj == NULL ||
17452 dobj->catId.tableoid != objId.tableoid ||
17453 dobj->catId.oid != objId.oid)
17454 dobj = findObjectByCatalogId(objId);
17457 * Failure to find objects mentioned in pg_depend is not unexpected,
17458 * since for example we don't collect info about TOAST tables.
17463 fprintf(stderr, "no referencing object %u %u\n",
17464 objId.tableoid, objId.oid);
17469 refdobj = findObjectByCatalogId(refobjId);
17471 if (refdobj == NULL)
17474 fprintf(stderr, "no referenced object %u %u\n",
17475 refobjId.tableoid, refobjId.oid);
17481 * Ordinarily, table rowtypes have implicit dependencies on their
17482 * tables. However, for a composite type the implicit dependency goes
17483 * the other way in pg_depend; which is the right thing for DROP but
17484 * it doesn't produce the dependency ordering we need. So in that one
17485 * case, we reverse the direction of the dependency.
17487 if (deptype == 'i' &&
17488 dobj->objType == DO_TABLE &&
17489 refdobj->objType == DO_TYPE)
17490 addObjectDependency(refdobj, dobj->dumpId);
17493 addObjectDependency(dobj, refdobj->dumpId);
17498 destroyPQExpBuffer(query);
17503 * createBoundaryObjects - create dummy DumpableObjects to represent
17504 * dump section boundaries.
17506 static DumpableObject *
17507 createBoundaryObjects(void)
17509 DumpableObject *dobjs;
17511 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17513 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17514 dobjs[0].catId = nilCatalogId;
17515 AssignDumpId(dobjs + 0);
17516 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17518 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17519 dobjs[1].catId = nilCatalogId;
17520 AssignDumpId(dobjs + 1);
17521 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17527 * addBoundaryDependencies - add dependencies as needed to enforce the dump
17528 * section boundaries.
17531 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17532 DumpableObject *boundaryObjs)
17534 DumpableObject *preDataBound = boundaryObjs + 0;
17535 DumpableObject *postDataBound = boundaryObjs + 1;
17538 for (i = 0; i < numObjs; i++)
17540 DumpableObject *dobj = dobjs[i];
17543 * The classification of object types here must match the SECTION_xxx
17544 * values assigned during subsequent ArchiveEntry calls!
17546 switch (dobj->objType)
17551 case DO_SHELL_TYPE:
17555 case DO_ACCESS_METHOD:
17559 case DO_CONVERSION:
17564 case DO_DUMMY_TYPE:
17567 case DO_TSTEMPLATE:
17570 case DO_FOREIGN_SERVER:
17573 /* Pre-data objects: must come before the pre-data boundary */
17574 addObjectDependency(preDataBound, dobj->dumpId);
17576 case DO_TABLE_DATA:
17577 case DO_SEQUENCE_SET:
17579 /* Data objects: must come between the boundaries */
17580 addObjectDependency(dobj, preDataBound->dumpId);
17581 addObjectDependency(postDataBound, dobj->dumpId);
17585 case DO_REFRESH_MATVIEW:
17587 case DO_EVENT_TRIGGER:
17588 case DO_DEFAULT_ACL:
17590 case DO_PUBLICATION:
17591 case DO_PUBLICATION_REL:
17592 case DO_SUBSCRIPTION:
17593 /* Post-data objects: must come after the post-data boundary */
17594 addObjectDependency(dobj, postDataBound->dumpId);
17597 /* Rules are post-data, but only if dumped separately */
17598 if (((RuleInfo *) dobj)->separate)
17599 addObjectDependency(dobj, postDataBound->dumpId);
17601 case DO_CONSTRAINT:
17602 case DO_FK_CONSTRAINT:
17603 /* Constraints are post-data, but only if dumped separately */
17604 if (((ConstraintInfo *) dobj)->separate)
17605 addObjectDependency(dobj, postDataBound->dumpId);
17607 case DO_PRE_DATA_BOUNDARY:
17608 /* nothing to do */
17610 case DO_POST_DATA_BOUNDARY:
17611 /* must come after the pre-data boundary */
17612 addObjectDependency(dobj, preDataBound->dumpId);
17620 * BuildArchiveDependencies - create dependency data for archive TOC entries
17622 * The raw dependency data obtained by getDependencies() is not terribly
17623 * useful in an archive dump, because in many cases there are dependency
17624 * chains linking through objects that don't appear explicitly in the dump.
17625 * For example, a view will depend on its _RETURN rule while the _RETURN rule
17626 * will depend on other objects --- but the rule will not appear as a separate
17627 * object in the dump. We need to adjust the view's dependencies to include
17628 * whatever the rule depends on that is included in the dump.
17630 * Just to make things more complicated, there are also "special" dependencies
17631 * such as the dependency of a TABLE DATA item on its TABLE, which we must
17632 * not rearrange because pg_restore knows that TABLE DATA only depends on
17633 * its table. In these cases we must leave the dependencies strictly as-is
17634 * even if they refer to not-to-be-dumped objects.
17636 * To handle this, the convention is that "special" dependencies are created
17637 * during ArchiveEntry calls, and an archive TOC item that has any such
17638 * entries will not be touched here. Otherwise, we recursively search the
17639 * DumpableObject data structures to build the correct dependencies for each
17640 * archive TOC item.
17643 BuildArchiveDependencies(Archive *fout)
17645 ArchiveHandle *AH = (ArchiveHandle *) fout;
17648 /* Scan all TOC entries in the archive */
17649 for (te = AH->toc->next; te != AH->toc; te = te->next)
17651 DumpableObject *dobj;
17652 DumpId *dependencies;
17656 /* No need to process entries that will not be dumped */
17659 /* Ignore entries that already have "special" dependencies */
17662 /* Otherwise, look up the item's original DumpableObject, if any */
17663 dobj = findObjectByDumpId(te->dumpId);
17666 /* No work if it has no dependencies */
17667 if (dobj->nDeps <= 0)
17669 /* Set up work array */
17671 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
17673 /* Recursively find all dumpable dependencies */
17674 findDumpableDependencies(AH, dobj,
17675 &dependencies, &nDeps, &allocDeps);
17676 /* And save 'em ... */
17679 dependencies = (DumpId *) pg_realloc(dependencies,
17680 nDeps * sizeof(DumpId));
17681 te->dependencies = dependencies;
17685 free(dependencies);
17689 /* Recursive search subroutine for BuildArchiveDependencies */
17691 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
17692 DumpId **dependencies, int *nDeps, int *allocDeps)
17697 * Ignore section boundary objects: if we search through them, we'll
17698 * report lots of bogus dependencies.
17700 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
17701 dobj->objType == DO_POST_DATA_BOUNDARY)
17704 for (i = 0; i < dobj->nDeps; i++)
17706 DumpId depid = dobj->dependencies[i];
17708 if (TocIDRequired(AH, depid) != 0)
17710 /* Object will be dumped, so just reference it as a dependency */
17711 if (*nDeps >= *allocDeps)
17714 *dependencies = (DumpId *) pg_realloc(*dependencies,
17715 *allocDeps * sizeof(DumpId));
17717 (*dependencies)[*nDeps] = depid;
17723 * Object will not be dumped, so recursively consider its deps. We
17724 * rely on the assumption that sortDumpableObjects already broke
17725 * any dependency loops, else we might recurse infinitely.
17727 DumpableObject *otherdobj = findObjectByDumpId(depid);
17730 findDumpableDependencies(AH, otherdobj,
17731 dependencies, nDeps, allocDeps);
17738 * selectSourceSchema - make the specified schema the active search path
17739 * in the source database.
17741 * NB: pg_catalog is explicitly searched after the specified schema;
17742 * so user names are only qualified if they are cross-schema references,
17743 * and system names are only qualified if they conflict with a user name
17744 * in the current schema.
17746 * Whenever the selected schema is not pg_catalog, be careful to qualify
17747 * references to system catalogs and types in our emitted commands!
17749 * This function is called only from selectSourceSchemaOnAH and
17750 * selectSourceSchema.
17753 selectSourceSchema(Archive *fout, const char *schemaName)
17757 /* This is checked by the callers already */
17758 Assert(schemaName != NULL && *schemaName != '\0');
17760 query = createPQExpBuffer();
17761 appendPQExpBuffer(query, "SET search_path = %s",
17762 fmtId(schemaName));
17763 if (strcmp(schemaName, "pg_catalog") != 0)
17764 appendPQExpBufferStr(query, ", pg_catalog");
17766 ExecuteSqlStatement(fout, query->data);
17768 destroyPQExpBuffer(query);
17772 * getFormattedTypeName - retrieve a nicely-formatted type name for the
17775 * NB: the result may depend on the currently-selected search_path; this is
17776 * why we don't try to cache the names.
17779 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
17787 if ((opts & zeroAsOpaque) != 0)
17788 return pg_strdup(g_opaque_type);
17789 else if ((opts & zeroAsAny) != 0)
17790 return pg_strdup("'any'");
17791 else if ((opts & zeroAsStar) != 0)
17792 return pg_strdup("*");
17793 else if ((opts & zeroAsNone) != 0)
17794 return pg_strdup("NONE");
17797 query = createPQExpBuffer();
17798 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
17801 res = ExecuteSqlQueryForSingleRow(fout, query->data);
17803 /* result of format_type is already quoted */
17804 result = pg_strdup(PQgetvalue(res, 0, 0));
17807 destroyPQExpBuffer(query);
17813 * Return a column list clause for the given relation.
17815 * Special case: if there are no undropped columns in the relation, return
17816 * "", not an invalid "()" column list.
17818 static const char *
17819 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
17821 int numatts = ti->numatts;
17822 char **attnames = ti->attnames;
17823 bool *attisdropped = ti->attisdropped;
17827 appendPQExpBufferChar(buffer, '(');
17829 for (i = 0; i < numatts; i++)
17831 if (attisdropped[i])
17834 appendPQExpBufferStr(buffer, ", ");
17835 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
17840 return ""; /* no undropped columns */
17842 appendPQExpBufferChar(buffer, ')');
17843 return buffer->data;
17847 * Check if a reloptions array is nonempty.
17850 nonemptyReloptions(const char *reloptions)
17852 /* Don't want to print it if it's just "{}" */
17853 return (reloptions != NULL && strlen(reloptions) > 2);
17857 * Format a reloptions array and append it to the given buffer.
17859 * "prefix" is prepended to the option names; typically it's "" or "toast.".
17862 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
17863 const char *prefix, Archive *fout)
17867 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
17868 fout->std_strings);
17870 write_msg(NULL, "WARNING: could not parse reloptions array\n");