1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2018, 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_aggregate_d.h"
46 #include "catalog/pg_am_d.h"
47 #include "catalog/pg_attribute_d.h"
48 #include "catalog/pg_cast_d.h"
49 #include "catalog/pg_class_d.h"
50 #include "catalog/pg_default_acl_d.h"
51 #include "catalog/pg_largeobject_d.h"
52 #include "catalog/pg_largeobject_metadata_d.h"
53 #include "catalog/pg_proc_d.h"
54 #include "catalog/pg_trigger_d.h"
55 #include "catalog/pg_type_d.h"
56 #include "libpq/libpq-fs.h"
58 #include "dumputils.h"
60 #include "pg_backup_db.h"
61 #include "pg_backup_utils.h"
63 #include "fe_utils/connect.h"
64 #include "fe_utils/string_utils.h"
69 const char *descr; /* comment for an object */
70 Oid classoid; /* object class (catalog OID) */
71 Oid objoid; /* object OID */
72 int objsubid; /* subobject (table column #) */
77 const char *provider; /* label provider of this security label */
78 const char *label; /* security label for an object */
79 Oid classoid; /* object class (catalog OID) */
80 Oid objoid; /* object OID */
81 int objsubid; /* subobject (table column #) */
84 typedef enum OidOptions
93 bool g_verbose; /* User wants verbose narration of our
95 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
101 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102 * FirstNormalObjectId - 1.
104 static Oid g_last_builtin_oid; /* value of the last builtin oid */
106 /* The specified names/patterns should to match at least one entity */
107 static int strict_names = 0;
110 * Object inclusion/exclusion lists
112 * The string lists record the patterns given by command-line switches,
113 * which we then convert to lists of OIDs of matching objects.
115 static SimpleStringList schema_include_patterns = {NULL, NULL};
116 static SimpleOidList schema_include_oids = {NULL, NULL};
117 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
118 static SimpleOidList schema_exclude_oids = {NULL, NULL};
120 static SimpleStringList table_include_patterns = {NULL, NULL};
121 static SimpleOidList table_include_oids = {NULL, NULL};
122 static SimpleStringList table_exclude_patterns = {NULL, NULL};
123 static SimpleOidList table_exclude_oids = {NULL, NULL};
124 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
125 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
128 char g_opaque_type[10]; /* name for the opaque type */
130 /* placeholders for the delimiters for comments */
131 char g_comment_start[10];
132 char g_comment_end[10];
134 static const CatalogId nilCatalogId = {0, 0};
137 * Macro for producing quoted, schema-qualified name of a dumpable object.
139 #define fmtQualifiedDumpable(obj) \
140 fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
143 static void help(const char *progname);
144 static void setup_connection(Archive *AH,
145 const char *dumpencoding, const char *dumpsnapshot,
147 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
148 static void expand_schema_name_patterns(Archive *fout,
149 SimpleStringList *patterns,
152 static void expand_table_name_patterns(Archive *fout,
153 SimpleStringList *patterns,
156 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
157 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
158 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *type, const char *name,
161 const char *namespace, const char *owner,
162 CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164 CommentItem **items);
165 static int collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
167 const char *namespace, const char *owner,
168 CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170 SecLabelItem **items);
171 static int collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
182 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
183 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
184 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
185 static void dumpFunc(Archive *fout, FuncInfo *finfo);
186 static void dumpCast(Archive *fout, CastInfo *cast);
187 static void dumpTransform(Archive *fout, TransformInfo *transform);
188 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
189 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
190 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
191 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
192 static void dumpCollation(Archive *fout, CollInfo *collinfo);
193 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
194 static void dumpRule(Archive *fout, RuleInfo *rinfo);
195 static void dumpAgg(Archive *fout, AggInfo *agginfo);
196 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
197 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
198 static void dumpTable(Archive *fout, TableInfo *tbinfo);
199 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
200 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
201 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
202 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
203 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
204 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
205 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
206 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
207 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
208 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
209 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
210 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
211 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
212 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
213 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
214 static void dumpUserMappings(Archive *fout,
215 const char *servername, const char *namespace,
216 const char *owner, CatalogId catalogId, DumpId dumpId);
217 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
219 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
220 const char *type, const char *name, const char *subname,
221 const char *nspname, const char *owner,
222 const char *acls, const char *racls,
223 const char *initacls, const char *initracls);
225 static void getDependencies(Archive *fout);
226 static void BuildArchiveDependencies(Archive *fout);
227 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
228 DumpId **dependencies, int *nDeps, int *allocDeps);
230 static DumpableObject *createBoundaryObjects(void);
231 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
232 DumpableObject *boundaryObjs);
234 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
235 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
236 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
237 static void buildMatViewRefreshDependencies(Archive *fout);
238 static void getTableDataFKConstraints(void);
239 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
241 static char *format_function_arguments_old(Archive *fout,
242 FuncInfo *finfo, int nallargs,
246 static char *format_function_signature(Archive *fout,
247 FuncInfo *finfo, bool honor_quotes);
248 static char *convertRegProcReference(Archive *fout,
250 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
251 static char *convertTSFunction(Archive *fout, Oid funcOid);
252 static Oid findLastBuiltinOid_V71(Archive *fout);
253 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
254 static void getBlobs(Archive *fout);
255 static void dumpBlob(Archive *fout, BlobInfo *binfo);
256 static int dumpBlobs(Archive *fout, void *arg);
257 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
258 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
259 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
260 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
261 static void dumpDatabase(Archive *AH);
262 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
263 const char *dbname, Oid dboid);
264 static void dumpEncoding(Archive *AH);
265 static void dumpStdStrings(Archive *AH);
266 static void dumpSearchPath(Archive *AH);
267 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
268 PQExpBuffer upgrade_buffer,
270 bool force_array_type);
271 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
272 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
273 static void binary_upgrade_set_pg_class_oids(Archive *fout,
274 PQExpBuffer upgrade_buffer,
275 Oid pg_class_oid, bool is_index);
276 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
277 DumpableObject *dobj,
280 const char *objnamespace);
281 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
282 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
283 static bool nonemptyReloptions(const char *reloptions);
284 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
285 const char *prefix, Archive *fout);
286 static char *get_synchronized_snapshot(Archive *fout);
287 static void setupDumpWorker(Archive *AHX);
288 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
292 main(int argc, char **argv)
295 const char *filename = NULL;
296 const char *format = "p";
299 DumpableObject **dobjs;
301 DumpableObject *boundaryObjs;
304 RestoreOptions *ropt;
305 Archive *fout; /* the script file */
306 const char *dumpencoding = NULL;
307 const char *dumpsnapshot = NULL;
308 char *use_role = NULL;
310 trivalue prompt_password = TRI_DEFAULT;
311 int compressLevel = -1;
313 ArchiveFormat archiveFormat = archUnknown;
314 ArchiveMode archiveMode;
316 static DumpOptions dopt;
318 static struct option long_options[] = {
319 {"data-only", no_argument, NULL, 'a'},
320 {"blobs", no_argument, NULL, 'b'},
321 {"no-blobs", no_argument, NULL, 'B'},
322 {"clean", no_argument, NULL, 'c'},
323 {"create", no_argument, NULL, 'C'},
324 {"dbname", required_argument, NULL, 'd'},
325 {"file", required_argument, NULL, 'f'},
326 {"format", required_argument, NULL, 'F'},
327 {"host", required_argument, NULL, 'h'},
328 {"jobs", 1, NULL, 'j'},
329 {"no-reconnect", no_argument, NULL, 'R'},
330 {"oids", no_argument, NULL, 'o'},
331 {"no-owner", no_argument, NULL, 'O'},
332 {"port", required_argument, NULL, 'p'},
333 {"schema", required_argument, NULL, 'n'},
334 {"exclude-schema", required_argument, NULL, 'N'},
335 {"schema-only", no_argument, NULL, 's'},
336 {"superuser", required_argument, NULL, 'S'},
337 {"table", required_argument, NULL, 't'},
338 {"exclude-table", required_argument, NULL, 'T'},
339 {"no-password", no_argument, NULL, 'w'},
340 {"password", no_argument, NULL, 'W'},
341 {"username", required_argument, NULL, 'U'},
342 {"verbose", no_argument, NULL, 'v'},
343 {"no-privileges", no_argument, NULL, 'x'},
344 {"no-acl", no_argument, NULL, 'x'},
345 {"compress", required_argument, NULL, 'Z'},
346 {"encoding", required_argument, NULL, 'E'},
347 {"help", no_argument, NULL, '?'},
348 {"version", no_argument, NULL, 'V'},
351 * the following options don't have an equivalent short option letter
353 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
354 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
355 {"column-inserts", no_argument, &dopt.column_inserts, 1},
356 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
357 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
358 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
359 {"exclude-table-data", required_argument, NULL, 4},
360 {"if-exists", no_argument, &dopt.if_exists, 1},
361 {"inserts", no_argument, &dopt.dump_inserts, 1},
362 {"lock-wait-timeout", required_argument, NULL, 2},
363 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
364 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
365 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
366 {"role", required_argument, NULL, 3},
367 {"section", required_argument, NULL, 5},
368 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
369 {"snapshot", required_argument, NULL, 6},
370 {"strict-names", no_argument, &strict_names, 1},
371 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
372 {"no-comments", no_argument, &dopt.no_comments, 1},
373 {"no-publications", no_argument, &dopt.no_publications, 1},
374 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
375 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
376 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
377 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
378 {"no-sync", no_argument, NULL, 7},
379 {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
384 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
387 * Initialize what we need for parallel execution, especially for thread
388 * support on Windows.
390 init_parallel_dump_utils();
394 strcpy(g_comment_start, "-- ");
395 g_comment_end[0] = '\0';
396 strcpy(g_opaque_type, "opaque");
398 progname = get_progname(argv[0]);
402 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
407 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
409 puts("pg_dump (PostgreSQL) " PG_VERSION);
414 InitDumpOptions(&dopt);
416 while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
417 long_options, &optindex)) != -1)
421 case 'a': /* Dump data only */
422 dopt.dataOnly = true;
425 case 'b': /* Dump blobs */
426 dopt.outputBlobs = true;
429 case 'B': /* Don't dump blobs */
430 dopt.dontOutputBlobs = true;
433 case 'c': /* clean (i.e., drop) schema prior to create */
434 dopt.outputClean = 1;
437 case 'C': /* Create DB */
438 dopt.outputCreateDB = 1;
441 case 'd': /* database name */
442 dopt.dbname = pg_strdup(optarg);
445 case 'E': /* Dump encoding */
446 dumpencoding = pg_strdup(optarg);
450 filename = pg_strdup(optarg);
454 format = pg_strdup(optarg);
457 case 'h': /* server host */
458 dopt.pghost = pg_strdup(optarg);
461 case 'j': /* number of dump jobs */
462 numWorkers = atoi(optarg);
465 case 'n': /* include schema(s) */
466 simple_string_list_append(&schema_include_patterns, optarg);
467 dopt.include_everything = false;
470 case 'N': /* exclude schema(s) */
471 simple_string_list_append(&schema_exclude_patterns, optarg);
474 case 'o': /* Dump oids */
478 case 'O': /* Don't reconnect to match owner */
479 dopt.outputNoOwner = 1;
482 case 'p': /* server port */
483 dopt.pgport = pg_strdup(optarg);
487 /* no-op, still accepted for backwards compatibility */
490 case 's': /* dump schema only */
491 dopt.schemaOnly = true;
494 case 'S': /* Username for superuser in plain text output */
495 dopt.outputSuperuser = pg_strdup(optarg);
498 case 't': /* include table(s) */
499 simple_string_list_append(&table_include_patterns, optarg);
500 dopt.include_everything = false;
503 case 'T': /* exclude table(s) */
504 simple_string_list_append(&table_exclude_patterns, optarg);
508 dopt.username = pg_strdup(optarg);
511 case 'v': /* verbose */
516 prompt_password = TRI_NO;
520 prompt_password = TRI_YES;
523 case 'x': /* skip ACL dump */
524 dopt.aclsSkip = true;
527 case 'Z': /* Compression Level */
528 compressLevel = atoi(optarg);
529 if (compressLevel < 0 || compressLevel > 9)
531 write_msg(NULL, "compression level must be in range 0..9\n");
537 /* This covers the long options. */
540 case 2: /* lock-wait-timeout */
541 dopt.lockWaitTimeout = pg_strdup(optarg);
544 case 3: /* SET ROLE */
545 use_role = pg_strdup(optarg);
548 case 4: /* exclude table(s) data */
549 simple_string_list_append(&tabledata_exclude_patterns, optarg);
552 case 5: /* section */
553 set_dump_section(optarg, &dopt.dumpSections);
556 case 6: /* snapshot */
557 dumpsnapshot = pg_strdup(optarg);
560 case 7: /* no-sync */
565 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
571 * Non-option argument specifies database name as long as it wasn't
572 * already specified with -d / --dbname
574 if (optind < argc && dopt.dbname == NULL)
575 dopt.dbname = argv[optind++];
577 /* Complain if any arguments remain */
580 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
581 progname, argv[optind]);
582 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
587 /* --column-inserts implies --inserts */
588 if (dopt.column_inserts)
589 dopt.dump_inserts = 1;
592 * Binary upgrade mode implies dumping sequence data even in schema-only
593 * mode. This is not exposed as a separate option, but kept separate
594 * internally for clarity.
596 if (dopt.binary_upgrade)
597 dopt.sequence_data = 1;
599 if (dopt.dataOnly && dopt.schemaOnly)
601 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
605 if (dopt.dataOnly && dopt.outputClean)
607 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
611 if (dopt.dump_inserts && dopt.oids)
613 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
614 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
618 if (dopt.if_exists && !dopt.outputClean)
619 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
621 if (dopt.do_nothing && !(dopt.dump_inserts || dopt.column_inserts))
622 exit_horribly(NULL, "option --on-conflict-do-nothing requires option --inserts or --column-inserts\n");
624 /* Identify archive format to emit */
625 archiveFormat = parseArchiveFormat(format, &archiveMode);
627 /* archiveFormat specific setup */
628 if (archiveFormat == archNull)
631 /* Custom and directory formats are compressed by default, others not */
632 if (compressLevel == -1)
635 if (archiveFormat == archCustom || archiveFormat == archDirectory)
636 compressLevel = Z_DEFAULT_COMPRESSION;
643 if (compressLevel != 0)
644 write_msg(NULL, "WARNING: requested compression not available in this "
645 "installation -- archive will be uncompressed\n");
650 * If emitting an archive format, we always want to emit a DATABASE item,
651 * in case --create is specified at pg_restore time.
654 dopt.outputCreateDB = 1;
657 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
658 * parallel jobs because that's the maximum limit for the
659 * WaitForMultipleObjects() call.
663 || numWorkers > MAXIMUM_WAIT_OBJECTS
666 exit_horribly(NULL, "invalid number of parallel jobs\n");
668 /* Parallel backup only in the directory archive format so far */
669 if (archiveFormat != archDirectory && numWorkers > 1)
670 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
672 /* Open the output file */
673 fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
674 archiveMode, setupDumpWorker);
676 /* Make dump options accessible right away */
677 SetArchiveOptions(fout, &dopt, NULL);
679 /* Register the cleanup hook */
680 on_exit_close_archive(fout);
682 /* Let the archiver know how noisy to be */
683 fout->verbose = g_verbose;
686 * We allow the server to be back to 8.0, and up to any minor release of
687 * our own major version. (See also version check in pg_dumpall.c.)
689 fout->minRemoteVersion = 80000;
690 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
692 fout->numWorkers = numWorkers;
695 * Open the database using the Archiver, so it knows about it. Errors mean
698 ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
699 setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
702 * Disable security label support if server version < v9.1.x (prevents
703 * access to nonexistent pg_seclabel catalog)
705 if (fout->remoteVersion < 90100)
706 dopt.no_security_labels = 1;
709 * On hot standbys, never try to dump unlogged table data, since it will
710 * just throw an error.
713 dopt.no_unlogged_table_data = true;
715 /* Select the appropriate subquery to convert user IDs to names */
716 if (fout->remoteVersion >= 80100)
717 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
719 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
721 /* check the version for the synchronized snapshots feature */
722 if (numWorkers > 1 && fout->remoteVersion < 90200
723 && !dopt.no_synchronized_snapshots)
725 "Synchronized snapshots are not supported by this server version.\n"
726 "Run with --no-synchronized-snapshots instead if you do not need\n"
727 "synchronized snapshots.\n");
729 /* check the version when a snapshot is explicitly specified by user */
730 if (dumpsnapshot && fout->remoteVersion < 90200)
732 "Exported snapshots are not supported by this server version.\n");
735 * Find the last built-in OID, if needed (prior to 8.1)
737 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
739 if (fout->remoteVersion < 80100)
740 g_last_builtin_oid = findLastBuiltinOid_V71(fout);
742 g_last_builtin_oid = FirstNormalObjectId - 1;
745 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
747 /* Expand schema selection patterns into OID lists */
748 if (schema_include_patterns.head != NULL)
750 expand_schema_name_patterns(fout, &schema_include_patterns,
751 &schema_include_oids,
753 if (schema_include_oids.head == NULL)
754 exit_horribly(NULL, "no matching schemas were found\n");
756 expand_schema_name_patterns(fout, &schema_exclude_patterns,
757 &schema_exclude_oids,
759 /* non-matching exclusion patterns aren't an error */
761 /* Expand table selection patterns into OID lists */
762 if (table_include_patterns.head != NULL)
764 expand_table_name_patterns(fout, &table_include_patterns,
767 if (table_include_oids.head == NULL)
768 exit_horribly(NULL, "no matching tables were found\n");
770 expand_table_name_patterns(fout, &table_exclude_patterns,
774 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
775 &tabledata_exclude_oids,
778 /* non-matching exclusion patterns aren't an error */
781 * Dumping blobs is the default for dumps where an inclusion switch is not
782 * used (an "include everything" dump). -B can be used to exclude blobs
783 * from those dumps. -b can be used to include blobs even when an
784 * inclusion switch is used.
786 * -s means "schema only" and blobs are data, not schema, so we never
787 * include blobs when -s is used.
789 if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
790 dopt.outputBlobs = true;
793 * Now scan the database and create DumpableObject structs for all the
794 * objects we intend to dump.
796 tblinfo = getSchemaData(fout, &numTables);
798 if (fout->remoteVersion < 80400)
799 guessConstraintInheritance(tblinfo, numTables);
801 if (!dopt.schemaOnly)
803 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
804 buildMatViewRefreshDependencies(fout);
806 getTableDataFKConstraints();
809 if (dopt.schemaOnly && dopt.sequence_data)
810 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
813 * In binary-upgrade mode, we do not have to worry about the actual blob
814 * data or the associated metadata that resides in the pg_largeobject and
815 * pg_largeobject_metadata tables, respectively.
817 * However, we do need to collect blob information as there may be
818 * comments or other information on blobs that we do need to dump out.
820 if (dopt.outputBlobs || dopt.binary_upgrade)
824 * Collect dependency data to assist in ordering the objects.
826 getDependencies(fout);
828 /* Lastly, create dummy objects to represent the section boundaries */
829 boundaryObjs = createBoundaryObjects();
831 /* Get pointers to all the known DumpableObjects */
832 getDumpableObjects(&dobjs, &numObjs);
835 * Add dummy dependencies to enforce the dump section ordering.
837 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
840 * Sort the objects into a safe dump order (no forward references).
842 * We rely on dependency information to help us determine a safe order, so
843 * the initial sort is mostly for cosmetic purposes: we sort by name to
844 * ensure that logically identical schemas will dump identically.
846 sortDumpableObjectsByTypeName(dobjs, numObjs);
848 /* If we do a parallel dump, we want the largest tables to go first */
849 if (archiveFormat == archDirectory && numWorkers > 1)
850 sortDataAndIndexObjectsBySize(dobjs, numObjs);
852 sortDumpableObjects(dobjs, numObjs,
853 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
856 * Create archive TOC entries for all the objects to be dumped, in a safe
860 /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
862 dumpStdStrings(fout);
863 dumpSearchPath(fout);
865 /* The database items are always next, unless we don't want them at all */
866 if (dopt.outputCreateDB)
869 /* Now the rearrangeable objects. */
870 for (i = 0; i < numObjs; i++)
871 dumpDumpableObject(fout, dobjs[i]);
874 * Set up options info to ensure we dump what we want.
876 ropt = NewRestoreOptions();
877 ropt->filename = filename;
879 /* if you change this list, see dumpOptionsFromRestoreOptions */
880 ropt->dropSchema = dopt.outputClean;
881 ropt->dataOnly = dopt.dataOnly;
882 ropt->schemaOnly = dopt.schemaOnly;
883 ropt->if_exists = dopt.if_exists;
884 ropt->column_inserts = dopt.column_inserts;
885 ropt->dumpSections = dopt.dumpSections;
886 ropt->aclsSkip = dopt.aclsSkip;
887 ropt->superuser = dopt.outputSuperuser;
888 ropt->createDB = dopt.outputCreateDB;
889 ropt->noOwner = dopt.outputNoOwner;
890 ropt->noTablespace = dopt.outputNoTablespaces;
891 ropt->disable_triggers = dopt.disable_triggers;
892 ropt->use_setsessauth = dopt.use_setsessauth;
893 ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
894 ropt->dump_inserts = dopt.dump_inserts;
895 ropt->no_comments = dopt.no_comments;
896 ropt->no_publications = dopt.no_publications;
897 ropt->no_security_labels = dopt.no_security_labels;
898 ropt->no_subscriptions = dopt.no_subscriptions;
899 ropt->lockWaitTimeout = dopt.lockWaitTimeout;
900 ropt->include_everything = dopt.include_everything;
901 ropt->enable_row_security = dopt.enable_row_security;
902 ropt->sequence_data = dopt.sequence_data;
903 ropt->binary_upgrade = dopt.binary_upgrade;
905 if (compressLevel == -1)
906 ropt->compression = 0;
908 ropt->compression = compressLevel;
910 ropt->suppressDumpWarnings = true; /* We've already shown them */
912 SetArchiveOptions(fout, &dopt, ropt);
914 /* Mark which entries should be output */
915 ProcessArchiveRestoreOptions(fout);
918 * The archive's TOC entries are now marked as to which ones will actually
919 * be output, so we can set up their dependency lists properly. This isn't
920 * necessary for plain-text output, though.
923 BuildArchiveDependencies(fout);
926 * And finally we can do the actual output.
928 * Note: for non-plain-text output formats, the output file is written
929 * inside CloseArchive(). This is, um, bizarre; but not worth changing
933 RestoreArchive(fout);
942 help(const char *progname)
944 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
945 printf(_("Usage:\n"));
946 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
948 printf(_("\nGeneral options:\n"));
949 printf(_(" -f, --file=FILENAME output file or directory name\n"));
950 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
951 " plain text (default))\n"));
952 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
953 printf(_(" -v, --verbose verbose mode\n"));
954 printf(_(" -V, --version output version information, then exit\n"));
955 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
956 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
957 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
958 printf(_(" -?, --help show this help, then exit\n"));
960 printf(_("\nOptions controlling the output content:\n"));
961 printf(_(" -a, --data-only dump only the data, not the schema\n"));
962 printf(_(" -b, --blobs include large objects in dump\n"));
963 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
964 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
965 printf(_(" -C, --create include commands to create database in dump\n"));
966 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
967 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
968 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
969 printf(_(" -o, --oids include OIDs in dump\n"));
970 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
971 " plain-text format\n"));
972 printf(_(" -s, --schema-only dump only the schema, no data\n"));
973 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
974 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
975 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
976 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
977 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
978 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
979 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
980 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
981 printf(_(" --enable-row-security enable row security (dump only content user has\n"
983 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
984 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
985 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
986 printf(_(" --load-via-partition-root load partitions via the root table\n"));
987 printf(_(" --no-comments do not dump comments\n"));
988 printf(_(" --no-publications do not dump publications\n"));
989 printf(_(" --no-security-labels do not dump security label assignments\n"));
990 printf(_(" --no-subscriptions do not dump subscriptions\n"));
991 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
992 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
993 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
994 printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
995 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
996 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
997 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
998 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
999 printf(_(" --strict-names require table and/or schema include patterns to\n"
1000 " match at least one entity each\n"));
1001 printf(_(" --use-set-session-authorization\n"
1002 " use SET SESSION AUTHORIZATION commands instead of\n"
1003 " ALTER OWNER commands to set ownership\n"));
1005 printf(_("\nConnection options:\n"));
1006 printf(_(" -d, --dbname=DBNAME database to dump\n"));
1007 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1008 printf(_(" -p, --port=PORT database server port number\n"));
1009 printf(_(" -U, --username=NAME connect as specified database user\n"));
1010 printf(_(" -w, --no-password never prompt for password\n"));
1011 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1012 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1014 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1015 "variable value is used.\n\n"));
1016 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1020 setup_connection(Archive *AH, const char *dumpencoding,
1021 const char *dumpsnapshot, char *use_role)
1023 DumpOptions *dopt = AH->dopt;
1024 PGconn *conn = GetConnection(AH);
1025 const char *std_strings;
1027 PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1030 * Set the client encoding if requested.
1034 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1035 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1040 * Get the active encoding and the standard_conforming_strings setting, so
1041 * we know how to escape strings.
1043 AH->encoding = PQclientEncoding(conn);
1045 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1046 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1049 * Set the role if requested. In a parallel dump worker, we'll be passed
1050 * use_role == NULL, but AH->use_role is already set (if user specified it
1051 * originally) and we should use that.
1053 if (!use_role && AH->use_role)
1054 use_role = AH->use_role;
1056 /* Set the role if requested */
1057 if (use_role && AH->remoteVersion >= 80100)
1059 PQExpBuffer query = createPQExpBuffer();
1061 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1062 ExecuteSqlStatement(AH, query->data);
1063 destroyPQExpBuffer(query);
1065 /* save it for possible later use by parallel workers */
1067 AH->use_role = pg_strdup(use_role);
1070 /* Set the datestyle to ISO to ensure the dump's portability */
1071 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1073 /* Likewise, avoid using sql_standard intervalstyle */
1074 if (AH->remoteVersion >= 80400)
1075 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1078 * Set extra_float_digits so that we can dump float data exactly (given
1079 * correctly implemented float I/O code, anyway)
1081 if (AH->remoteVersion >= 90000)
1082 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1084 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1087 * If synchronized scanning is supported, disable it, to prevent
1088 * unpredictable changes in row ordering across a dump and reload.
1090 if (AH->remoteVersion >= 80300)
1091 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1094 * Disable timeouts if supported.
1096 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1097 if (AH->remoteVersion >= 90300)
1098 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1099 if (AH->remoteVersion >= 90600)
1100 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1103 * Quote all identifiers, if requested.
1105 if (quote_all_identifiers && AH->remoteVersion >= 90100)
1106 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1109 * Adjust row-security mode, if supported.
1111 if (AH->remoteVersion >= 90500)
1113 if (dopt->enable_row_security)
1114 ExecuteSqlStatement(AH, "SET row_security = on");
1116 ExecuteSqlStatement(AH, "SET row_security = off");
1120 * Start transaction-snapshot mode transaction to dump consistent data.
1122 ExecuteSqlStatement(AH, "BEGIN");
1123 if (AH->remoteVersion >= 90100)
1126 * To support the combination of serializable_deferrable with the jobs
1127 * option we use REPEATABLE READ for the worker connections that are
1128 * passed a snapshot. As long as the snapshot is acquired in a
1129 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1130 * REPEATABLE READ transaction provides the appropriate integrity
1131 * guarantees. This is a kluge, but safe for back-patching.
1133 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1134 ExecuteSqlStatement(AH,
1135 "SET TRANSACTION ISOLATION LEVEL "
1136 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1138 ExecuteSqlStatement(AH,
1139 "SET TRANSACTION ISOLATION LEVEL "
1140 "REPEATABLE READ, READ ONLY");
1144 ExecuteSqlStatement(AH,
1145 "SET TRANSACTION ISOLATION LEVEL "
1146 "SERIALIZABLE, READ ONLY");
1150 * If user specified a snapshot to use, select that. In a parallel dump
1151 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1152 * is already set (if the server can handle it) and we should use that.
1155 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1157 if (AH->sync_snapshot_id)
1159 PQExpBuffer query = createPQExpBuffer();
1161 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1162 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1163 ExecuteSqlStatement(AH, query->data);
1164 destroyPQExpBuffer(query);
1166 else if (AH->numWorkers > 1 &&
1167 AH->remoteVersion >= 90200 &&
1168 !dopt->no_synchronized_snapshots)
1170 if (AH->isStandby && AH->remoteVersion < 100000)
1172 "Synchronized snapshots on standby servers are not supported by this server version.\n"
1173 "Run with --no-synchronized-snapshots instead if you do not need\n"
1174 "synchronized snapshots.\n");
1177 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1181 /* Set up connection for a parallel worker process */
1183 setupDumpWorker(Archive *AH)
1186 * We want to re-select all the same values the master connection is
1187 * using. We'll have inherited directly-usable values in
1188 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1189 * inherited encoding value back to a string to pass to setup_connection.
1191 setup_connection(AH,
1192 pg_encoding_to_char(AH->encoding),
1198 get_synchronized_snapshot(Archive *fout)
1200 char *query = "SELECT pg_catalog.pg_export_snapshot()";
1204 res = ExecuteSqlQueryForSingleRow(fout, query);
1205 result = pg_strdup(PQgetvalue(res, 0, 0));
1211 static ArchiveFormat
1212 parseArchiveFormat(const char *format, ArchiveMode *mode)
1214 ArchiveFormat archiveFormat;
1216 *mode = archModeWrite;
1218 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1220 /* This is used by pg_dumpall, and is not documented */
1221 archiveFormat = archNull;
1222 *mode = archModeAppend;
1224 else if (pg_strcasecmp(format, "c") == 0)
1225 archiveFormat = archCustom;
1226 else if (pg_strcasecmp(format, "custom") == 0)
1227 archiveFormat = archCustom;
1228 else if (pg_strcasecmp(format, "d") == 0)
1229 archiveFormat = archDirectory;
1230 else if (pg_strcasecmp(format, "directory") == 0)
1231 archiveFormat = archDirectory;
1232 else if (pg_strcasecmp(format, "p") == 0)
1233 archiveFormat = archNull;
1234 else if (pg_strcasecmp(format, "plain") == 0)
1235 archiveFormat = archNull;
1236 else if (pg_strcasecmp(format, "t") == 0)
1237 archiveFormat = archTar;
1238 else if (pg_strcasecmp(format, "tar") == 0)
1239 archiveFormat = archTar;
1241 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1242 return archiveFormat;
1246 * Find the OIDs of all schemas matching the given list of patterns,
1247 * and append them to the given OID list.
1250 expand_schema_name_patterns(Archive *fout,
1251 SimpleStringList *patterns,
1252 SimpleOidList *oids,
1257 SimpleStringListCell *cell;
1260 if (patterns->head == NULL)
1261 return; /* nothing to do */
1263 query = createPQExpBuffer();
1266 * The loop below runs multiple SELECTs might sometimes result in
1267 * duplicate entries in the OID list, but we don't care.
1270 for (cell = patterns->head; cell; cell = cell->next)
1272 appendPQExpBuffer(query,
1273 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1274 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1275 false, NULL, "n.nspname", NULL, NULL);
1277 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1278 if (strict_names && PQntuples(res) == 0)
1279 exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1281 for (i = 0; i < PQntuples(res); i++)
1283 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1287 resetPQExpBuffer(query);
1290 destroyPQExpBuffer(query);
1294 * Find the OIDs of all tables matching the given list of patterns,
1295 * and append them to the given OID list.
1298 expand_table_name_patterns(Archive *fout,
1299 SimpleStringList *patterns, SimpleOidList *oids,
1304 SimpleStringListCell *cell;
1307 if (patterns->head == NULL)
1308 return; /* nothing to do */
1310 query = createPQExpBuffer();
1313 * this might sometimes result in duplicate entries in the OID list, but
1317 for (cell = patterns->head; cell; cell = cell->next)
1320 * Query must remain ABSOLUTELY devoid of unqualified names. This
1321 * would be unnecessary given a pg_table_is_visible() variant taking a
1322 * search_path argument.
1324 appendPQExpBuffer(query,
1326 "\nFROM pg_catalog.pg_class c"
1327 "\n LEFT JOIN pg_catalog.pg_namespace n"
1328 "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1329 "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1330 "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1331 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1332 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1333 RELKIND_PARTITIONED_TABLE);
1334 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1335 false, "n.nspname", "c.relname", NULL,
1336 "pg_catalog.pg_table_is_visible(c.oid)");
1338 ExecuteSqlStatement(fout, "RESET search_path");
1339 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1340 PQclear(ExecuteSqlQueryForSingleRow(fout,
1341 ALWAYS_SECURE_SEARCH_PATH_SQL));
1342 if (strict_names && PQntuples(res) == 0)
1343 exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1345 for (i = 0; i < PQntuples(res); i++)
1347 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1351 resetPQExpBuffer(query);
1354 destroyPQExpBuffer(query);
1358 * checkExtensionMembership
1359 * Determine whether object is an extension member, and if so,
1360 * record an appropriate dependency and set the object's dump flag.
1362 * It's important to call this for each object that could be an extension
1363 * member. Generally, we integrate this with determining the object's
1364 * to-be-dumped-ness, since extension membership overrides other rules for that.
1366 * Returns true if object is an extension member, else false.
1369 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1371 ExtensionInfo *ext = findOwningExtension(dobj->catId);
1376 dobj->ext_member = true;
1378 /* Record dependency so that getDependencies needn't deal with that */
1379 addObjectDependency(dobj, ext->dobj.dumpId);
1382 * In 9.6 and above, mark the member object to have any non-initial ACL,
1383 * policies, and security labels dumped.
1385 * Note that any initial ACLs (see pg_init_privs) will be removed when we
1386 * extract the information about the object. We don't provide support for
1387 * initial policies and security labels and it seems unlikely for those to
1388 * ever exist, but we may have to revisit this later.
1390 * Prior to 9.6, we do not include any extension member components.
1392 * In binary upgrades, we still dump all components of the members
1393 * individually, since the idea is to exactly reproduce the database
1394 * contents rather than replace the extension contents with something
1397 if (fout->dopt->binary_upgrade)
1398 dobj->dump = ext->dobj.dump;
1401 if (fout->remoteVersion < 90600)
1402 dobj->dump = DUMP_COMPONENT_NONE;
1404 dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1405 DUMP_COMPONENT_SECLABEL |
1406 DUMP_COMPONENT_POLICY);
1413 * selectDumpableNamespace: policy-setting subroutine
1414 * Mark a namespace as to be dumped or not
1417 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1420 * If specific tables are being dumped, do not dump any complete
1421 * namespaces. If specific namespaces are being dumped, dump just those
1422 * namespaces. Otherwise, dump all non-system namespaces.
1424 if (table_include_oids.head != NULL)
1425 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1426 else if (schema_include_oids.head != NULL)
1427 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1428 simple_oid_list_member(&schema_include_oids,
1429 nsinfo->dobj.catId.oid) ?
1430 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1431 else if (fout->remoteVersion >= 90600 &&
1432 strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1435 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1436 * they are interesting (and not the original ACLs which were set at
1437 * initdb time, see pg_init_privs).
1439 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1441 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1442 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1444 /* Other system schemas don't get dumped */
1445 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1447 else if (strcmp(nsinfo->dobj.name, "public") == 0)
1450 * The public schema is a strange beast that sits in a sort of
1451 * no-mans-land between being a system object and a user object. We
1452 * don't want to dump creation or comment commands for it, because
1453 * that complicates matters for non-superuser use of pg_dump. But we
1454 * should dump any ACL changes that have occurred for it, and of
1455 * course we should dump contained objects.
1457 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1458 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1461 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1464 * In any case, a namespace can be excluded by an exclusion switch
1466 if (nsinfo->dobj.dump_contains &&
1467 simple_oid_list_member(&schema_exclude_oids,
1468 nsinfo->dobj.catId.oid))
1469 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1472 * If the schema belongs to an extension, allow extension membership to
1473 * override the dump decision for the schema itself. However, this does
1474 * not change dump_contains, so this won't change what we do with objects
1475 * within the schema. (If they belong to the extension, they'll get
1476 * suppressed by it, otherwise not.)
1478 (void) checkExtensionMembership(&nsinfo->dobj, fout);
1482 * selectDumpableTable: policy-setting subroutine
1483 * Mark a table as to be dumped or not
1486 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1488 if (checkExtensionMembership(&tbinfo->dobj, fout))
1489 return; /* extension membership overrides all else */
1492 * If specific tables are being dumped, dump just those tables; else, dump
1493 * according to the parent namespace's dump flag.
1495 if (table_include_oids.head != NULL)
1496 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1497 tbinfo->dobj.catId.oid) ?
1498 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1500 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1503 * In any case, a table can be excluded by an exclusion switch
1505 if (tbinfo->dobj.dump &&
1506 simple_oid_list_member(&table_exclude_oids,
1507 tbinfo->dobj.catId.oid))
1508 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1512 * selectDumpableType: policy-setting subroutine
1513 * Mark a type as to be dumped or not
1515 * If it's a table's rowtype or an autogenerated array type, we also apply a
1516 * special type code to facilitate sorting into the desired order. (We don't
1517 * want to consider those to be ordinary types because that would bring tables
1518 * up into the datatype part of the dump order.) We still set the object's
1519 * dump flag; that's not going to cause the dummy type to be dumped, but we
1520 * need it so that casts involving such types will be dumped correctly -- see
1521 * dumpCast. This means the flag should be set the same as for the underlying
1522 * object (the table or base type).
1525 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1527 /* skip complex types, except for standalone composite types */
1528 if (OidIsValid(tyinfo->typrelid) &&
1529 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1531 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1533 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1534 if (tytable != NULL)
1535 tyinfo->dobj.dump = tytable->dobj.dump;
1537 tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1541 /* skip auto-generated array types */
1542 if (tyinfo->isArray)
1544 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1547 * Fall through to set the dump flag; we assume that the subsequent
1548 * rules will do the same thing as they would for the array's base
1549 * type. (We cannot reliably look up the base type here, since
1550 * getTypes may not have processed it yet.)
1554 if (checkExtensionMembership(&tyinfo->dobj, fout))
1555 return; /* extension membership overrides all else */
1557 /* Dump based on if the contents of the namespace are being dumped */
1558 tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1562 * selectDumpableDefaultACL: policy-setting subroutine
1563 * Mark a default ACL as to be dumped or not
1565 * For per-schema default ACLs, dump if the schema is to be dumped.
1566 * Otherwise dump if we are dumping "everything". Note that dataOnly
1567 * and aclsSkip are checked separately.
1570 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1572 /* Default ACLs can't be extension members */
1574 if (dinfo->dobj.namespace)
1575 /* default ACLs are considered part of the namespace */
1576 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1578 dinfo->dobj.dump = dopt->include_everything ?
1579 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1583 * selectDumpableCast: policy-setting subroutine
1584 * Mark a cast as to be dumped or not
1586 * Casts do not belong to any particular namespace (since they haven't got
1587 * names), nor do they have identifiable owners. To distinguish user-defined
1588 * casts from built-in ones, we must resort to checking whether the cast's
1589 * OID is in the range reserved for initdb.
1592 selectDumpableCast(CastInfo *cast, Archive *fout)
1594 if (checkExtensionMembership(&cast->dobj, fout))
1595 return; /* extension membership overrides all else */
1598 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1599 * support ACLs currently.
1601 if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1602 cast->dobj.dump = DUMP_COMPONENT_NONE;
1604 cast->dobj.dump = fout->dopt->include_everything ?
1605 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1609 * selectDumpableProcLang: policy-setting subroutine
1610 * Mark a procedural language as to be dumped or not
1612 * Procedural languages do not belong to any particular namespace. To
1613 * identify built-in languages, we must resort to checking whether the
1614 * language's OID is in the range reserved for initdb.
1617 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1619 if (checkExtensionMembership(&plang->dobj, fout))
1620 return; /* extension membership overrides all else */
1623 * Only include procedural languages when we are dumping everything.
1625 * For from-initdb procedural languages, only include ACLs, as we do for
1626 * the pg_catalog namespace. We need this because procedural languages do
1627 * not live in any namespace.
1629 if (!fout->dopt->include_everything)
1630 plang->dobj.dump = DUMP_COMPONENT_NONE;
1633 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1634 plang->dobj.dump = fout->remoteVersion < 90600 ?
1635 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1637 plang->dobj.dump = DUMP_COMPONENT_ALL;
1642 * selectDumpableAccessMethod: policy-setting subroutine
1643 * Mark an access method as to be dumped or not
1645 * Access methods do not belong to any particular namespace. To identify
1646 * built-in access methods, we must resort to checking whether the
1647 * method's OID is in the range reserved for initdb.
1650 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1652 if (checkExtensionMembership(&method->dobj, fout))
1653 return; /* extension membership overrides all else */
1656 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1657 * they do not support ACLs currently.
1659 if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1660 method->dobj.dump = DUMP_COMPONENT_NONE;
1662 method->dobj.dump = fout->dopt->include_everything ?
1663 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1667 * selectDumpableExtension: policy-setting subroutine
1668 * Mark an extension as to be dumped or not
1670 * Built-in extensions should be skipped except for checking ACLs, since we
1671 * assume those will already be installed in the target database. We identify
1672 * such extensions by their having OIDs in the range reserved for initdb.
1673 * We dump all user-added extensions by default, or none of them if
1674 * include_everything is false (i.e., a --schema or --table switch was given).
1677 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1680 * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1681 * change permissions on their member objects, if they wish to, and have
1682 * those changes preserved.
1684 if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1685 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1687 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1688 dopt->include_everything ? DUMP_COMPONENT_ALL :
1689 DUMP_COMPONENT_NONE;
1693 * selectDumpablePublicationTable: policy-setting subroutine
1694 * Mark a publication table as to be dumped or not
1696 * Publication tables have schemas, but those are ignored in decision making,
1697 * because publications are only dumped when we are dumping everything.
1700 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1702 if (checkExtensionMembership(dobj, fout))
1703 return; /* extension membership overrides all else */
1705 dobj->dump = fout->dopt->include_everything ?
1706 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1710 * selectDumpableObject: policy-setting subroutine
1711 * Mark a generic dumpable object as to be dumped or not
1713 * Use this only for object types without a special-case routine above.
1716 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1718 if (checkExtensionMembership(dobj, fout))
1719 return; /* extension membership overrides all else */
1722 * Default policy is to dump if parent namespace is dumpable, or for
1723 * non-namespace-associated items, dump if we're dumping "everything".
1725 if (dobj->namespace)
1726 dobj->dump = dobj->namespace->dobj.dump_contains;
1728 dobj->dump = fout->dopt->include_everything ?
1729 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1733 * Dump a table's contents for loading using the COPY command
1734 * - this routine is called by the Archiver when it wants the table
1739 dumpTableData_copy(Archive *fout, void *dcontext)
1741 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1742 TableInfo *tbinfo = tdinfo->tdtable;
1743 const char *classname = tbinfo->dobj.name;
1744 const bool hasoids = tbinfo->hasoids;
1745 const bool oids = tdinfo->oids;
1746 PQExpBuffer q = createPQExpBuffer();
1749 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1750 * which uses it already.
1752 PQExpBuffer clistBuf = createPQExpBuffer();
1753 PGconn *conn = GetConnection(fout);
1757 const char *column_list;
1760 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1761 tbinfo->dobj.namespace->dobj.name, classname);
1764 * Specify the column list explicitly so that we have no possibility of
1765 * retrieving data in the wrong column order. (The default column
1766 * ordering of COPY will not be what we want in certain corner cases
1767 * involving ADD COLUMN and inheritance.)
1769 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1771 if (oids && hasoids)
1773 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1774 fmtQualifiedDumpable(tbinfo),
1777 else if (tdinfo->filtercond)
1779 /* Note: this syntax is only supported in 8.2 and up */
1780 appendPQExpBufferStr(q, "COPY (SELECT ");
1781 /* klugery to get rid of parens in column list */
1782 if (strlen(column_list) > 2)
1784 appendPQExpBufferStr(q, column_list + 1);
1785 q->data[q->len - 1] = ' ';
1788 appendPQExpBufferStr(q, "* ");
1789 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1790 fmtQualifiedDumpable(tbinfo),
1791 tdinfo->filtercond);
1795 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1796 fmtQualifiedDumpable(tbinfo),
1799 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1801 destroyPQExpBuffer(clistBuf);
1805 ret = PQgetCopyData(conn, ©buf, 0);
1808 break; /* done or error */
1812 WriteData(fout, copybuf, ret);
1819 * There was considerable discussion in late July, 2000 regarding
1820 * slowing down pg_dump when backing up large tables. Users with both
1821 * slow & fast (multi-processor) machines experienced performance
1822 * degradation when doing a backup.
1824 * Initial attempts based on sleeping for a number of ms for each ms
1825 * of work were deemed too complex, then a simple 'sleep in each loop'
1826 * implementation was suggested. The latter failed because the loop
1827 * was too tight. Finally, the following was implemented:
1829 * If throttle is non-zero, then
1830 * See how long since the last sleep.
1831 * Work out how long to sleep (based on ratio).
1832 * If sleep is more than 100ms, then
1838 * where the throttle value was the number of ms to sleep per ms of
1839 * work. The calculation was done in each loop.
1841 * Most of the hard work is done in the backend, and this solution
1842 * still did not work particularly well: on slow machines, the ratio
1843 * was 50:1, and on medium paced machines, 1:1, and on fast
1844 * multi-processor machines, it had little or no effect, for reasons
1845 * that were unclear.
1847 * Further discussion ensued, and the proposal was dropped.
1849 * For those people who want this feature, it can be implemented using
1850 * gettimeofday in each loop, calculating the time since last sleep,
1851 * multiplying that by the sleep ratio, then if the result is more
1852 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1853 * function to sleep for a subsecond period ie.
1855 * select(0, NULL, NULL, NULL, &tvi);
1857 * This will return after the interval specified in the structure tvi.
1858 * Finally, call gettimeofday again to save the 'last sleep time'.
1862 archprintf(fout, "\\.\n\n\n");
1866 /* copy data transfer failed */
1867 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1868 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1869 write_msg(NULL, "The command was: %s\n", q->data);
1873 /* Check command status and return to normal libpq state */
1874 res = PQgetResult(conn);
1875 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1877 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1878 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1879 write_msg(NULL, "The command was: %s\n", q->data);
1884 /* Do this to ensure we've pumped libpq back to idle state */
1885 if (PQgetResult(conn) != NULL)
1886 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1889 destroyPQExpBuffer(q);
1894 * Dump table data using INSERT commands.
1896 * Caution: when we restore from an archive file direct to database, the
1897 * INSERT commands emitted by this function have to be parsed by
1898 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1899 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1902 dumpTableData_insert(Archive *fout, void *dcontext)
1904 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1905 TableInfo *tbinfo = tdinfo->tdtable;
1906 DumpOptions *dopt = fout->dopt;
1907 PQExpBuffer q = createPQExpBuffer();
1908 PQExpBuffer insertStmt = NULL;
1914 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1915 "SELECT * FROM ONLY %s",
1916 fmtQualifiedDumpable(tbinfo));
1917 if (tdinfo->filtercond)
1918 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1920 ExecuteSqlStatement(fout, q->data);
1924 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1926 nfields = PQnfields(res);
1927 for (tuple = 0; tuple < PQntuples(res); tuple++)
1930 * First time through, we build as much of the INSERT statement as
1931 * possible in "insertStmt", which we can then just print for each
1932 * line. If the table happens to have zero columns then this will
1933 * be a complete statement, otherwise it will end in "VALUES(" and
1934 * be ready to have the row's column values appended.
1936 if (insertStmt == NULL)
1938 TableInfo *targettab;
1940 insertStmt = createPQExpBuffer();
1943 * When load-via-partition-root is set, get the root table
1944 * name for the partition table, so that we can reload data
1945 * through the root table.
1947 if (dopt->load_via_partition_root && tbinfo->ispartition)
1948 targettab = getRootTableInfo(tbinfo);
1952 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1953 fmtQualifiedDumpable(targettab));
1955 /* corner case for zero-column table */
1958 appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1962 /* append the list of column names if required */
1963 if (dopt->column_inserts)
1965 appendPQExpBufferChar(insertStmt, '(');
1966 for (field = 0; field < nfields; field++)
1969 appendPQExpBufferStr(insertStmt, ", ");
1970 appendPQExpBufferStr(insertStmt,
1971 fmtId(PQfname(res, field)));
1973 appendPQExpBufferStr(insertStmt, ") ");
1976 if (tbinfo->needs_override)
1977 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1979 appendPQExpBufferStr(insertStmt, "VALUES (");
1983 archputs(insertStmt->data, fout);
1985 /* if it is zero-column table then we're done */
1989 for (field = 0; field < nfields; field++)
1992 archputs(", ", fout);
1993 if (PQgetisnull(res, tuple, field))
1995 archputs("NULL", fout);
1999 /* XXX This code is partially duplicated in ruleutils.c */
2000 switch (PQftype(res, field))
2011 * These types are printed without quotes unless
2012 * they contain values that aren't accepted by the
2013 * scanner unquoted (e.g., 'NaN'). Note that
2014 * strtod() and friends might accept NaN, so we
2015 * can't use that to test.
2017 * In reality we only need to defend against
2018 * infinity and NaN, so we need not get too crazy
2019 * about pattern matching here.
2021 const char *s = PQgetvalue(res, tuple, field);
2023 if (strspn(s, "0123456789 +-eE.") == strlen(s))
2026 archprintf(fout, "'%s'", s);
2032 archprintf(fout, "B'%s'",
2033 PQgetvalue(res, tuple, field));
2037 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2038 archputs("true", fout);
2040 archputs("false", fout);
2044 /* All other types are printed as string literals. */
2045 resetPQExpBuffer(q);
2046 appendStringLiteralAH(q,
2047 PQgetvalue(res, tuple, field),
2049 archputs(q->data, fout);
2054 if (!dopt->do_nothing)
2055 archputs(");\n", fout);
2057 archputs(") ON CONFLICT DO NOTHING;\n", fout);
2060 if (PQntuples(res) <= 0)
2068 archputs("\n\n", fout);
2070 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2072 destroyPQExpBuffer(q);
2073 if (insertStmt != NULL)
2074 destroyPQExpBuffer(insertStmt);
2081 * get the root TableInfo for the given partition table.
2084 getRootTableInfo(TableInfo *tbinfo)
2086 TableInfo *parentTbinfo;
2088 Assert(tbinfo->ispartition);
2089 Assert(tbinfo->numParents == 1);
2091 parentTbinfo = tbinfo->parents[0];
2092 while (parentTbinfo->ispartition)
2094 Assert(parentTbinfo->numParents == 1);
2095 parentTbinfo = parentTbinfo->parents[0];
2098 return parentTbinfo;
2103 * dump the contents of a single table
2105 * Actually, this just makes an ArchiveEntry for the table contents.
2108 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2110 DumpOptions *dopt = fout->dopt;
2111 TableInfo *tbinfo = tdinfo->tdtable;
2112 PQExpBuffer copyBuf = createPQExpBuffer();
2113 PQExpBuffer clistBuf = createPQExpBuffer();
2114 DataDumperPtr dumpFn;
2116 const char *copyFrom;
2118 if (!dopt->dump_inserts)
2120 /* Dump/restore using COPY */
2121 dumpFn = dumpTableData_copy;
2124 * When load-via-partition-root is set, get the root table name for
2125 * the partition table, so that we can reload data through the root
2128 if (dopt->load_via_partition_root && tbinfo->ispartition)
2130 TableInfo *parentTbinfo;
2132 parentTbinfo = getRootTableInfo(tbinfo);
2133 copyFrom = fmtQualifiedDumpable(parentTbinfo);
2136 copyFrom = fmtQualifiedDumpable(tbinfo);
2138 /* must use 2 steps here 'cause fmtId is nonreentrant */
2139 appendPQExpBuffer(copyBuf, "COPY %s ",
2141 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2142 fmtCopyColumnList(tbinfo, clistBuf),
2143 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2144 copyStmt = copyBuf->data;
2148 /* Restore using INSERT */
2149 dumpFn = dumpTableData_insert;
2154 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2155 * dependency on its table as "special" and pass it to ArchiveEntry now.
2156 * See comments for BuildArchiveDependencies.
2158 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2159 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2160 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2161 NULL, tbinfo->rolname,
2162 false, "TABLE DATA", SECTION_DATA,
2164 &(tbinfo->dobj.dumpId), 1,
2167 destroyPQExpBuffer(copyBuf);
2168 destroyPQExpBuffer(clistBuf);
2172 * refreshMatViewData -
2173 * load or refresh the contents of a single materialized view
2175 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2179 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2181 TableInfo *tbinfo = tdinfo->tdtable;
2184 /* If the materialized view is not flagged as populated, skip this. */
2185 if (!tbinfo->relispopulated)
2188 q = createPQExpBuffer();
2190 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2191 fmtQualifiedDumpable(tbinfo));
2193 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2195 tdinfo->dobj.catId, /* catalog ID */
2196 tdinfo->dobj.dumpId, /* dump ID */
2197 tbinfo->dobj.name, /* Name */
2198 tbinfo->dobj.namespace->dobj.name, /* Namespace */
2199 NULL, /* Tablespace */
2200 tbinfo->rolname, /* Owner */
2201 false, /* with oids */
2202 "MATERIALIZED VIEW DATA", /* Desc */
2203 SECTION_POST_DATA, /* Section */
2204 q->data, /* Create */
2207 tdinfo->dobj.dependencies, /* Deps */
2208 tdinfo->dobj.nDeps, /* # Deps */
2210 NULL); /* Dumper Arg */
2212 destroyPQExpBuffer(q);
2217 * set up dumpable objects representing the contents of tables
2220 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2224 for (i = 0; i < numTables; i++)
2226 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2227 (!relkind || tblinfo[i].relkind == relkind))
2228 makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2233 * Make a dumpable object for the data of this specific table
2235 * Note: we make a TableDataInfo if and only if we are going to dump the
2236 * table data; the "dump" flag in such objects isn't used.
2239 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2241 TableDataInfo *tdinfo;
2244 * Nothing to do if we already decided to dump the table. This will
2245 * happen for "config" tables.
2247 if (tbinfo->dataObj != NULL)
2250 /* Skip VIEWs (no data to dump) */
2251 if (tbinfo->relkind == RELKIND_VIEW)
2253 /* Skip FOREIGN TABLEs (no data to dump) */
2254 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2256 /* Skip partitioned tables (data in partitions) */
2257 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2260 /* Don't dump data in unlogged tables, if so requested */
2261 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2262 dopt->no_unlogged_table_data)
2265 /* Check that the data is not explicitly excluded */
2266 if (simple_oid_list_member(&tabledata_exclude_oids,
2267 tbinfo->dobj.catId.oid))
2270 /* OK, let's dump it */
2271 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2273 if (tbinfo->relkind == RELKIND_MATVIEW)
2274 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2275 else if (tbinfo->relkind == RELKIND_SEQUENCE)
2276 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2278 tdinfo->dobj.objType = DO_TABLE_DATA;
2281 * Note: use tableoid 0 so that this object won't be mistaken for
2282 * something that pg_depend entries apply to.
2284 tdinfo->dobj.catId.tableoid = 0;
2285 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2286 AssignDumpId(&tdinfo->dobj);
2287 tdinfo->dobj.name = tbinfo->dobj.name;
2288 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2289 tdinfo->tdtable = tbinfo;
2290 tdinfo->oids = oids;
2291 tdinfo->filtercond = NULL; /* might get set later */
2292 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2294 tbinfo->dataObj = tdinfo;
2298 * The refresh for a materialized view must be dependent on the refresh for
2299 * any materialized view that this one is dependent on.
2301 * This must be called after all the objects are created, but before they are
2305 buildMatViewRefreshDependencies(Archive *fout)
2315 /* No Mat Views before 9.3. */
2316 if (fout->remoteVersion < 90300)
2319 query = createPQExpBuffer();
2321 appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2323 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2324 "FROM pg_depend d1 "
2325 "JOIN pg_class c1 ON c1.oid = d1.objid "
2326 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2327 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2328 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2329 "AND d2.objid = r1.oid "
2330 "AND d2.refobjid <> d1.objid "
2331 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2332 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2333 CppAsString2(RELKIND_VIEW) ") "
2334 "WHERE d1.classid = 'pg_class'::regclass "
2336 "SELECT w.objid, d3.refobjid, c3.relkind "
2338 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2339 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2340 "AND d3.objid = r3.oid "
2341 "AND d3.refobjid <> w.refobjid "
2342 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2343 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2344 CppAsString2(RELKIND_VIEW) ") "
2346 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2348 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2350 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2352 ntups = PQntuples(res);
2354 i_classid = PQfnumber(res, "classid");
2355 i_objid = PQfnumber(res, "objid");
2356 i_refobjid = PQfnumber(res, "refobjid");
2358 for (i = 0; i < ntups; i++)
2362 DumpableObject *dobj;
2363 DumpableObject *refdobj;
2365 TableInfo *reftbinfo;
2367 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2368 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2369 refobjId.tableoid = objId.tableoid;
2370 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2372 dobj = findObjectByCatalogId(objId);
2376 Assert(dobj->objType == DO_TABLE);
2377 tbinfo = (TableInfo *) dobj;
2378 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2379 dobj = (DumpableObject *) tbinfo->dataObj;
2382 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2384 refdobj = findObjectByCatalogId(refobjId);
2385 if (refdobj == NULL)
2388 Assert(refdobj->objType == DO_TABLE);
2389 reftbinfo = (TableInfo *) refdobj;
2390 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2391 refdobj = (DumpableObject *) reftbinfo->dataObj;
2392 if (refdobj == NULL)
2394 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2396 addObjectDependency(dobj, refdobj->dumpId);
2398 if (!reftbinfo->relispopulated)
2399 tbinfo->relispopulated = false;
2404 destroyPQExpBuffer(query);
2408 * getTableDataFKConstraints -
2409 * add dump-order dependencies reflecting foreign key constraints
2411 * This code is executed only in a data-only dump --- in schema+data dumps
2412 * we handle foreign key issues by not creating the FK constraints until
2413 * after the data is loaded. In a data-only dump, however, we want to
2414 * order the table data objects in such a way that a table's referenced
2415 * tables are restored first. (In the presence of circular references or
2416 * self-references this may be impossible; we'll detect and complain about
2417 * that during the dependency sorting step.)
2420 getTableDataFKConstraints(void)
2422 DumpableObject **dobjs;
2426 /* Search through all the dumpable objects for FK constraints */
2427 getDumpableObjects(&dobjs, &numObjs);
2428 for (i = 0; i < numObjs; i++)
2430 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2432 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2435 /* Not interesting unless both tables are to be dumped */
2436 if (cinfo->contable == NULL ||
2437 cinfo->contable->dataObj == NULL)
2439 ftable = findTableByOid(cinfo->confrelid);
2440 if (ftable == NULL ||
2441 ftable->dataObj == NULL)
2445 * Okay, make referencing table's TABLE_DATA object depend on the
2446 * referenced table's TABLE_DATA object.
2448 addObjectDependency(&cinfo->contable->dataObj->dobj,
2449 ftable->dataObj->dobj.dumpId);
2457 * guessConstraintInheritance:
2458 * In pre-8.4 databases, we can't tell for certain which constraints
2459 * are inherited. We assume a CHECK constraint is inherited if its name
2460 * matches the name of any constraint in the parent. Originally this code
2461 * tried to compare the expression texts, but that can fail for various
2462 * reasons --- for example, if the parent and child tables are in different
2463 * schemas, reverse-listing of function calls may produce different text
2464 * (schema-qualified or not) depending on search path.
2466 * In 8.4 and up we can rely on the conislocal field to decide which
2467 * constraints must be dumped; much safer.
2469 * This function assumes all conislocal flags were initialized to true.
2470 * It clears the flag on anything that seems to be inherited.
2473 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2479 for (i = 0; i < numTables; i++)
2481 TableInfo *tbinfo = &(tblinfo[i]);
2483 TableInfo **parents;
2486 /* Sequences and views never have parents */
2487 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2488 tbinfo->relkind == RELKIND_VIEW)
2491 /* Don't bother computing anything for non-target tables, either */
2492 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2495 numParents = tbinfo->numParents;
2496 parents = tbinfo->parents;
2498 if (numParents == 0)
2499 continue; /* nothing to see here, move along */
2501 /* scan for inherited CHECK constraints */
2502 for (j = 0; j < tbinfo->ncheck; j++)
2504 ConstraintInfo *constr;
2506 constr = &(tbinfo->checkexprs[j]);
2508 for (k = 0; k < numParents; k++)
2512 parent = parents[k];
2513 for (l = 0; l < parent->ncheck; l++)
2515 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2517 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2519 constr->conislocal = false;
2523 if (!constr->conislocal)
2533 * dump the database definition
2536 dumpDatabase(Archive *fout)
2538 DumpOptions *dopt = fout->dopt;
2539 PQExpBuffer dbQry = createPQExpBuffer();
2540 PQExpBuffer delQry = createPQExpBuffer();
2541 PQExpBuffer creaQry = createPQExpBuffer();
2542 PQExpBuffer labelq = createPQExpBuffer();
2543 PGconn *conn = GetConnection(fout);
2561 const char *datname,
2576 write_msg(NULL, "saving database definition\n");
2578 /* Fetch the database-level properties for this database */
2579 if (fout->remoteVersion >= 90600)
2581 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2582 "(%s datdba) AS dba, "
2583 "pg_encoding_to_char(encoding) AS encoding, "
2584 "datcollate, datctype, datfrozenxid, datminmxid, "
2585 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2586 " SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2587 " EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2589 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2590 " SELECT unnest(acldefault('d',datdba)) AS acl "
2591 " EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2593 "datistemplate, datconnlimit, "
2594 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2595 "shobj_description(oid, 'pg_database') AS description "
2598 "WHERE datname = current_database()",
2601 else if (fout->remoteVersion >= 90300)
2603 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2604 "(%s datdba) AS dba, "
2605 "pg_encoding_to_char(encoding) AS encoding, "
2606 "datcollate, datctype, datfrozenxid, datminmxid, "
2607 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2608 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2609 "shobj_description(oid, 'pg_database') AS description "
2612 "WHERE datname = current_database()",
2615 else if (fout->remoteVersion >= 80400)
2617 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2618 "(%s datdba) AS dba, "
2619 "pg_encoding_to_char(encoding) AS encoding, "
2620 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2621 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2622 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2623 "shobj_description(oid, 'pg_database') AS description "
2626 "WHERE datname = current_database()",
2629 else if (fout->remoteVersion >= 80200)
2631 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2632 "(%s datdba) AS dba, "
2633 "pg_encoding_to_char(encoding) AS encoding, "
2634 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2635 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2636 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2637 "shobj_description(oid, 'pg_database') AS description "
2640 "WHERE datname = current_database()",
2645 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2646 "(%s datdba) AS dba, "
2647 "pg_encoding_to_char(encoding) AS encoding, "
2648 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2649 "datacl, '' as rdatacl, datistemplate, "
2650 "-1 as datconnlimit, "
2651 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2653 "WHERE datname = current_database()",
2657 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2659 i_tableoid = PQfnumber(res, "tableoid");
2660 i_oid = PQfnumber(res, "oid");
2661 i_datname = PQfnumber(res, "datname");
2662 i_dba = PQfnumber(res, "dba");
2663 i_encoding = PQfnumber(res, "encoding");
2664 i_collate = PQfnumber(res, "datcollate");
2665 i_ctype = PQfnumber(res, "datctype");
2666 i_frozenxid = PQfnumber(res, "datfrozenxid");
2667 i_minmxid = PQfnumber(res, "datminmxid");
2668 i_datacl = PQfnumber(res, "datacl");
2669 i_rdatacl = PQfnumber(res, "rdatacl");
2670 i_datistemplate = PQfnumber(res, "datistemplate");
2671 i_datconnlimit = PQfnumber(res, "datconnlimit");
2672 i_tablespace = PQfnumber(res, "tablespace");
2674 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2675 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2676 datname = PQgetvalue(res, 0, i_datname);
2677 dba = PQgetvalue(res, 0, i_dba);
2678 encoding = PQgetvalue(res, 0, i_encoding);
2679 collate = PQgetvalue(res, 0, i_collate);
2680 ctype = PQgetvalue(res, 0, i_ctype);
2681 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2682 minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2683 datacl = PQgetvalue(res, 0, i_datacl);
2684 rdatacl = PQgetvalue(res, 0, i_rdatacl);
2685 datistemplate = PQgetvalue(res, 0, i_datistemplate);
2686 datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2687 tablespace = PQgetvalue(res, 0, i_tablespace);
2689 qdatname = pg_strdup(fmtId(datname));
2692 * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2693 * and tablespace since those can't be altered later. Other DB properties
2694 * are left to the DATABASE PROPERTIES entry, so that they can be applied
2695 * after reconnecting to the target DB.
2697 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2699 if (strlen(encoding) > 0)
2701 appendPQExpBufferStr(creaQry, " ENCODING = ");
2702 appendStringLiteralAH(creaQry, encoding, fout);
2704 if (strlen(collate) > 0)
2706 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2707 appendStringLiteralAH(creaQry, collate, fout);
2709 if (strlen(ctype) > 0)
2711 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2712 appendStringLiteralAH(creaQry, ctype, fout);
2716 * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2717 * thing; the decision whether to specify a tablespace should be left till
2718 * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2719 * label the DATABASE entry with the tablespace and let the normal
2720 * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2721 * attention to default_tablespace, so that won't work.
2723 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2724 !dopt->outputNoTablespaces)
2725 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2727 appendPQExpBufferStr(creaQry, ";\n");
2729 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2732 dbDumpId = createDumpId();
2735 dbCatId, /* catalog ID */
2736 dbDumpId, /* dump ID */
2738 NULL, /* Namespace */
2739 NULL, /* Tablespace */
2741 false, /* with oids */
2742 "DATABASE", /* Desc */
2743 SECTION_PRE_DATA, /* Section */
2744 creaQry->data, /* Create */
2745 delQry->data, /* Del */
2750 NULL); /* Dumper Arg */
2752 /* Compute correct tag for archive entry */
2753 appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2755 /* Dump DB comment if any */
2756 if (fout->remoteVersion >= 80200)
2759 * 8.2 and up keep comments on shared objects in a shared table, so we
2760 * cannot use the dumpComment() code used for other database objects.
2761 * Be careful that the ArchiveEntry parameters match that function.
2763 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2765 if (comment && *comment && !dopt->no_comments)
2767 resetPQExpBuffer(dbQry);
2770 * Generates warning when loaded into a differently-named
2773 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2774 appendStringLiteralAH(dbQry, comment, fout);
2775 appendPQExpBufferStr(dbQry, ";\n");
2777 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2778 labelq->data, NULL, NULL, dba,
2779 false, "COMMENT", SECTION_NONE,
2780 dbQry->data, "", NULL,
2787 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2788 dbCatId, 0, dbDumpId);
2791 /* Dump DB security label, if enabled */
2792 if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2795 PQExpBuffer seclabelQry;
2797 seclabelQry = createPQExpBuffer();
2799 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2800 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2801 resetPQExpBuffer(seclabelQry);
2802 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2803 if (seclabelQry->len > 0)
2804 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2805 labelq->data, NULL, NULL, dba,
2806 false, "SECURITY LABEL", SECTION_NONE,
2807 seclabelQry->data, "", NULL,
2810 destroyPQExpBuffer(seclabelQry);
2815 * Dump ACL if any. Note that we do not support initial privileges
2816 * (pg_init_privs) on databases.
2818 dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2819 qdatname, NULL, NULL,
2820 dba, datacl, rdatacl, "", "");
2823 * Now construct a DATABASE PROPERTIES archive entry to restore any
2824 * non-default database-level properties. (The reason this must be
2825 * separate is that we cannot put any additional commands into the TOC
2826 * entry that has CREATE DATABASE. pg_restore would execute such a group
2827 * in an implicit transaction block, and the backend won't allow CREATE
2828 * DATABASE in that context.)
2830 resetPQExpBuffer(creaQry);
2831 resetPQExpBuffer(delQry);
2833 if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2834 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2835 qdatname, datconnlimit);
2837 if (strcmp(datistemplate, "t") == 0)
2839 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2843 * The backend won't accept DROP DATABASE on a template database. We
2844 * can deal with that by removing the template marking before the DROP
2845 * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
2846 * since no such command is currently supported, fake it with a direct
2847 * UPDATE on pg_database.
2849 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2850 "SET datistemplate = false WHERE datname = ");
2851 appendStringLiteralAH(delQry, datname, fout);
2852 appendPQExpBufferStr(delQry, ";\n");
2855 /* Add database-specific SET options */
2856 dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2859 * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2860 * entry, too, for lack of a better place.
2862 if (dopt->binary_upgrade)
2864 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2865 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2866 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2868 frozenxid, minmxid);
2869 appendStringLiteralAH(creaQry, datname, fout);
2870 appendPQExpBufferStr(creaQry, ";\n");
2873 if (creaQry->len > 0)
2874 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2875 datname, NULL, NULL, dba,
2876 false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2877 creaQry->data, delQry->data, NULL,
2882 * pg_largeobject and pg_largeobject_metadata come from the old system
2883 * intact, so set their relfrozenxids and relminmxids.
2885 if (dopt->binary_upgrade)
2888 PQExpBuffer loFrozenQry = createPQExpBuffer();
2889 PQExpBuffer loOutQry = createPQExpBuffer();
2896 if (fout->remoteVersion >= 90300)
2897 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2898 "FROM pg_catalog.pg_class\n"
2899 "WHERE oid = %u;\n",
2900 LargeObjectRelationId);
2902 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2903 "FROM pg_catalog.pg_class\n"
2904 "WHERE oid = %u;\n",
2905 LargeObjectRelationId);
2907 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2909 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2910 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2912 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2913 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2914 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2915 "WHERE oid = %u;\n",
2916 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2917 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2918 LargeObjectRelationId);
2919 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2920 "pg_largeobject", NULL, NULL, "",
2921 false, "pg_largeobject", SECTION_PRE_DATA,
2922 loOutQry->data, "", NULL,
2929 * pg_largeobject_metadata
2931 if (fout->remoteVersion >= 90000)
2933 resetPQExpBuffer(loFrozenQry);
2934 resetPQExpBuffer(loOutQry);
2936 if (fout->remoteVersion >= 90300)
2937 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2938 "FROM pg_catalog.pg_class\n"
2939 "WHERE oid = %u;\n",
2940 LargeObjectMetadataRelationId);
2942 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2943 "FROM pg_catalog.pg_class\n"
2944 "WHERE oid = %u;\n",
2945 LargeObjectMetadataRelationId);
2947 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2949 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2950 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2952 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2953 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2954 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2955 "WHERE oid = %u;\n",
2956 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2957 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2958 LargeObjectMetadataRelationId);
2959 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2960 "pg_largeobject_metadata", NULL, NULL, "",
2961 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2962 loOutQry->data, "", NULL,
2969 destroyPQExpBuffer(loFrozenQry);
2970 destroyPQExpBuffer(loOutQry);
2976 destroyPQExpBuffer(dbQry);
2977 destroyPQExpBuffer(delQry);
2978 destroyPQExpBuffer(creaQry);
2979 destroyPQExpBuffer(labelq);
2983 * Collect any database-specific or role-and-database-specific SET options
2984 * for this database, and append them to outbuf.
2987 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
2988 const char *dbname, Oid dboid)
2990 PGconn *conn = GetConnection(AH);
2991 PQExpBuffer buf = createPQExpBuffer();
2996 * First collect database-specific options. Pre-8.4 server versions lack
2997 * unnest(), so we do this the hard way by querying once per subscript.
3001 if (AH->remoteVersion >= 90000)
3002 printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3003 "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3006 printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3008 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3010 if (PQntuples(res) == 1 &&
3011 !PQgetisnull(res, 0, 0))
3013 makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3014 "DATABASE", dbname, NULL, NULL,
3026 /* Now look for role-and-database-specific options */
3027 if (AH->remoteVersion >= 90000)
3029 /* Here we can assume we have unnest() */
3030 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3031 "FROM pg_db_role_setting s, pg_roles r "
3032 "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3035 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3037 if (PQntuples(res) > 0)
3041 for (i = 0; i < PQntuples(res); i++)
3042 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3043 "ROLE", PQgetvalue(res, i, 0),
3051 destroyPQExpBuffer(buf);
3055 * dumpEncoding: put the correct encoding into the archive
3058 dumpEncoding(Archive *AH)
3060 const char *encname = pg_encoding_to_char(AH->encoding);
3061 PQExpBuffer qry = createPQExpBuffer();
3064 write_msg(NULL, "saving encoding = %s\n", encname);
3066 appendPQExpBufferStr(qry, "SET client_encoding = ");
3067 appendStringLiteralAH(qry, encname, AH);
3068 appendPQExpBufferStr(qry, ";\n");
3070 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3071 "ENCODING", NULL, NULL, "",
3072 false, "ENCODING", SECTION_PRE_DATA,
3073 qry->data, "", NULL,
3077 destroyPQExpBuffer(qry);
3082 * dumpStdStrings: put the correct escape string behavior into the archive
3085 dumpStdStrings(Archive *AH)
3087 const char *stdstrings = AH->std_strings ? "on" : "off";
3088 PQExpBuffer qry = createPQExpBuffer();
3091 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3094 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3097 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3098 "STDSTRINGS", NULL, NULL, "",
3099 false, "STDSTRINGS", SECTION_PRE_DATA,
3100 qry->data, "", NULL,
3104 destroyPQExpBuffer(qry);
3108 * dumpSearchPath: record the active search_path in the archive
3111 dumpSearchPath(Archive *AH)
3113 PQExpBuffer qry = createPQExpBuffer();
3114 PQExpBuffer path = createPQExpBuffer();
3116 char **schemanames = NULL;
3117 int nschemanames = 0;
3121 * We use the result of current_schemas(), not the search_path GUC,
3122 * because that might contain wildcards such as "$user", which won't
3123 * necessarily have the same value during restore. Also, this way avoids
3124 * listing schemas that may appear in search_path but not actually exist,
3125 * which seems like a prudent exclusion.
3127 res = ExecuteSqlQueryForSingleRow(AH,
3128 "SELECT pg_catalog.current_schemas(false)");
3130 if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3131 exit_horribly(NULL, "could not parse result of current_schemas()\n");
3134 * We use set_config(), not a simple "SET search_path" command, because
3135 * the latter has less-clean behavior if the search path is empty. While
3136 * that's likely to get fixed at some point, it seems like a good idea to
3137 * be as backwards-compatible as possible in what we put into archives.
3139 for (i = 0; i < nschemanames; i++)
3142 appendPQExpBufferStr(path, ", ");
3143 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3146 appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3147 appendStringLiteralAH(qry, path->data, AH);
3148 appendPQExpBufferStr(qry, ", false);\n");
3151 write_msg(NULL, "saving search_path = %s\n", path->data);
3153 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3154 "SEARCHPATH", NULL, NULL, "",
3155 false, "SEARCHPATH", SECTION_PRE_DATA,
3156 qry->data, "", NULL,
3160 /* Also save it in AH->searchpath, in case we're doing plain text dump */
3161 AH->searchpath = pg_strdup(qry->data);
3166 destroyPQExpBuffer(qry);
3167 destroyPQExpBuffer(path);
3173 * Collect schema-level data about large objects
3176 getBlobs(Archive *fout)
3178 DumpOptions *dopt = fout->dopt;
3179 PQExpBuffer blobQry = createPQExpBuffer();
3181 DumpableObject *bdata;
3192 /* Verbose message */
3194 write_msg(NULL, "reading large objects\n");
3196 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3197 if (fout->remoteVersion >= 90600)
3199 PQExpBuffer acl_subquery = createPQExpBuffer();
3200 PQExpBuffer racl_subquery = createPQExpBuffer();
3201 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3202 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3204 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3205 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3206 dopt->binary_upgrade);
3208 appendPQExpBuffer(blobQry,
3209 "SELECT l.oid, (%s l.lomowner) AS rolname, "
3212 "%s AS initlomacl, "
3213 "%s AS initrlomacl "
3214 "FROM pg_largeobject_metadata l "
3215 "LEFT JOIN pg_init_privs pip ON "
3216 "(l.oid = pip.objoid "
3217 "AND pip.classoid = 'pg_largeobject'::regclass "
3218 "AND pip.objsubid = 0) ",
3221 racl_subquery->data,
3222 init_acl_subquery->data,
3223 init_racl_subquery->data);
3225 destroyPQExpBuffer(acl_subquery);
3226 destroyPQExpBuffer(racl_subquery);
3227 destroyPQExpBuffer(init_acl_subquery);
3228 destroyPQExpBuffer(init_racl_subquery);
3230 else if (fout->remoteVersion >= 90000)
3231 appendPQExpBuffer(blobQry,
3232 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3233 "NULL AS rlomacl, NULL AS initlomacl, "
3234 "NULL AS initrlomacl "
3235 " FROM pg_largeobject_metadata",
3238 appendPQExpBufferStr(blobQry,
3239 "SELECT DISTINCT loid AS oid, "
3240 "NULL::name AS rolname, NULL::oid AS lomacl, "
3241 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3242 "NULL::oid AS initrlomacl "
3243 " FROM pg_largeobject");
3245 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3247 i_oid = PQfnumber(res, "oid");
3248 i_lomowner = PQfnumber(res, "rolname");
3249 i_lomacl = PQfnumber(res, "lomacl");
3250 i_rlomacl = PQfnumber(res, "rlomacl");
3251 i_initlomacl = PQfnumber(res, "initlomacl");
3252 i_initrlomacl = PQfnumber(res, "initrlomacl");
3254 ntups = PQntuples(res);
3257 * Each large object has its own BLOB archive entry.
3259 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3261 for (i = 0; i < ntups; i++)
3263 binfo[i].dobj.objType = DO_BLOB;
3264 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3265 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3266 AssignDumpId(&binfo[i].dobj);
3268 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3269 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3270 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3271 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3272 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3273 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3275 if (PQgetisnull(res, i, i_lomacl) &&
3276 PQgetisnull(res, i, i_rlomacl) &&
3277 PQgetisnull(res, i, i_initlomacl) &&
3278 PQgetisnull(res, i, i_initrlomacl))
3279 binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3282 * In binary-upgrade mode for blobs, we do *not* dump out the data or
3283 * the ACLs, should any exist. The data and ACL (if any) will be
3284 * copied by pg_upgrade, which simply copies the pg_largeobject and
3285 * pg_largeobject_metadata tables.
3287 * We *do* dump out the definition of the blob because we need that to
3288 * make the restoration of the comments, and anything else, work since
3289 * pg_upgrade copies the files behind pg_largeobject and
3290 * pg_largeobject_metadata after the dump is restored.
3292 if (dopt->binary_upgrade)
3293 binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3297 * If we have any large objects, a "BLOBS" archive entry is needed. This
3298 * is just a placeholder for sorting; it carries no data now.
3302 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3303 bdata->objType = DO_BLOB_DATA;
3304 bdata->catId = nilCatalogId;
3305 AssignDumpId(bdata);
3306 bdata->name = pg_strdup("BLOBS");
3310 destroyPQExpBuffer(blobQry);
3316 * dump the definition (metadata) of the given large object
3319 dumpBlob(Archive *fout, BlobInfo *binfo)
3321 PQExpBuffer cquery = createPQExpBuffer();
3322 PQExpBuffer dquery = createPQExpBuffer();
3324 appendPQExpBuffer(cquery,
3325 "SELECT pg_catalog.lo_create('%s');\n",
3328 appendPQExpBuffer(dquery,
3329 "SELECT pg_catalog.lo_unlink('%s');\n",
3332 if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3333 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3336 binfo->rolname, false,
3337 "BLOB", SECTION_PRE_DATA,
3338 cquery->data, dquery->data, NULL,
3342 /* Dump comment if any */
3343 if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3344 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3345 NULL, binfo->rolname,
3346 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3348 /* Dump security label if any */
3349 if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3350 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3351 NULL, binfo->rolname,
3352 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3354 /* Dump ACL if any */
3355 if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3356 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3357 binfo->dobj.name, NULL,
3358 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3359 binfo->initblobacl, binfo->initrblobacl);
3361 destroyPQExpBuffer(cquery);
3362 destroyPQExpBuffer(dquery);
3367 * dump the data contents of all large objects
3370 dumpBlobs(Archive *fout, void *arg)
3372 const char *blobQry;
3373 const char *blobFetchQry;
3374 PGconn *conn = GetConnection(fout);
3376 char buf[LOBBUFSIZE];
3382 write_msg(NULL, "saving large objects\n");
3385 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3386 * the already-in-memory dumpable objects instead...
3388 if (fout->remoteVersion >= 90000)
3389 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3391 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3393 ExecuteSqlStatement(fout, blobQry);
3395 /* Command to fetch from cursor */
3396 blobFetchQry = "FETCH 1000 IN bloboid";
3401 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3403 /* Process the tuples, if any */
3404 ntups = PQntuples(res);
3405 for (i = 0; i < ntups; i++)
3410 blobOid = atooid(PQgetvalue(res, i, 0));
3412 loFd = lo_open(conn, blobOid, INV_READ);
3414 exit_horribly(NULL, "could not open large object %u: %s",
3415 blobOid, PQerrorMessage(conn));
3417 StartBlob(fout, blobOid);
3419 /* Now read it in chunks, sending data to archive */
3422 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3424 exit_horribly(NULL, "error reading large object %u: %s",
3425 blobOid, PQerrorMessage(conn));
3427 WriteData(fout, buf, cnt);
3430 lo_close(conn, loFd);
3432 EndBlob(fout, blobOid);
3436 } while (ntups > 0);
3443 * get information about policies on a dumpable table.
3446 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3450 PolicyInfo *polinfo;
3455 int i_polpermissive;
3463 if (fout->remoteVersion < 90500)
3466 query = createPQExpBuffer();
3468 for (i = 0; i < numTables; i++)
3470 TableInfo *tbinfo = &tblinfo[i];
3472 /* Ignore row security on tables not to be dumped */
3473 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3477 write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3478 tbinfo->dobj.namespace->dobj.name,
3482 * Get row security enabled information for the table. We represent
3483 * RLS enabled on a table by creating PolicyInfo object with an empty
3489 * Note: use tableoid 0 so that this object won't be mistaken for
3490 * something that pg_depend entries apply to.
3492 polinfo = pg_malloc(sizeof(PolicyInfo));
3493 polinfo->dobj.objType = DO_POLICY;
3494 polinfo->dobj.catId.tableoid = 0;
3495 polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3496 AssignDumpId(&polinfo->dobj);
3497 polinfo->dobj.namespace = tbinfo->dobj.namespace;
3498 polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3499 polinfo->poltable = tbinfo;
3500 polinfo->polname = NULL;
3501 polinfo->polcmd = '\0';
3502 polinfo->polpermissive = 0;
3503 polinfo->polroles = NULL;
3504 polinfo->polqual = NULL;
3505 polinfo->polwithcheck = NULL;
3509 write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3510 tbinfo->dobj.namespace->dobj.name,
3513 resetPQExpBuffer(query);
3515 /* Get the policies for the table. */
3516 if (fout->remoteVersion >= 100000)
3517 appendPQExpBuffer(query,
3518 "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3519 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3520 " 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, "
3521 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3522 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3523 "FROM pg_catalog.pg_policy pol "
3524 "WHERE polrelid = '%u'",
3525 tbinfo->dobj.catId.oid);
3527 appendPQExpBuffer(query,
3528 "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3529 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3530 " 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, "
3531 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3532 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3533 "FROM pg_catalog.pg_policy pol "
3534 "WHERE polrelid = '%u'",
3535 tbinfo->dobj.catId.oid);
3536 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3538 ntups = PQntuples(res);
3543 * No explicit policies to handle (only the default-deny policy,
3544 * which is handled as part of the table definition). Clean up
3551 i_oid = PQfnumber(res, "oid");
3552 i_tableoid = PQfnumber(res, "tableoid");
3553 i_polname = PQfnumber(res, "polname");
3554 i_polcmd = PQfnumber(res, "polcmd");
3555 i_polpermissive = PQfnumber(res, "polpermissive");
3556 i_polroles = PQfnumber(res, "polroles");
3557 i_polqual = PQfnumber(res, "polqual");
3558 i_polwithcheck = PQfnumber(res, "polwithcheck");
3560 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3562 for (j = 0; j < ntups; j++)
3564 polinfo[j].dobj.objType = DO_POLICY;
3565 polinfo[j].dobj.catId.tableoid =
3566 atooid(PQgetvalue(res, j, i_tableoid));
3567 polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3568 AssignDumpId(&polinfo[j].dobj);
3569 polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3570 polinfo[j].poltable = tbinfo;
3571 polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3572 polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3574 polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3575 polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3577 if (PQgetisnull(res, j, i_polroles))
3578 polinfo[j].polroles = NULL;
3580 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3582 if (PQgetisnull(res, j, i_polqual))
3583 polinfo[j].polqual = NULL;
3585 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3587 if (PQgetisnull(res, j, i_polwithcheck))
3588 polinfo[j].polwithcheck = NULL;
3590 polinfo[j].polwithcheck
3591 = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3595 destroyPQExpBuffer(query);
3600 * dump the definition of the given policy
3603 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3605 DumpOptions *dopt = fout->dopt;
3606 TableInfo *tbinfo = polinfo->poltable;
3616 * If polname is NULL, then this record is just indicating that ROW LEVEL
3617 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3618 * ROW LEVEL SECURITY.
3620 if (polinfo->polname == NULL)
3622 query = createPQExpBuffer();
3624 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3625 fmtQualifiedDumpable(polinfo));
3627 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3628 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3630 polinfo->dobj.namespace->dobj.name,
3632 tbinfo->rolname, false,
3633 "ROW SECURITY", SECTION_POST_DATA,
3634 query->data, "", NULL,
3638 destroyPQExpBuffer(query);
3642 if (polinfo->polcmd == '*')
3644 else if (polinfo->polcmd == 'r')
3645 cmd = " FOR SELECT";
3646 else if (polinfo->polcmd == 'a')
3647 cmd = " FOR INSERT";
3648 else if (polinfo->polcmd == 'w')
3649 cmd = " FOR UPDATE";
3650 else if (polinfo->polcmd == 'd')
3651 cmd = " FOR DELETE";
3654 write_msg(NULL, "unexpected policy command type: %c\n",
3659 query = createPQExpBuffer();
3660 delqry = createPQExpBuffer();
3662 appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3664 appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3665 !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3667 if (polinfo->polroles != NULL)
3668 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3670 if (polinfo->polqual != NULL)
3671 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3673 if (polinfo->polwithcheck != NULL)
3674 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3676 appendPQExpBuffer(query, ";\n");
3678 appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3679 appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3681 tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3683 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3684 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3686 polinfo->dobj.namespace->dobj.name,
3688 tbinfo->rolname, false,
3689 "POLICY", SECTION_POST_DATA,
3690 query->data, delqry->data, NULL,
3695 destroyPQExpBuffer(query);
3696 destroyPQExpBuffer(delqry);
3701 * get information about publications
3704 getPublications(Archive *fout)
3706 DumpOptions *dopt = fout->dopt;
3709 PublicationInfo *pubinfo;
3722 if (dopt->no_publications || fout->remoteVersion < 100000)
3725 query = createPQExpBuffer();
3727 resetPQExpBuffer(query);
3729 /* Get the publications. */
3730 if (fout->remoteVersion >= 110000)
3731 appendPQExpBuffer(query,
3732 "SELECT p.tableoid, p.oid, p.pubname, "
3733 "(%s p.pubowner) AS rolname, "
3734 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3735 "FROM pg_publication p",
3738 appendPQExpBuffer(query,
3739 "SELECT p.tableoid, p.oid, p.pubname, "
3740 "(%s p.pubowner) AS rolname, "
3741 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3742 "FROM pg_publication p",
3745 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3747 ntups = PQntuples(res);
3749 i_tableoid = PQfnumber(res, "tableoid");
3750 i_oid = PQfnumber(res, "oid");
3751 i_pubname = PQfnumber(res, "pubname");
3752 i_rolname = PQfnumber(res, "rolname");
3753 i_puballtables = PQfnumber(res, "puballtables");
3754 i_pubinsert = PQfnumber(res, "pubinsert");
3755 i_pubupdate = PQfnumber(res, "pubupdate");
3756 i_pubdelete = PQfnumber(res, "pubdelete");
3757 i_pubtruncate = PQfnumber(res, "pubtruncate");
3759 pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3761 for (i = 0; i < ntups; i++)
3763 pubinfo[i].dobj.objType = DO_PUBLICATION;
3764 pubinfo[i].dobj.catId.tableoid =
3765 atooid(PQgetvalue(res, i, i_tableoid));
3766 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3767 AssignDumpId(&pubinfo[i].dobj);
3768 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3769 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3770 pubinfo[i].puballtables =
3771 (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3772 pubinfo[i].pubinsert =
3773 (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3774 pubinfo[i].pubupdate =
3775 (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3776 pubinfo[i].pubdelete =
3777 (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3778 pubinfo[i].pubtruncate =
3779 (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
3781 if (strlen(pubinfo[i].rolname) == 0)
3782 write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3783 pubinfo[i].dobj.name);
3785 /* Decide whether we want to dump it */
3786 selectDumpableObject(&(pubinfo[i].dobj), fout);
3790 destroyPQExpBuffer(query);
3795 * dump the definition of the given publication
3798 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3805 if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3808 delq = createPQExpBuffer();
3809 query = createPQExpBuffer();
3811 qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3813 appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3816 appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3819 if (pubinfo->puballtables)
3820 appendPQExpBufferStr(query, " FOR ALL TABLES");
3822 appendPQExpBufferStr(query, " WITH (publish = '");
3823 if (pubinfo->pubinsert)
3825 appendPQExpBufferStr(query, "insert");
3829 if (pubinfo->pubupdate)
3832 appendPQExpBufferStr(query, ", ");
3834 appendPQExpBufferStr(query, "update");
3838 if (pubinfo->pubdelete)
3841 appendPQExpBufferStr(query, ", ");
3843 appendPQExpBufferStr(query, "delete");
3847 if (pubinfo->pubtruncate)
3850 appendPQExpBufferStr(query, ", ");
3852 appendPQExpBufferStr(query, "truncate");
3856 appendPQExpBufferStr(query, "');\n");
3858 ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3862 pubinfo->rolname, false,
3863 "PUBLICATION", SECTION_POST_DATA,
3864 query->data, delq->data, NULL,
3868 if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3869 dumpComment(fout, "PUBLICATION", qpubname,
3870 NULL, pubinfo->rolname,
3871 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3873 if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3874 dumpSecLabel(fout, "PUBLICATION", qpubname,
3875 NULL, pubinfo->rolname,
3876 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3878 destroyPQExpBuffer(delq);
3879 destroyPQExpBuffer(query);
3884 * getPublicationTables
3885 * get information about publication membership for dumpable tables.
3888 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3892 PublicationRelInfo *pubrinfo;
3900 if (fout->remoteVersion < 100000)
3903 query = createPQExpBuffer();
3905 for (i = 0; i < numTables; i++)
3907 TableInfo *tbinfo = &tblinfo[i];
3909 /* Only plain tables can be aded to publications. */
3910 if (tbinfo->relkind != RELKIND_RELATION)
3914 * Ignore publication membership of tables whose definitions are not
3917 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3921 write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3922 tbinfo->dobj.namespace->dobj.name,
3925 resetPQExpBuffer(query);
3927 /* Get the publication membership for the table. */
3928 appendPQExpBuffer(query,
3929 "SELECT pr.tableoid, pr.oid, p.pubname "
3930 "FROM pg_publication_rel pr, pg_publication p "
3931 "WHERE pr.prrelid = '%u'"
3932 " AND p.oid = pr.prpubid",
3933 tbinfo->dobj.catId.oid);
3934 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3936 ntups = PQntuples(res);
3941 * Table is not member of any publications. Clean up and return.
3947 i_tableoid = PQfnumber(res, "tableoid");
3948 i_oid = PQfnumber(res, "oid");
3949 i_pubname = PQfnumber(res, "pubname");
3951 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3953 for (j = 0; j < ntups; j++)
3955 pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3956 pubrinfo[j].dobj.catId.tableoid =
3957 atooid(PQgetvalue(res, j, i_tableoid));
3958 pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3959 AssignDumpId(&pubrinfo[j].dobj);
3960 pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3961 pubrinfo[j].dobj.name = tbinfo->dobj.name;
3962 pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3963 pubrinfo[j].pubtable = tbinfo;
3965 /* Decide whether we want to dump it */
3966 selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3970 destroyPQExpBuffer(query);
3974 * dumpPublicationTable
3975 * dump the definition of the given publication table mapping
3978 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3980 TableInfo *tbinfo = pubrinfo->pubtable;
3984 if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3987 tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3989 query = createPQExpBuffer();
3991 appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3992 fmtId(pubrinfo->pubname));
3993 appendPQExpBuffer(query, " %s;\n",
3994 fmtQualifiedDumpable(tbinfo));
3997 * There is no point in creating drop query as drop query as the drop is
3998 * done by table drop.
4000 ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4002 tbinfo->dobj.namespace->dobj.name,
4005 "PUBLICATION TABLE", SECTION_POST_DATA,
4006 query->data, "", NULL,
4011 destroyPQExpBuffer(query);
4015 * Is the currently connected user a superuser?
4018 is_superuser(Archive *fout)
4020 ArchiveHandle *AH = (ArchiveHandle *) fout;
4023 val = PQparameterStatus(AH->connection, "is_superuser");
4025 if (val && strcmp(val, "on") == 0)
4033 * get information about subscriptions
4036 getSubscriptions(Archive *fout)
4038 DumpOptions *dopt = fout->dopt;
4041 SubscriptionInfo *subinfo;
4048 int i_subsynccommit;
4049 int i_subpublications;
4053 if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4056 if (!is_superuser(fout))
4060 res = ExecuteSqlQuery(fout,
4061 "SELECT count(*) FROM pg_subscription "
4062 "WHERE subdbid = (SELECT oid FROM pg_database"
4063 " WHERE datname = current_database())",
4065 n = atoi(PQgetvalue(res, 0, 0));
4067 write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4072 query = createPQExpBuffer();
4074 resetPQExpBuffer(query);
4076 /* Get the subscriptions in current database. */
4077 appendPQExpBuffer(query,
4078 "SELECT s.tableoid, s.oid, s.subname,"
4079 "(%s s.subowner) AS rolname, "
4080 " s.subconninfo, s.subslotname, s.subsynccommit, "
4081 " s.subpublications "
4082 "FROM pg_subscription s "
4083 "WHERE s.subdbid = (SELECT oid FROM pg_database"
4084 " WHERE datname = current_database())",
4086 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4088 ntups = PQntuples(res);
4090 i_tableoid = PQfnumber(res, "tableoid");
4091 i_oid = PQfnumber(res, "oid");
4092 i_subname = PQfnumber(res, "subname");
4093 i_rolname = PQfnumber(res, "rolname");
4094 i_subconninfo = PQfnumber(res, "subconninfo");
4095 i_subslotname = PQfnumber(res, "subslotname");
4096 i_subsynccommit = PQfnumber(res, "subsynccommit");
4097 i_subpublications = PQfnumber(res, "subpublications");
4099 subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4101 for (i = 0; i < ntups; i++)
4103 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4104 subinfo[i].dobj.catId.tableoid =
4105 atooid(PQgetvalue(res, i, i_tableoid));
4106 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4107 AssignDumpId(&subinfo[i].dobj);
4108 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4109 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4110 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4111 if (PQgetisnull(res, i, i_subslotname))
4112 subinfo[i].subslotname = NULL;
4114 subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4115 subinfo[i].subsynccommit =
4116 pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4117 subinfo[i].subpublications =
4118 pg_strdup(PQgetvalue(res, i, i_subpublications));
4120 if (strlen(subinfo[i].rolname) == 0)
4121 write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4122 subinfo[i].dobj.name);
4124 /* Decide whether we want to dump it */
4125 selectDumpableObject(&(subinfo[i].dobj), fout);
4129 destroyPQExpBuffer(query);
4134 * dump the definition of the given subscription
4137 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4141 PQExpBuffer publications;
4143 char **pubnames = NULL;
4147 if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4150 delq = createPQExpBuffer();
4151 query = createPQExpBuffer();
4153 qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4155 appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4158 appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4160 appendStringLiteralAH(query, subinfo->subconninfo, fout);
4162 /* Build list of quoted publications and append them to query. */
4163 if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4166 "WARNING: could not parse subpublications array\n");
4173 publications = createPQExpBuffer();
4174 for (i = 0; i < npubnames; i++)
4177 appendPQExpBufferStr(publications, ", ");
4179 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4182 appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4183 if (subinfo->subslotname)
4184 appendStringLiteralAH(query, subinfo->subslotname, fout);
4186 appendPQExpBufferStr(query, "NONE");
4188 if (strcmp(subinfo->subsynccommit, "off") != 0)
4189 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4191 appendPQExpBufferStr(query, ");\n");
4193 ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4197 subinfo->rolname, false,
4198 "SUBSCRIPTION", SECTION_POST_DATA,
4199 query->data, delq->data, NULL,
4203 if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4204 dumpComment(fout, "SUBSCRIPTION", qsubname,
4205 NULL, subinfo->rolname,
4206 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4208 if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4209 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4210 NULL, subinfo->rolname,
4211 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4213 destroyPQExpBuffer(publications);
4217 destroyPQExpBuffer(delq);
4218 destroyPQExpBuffer(query);
4223 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4224 PQExpBuffer upgrade_buffer,
4226 bool force_array_type)
4228 PQExpBuffer upgrade_query = createPQExpBuffer();
4230 Oid pg_type_array_oid;
4232 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4233 appendPQExpBuffer(upgrade_buffer,
4234 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4237 /* we only support old >= 8.3 for binary upgrades */
4238 appendPQExpBuffer(upgrade_query,
4240 "FROM pg_catalog.pg_type "
4241 "WHERE oid = '%u'::pg_catalog.oid;",
4244 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4246 pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4250 if (!OidIsValid(pg_type_array_oid) && force_array_type)
4253 * If the old version didn't assign an array type, but the new version
4254 * does, we must select an unused type OID to assign. This currently
4255 * only happens for domains, when upgrading pre-v11 to v11 and up.
4257 * Note: local state here is kind of ugly, but we must have some,
4258 * since we mustn't choose the same unused OID more than once.
4260 static Oid next_possible_free_oid = FirstNormalObjectId;
4265 ++next_possible_free_oid;
4266 printfPQExpBuffer(upgrade_query,
4267 "SELECT EXISTS(SELECT 1 "
4268 "FROM pg_catalog.pg_type "
4269 "WHERE oid = '%u'::pg_catalog.oid);",
4270 next_possible_free_oid);
4271 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4272 is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4276 pg_type_array_oid = next_possible_free_oid;
4279 if (OidIsValid(pg_type_array_oid))
4281 appendPQExpBufferStr(upgrade_buffer,
4282 "\n-- For binary upgrade, must preserve pg_type array oid\n");
4283 appendPQExpBuffer(upgrade_buffer,
4284 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4288 destroyPQExpBuffer(upgrade_query);
4292 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4293 PQExpBuffer upgrade_buffer,
4296 PQExpBuffer upgrade_query = createPQExpBuffer();
4297 PGresult *upgrade_res;
4299 bool toast_set = false;
4301 /* we only support old >= 8.3 for binary upgrades */
4302 appendPQExpBuffer(upgrade_query,
4303 "SELECT c.reltype AS crel, t.reltype AS trel "
4304 "FROM pg_catalog.pg_class c "
4305 "LEFT JOIN pg_catalog.pg_class t ON "
4306 " (c.reltoastrelid = t.oid) "
4307 "WHERE c.oid = '%u'::pg_catalog.oid;",
4310 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4312 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4314 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4315 pg_type_oid, false);
4317 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4319 /* Toast tables do not have pg_type array rows */
4320 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4321 PQfnumber(upgrade_res, "trel")));
4323 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4324 appendPQExpBuffer(upgrade_buffer,
4325 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4331 PQclear(upgrade_res);
4332 destroyPQExpBuffer(upgrade_query);
4338 binary_upgrade_set_pg_class_oids(Archive *fout,
4339 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4342 PQExpBuffer upgrade_query = createPQExpBuffer();
4343 PGresult *upgrade_res;
4344 Oid pg_class_reltoastrelid;
4345 Oid pg_index_indexrelid;
4347 appendPQExpBuffer(upgrade_query,
4348 "SELECT c.reltoastrelid, i.indexrelid "
4349 "FROM pg_catalog.pg_class c LEFT JOIN "
4350 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4351 "WHERE c.oid = '%u'::pg_catalog.oid;",
4354 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4356 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4357 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4359 appendPQExpBufferStr(upgrade_buffer,
4360 "\n-- For binary upgrade, must preserve pg_class oids\n");
4364 appendPQExpBuffer(upgrade_buffer,
4365 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4367 /* only tables have toast tables, not indexes */
4368 if (OidIsValid(pg_class_reltoastrelid))
4371 * One complexity is that the table definition might not require
4372 * the creation of a TOAST table, and the TOAST table might have
4373 * been created long after table creation, when the table was
4374 * loaded with wide data. By setting the TOAST oid we force
4375 * creation of the TOAST heap and TOAST index by the backend so we
4376 * can cleanly copy the files during binary upgrade.
4379 appendPQExpBuffer(upgrade_buffer,
4380 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4381 pg_class_reltoastrelid);
4383 /* every toast table has an index */
4384 appendPQExpBuffer(upgrade_buffer,
4385 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4386 pg_index_indexrelid);
4390 appendPQExpBuffer(upgrade_buffer,
4391 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4394 appendPQExpBufferChar(upgrade_buffer, '\n');
4396 PQclear(upgrade_res);
4397 destroyPQExpBuffer(upgrade_query);
4401 * If the DumpableObject is a member of an extension, add a suitable
4402 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4404 * For somewhat historical reasons, objname should already be quoted,
4405 * but not objnamespace (if any).
4408 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4409 DumpableObject *dobj,
4410 const char *objtype,
4411 const char *objname,
4412 const char *objnamespace)
4414 DumpableObject *extobj = NULL;
4417 if (!dobj->ext_member)
4421 * Find the parent extension. We could avoid this search if we wanted to
4422 * add a link field to DumpableObject, but the space costs of that would
4423 * be considerable. We assume that member objects could only have a
4424 * direct dependency on their own extension, not any others.
4426 for (i = 0; i < dobj->nDeps; i++)
4428 extobj = findObjectByDumpId(dobj->dependencies[i]);
4429 if (extobj && extobj->objType == DO_EXTENSION)
4434 exit_horribly(NULL, "could not find parent extension for %s %s\n",
4437 appendPQExpBufferStr(upgrade_buffer,
4438 "\n-- For binary upgrade, handle extension membership the hard way\n");
4439 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4440 fmtId(extobj->name),
4442 if (objnamespace && *objnamespace)
4443 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4444 appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4449 * read all namespaces in the system catalogs and return them in the
4450 * NamespaceInfo* structure
4452 * numNamespaces is set to the number of namespaces read in
4455 getNamespaces(Archive *fout, int *numNamespaces)
4457 DumpOptions *dopt = fout->dopt;
4462 NamespaceInfo *nsinfo;
4472 query = createPQExpBuffer();
4475 * we fetch all namespaces including system ones, so that every object we
4476 * read in can be linked to a containing namespace.
4478 if (fout->remoteVersion >= 90600)
4480 PQExpBuffer acl_subquery = createPQExpBuffer();
4481 PQExpBuffer racl_subquery = createPQExpBuffer();
4482 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4483 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4485 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4486 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4487 dopt->binary_upgrade);
4489 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4490 "(%s nspowner) AS rolname, "
4493 "%s as initnspacl, "
4494 "%s as initrnspacl "
4495 "FROM pg_namespace n "
4496 "LEFT JOIN pg_init_privs pip "
4497 "ON (n.oid = pip.objoid "
4498 "AND pip.classoid = 'pg_namespace'::regclass "
4499 "AND pip.objsubid = 0",
4502 racl_subquery->data,
4503 init_acl_subquery->data,
4504 init_racl_subquery->data);
4506 appendPQExpBuffer(query, ") ");
4508 destroyPQExpBuffer(acl_subquery);
4509 destroyPQExpBuffer(racl_subquery);
4510 destroyPQExpBuffer(init_acl_subquery);
4511 destroyPQExpBuffer(init_racl_subquery);
4514 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4515 "(%s nspowner) AS rolname, "
4516 "nspacl, NULL as rnspacl, "
4517 "NULL AS initnspacl, NULL as initrnspacl "
4518 "FROM pg_namespace",
4521 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4523 ntups = PQntuples(res);
4525 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4527 i_tableoid = PQfnumber(res, "tableoid");
4528 i_oid = PQfnumber(res, "oid");
4529 i_nspname = PQfnumber(res, "nspname");
4530 i_rolname = PQfnumber(res, "rolname");
4531 i_nspacl = PQfnumber(res, "nspacl");
4532 i_rnspacl = PQfnumber(res, "rnspacl");
4533 i_initnspacl = PQfnumber(res, "initnspacl");
4534 i_initrnspacl = PQfnumber(res, "initrnspacl");
4536 for (i = 0; i < ntups; i++)
4538 nsinfo[i].dobj.objType = DO_NAMESPACE;
4539 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4540 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4541 AssignDumpId(&nsinfo[i].dobj);
4542 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4543 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4544 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4545 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4546 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4547 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4549 /* Decide whether to dump this namespace */
4550 selectDumpableNamespace(&nsinfo[i], fout);
4553 * Do not try to dump ACL if the ACL is empty or the default.
4555 * This is useful because, for some schemas/objects, the only
4556 * component we are going to try and dump is the ACL and if we can
4557 * remove that then 'dump' goes to zero/false and we don't consider
4558 * this object for dumping at all later on.
4560 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4561 PQgetisnull(res, i, i_initnspacl) &&
4562 PQgetisnull(res, i, i_initrnspacl))
4563 nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4565 if (strlen(nsinfo[i].rolname) == 0)
4566 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4567 nsinfo[i].dobj.name);
4571 destroyPQExpBuffer(query);
4573 *numNamespaces = ntups;
4580 * given a namespace OID, look up the info read by getNamespaces
4582 static NamespaceInfo *
4583 findNamespace(Archive *fout, Oid nsoid)
4585 NamespaceInfo *nsinfo;
4587 nsinfo = findNamespaceByOid(nsoid);
4589 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4595 * read all extensions in the system catalogs and return them in the
4596 * ExtensionInfo* structure
4598 * numExtensions is set to the number of extensions read in
4601 getExtensions(Archive *fout, int *numExtensions)
4603 DumpOptions *dopt = fout->dopt;
4608 ExtensionInfo *extinfo;
4613 int i_extrelocatable;
4619 * Before 9.1, there are no extensions.
4621 if (fout->remoteVersion < 90100)
4627 query = createPQExpBuffer();
4629 appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4630 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4631 "FROM pg_extension x "
4632 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4634 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4636 ntups = PQntuples(res);
4638 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4640 i_tableoid = PQfnumber(res, "tableoid");
4641 i_oid = PQfnumber(res, "oid");
4642 i_extname = PQfnumber(res, "extname");
4643 i_nspname = PQfnumber(res, "nspname");
4644 i_extrelocatable = PQfnumber(res, "extrelocatable");
4645 i_extversion = PQfnumber(res, "extversion");
4646 i_extconfig = PQfnumber(res, "extconfig");
4647 i_extcondition = PQfnumber(res, "extcondition");
4649 for (i = 0; i < ntups; i++)
4651 extinfo[i].dobj.objType = DO_EXTENSION;
4652 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4653 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4654 AssignDumpId(&extinfo[i].dobj);
4655 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4656 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4657 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4658 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4659 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4660 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4662 /* Decide whether we want to dump it */
4663 selectDumpableExtension(&(extinfo[i]), dopt);
4667 destroyPQExpBuffer(query);
4669 *numExtensions = ntups;
4676 * read all types in the system catalogs and return them in the
4677 * TypeInfo* structure
4679 * numTypes is set to the number of types read in
4681 * NB: this must run after getFuncs() because we assume we can do
4685 getTypes(Archive *fout, int *numTypes)
4687 DumpOptions *dopt = fout->dopt;
4691 PQExpBuffer query = createPQExpBuffer();
4693 ShellTypeInfo *stinfo;
4711 * we include even the built-in types because those may be used as array
4712 * elements by user-defined types
4714 * we filter out the built-in types when we dump out the types
4716 * same approach for undefined (shell) types and array types
4718 * Note: as of 8.3 we can reliably detect whether a type is an
4719 * auto-generated array type by checking the element type's typarray.
4720 * (Before that the test is capable of generating false positives.) We
4721 * still check for name beginning with '_', though, so as to avoid the
4722 * cost of the subselect probe for all standard types. This would have to
4723 * be revisited if the backend ever allows renaming of array types.
4726 if (fout->remoteVersion >= 90600)
4728 PQExpBuffer acl_subquery = createPQExpBuffer();
4729 PQExpBuffer racl_subquery = createPQExpBuffer();
4730 PQExpBuffer initacl_subquery = createPQExpBuffer();
4731 PQExpBuffer initracl_subquery = createPQExpBuffer();
4733 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4734 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4735 dopt->binary_upgrade);
4737 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4741 "%s AS inittypacl, "
4742 "%s AS initrtypacl, "
4743 "(%s t.typowner) AS rolname, "
4744 "t.typelem, t.typrelid, "
4745 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4746 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4747 "t.typtype, t.typisdefined, "
4748 "t.typname[0] = '_' AND t.typelem != 0 AND "
4749 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4751 "LEFT JOIN pg_init_privs pip ON "
4752 "(t.oid = pip.objoid "
4753 "AND pip.classoid = 'pg_type'::regclass "
4754 "AND pip.objsubid = 0) ",
4756 racl_subquery->data,
4757 initacl_subquery->data,
4758 initracl_subquery->data,
4761 destroyPQExpBuffer(acl_subquery);
4762 destroyPQExpBuffer(racl_subquery);
4763 destroyPQExpBuffer(initacl_subquery);
4764 destroyPQExpBuffer(initracl_subquery);
4766 else if (fout->remoteVersion >= 90200)
4768 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4769 "typnamespace, typacl, NULL as rtypacl, "
4770 "NULL AS inittypacl, NULL AS initrtypacl, "
4771 "(%s typowner) AS rolname, "
4772 "typelem, typrelid, "
4773 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4774 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4775 "typtype, typisdefined, "
4776 "typname[0] = '_' AND typelem != 0 AND "
4777 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4781 else if (fout->remoteVersion >= 80300)
4783 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4784 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4785 "NULL AS inittypacl, NULL AS initrtypacl, "
4786 "(%s typowner) AS rolname, "
4787 "typelem, typrelid, "
4788 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4789 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4790 "typtype, typisdefined, "
4791 "typname[0] = '_' AND typelem != 0 AND "
4792 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4798 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4799 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4800 "NULL AS inittypacl, NULL AS initrtypacl, "
4801 "(%s typowner) AS rolname, "
4802 "typelem, typrelid, "
4803 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4804 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4805 "typtype, typisdefined, "
4806 "typname[0] = '_' AND typelem != 0 AS isarray "
4811 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4813 ntups = PQntuples(res);
4815 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4817 i_tableoid = PQfnumber(res, "tableoid");
4818 i_oid = PQfnumber(res, "oid");
4819 i_typname = PQfnumber(res, "typname");
4820 i_typnamespace = PQfnumber(res, "typnamespace");
4821 i_typacl = PQfnumber(res, "typacl");
4822 i_rtypacl = PQfnumber(res, "rtypacl");
4823 i_inittypacl = PQfnumber(res, "inittypacl");
4824 i_initrtypacl = PQfnumber(res, "initrtypacl");
4825 i_rolname = PQfnumber(res, "rolname");
4826 i_typelem = PQfnumber(res, "typelem");
4827 i_typrelid = PQfnumber(res, "typrelid");
4828 i_typrelkind = PQfnumber(res, "typrelkind");
4829 i_typtype = PQfnumber(res, "typtype");
4830 i_typisdefined = PQfnumber(res, "typisdefined");
4831 i_isarray = PQfnumber(res, "isarray");
4833 for (i = 0; i < ntups; i++)
4835 tyinfo[i].dobj.objType = DO_TYPE;
4836 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4837 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4838 AssignDumpId(&tyinfo[i].dobj);
4839 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4840 tyinfo[i].dobj.namespace =
4842 atooid(PQgetvalue(res, i, i_typnamespace)));
4843 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4844 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4845 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4846 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4847 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4848 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4849 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4850 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4851 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4852 tyinfo[i].shellType = NULL;
4854 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4855 tyinfo[i].isDefined = true;
4857 tyinfo[i].isDefined = false;
4859 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4860 tyinfo[i].isArray = true;
4862 tyinfo[i].isArray = false;
4864 /* Decide whether we want to dump it */
4865 selectDumpableType(&tyinfo[i], fout);
4867 /* Do not try to dump ACL if no ACL exists. */
4868 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4869 PQgetisnull(res, i, i_inittypacl) &&
4870 PQgetisnull(res, i, i_initrtypacl))
4871 tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4874 * If it's a domain, fetch info about its constraints, if any
4876 tyinfo[i].nDomChecks = 0;
4877 tyinfo[i].domChecks = NULL;
4878 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4879 tyinfo[i].typtype == TYPTYPE_DOMAIN)
4880 getDomainConstraints(fout, &(tyinfo[i]));
4883 * If it's a base type, make a DumpableObject representing a shell
4884 * definition of the type. We will need to dump that ahead of the I/O
4885 * functions for the type. Similarly, range types need a shell
4886 * definition in case they have a canonicalize function.
4888 * Note: the shell type doesn't have a catId. You might think it
4889 * should copy the base type's catId, but then it might capture the
4890 * pg_depend entries for the type, which we don't want.
4892 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4893 (tyinfo[i].typtype == TYPTYPE_BASE ||
4894 tyinfo[i].typtype == TYPTYPE_RANGE))
4896 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4897 stinfo->dobj.objType = DO_SHELL_TYPE;
4898 stinfo->dobj.catId = nilCatalogId;
4899 AssignDumpId(&stinfo->dobj);
4900 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4901 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4902 stinfo->baseType = &(tyinfo[i]);
4903 tyinfo[i].shellType = stinfo;
4906 * Initially mark the shell type as not to be dumped. We'll only
4907 * dump it if the I/O or canonicalize functions need to be dumped;
4908 * this is taken care of while sorting dependencies.
4910 stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4913 if (strlen(tyinfo[i].rolname) == 0)
4914 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4915 tyinfo[i].dobj.name);
4922 destroyPQExpBuffer(query);
4929 * read all operators in the system catalogs and return them in the
4930 * OprInfo* structure
4932 * numOprs is set to the number of operators read in
4935 getOperators(Archive *fout, int *numOprs)
4940 PQExpBuffer query = createPQExpBuffer();
4951 * find all operators, including builtin operators; we filter out
4952 * system-defined operators at dump-out time.
4955 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4957 "(%s oprowner) AS rolname, "
4959 "oprcode::oid AS oprcode "
4963 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4965 ntups = PQntuples(res);
4968 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4970 i_tableoid = PQfnumber(res, "tableoid");
4971 i_oid = PQfnumber(res, "oid");
4972 i_oprname = PQfnumber(res, "oprname");
4973 i_oprnamespace = PQfnumber(res, "oprnamespace");
4974 i_rolname = PQfnumber(res, "rolname");
4975 i_oprkind = PQfnumber(res, "oprkind");
4976 i_oprcode = PQfnumber(res, "oprcode");
4978 for (i = 0; i < ntups; i++)
4980 oprinfo[i].dobj.objType = DO_OPERATOR;
4981 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4982 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4983 AssignDumpId(&oprinfo[i].dobj);
4984 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4985 oprinfo[i].dobj.namespace =
4987 atooid(PQgetvalue(res, i, i_oprnamespace)));
4988 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4989 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4990 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4992 /* Decide whether we want to dump it */
4993 selectDumpableObject(&(oprinfo[i].dobj), fout);
4995 /* Operators do not currently have ACLs. */
4996 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4998 if (strlen(oprinfo[i].rolname) == 0)
4999 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
5000 oprinfo[i].dobj.name);
5005 destroyPQExpBuffer(query);
5012 * read all collations in the system catalogs and return them in the
5013 * CollInfo* structure
5015 * numCollations is set to the number of collations read in
5018 getCollations(Archive *fout, int *numCollations)
5028 int i_collnamespace;
5031 /* Collations didn't exist pre-9.1 */
5032 if (fout->remoteVersion < 90100)
5038 query = createPQExpBuffer();
5041 * find all collations, including builtin collations; we filter out
5042 * system-defined collations at dump-out time.
5045 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5047 "(%s collowner) AS rolname "
5048 "FROM pg_collation",
5051 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5053 ntups = PQntuples(res);
5054 *numCollations = ntups;
5056 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5058 i_tableoid = PQfnumber(res, "tableoid");
5059 i_oid = PQfnumber(res, "oid");
5060 i_collname = PQfnumber(res, "collname");
5061 i_collnamespace = PQfnumber(res, "collnamespace");
5062 i_rolname = PQfnumber(res, "rolname");
5064 for (i = 0; i < ntups; i++)
5066 collinfo[i].dobj.objType = DO_COLLATION;
5067 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5068 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5069 AssignDumpId(&collinfo[i].dobj);
5070 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5071 collinfo[i].dobj.namespace =
5073 atooid(PQgetvalue(res, i, i_collnamespace)));
5074 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5076 /* Decide whether we want to dump it */
5077 selectDumpableObject(&(collinfo[i].dobj), fout);
5079 /* Collations do not currently have ACLs. */
5080 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5085 destroyPQExpBuffer(query);
5092 * read all conversions in the system catalogs and return them in the
5093 * ConvInfo* structure
5095 * numConversions is set to the number of conversions read in
5098 getConversions(Archive *fout, int *numConversions)
5111 query = createPQExpBuffer();
5114 * find all conversions, including builtin conversions; we filter out
5115 * system-defined conversions at dump-out time.
5118 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5120 "(%s conowner) AS rolname "
5121 "FROM pg_conversion",
5124 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5126 ntups = PQntuples(res);
5127 *numConversions = ntups;
5129 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5131 i_tableoid = PQfnumber(res, "tableoid");
5132 i_oid = PQfnumber(res, "oid");
5133 i_conname = PQfnumber(res, "conname");
5134 i_connamespace = PQfnumber(res, "connamespace");
5135 i_rolname = PQfnumber(res, "rolname");
5137 for (i = 0; i < ntups; i++)
5139 convinfo[i].dobj.objType = DO_CONVERSION;
5140 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5141 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5142 AssignDumpId(&convinfo[i].dobj);
5143 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5144 convinfo[i].dobj.namespace =
5146 atooid(PQgetvalue(res, i, i_connamespace)));
5147 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5149 /* Decide whether we want to dump it */
5150 selectDumpableObject(&(convinfo[i].dobj), fout);
5152 /* Conversions do not currently have ACLs. */
5153 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5158 destroyPQExpBuffer(query);
5165 * read all user-defined access methods in the system catalogs and return
5166 * them in the AccessMethodInfo* structure
5168 * numAccessMethods is set to the number of access methods read in
5171 getAccessMethods(Archive *fout, int *numAccessMethods)
5177 AccessMethodInfo *aminfo;
5184 /* Before 9.6, there are no user-defined access methods */
5185 if (fout->remoteVersion < 90600)
5187 *numAccessMethods = 0;
5191 query = createPQExpBuffer();
5193 /* Select all access methods from pg_am table */
5194 appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5195 "amhandler::pg_catalog.regproc AS amhandler "
5198 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5200 ntups = PQntuples(res);
5201 *numAccessMethods = ntups;
5203 aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5205 i_tableoid = PQfnumber(res, "tableoid");
5206 i_oid = PQfnumber(res, "oid");
5207 i_amname = PQfnumber(res, "amname");
5208 i_amhandler = PQfnumber(res, "amhandler");
5209 i_amtype = PQfnumber(res, "amtype");
5211 for (i = 0; i < ntups; i++)
5213 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5214 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5215 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5216 AssignDumpId(&aminfo[i].dobj);
5217 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5218 aminfo[i].dobj.namespace = NULL;
5219 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5220 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5222 /* Decide whether we want to dump it */
5223 selectDumpableAccessMethod(&(aminfo[i]), fout);
5225 /* Access methods do not currently have ACLs. */
5226 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5231 destroyPQExpBuffer(query);
5239 * read all opclasses in the system catalogs and return them in the
5240 * OpclassInfo* structure
5242 * numOpclasses is set to the number of opclasses read in
5245 getOpclasses(Archive *fout, int *numOpclasses)
5250 PQExpBuffer query = createPQExpBuffer();
5251 OpclassInfo *opcinfo;
5259 * find all opclasses, including builtin opclasses; we filter out
5260 * system-defined opclasses at dump-out time.
5263 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5265 "(%s opcowner) AS rolname "
5269 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5271 ntups = PQntuples(res);
5272 *numOpclasses = ntups;
5274 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5276 i_tableoid = PQfnumber(res, "tableoid");
5277 i_oid = PQfnumber(res, "oid");
5278 i_opcname = PQfnumber(res, "opcname");
5279 i_opcnamespace = PQfnumber(res, "opcnamespace");
5280 i_rolname = PQfnumber(res, "rolname");
5282 for (i = 0; i < ntups; i++)
5284 opcinfo[i].dobj.objType = DO_OPCLASS;
5285 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5286 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5287 AssignDumpId(&opcinfo[i].dobj);
5288 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5289 opcinfo[i].dobj.namespace =
5291 atooid(PQgetvalue(res, i, i_opcnamespace)));
5292 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5294 /* Decide whether we want to dump it */
5295 selectDumpableObject(&(opcinfo[i].dobj), fout);
5297 /* Op Classes do not currently have ACLs. */
5298 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5300 if (strlen(opcinfo[i].rolname) == 0)
5301 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5302 opcinfo[i].dobj.name);
5307 destroyPQExpBuffer(query);
5314 * read all opfamilies in the system catalogs and return them in the
5315 * OpfamilyInfo* structure
5317 * numOpfamilies is set to the number of opfamilies read in
5320 getOpfamilies(Archive *fout, int *numOpfamilies)
5326 OpfamilyInfo *opfinfo;
5333 /* Before 8.3, there is no separate concept of opfamilies */
5334 if (fout->remoteVersion < 80300)
5340 query = createPQExpBuffer();
5343 * find all opfamilies, including builtin opfamilies; we filter out
5344 * system-defined opfamilies at dump-out time.
5347 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5349 "(%s opfowner) AS rolname "
5353 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5355 ntups = PQntuples(res);
5356 *numOpfamilies = ntups;
5358 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5360 i_tableoid = PQfnumber(res, "tableoid");
5361 i_oid = PQfnumber(res, "oid");
5362 i_opfname = PQfnumber(res, "opfname");
5363 i_opfnamespace = PQfnumber(res, "opfnamespace");
5364 i_rolname = PQfnumber(res, "rolname");
5366 for (i = 0; i < ntups; i++)
5368 opfinfo[i].dobj.objType = DO_OPFAMILY;
5369 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5370 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5371 AssignDumpId(&opfinfo[i].dobj);
5372 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5373 opfinfo[i].dobj.namespace =
5375 atooid(PQgetvalue(res, i, i_opfnamespace)));
5376 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5378 /* Decide whether we want to dump it */
5379 selectDumpableObject(&(opfinfo[i].dobj), fout);
5381 /* Extensions do not currently have ACLs. */
5382 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5384 if (strlen(opfinfo[i].rolname) == 0)
5385 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5386 opfinfo[i].dobj.name);
5391 destroyPQExpBuffer(query);
5398 * read all the user-defined aggregates in the system catalogs and
5399 * return them in the AggInfo* structure
5401 * numAggs is set to the number of aggregates read in
5404 getAggregates(Archive *fout, int *numAggs)
5406 DumpOptions *dopt = fout->dopt;
5410 PQExpBuffer query = createPQExpBuffer();
5425 * Find all interesting aggregates. See comment in getFuncs() for the
5426 * rationale behind the filtering logic.
5428 if (fout->remoteVersion >= 90600)
5430 PQExpBuffer acl_subquery = createPQExpBuffer();
5431 PQExpBuffer racl_subquery = createPQExpBuffer();
5432 PQExpBuffer initacl_subquery = createPQExpBuffer();
5433 PQExpBuffer initracl_subquery = createPQExpBuffer();
5434 const char *agg_check;
5436 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5437 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5438 dopt->binary_upgrade);
5440 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5443 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5444 "p.proname AS aggname, "
5445 "p.pronamespace AS aggnamespace, "
5446 "p.pronargs, p.proargtypes, "
5447 "(%s p.proowner) AS rolname, "
5450 "%s AS initaggacl, "
5451 "%s AS initraggacl "
5453 "LEFT JOIN pg_init_privs pip ON "
5454 "(p.oid = pip.objoid "
5455 "AND pip.classoid = 'pg_proc'::regclass "
5456 "AND pip.objsubid = 0) "
5458 "p.pronamespace != "
5459 "(SELECT oid FROM pg_namespace "
5460 "WHERE nspname = 'pg_catalog') OR "
5461 "p.proacl IS DISTINCT FROM pip.initprivs",
5464 racl_subquery->data,
5465 initacl_subquery->data,
5466 initracl_subquery->data,
5468 if (dopt->binary_upgrade)
5469 appendPQExpBufferStr(query,
5470 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5471 "classid = 'pg_proc'::regclass AND "
5472 "objid = p.oid AND "
5473 "refclassid = 'pg_extension'::regclass AND "
5475 appendPQExpBufferChar(query, ')');
5477 destroyPQExpBuffer(acl_subquery);
5478 destroyPQExpBuffer(racl_subquery);
5479 destroyPQExpBuffer(initacl_subquery);
5480 destroyPQExpBuffer(initracl_subquery);
5482 else if (fout->remoteVersion >= 80200)
5484 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5485 "pronamespace AS aggnamespace, "
5486 "pronargs, proargtypes, "
5487 "(%s proowner) AS rolname, "
5488 "proacl AS aggacl, "
5490 "NULL AS initaggacl, NULL AS initraggacl "
5492 "WHERE proisagg AND ("
5494 "(SELECT oid FROM pg_namespace "
5495 "WHERE nspname = 'pg_catalog')",
5497 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5498 appendPQExpBufferStr(query,
5499 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5500 "classid = 'pg_proc'::regclass AND "
5501 "objid = p.oid AND "
5502 "refclassid = 'pg_extension'::regclass AND "
5504 appendPQExpBufferChar(query, ')');
5508 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5509 "pronamespace AS aggnamespace, "
5510 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5512 "(%s proowner) AS rolname, "
5513 "proacl AS aggacl, "
5515 "NULL AS initaggacl, NULL AS initraggacl "
5518 "AND pronamespace != "
5519 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5523 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5525 ntups = PQntuples(res);
5528 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5530 i_tableoid = PQfnumber(res, "tableoid");
5531 i_oid = PQfnumber(res, "oid");
5532 i_aggname = PQfnumber(res, "aggname");
5533 i_aggnamespace = PQfnumber(res, "aggnamespace");
5534 i_pronargs = PQfnumber(res, "pronargs");
5535 i_proargtypes = PQfnumber(res, "proargtypes");
5536 i_rolname = PQfnumber(res, "rolname");
5537 i_aggacl = PQfnumber(res, "aggacl");
5538 i_raggacl = PQfnumber(res, "raggacl");
5539 i_initaggacl = PQfnumber(res, "initaggacl");
5540 i_initraggacl = PQfnumber(res, "initraggacl");
5542 for (i = 0; i < ntups; i++)
5544 agginfo[i].aggfn.dobj.objType = DO_AGG;
5545 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5546 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5547 AssignDumpId(&agginfo[i].aggfn.dobj);
5548 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5549 agginfo[i].aggfn.dobj.namespace =
5551 atooid(PQgetvalue(res, i, i_aggnamespace)));
5552 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5553 if (strlen(agginfo[i].aggfn.rolname) == 0)
5554 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5555 agginfo[i].aggfn.dobj.name);
5556 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5557 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
5558 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5559 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5560 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5561 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5562 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5563 if (agginfo[i].aggfn.nargs == 0)
5564 agginfo[i].aggfn.argtypes = NULL;
5567 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5568 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5569 agginfo[i].aggfn.argtypes,
5570 agginfo[i].aggfn.nargs);
5573 /* Decide whether we want to dump it */
5574 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5576 /* Do not try to dump ACL if no ACL exists. */
5577 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5578 PQgetisnull(res, i, i_initaggacl) &&
5579 PQgetisnull(res, i, i_initraggacl))
5580 agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5585 destroyPQExpBuffer(query);
5592 * read all the user-defined functions in the system catalogs and
5593 * return them in the FuncInfo* structure
5595 * numFuncs is set to the number of functions read in
5598 getFuncs(Archive *fout, int *numFuncs)
5600 DumpOptions *dopt = fout->dopt;
5604 PQExpBuffer query = createPQExpBuffer();
5621 * Find all interesting functions. This is a bit complicated:
5623 * 1. Always exclude aggregates; those are handled elsewhere.
5625 * 2. Always exclude functions that are internally dependent on something
5626 * else, since presumably those will be created as a result of creating
5627 * the something else. This currently acts only to suppress constructor
5628 * functions for range types (so we only need it in 9.2 and up). Note
5629 * this is OK only because the constructors don't have any dependencies
5630 * the range type doesn't have; otherwise we might not get creation
5633 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5634 * they're members of extensions and we are in binary-upgrade mode then
5635 * include them, since we want to dump extension members individually in
5636 * that mode. Also, if they are used by casts or transforms then we need
5637 * to gather the information about them, though they won't be dumped if
5638 * they are built-in. Also, in 9.6 and up, include functions in
5639 * pg_catalog if they have an ACL different from what's shown in
5642 if (fout->remoteVersion >= 90600)
5644 PQExpBuffer acl_subquery = createPQExpBuffer();
5645 PQExpBuffer racl_subquery = createPQExpBuffer();
5646 PQExpBuffer initacl_subquery = createPQExpBuffer();
5647 PQExpBuffer initracl_subquery = createPQExpBuffer();
5648 const char *not_agg_check;
5650 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5651 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5652 dopt->binary_upgrade);
5654 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5655 : "NOT p.proisagg");
5657 appendPQExpBuffer(query,
5658 "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5659 "p.pronargs, p.proargtypes, p.prorettype, "
5662 "%s AS initproacl, "
5663 "%s AS initrproacl, "
5665 "(%s p.proowner) AS rolname "
5667 "LEFT JOIN pg_init_privs pip ON "
5668 "(p.oid = pip.objoid "
5669 "AND pip.classoid = 'pg_proc'::regclass "
5670 "AND pip.objsubid = 0) "
5672 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5673 "WHERE classid = 'pg_proc'::regclass AND "
5674 "objid = p.oid AND deptype = 'i')"
5676 "\n pronamespace != "
5677 "(SELECT oid FROM pg_namespace "
5678 "WHERE nspname = 'pg_catalog')"
5679 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5680 "\n WHERE pg_cast.oid > %u "
5681 "\n AND p.oid = pg_cast.castfunc)"
5682 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5683 "\n WHERE pg_transform.oid > %u AND "
5684 "\n (p.oid = pg_transform.trffromsql"
5685 "\n OR p.oid = pg_transform.trftosql))",
5687 racl_subquery->data,
5688 initacl_subquery->data,
5689 initracl_subquery->data,
5693 g_last_builtin_oid);
5694 if (dopt->binary_upgrade)
5695 appendPQExpBufferStr(query,
5696 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5697 "classid = 'pg_proc'::regclass AND "
5698 "objid = p.oid AND "
5699 "refclassid = 'pg_extension'::regclass AND "
5701 appendPQExpBufferStr(query,
5702 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5703 appendPQExpBufferChar(query, ')');
5705 destroyPQExpBuffer(acl_subquery);
5706 destroyPQExpBuffer(racl_subquery);
5707 destroyPQExpBuffer(initacl_subquery);
5708 destroyPQExpBuffer(initracl_subquery);
5712 appendPQExpBuffer(query,
5713 "SELECT tableoid, oid, proname, prolang, "
5714 "pronargs, proargtypes, prorettype, proacl, "
5716 "NULL as initproacl, NULL AS initrproacl, "
5718 "(%s proowner) AS rolname "
5720 "WHERE NOT proisagg",
5722 if (fout->remoteVersion >= 90200)
5723 appendPQExpBufferStr(query,
5724 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5725 "WHERE classid = 'pg_proc'::regclass AND "
5726 "objid = p.oid AND deptype = 'i')");
5727 appendPQExpBuffer(query,
5729 "\n pronamespace != "
5730 "(SELECT oid FROM pg_namespace "
5731 "WHERE nspname = 'pg_catalog')"
5732 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5733 "\n WHERE pg_cast.oid > '%u'::oid"
5734 "\n AND p.oid = pg_cast.castfunc)",
5735 g_last_builtin_oid);
5737 if (fout->remoteVersion >= 90500)
5738 appendPQExpBuffer(query,
5739 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5740 "\n WHERE pg_transform.oid > '%u'::oid"
5741 "\n AND (p.oid = pg_transform.trffromsql"
5742 "\n OR p.oid = pg_transform.trftosql))",
5743 g_last_builtin_oid);
5745 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5746 appendPQExpBufferStr(query,
5747 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5748 "classid = 'pg_proc'::regclass AND "
5749 "objid = p.oid AND "
5750 "refclassid = 'pg_extension'::regclass AND "
5752 appendPQExpBufferChar(query, ')');
5755 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5757 ntups = PQntuples(res);
5761 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5763 i_tableoid = PQfnumber(res, "tableoid");
5764 i_oid = PQfnumber(res, "oid");
5765 i_proname = PQfnumber(res, "proname");
5766 i_pronamespace = PQfnumber(res, "pronamespace");
5767 i_rolname = PQfnumber(res, "rolname");
5768 i_prolang = PQfnumber(res, "prolang");
5769 i_pronargs = PQfnumber(res, "pronargs");
5770 i_proargtypes = PQfnumber(res, "proargtypes");
5771 i_prorettype = PQfnumber(res, "prorettype");
5772 i_proacl = PQfnumber(res, "proacl");
5773 i_rproacl = PQfnumber(res, "rproacl");
5774 i_initproacl = PQfnumber(res, "initproacl");
5775 i_initrproacl = PQfnumber(res, "initrproacl");
5777 for (i = 0; i < ntups; i++)
5779 finfo[i].dobj.objType = DO_FUNC;
5780 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5781 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5782 AssignDumpId(&finfo[i].dobj);
5783 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5784 finfo[i].dobj.namespace =
5786 atooid(PQgetvalue(res, i, i_pronamespace)));
5787 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5788 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5789 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5790 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5791 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5792 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5793 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5794 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5795 if (finfo[i].nargs == 0)
5796 finfo[i].argtypes = NULL;
5799 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5800 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5801 finfo[i].argtypes, finfo[i].nargs);
5804 /* Decide whether we want to dump it */
5805 selectDumpableObject(&(finfo[i].dobj), fout);
5807 /* Do not try to dump ACL if no ACL exists. */
5808 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5809 PQgetisnull(res, i, i_initproacl) &&
5810 PQgetisnull(res, i, i_initrproacl))
5811 finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5813 if (strlen(finfo[i].rolname) == 0)
5815 "WARNING: owner of function \"%s\" appears to be invalid\n",
5816 finfo[i].dobj.name);
5821 destroyPQExpBuffer(query);
5828 * read all the tables (no indexes)
5829 * in the system catalogs return them in the TableInfo* structure
5831 * numTables is set to the number of tables read in
5834 getTables(Archive *fout, int *numTables)
5836 DumpOptions *dopt = fout->dopt;
5840 PQExpBuffer query = createPQExpBuffer();
5853 int i_relhastriggers;
5857 int i_relforcerowsec;
5862 int i_toastfrozenxid;
5864 int i_relpersistence;
5865 int i_relispopulated;
5869 int i_reltablespace;
5872 int i_toastreloptions;
5875 int i_is_identity_sequence;
5882 * Find all the tables and table-like objects.
5884 * We include system catalogs, so that we can work if a user table is
5885 * defined to inherit from a system catalog (pretty weird, but...)
5887 * We ignore relations that are not ordinary tables, sequences, views,
5888 * materialized views, composite types, or foreign tables.
5890 * Composite-type table entries won't be dumped as such, but we have to
5891 * make a DumpableObject for them so that we can track dependencies of the
5892 * composite type (pg_depend entries for columns of the composite type
5893 * link to the pg_class entry not the pg_type entry).
5895 * Note: in this phase we should collect only a minimal amount of
5896 * information about each table, basically just enough to decide if it is
5897 * interesting. We must fetch all tables in this phase because otherwise
5898 * we cannot correctly identify inherited columns, owned sequences, etc.
5901 if (fout->remoteVersion >= 90600)
5903 char *partkeydef = "NULL";
5904 char *ispartition = "false";
5905 char *partbound = "NULL";
5907 PQExpBuffer acl_subquery = createPQExpBuffer();
5908 PQExpBuffer racl_subquery = createPQExpBuffer();
5909 PQExpBuffer initacl_subquery = createPQExpBuffer();
5910 PQExpBuffer initracl_subquery = createPQExpBuffer();
5912 PQExpBuffer attacl_subquery = createPQExpBuffer();
5913 PQExpBuffer attracl_subquery = createPQExpBuffer();
5914 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5915 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5918 * Collect the information about any partitioned tables, which were
5922 if (fout->remoteVersion >= 100000)
5924 partkeydef = "pg_get_partkeydef(c.oid)";
5925 ispartition = "c.relispartition";
5926 partbound = "pg_get_expr(c.relpartbound, c.oid)";
5930 * Left join to pick up dependency info linking sequences to their
5931 * owning column, if any (note this dependency is AUTO as of 8.2)
5933 * Left join to detect if any privileges are still as-set-at-init, in
5934 * which case we won't dump out ACL commands for those.
5937 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5938 initracl_subquery, "c.relacl", "c.relowner",
5939 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5940 " THEN 's' ELSE 'r' END::\"char\"",
5941 dopt->binary_upgrade);
5943 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5944 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5945 dopt->binary_upgrade);
5947 appendPQExpBuffer(query,
5948 "SELECT c.tableoid, c.oid, c.relname, "
5949 "%s AS relacl, %s as rrelacl, "
5950 "%s AS initrelacl, %s as initrrelacl, "
5951 "c.relkind, c.relnamespace, "
5952 "(%s c.relowner) AS rolname, "
5953 "c.relchecks, c.relhastriggers, "
5954 "c.relhasindex, c.relhasrules, c.relhasoids, "
5955 "c.relrowsecurity, c.relforcerowsecurity, "
5956 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5957 "tc.relfrozenxid AS tfrozenxid, "
5958 "tc.relminmxid AS tminmxid, "
5959 "c.relpersistence, c.relispopulated, "
5960 "c.relreplident, c.relpages, "
5961 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5962 "d.refobjid AS owning_tab, "
5963 "d.refobjsubid AS owning_col, "
5964 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5965 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5966 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5967 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5968 "tc.reloptions AS toast_reloptions, "
5969 "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, "
5970 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5971 "(c.oid = pip.objoid "
5972 "AND pip.classoid = 'pg_class'::regclass "
5973 "AND pip.objsubid = at.attnum)"
5974 "WHERE at.attrelid = c.oid AND ("
5976 "OR %s IS NOT NULL "
5977 "OR %s IS NOT NULL "
5981 "%s AS partkeydef, "
5982 "%s AS ispartition, "
5985 "LEFT JOIN pg_depend d ON "
5986 "(c.relkind = '%c' AND "
5987 "d.classid = c.tableoid AND d.objid = c.oid AND "
5988 "d.objsubid = 0 AND "
5989 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5990 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5991 "LEFT JOIN pg_init_privs pip ON "
5992 "(c.oid = pip.objoid "
5993 "AND pip.classoid = 'pg_class'::regclass "
5994 "AND pip.objsubid = 0) "
5995 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5998 racl_subquery->data,
5999 initacl_subquery->data,
6000 initracl_subquery->data,
6003 attacl_subquery->data,
6004 attracl_subquery->data,
6005 attinitacl_subquery->data,
6006 attinitracl_subquery->data,
6011 RELKIND_RELATION, RELKIND_SEQUENCE,
6012 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6013 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
6014 RELKIND_PARTITIONED_TABLE);
6016 destroyPQExpBuffer(acl_subquery);
6017 destroyPQExpBuffer(racl_subquery);
6018 destroyPQExpBuffer(initacl_subquery);
6019 destroyPQExpBuffer(initracl_subquery);
6021 destroyPQExpBuffer(attacl_subquery);
6022 destroyPQExpBuffer(attracl_subquery);
6023 destroyPQExpBuffer(attinitacl_subquery);
6024 destroyPQExpBuffer(attinitracl_subquery);
6026 else if (fout->remoteVersion >= 90500)
6029 * Left join to pick up dependency info linking sequences to their
6030 * owning column, if any (note this dependency is AUTO as of 8.2)
6032 appendPQExpBuffer(query,
6033 "SELECT c.tableoid, c.oid, c.relname, "
6034 "c.relacl, NULL as rrelacl, "
6035 "NULL AS initrelacl, NULL AS initrrelacl, "
6038 "(%s c.relowner) AS rolname, "
6039 "c.relchecks, c.relhastriggers, "
6040 "c.relhasindex, c.relhasrules, c.relhasoids, "
6041 "c.relrowsecurity, c.relforcerowsecurity, "
6042 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6043 "tc.relfrozenxid AS tfrozenxid, "
6044 "tc.relminmxid AS tminmxid, "
6045 "c.relpersistence, c.relispopulated, "
6046 "c.relreplident, c.relpages, "
6047 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6048 "d.refobjid AS owning_tab, "
6049 "d.refobjsubid AS owning_col, "
6050 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6051 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6052 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6053 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6054 "tc.reloptions AS toast_reloptions, "
6055 "NULL AS changed_acl, "
6056 "NULL AS partkeydef, "
6057 "false AS ispartition, "
6058 "NULL AS partbound "
6060 "LEFT JOIN pg_depend d ON "
6061 "(c.relkind = '%c' AND "
6062 "d.classid = c.tableoid AND d.objid = c.oid AND "
6063 "d.objsubid = 0 AND "
6064 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6065 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6066 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6070 RELKIND_RELATION, RELKIND_SEQUENCE,
6071 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6072 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6074 else if (fout->remoteVersion >= 90400)
6077 * Left join to pick up dependency info linking sequences to their
6078 * owning column, if any (note this dependency is AUTO as of 8.2)
6080 appendPQExpBuffer(query,
6081 "SELECT c.tableoid, c.oid, c.relname, "
6082 "c.relacl, NULL as rrelacl, "
6083 "NULL AS initrelacl, NULL AS initrrelacl, "
6086 "(%s c.relowner) AS rolname, "
6087 "c.relchecks, c.relhastriggers, "
6088 "c.relhasindex, c.relhasrules, c.relhasoids, "
6089 "'f'::bool AS relrowsecurity, "
6090 "'f'::bool AS relforcerowsecurity, "
6091 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6092 "tc.relfrozenxid AS tfrozenxid, "
6093 "tc.relminmxid AS tminmxid, "
6094 "c.relpersistence, c.relispopulated, "
6095 "c.relreplident, c.relpages, "
6096 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6097 "d.refobjid AS owning_tab, "
6098 "d.refobjsubid AS owning_col, "
6099 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6100 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6101 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6102 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6103 "tc.reloptions AS toast_reloptions, "
6104 "NULL AS changed_acl, "
6105 "NULL AS partkeydef, "
6106 "false AS ispartition, "
6107 "NULL AS partbound "
6109 "LEFT JOIN pg_depend d ON "
6110 "(c.relkind = '%c' AND "
6111 "d.classid = c.tableoid AND d.objid = c.oid AND "
6112 "d.objsubid = 0 AND "
6113 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6114 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6115 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6119 RELKIND_RELATION, RELKIND_SEQUENCE,
6120 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6121 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6123 else if (fout->remoteVersion >= 90300)
6126 * Left join to pick up dependency info linking sequences to their
6127 * owning column, if any (note this dependency is AUTO as of 8.2)
6129 appendPQExpBuffer(query,
6130 "SELECT c.tableoid, c.oid, c.relname, "
6131 "c.relacl, NULL as rrelacl, "
6132 "NULL AS initrelacl, NULL AS initrrelacl, "
6135 "(%s c.relowner) AS rolname, "
6136 "c.relchecks, c.relhastriggers, "
6137 "c.relhasindex, c.relhasrules, c.relhasoids, "
6138 "'f'::bool AS relrowsecurity, "
6139 "'f'::bool AS relforcerowsecurity, "
6140 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6141 "tc.relfrozenxid AS tfrozenxid, "
6142 "tc.relminmxid AS tminmxid, "
6143 "c.relpersistence, c.relispopulated, "
6144 "'d' AS relreplident, c.relpages, "
6145 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6146 "d.refobjid AS owning_tab, "
6147 "d.refobjsubid AS owning_col, "
6148 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6149 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6150 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6151 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6152 "tc.reloptions AS toast_reloptions, "
6153 "NULL AS changed_acl, "
6154 "NULL AS partkeydef, "
6155 "false AS ispartition, "
6156 "NULL AS partbound "
6158 "LEFT JOIN pg_depend d ON "
6159 "(c.relkind = '%c' AND "
6160 "d.classid = c.tableoid AND d.objid = c.oid AND "
6161 "d.objsubid = 0 AND "
6162 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6163 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6164 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6168 RELKIND_RELATION, RELKIND_SEQUENCE,
6169 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6170 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6172 else if (fout->remoteVersion >= 90100)
6175 * Left join to pick up dependency info linking sequences to their
6176 * owning column, if any (note this dependency is AUTO as of 8.2)
6178 appendPQExpBuffer(query,
6179 "SELECT c.tableoid, c.oid, c.relname, "
6180 "c.relacl, NULL as rrelacl, "
6181 "NULL AS initrelacl, NULL AS initrrelacl, "
6184 "(%s c.relowner) AS rolname, "
6185 "c.relchecks, c.relhastriggers, "
6186 "c.relhasindex, c.relhasrules, c.relhasoids, "
6187 "'f'::bool AS relrowsecurity, "
6188 "'f'::bool AS relforcerowsecurity, "
6189 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6190 "tc.relfrozenxid AS tfrozenxid, "
6192 "c.relpersistence, 't' as relispopulated, "
6193 "'d' AS relreplident, c.relpages, "
6194 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6195 "d.refobjid AS owning_tab, "
6196 "d.refobjsubid AS owning_col, "
6197 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6198 "c.reloptions AS reloptions, "
6199 "tc.reloptions AS toast_reloptions, "
6200 "NULL AS changed_acl, "
6201 "NULL AS partkeydef, "
6202 "false AS ispartition, "
6203 "NULL AS partbound "
6205 "LEFT JOIN pg_depend d ON "
6206 "(c.relkind = '%c' AND "
6207 "d.classid = c.tableoid AND d.objid = c.oid AND "
6208 "d.objsubid = 0 AND "
6209 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6210 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6211 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6215 RELKIND_RELATION, RELKIND_SEQUENCE,
6216 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6217 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6219 else if (fout->remoteVersion >= 90000)
6222 * Left join to pick up dependency info linking sequences to their
6223 * owning column, if any (note this dependency is AUTO as of 8.2)
6225 appendPQExpBuffer(query,
6226 "SELECT c.tableoid, c.oid, c.relname, "
6227 "c.relacl, NULL as rrelacl, "
6228 "NULL AS initrelacl, NULL AS initrrelacl, "
6231 "(%s c.relowner) AS rolname, "
6232 "c.relchecks, c.relhastriggers, "
6233 "c.relhasindex, c.relhasrules, c.relhasoids, "
6234 "'f'::bool AS relrowsecurity, "
6235 "'f'::bool AS relforcerowsecurity, "
6236 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6237 "tc.relfrozenxid AS tfrozenxid, "
6239 "'p' AS relpersistence, 't' as relispopulated, "
6240 "'d' AS relreplident, c.relpages, "
6241 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6242 "d.refobjid AS owning_tab, "
6243 "d.refobjsubid AS owning_col, "
6244 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6245 "c.reloptions AS reloptions, "
6246 "tc.reloptions AS toast_reloptions, "
6247 "NULL AS changed_acl, "
6248 "NULL AS partkeydef, "
6249 "false AS ispartition, "
6250 "NULL AS partbound "
6252 "LEFT JOIN pg_depend d ON "
6253 "(c.relkind = '%c' AND "
6254 "d.classid = c.tableoid AND d.objid = c.oid AND "
6255 "d.objsubid = 0 AND "
6256 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6257 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6258 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6262 RELKIND_RELATION, RELKIND_SEQUENCE,
6263 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6265 else if (fout->remoteVersion >= 80400)
6268 * Left join to pick up dependency info linking sequences to their
6269 * owning column, if any (note this dependency is AUTO as of 8.2)
6271 appendPQExpBuffer(query,
6272 "SELECT c.tableoid, c.oid, c.relname, "
6273 "c.relacl, NULL as rrelacl, "
6274 "NULL AS initrelacl, NULL AS initrrelacl, "
6277 "(%s c.relowner) AS rolname, "
6278 "c.relchecks, c.relhastriggers, "
6279 "c.relhasindex, c.relhasrules, c.relhasoids, "
6280 "'f'::bool AS relrowsecurity, "
6281 "'f'::bool AS relforcerowsecurity, "
6282 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6283 "tc.relfrozenxid AS tfrozenxid, "
6285 "'p' AS relpersistence, 't' as relispopulated, "
6286 "'d' AS relreplident, c.relpages, "
6287 "NULL AS reloftype, "
6288 "d.refobjid AS owning_tab, "
6289 "d.refobjsubid AS owning_col, "
6290 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6291 "c.reloptions AS reloptions, "
6292 "tc.reloptions AS toast_reloptions, "
6293 "NULL AS changed_acl, "
6294 "NULL AS partkeydef, "
6295 "false AS ispartition, "
6296 "NULL AS partbound "
6298 "LEFT JOIN pg_depend d ON "
6299 "(c.relkind = '%c' AND "
6300 "d.classid = c.tableoid AND d.objid = c.oid AND "
6301 "d.objsubid = 0 AND "
6302 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6303 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6304 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6308 RELKIND_RELATION, RELKIND_SEQUENCE,
6309 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6311 else if (fout->remoteVersion >= 80200)
6314 * Left join to pick up dependency info linking sequences to their
6315 * owning column, if any (note this dependency is AUTO as of 8.2)
6317 appendPQExpBuffer(query,
6318 "SELECT c.tableoid, c.oid, c.relname, "
6319 "c.relacl, NULL as rrelacl, "
6320 "NULL AS initrelacl, NULL AS initrrelacl, "
6323 "(%s c.relowner) AS rolname, "
6324 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6325 "c.relhasindex, c.relhasrules, c.relhasoids, "
6326 "'f'::bool AS relrowsecurity, "
6327 "'f'::bool AS relforcerowsecurity, "
6328 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6329 "tc.relfrozenxid AS tfrozenxid, "
6331 "'p' AS relpersistence, 't' as relispopulated, "
6332 "'d' AS relreplident, c.relpages, "
6333 "NULL AS reloftype, "
6334 "d.refobjid AS owning_tab, "
6335 "d.refobjsubid AS owning_col, "
6336 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6337 "c.reloptions AS reloptions, "
6338 "NULL AS toast_reloptions, "
6339 "NULL AS changed_acl, "
6340 "NULL AS partkeydef, "
6341 "false AS ispartition, "
6342 "NULL AS partbound "
6344 "LEFT JOIN pg_depend d ON "
6345 "(c.relkind = '%c' AND "
6346 "d.classid = c.tableoid AND d.objid = c.oid AND "
6347 "d.objsubid = 0 AND "
6348 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6349 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6350 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6354 RELKIND_RELATION, RELKIND_SEQUENCE,
6355 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6360 * Left join to pick up dependency info linking sequences to their
6361 * owning column, if any
6363 appendPQExpBuffer(query,
6364 "SELECT c.tableoid, c.oid, relname, "
6365 "relacl, NULL as rrelacl, "
6366 "NULL AS initrelacl, NULL AS initrrelacl, "
6367 "relkind, relnamespace, "
6368 "(%s relowner) AS rolname, "
6369 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6370 "relhasindex, relhasrules, relhasoids, "
6371 "'f'::bool AS relrowsecurity, "
6372 "'f'::bool AS relforcerowsecurity, "
6373 "0 AS relfrozenxid, 0 AS relminmxid,"
6375 "0 AS tfrozenxid, 0 AS tminmxid,"
6376 "'p' AS relpersistence, 't' as relispopulated, "
6377 "'d' AS relreplident, relpages, "
6378 "NULL AS reloftype, "
6379 "d.refobjid AS owning_tab, "
6380 "d.refobjsubid AS owning_col, "
6381 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6382 "NULL AS reloptions, "
6383 "NULL AS toast_reloptions, "
6384 "NULL AS changed_acl, "
6385 "NULL AS partkeydef, "
6386 "false AS ispartition, "
6387 "NULL AS partbound "
6389 "LEFT JOIN pg_depend d ON "
6390 "(c.relkind = '%c' AND "
6391 "d.classid = c.tableoid AND d.objid = c.oid AND "
6392 "d.objsubid = 0 AND "
6393 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6394 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6398 RELKIND_RELATION, RELKIND_SEQUENCE,
6399 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6402 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6404 ntups = PQntuples(res);
6409 * Extract data from result and lock dumpable tables. We do the locking
6410 * before anything else, to minimize the window wherein a table could
6411 * disappear under us.
6413 * Note that we have to save info about all tables here, even when dumping
6414 * only one, because we don't yet know which tables might be inheritance
6415 * ancestors of the target table.
6417 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6419 i_reltableoid = PQfnumber(res, "tableoid");
6420 i_reloid = PQfnumber(res, "oid");
6421 i_relname = PQfnumber(res, "relname");
6422 i_relnamespace = PQfnumber(res, "relnamespace");
6423 i_relacl = PQfnumber(res, "relacl");
6424 i_rrelacl = PQfnumber(res, "rrelacl");
6425 i_initrelacl = PQfnumber(res, "initrelacl");
6426 i_initrrelacl = PQfnumber(res, "initrrelacl");
6427 i_relkind = PQfnumber(res, "relkind");
6428 i_rolname = PQfnumber(res, "rolname");
6429 i_relchecks = PQfnumber(res, "relchecks");
6430 i_relhastriggers = PQfnumber(res, "relhastriggers");
6431 i_relhasindex = PQfnumber(res, "relhasindex");
6432 i_relhasrules = PQfnumber(res, "relhasrules");
6433 i_relrowsec = PQfnumber(res, "relrowsecurity");
6434 i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6435 i_relhasoids = PQfnumber(res, "relhasoids");
6436 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6437 i_relminmxid = PQfnumber(res, "relminmxid");
6438 i_toastoid = PQfnumber(res, "toid");
6439 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6440 i_toastminmxid = PQfnumber(res, "tminmxid");
6441 i_relpersistence = PQfnumber(res, "relpersistence");
6442 i_relispopulated = PQfnumber(res, "relispopulated");
6443 i_relreplident = PQfnumber(res, "relreplident");
6444 i_relpages = PQfnumber(res, "relpages");
6445 i_owning_tab = PQfnumber(res, "owning_tab");
6446 i_owning_col = PQfnumber(res, "owning_col");
6447 i_reltablespace = PQfnumber(res, "reltablespace");
6448 i_reloptions = PQfnumber(res, "reloptions");
6449 i_checkoption = PQfnumber(res, "checkoption");
6450 i_toastreloptions = PQfnumber(res, "toast_reloptions");
6451 i_reloftype = PQfnumber(res, "reloftype");
6452 i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6453 i_changed_acl = PQfnumber(res, "changed_acl");
6454 i_partkeydef = PQfnumber(res, "partkeydef");
6455 i_ispartition = PQfnumber(res, "ispartition");
6456 i_partbound = PQfnumber(res, "partbound");
6458 if (dopt->lockWaitTimeout)
6461 * Arrange to fail instead of waiting forever for a table lock.
6463 * NB: this coding assumes that the only queries issued within the
6464 * following loop are LOCK TABLEs; else the timeout may be undesirably
6465 * applied to other things too.
6467 resetPQExpBuffer(query);
6468 appendPQExpBufferStr(query, "SET statement_timeout = ");
6469 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6470 ExecuteSqlStatement(fout, query->data);
6473 for (i = 0; i < ntups; i++)
6475 tblinfo[i].dobj.objType = DO_TABLE;
6476 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6477 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6478 AssignDumpId(&tblinfo[i].dobj);
6479 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6480 tblinfo[i].dobj.namespace =
6482 atooid(PQgetvalue(res, i, i_relnamespace)));
6483 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6484 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6485 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6486 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6487 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6488 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6489 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6490 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6491 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6492 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6493 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6494 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6495 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6496 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6497 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6498 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6499 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6500 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6501 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6502 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6503 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6504 if (PQgetisnull(res, i, i_reloftype))
6505 tblinfo[i].reloftype = NULL;
6507 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6508 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6509 if (PQgetisnull(res, i, i_owning_tab))
6511 tblinfo[i].owning_tab = InvalidOid;
6512 tblinfo[i].owning_col = 0;
6516 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6517 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6519 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6520 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6521 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6522 tblinfo[i].checkoption = NULL;
6524 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6525 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6527 /* other fields were zeroed above */
6530 * Decide whether we want to dump this table.
6532 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6533 tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6535 selectDumpableTable(&tblinfo[i], fout);
6538 * If the table-level and all column-level ACLs for this table are
6539 * unchanged, then we don't need to worry about including the ACLs for
6540 * this table. If any column-level ACLs have been changed, the
6541 * 'changed_acl' column from the query will indicate that.
6543 * This can result in a significant performance improvement in cases
6544 * where we are only looking to dump out the ACL (eg: pg_catalog).
6546 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6547 PQgetisnull(res, i, i_initrelacl) &&
6548 PQgetisnull(res, i, i_initrrelacl) &&
6549 strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6550 tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6552 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6553 tblinfo[i].dummy_view = false; /* might get set during sort */
6554 tblinfo[i].postponed_def = false; /* might get set during sort */
6556 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6557 strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6559 /* Partition key string or NULL */
6560 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6561 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6562 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6565 * Read-lock target tables to make sure they aren't DROPPED or altered
6566 * in schema before we get around to dumping them.
6568 * Note that we don't explicitly lock parents of the target tables; we
6569 * assume our lock on the child is enough to prevent schema
6570 * alterations to parent tables.
6572 * NOTE: it'd be kinda nice to lock other relations too, not only
6573 * plain or partitioned tables, but the backend doesn't presently
6576 * We only need to lock the table for certain components; see
6579 if (tblinfo[i].dobj.dump &&
6580 (tblinfo[i].relkind == RELKIND_RELATION ||
6581 tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6582 (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6584 resetPQExpBuffer(query);
6585 appendPQExpBuffer(query,
6586 "LOCK TABLE %s IN ACCESS SHARE MODE",
6587 fmtQualifiedDumpable(&tblinfo[i]));
6588 ExecuteSqlStatement(fout, query->data);
6591 /* Emit notice if join for owner failed */
6592 if (strlen(tblinfo[i].rolname) == 0)
6593 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6594 tblinfo[i].dobj.name);
6597 if (dopt->lockWaitTimeout)
6599 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6604 destroyPQExpBuffer(query);
6611 * identify owned sequences and mark them as dumpable if owning table is
6613 * We used to do this in getTables(), but it's better to do it after the
6614 * index used by findTableByOid() has been set up.
6617 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6622 * Force sequences that are "owned" by table columns to be dumped whenever
6623 * their owning table is being dumped.
6625 for (i = 0; i < numTables; i++)
6627 TableInfo *seqinfo = &tblinfo[i];
6628 TableInfo *owning_tab;
6630 if (!OidIsValid(seqinfo->owning_tab))
6631 continue; /* not an owned sequence */
6633 owning_tab = findTableByOid(seqinfo->owning_tab);
6634 if (owning_tab == NULL)
6635 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6636 seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6639 * We need to dump the components that are being dumped for the table
6640 * and any components which the sequence is explicitly marked with.
6642 * We can't simply use the set of components which are being dumped
6643 * for the table as the table might be in an extension (and only the
6644 * non-extension components, eg: ACLs if changed, security labels, and
6645 * policies, are being dumped) while the sequence is not (and
6646 * therefore the definition and other components should also be
6649 * If the sequence is part of the extension then it should be properly
6650 * marked by checkExtensionMembership() and this will be a no-op as
6651 * the table will be equivalently marked.
6653 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6655 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6656 seqinfo->interesting = true;
6662 * read all the inheritance information
6663 * from the system catalogs return them in the InhInfo* structure
6665 * numInherits is set to the number of pairs read in
6668 getInherits(Archive *fout, int *numInherits)
6673 PQExpBuffer query = createPQExpBuffer();
6680 * Find all the inheritance information, excluding implicit inheritance
6681 * via partitioning. We handle that case using getPartitions(), because
6682 * we want more information about partitions than just the parent-child
6685 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6687 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6689 ntups = PQntuples(res);
6691 *numInherits = ntups;
6693 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6695 i_inhrelid = PQfnumber(res, "inhrelid");
6696 i_inhparent = PQfnumber(res, "inhparent");
6698 for (i = 0; i < ntups; i++)
6700 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6701 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6706 destroyPQExpBuffer(query);
6713 * get information about every index on a dumpable table
6715 * Note: index data is not returned directly to the caller, but it
6716 * does get entered into the DumpableObject tables.
6719 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6723 PQExpBuffer query = createPQExpBuffer();
6726 ConstraintInfo *constrinfo;
6749 for (i = 0; i < numTables; i++)
6751 TableInfo *tbinfo = &tblinfo[i];
6753 if (!tbinfo->hasindex)
6757 * Ignore indexes of tables whose definitions are not to be dumped.
6759 * We also need indexes on partitioned tables which have partitions to
6760 * be dumped, in order to dump the indexes on the partitions.
6762 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6763 !tbinfo->interesting)
6767 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6768 tbinfo->dobj.namespace->dobj.name,
6772 * The point of the messy-looking outer join is to find a constraint
6773 * that is related by an internal dependency link to the index. If we
6774 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6775 * assume an index won't have more than one internal dependency.
6777 * As of 9.0 we don't need to look at pg_depend but can check for a
6778 * match to pg_constraint.conindid. The check on conrelid is
6779 * redundant but useful because that column is indexed while conindid
6782 resetPQExpBuffer(query);
6783 if (fout->remoteVersion >= 110000)
6785 appendPQExpBuffer(query,
6786 "SELECT t.tableoid, t.oid, "
6787 "t.relname AS indexname, "
6788 "inh.inhparent AS parentidx, "
6789 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6790 "i.indnkeyatts AS indnkeyatts, "
6791 "i.indnatts AS indnatts, "
6792 "i.indkey, i.indisclustered, "
6793 "i.indisreplident, t.relpages, "
6794 "c.contype, c.conname, "
6795 "c.condeferrable, c.condeferred, "
6796 "c.tableoid AS contableoid, "
6798 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6799 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6800 "t.reloptions AS indreloptions "
6801 "FROM pg_catalog.pg_index i "
6802 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6803 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6804 "LEFT JOIN pg_catalog.pg_constraint c "
6805 "ON (i.indrelid = c.conrelid AND "
6806 "i.indexrelid = c.conindid AND "
6807 "c.contype IN ('p','u','x')) "
6808 "LEFT JOIN pg_catalog.pg_inherits inh "
6809 "ON (inh.inhrelid = indexrelid) "
6810 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6811 "AND (i.indisvalid OR t2.relkind = 'p') "
6813 "ORDER BY indexname",
6814 tbinfo->dobj.catId.oid);
6816 else if (fout->remoteVersion >= 90400)
6819 * the test on indisready is necessary in 9.2, and harmless in
6820 * earlier/later versions
6822 appendPQExpBuffer(query,
6823 "SELECT t.tableoid, t.oid, "
6824 "t.relname AS indexname, "
6826 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6827 "i.indnatts AS indnkeyatts, "
6828 "i.indnatts AS indnatts, "
6829 "i.indkey, i.indisclustered, "
6830 "i.indisreplident, t.relpages, "
6831 "c.contype, c.conname, "
6832 "c.condeferrable, c.condeferred, "
6833 "c.tableoid AS contableoid, "
6835 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6836 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6837 "t.reloptions AS indreloptions "
6838 "FROM pg_catalog.pg_index i "
6839 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6840 "LEFT JOIN pg_catalog.pg_constraint c "
6841 "ON (i.indrelid = c.conrelid AND "
6842 "i.indexrelid = c.conindid AND "
6843 "c.contype IN ('p','u','x')) "
6844 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6845 "AND i.indisvalid AND i.indisready "
6846 "ORDER BY indexname",
6847 tbinfo->dobj.catId.oid);
6849 else if (fout->remoteVersion >= 90000)
6852 * the test on indisready is necessary in 9.2, and harmless in
6853 * earlier/later versions
6855 appendPQExpBuffer(query,
6856 "SELECT t.tableoid, t.oid, "
6857 "t.relname AS indexname, "
6859 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6860 "i.indnatts AS indnkeyatts, "
6861 "i.indnatts AS indnatts, "
6862 "i.indkey, i.indisclustered, "
6863 "false AS indisreplident, t.relpages, "
6864 "c.contype, c.conname, "
6865 "c.condeferrable, c.condeferred, "
6866 "c.tableoid AS contableoid, "
6868 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6869 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6870 "t.reloptions AS indreloptions "
6871 "FROM pg_catalog.pg_index i "
6872 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6873 "LEFT JOIN pg_catalog.pg_constraint c "
6874 "ON (i.indrelid = c.conrelid AND "
6875 "i.indexrelid = c.conindid AND "
6876 "c.contype IN ('p','u','x')) "
6877 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6878 "AND i.indisvalid AND i.indisready "
6879 "ORDER BY indexname",
6880 tbinfo->dobj.catId.oid);
6882 else if (fout->remoteVersion >= 80200)
6884 appendPQExpBuffer(query,
6885 "SELECT t.tableoid, t.oid, "
6886 "t.relname AS indexname, "
6888 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6889 "i.indnatts AS indnkeyatts, "
6890 "i.indnatts AS indnatts, "
6891 "i.indkey, i.indisclustered, "
6892 "false AS indisreplident, t.relpages, "
6893 "c.contype, c.conname, "
6894 "c.condeferrable, c.condeferred, "
6895 "c.tableoid AS contableoid, "
6898 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6899 "t.reloptions AS indreloptions "
6900 "FROM pg_catalog.pg_index i "
6901 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6902 "LEFT JOIN pg_catalog.pg_depend d "
6903 "ON (d.classid = t.tableoid "
6904 "AND d.objid = t.oid "
6905 "AND d.deptype = 'i') "
6906 "LEFT JOIN pg_catalog.pg_constraint c "
6907 "ON (d.refclassid = c.tableoid "
6908 "AND d.refobjid = c.oid) "
6909 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6911 "ORDER BY indexname",
6912 tbinfo->dobj.catId.oid);
6916 appendPQExpBuffer(query,
6917 "SELECT t.tableoid, t.oid, "
6918 "t.relname AS indexname, "
6920 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6921 "t.relnatts AS indnkeyatts, "
6922 "t.relnatts AS indnatts, "
6923 "i.indkey, i.indisclustered, "
6924 "false AS indisreplident, t.relpages, "
6925 "c.contype, c.conname, "
6926 "c.condeferrable, c.condeferred, "
6927 "c.tableoid AS contableoid, "
6930 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6931 "null AS indreloptions "
6932 "FROM pg_catalog.pg_index i "
6933 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6934 "LEFT JOIN pg_catalog.pg_depend d "
6935 "ON (d.classid = t.tableoid "
6936 "AND d.objid = t.oid "
6937 "AND d.deptype = 'i') "
6938 "LEFT JOIN pg_catalog.pg_constraint c "
6939 "ON (d.refclassid = c.tableoid "
6940 "AND d.refobjid = c.oid) "
6941 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6942 "ORDER BY indexname",
6943 tbinfo->dobj.catId.oid);
6946 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6948 ntups = PQntuples(res);
6950 i_tableoid = PQfnumber(res, "tableoid");
6951 i_oid = PQfnumber(res, "oid");
6952 i_indexname = PQfnumber(res, "indexname");
6953 i_parentidx = PQfnumber(res, "parentidx");
6954 i_indexdef = PQfnumber(res, "indexdef");
6955 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
6956 i_indnatts = PQfnumber(res, "indnatts");
6957 i_indkey = PQfnumber(res, "indkey");
6958 i_indisclustered = PQfnumber(res, "indisclustered");
6959 i_indisreplident = PQfnumber(res, "indisreplident");
6960 i_relpages = PQfnumber(res, "relpages");
6961 i_contype = PQfnumber(res, "contype");
6962 i_conname = PQfnumber(res, "conname");
6963 i_condeferrable = PQfnumber(res, "condeferrable");
6964 i_condeferred = PQfnumber(res, "condeferred");
6965 i_contableoid = PQfnumber(res, "contableoid");
6966 i_conoid = PQfnumber(res, "conoid");
6967 i_condef = PQfnumber(res, "condef");
6968 i_tablespace = PQfnumber(res, "tablespace");
6969 i_indreloptions = PQfnumber(res, "indreloptions");
6971 tbinfo->indexes = indxinfo =
6972 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6973 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6974 tbinfo->numIndexes = ntups;
6976 for (j = 0; j < ntups; j++)
6980 indxinfo[j].dobj.objType = DO_INDEX;
6981 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6982 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6983 AssignDumpId(&indxinfo[j].dobj);
6984 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6985 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6986 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6987 indxinfo[j].indextable = tbinfo;
6988 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6989 indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
6990 indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
6991 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6992 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6993 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
6994 parseOidArray(PQgetvalue(res, j, i_indkey),
6995 indxinfo[j].indkeys, indxinfo[j].indnattrs);
6996 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6997 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6998 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6999 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
7000 contype = *(PQgetvalue(res, j, i_contype));
7002 if (contype == 'p' || contype == 'u' || contype == 'x')
7005 * If we found a constraint matching the index, create an
7008 constrinfo[j].dobj.objType = DO_CONSTRAINT;
7009 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7010 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7011 AssignDumpId(&constrinfo[j].dobj);
7012 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
7013 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7014 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7015 constrinfo[j].contable = tbinfo;
7016 constrinfo[j].condomain = NULL;
7017 constrinfo[j].contype = contype;
7019 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7021 constrinfo[j].condef = NULL;
7022 constrinfo[j].confrelid = InvalidOid;
7023 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7024 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7025 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7026 constrinfo[j].conislocal = true;
7027 constrinfo[j].separate = true;
7029 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7033 /* Plain secondary index */
7034 indxinfo[j].indexconstraint = 0;
7041 destroyPQExpBuffer(query);
7045 * getExtendedStatistics
7046 * get information about extended-statistics objects.
7048 * Note: extended statistics data is not returned directly to the caller, but
7049 * it does get entered into the DumpableObject tables.
7052 getExtendedStatistics(Archive *fout)
7056 StatsExtInfo *statsextinfo;
7065 /* Extended statistics were new in v10 */
7066 if (fout->remoteVersion < 100000)
7069 query = createPQExpBuffer();
7071 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7072 "stxnamespace, (%s stxowner) AS rolname "
7073 "FROM pg_catalog.pg_statistic_ext",
7076 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7078 ntups = PQntuples(res);
7080 i_tableoid = PQfnumber(res, "tableoid");
7081 i_oid = PQfnumber(res, "oid");
7082 i_stxname = PQfnumber(res, "stxname");
7083 i_stxnamespace = PQfnumber(res, "stxnamespace");
7084 i_rolname = PQfnumber(res, "rolname");
7086 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7088 for (i = 0; i < ntups; i++)
7090 statsextinfo[i].dobj.objType = DO_STATSEXT;
7091 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7092 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7093 AssignDumpId(&statsextinfo[i].dobj);
7094 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7095 statsextinfo[i].dobj.namespace =
7097 atooid(PQgetvalue(res, i, i_stxnamespace)));
7098 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7100 /* Decide whether we want to dump it */
7101 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7103 /* Stats objects do not currently have ACLs. */
7104 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7108 destroyPQExpBuffer(query);
7114 * Get info about constraints on dumpable tables.
7116 * Currently handles foreign keys only.
7117 * Unique and primary key constraints are handled with indexes,
7118 * while check constraints are processed in getTableAttrs().
7121 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7125 ConstraintInfo *constrinfo;
7135 query = createPQExpBuffer();
7137 for (i = 0; i < numTables; i++)
7139 TableInfo *tbinfo = &tblinfo[i];
7142 * For partitioned tables, foreign keys have no triggers so they must
7143 * be included anyway in case some foreign keys are defined.
7145 if ((!tbinfo->hastriggers &&
7146 tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7147 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7151 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7152 tbinfo->dobj.namespace->dobj.name,
7155 resetPQExpBuffer(query);
7156 if (fout->remoteVersion >= 110000)
7157 appendPQExpBuffer(query,
7158 "SELECT tableoid, oid, conname, confrelid, "
7159 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7160 "FROM pg_catalog.pg_constraint "
7161 "WHERE conrelid = '%u'::pg_catalog.oid "
7162 "AND conparentid = 0 "
7163 "AND contype = 'f'",
7164 tbinfo->dobj.catId.oid);
7166 appendPQExpBuffer(query,
7167 "SELECT tableoid, oid, conname, confrelid, "
7168 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7169 "FROM pg_catalog.pg_constraint "
7170 "WHERE conrelid = '%u'::pg_catalog.oid "
7171 "AND contype = 'f'",
7172 tbinfo->dobj.catId.oid);
7173 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7175 ntups = PQntuples(res);
7177 i_contableoid = PQfnumber(res, "tableoid");
7178 i_conoid = PQfnumber(res, "oid");
7179 i_conname = PQfnumber(res, "conname");
7180 i_confrelid = PQfnumber(res, "confrelid");
7181 i_condef = PQfnumber(res, "condef");
7183 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7185 for (j = 0; j < ntups; j++)
7187 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7188 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7189 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7190 AssignDumpId(&constrinfo[j].dobj);
7191 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7192 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7193 constrinfo[j].contable = tbinfo;
7194 constrinfo[j].condomain = NULL;
7195 constrinfo[j].contype = 'f';
7196 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7197 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7198 constrinfo[j].conindex = 0;
7199 constrinfo[j].condeferrable = false;
7200 constrinfo[j].condeferred = false;
7201 constrinfo[j].conislocal = true;
7202 constrinfo[j].separate = true;
7208 destroyPQExpBuffer(query);
7212 * getDomainConstraints
7214 * Get info about constraints on a domain.
7217 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7220 ConstraintInfo *constrinfo;
7229 query = createPQExpBuffer();
7231 if (fout->remoteVersion >= 90100)
7232 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7233 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7235 "FROM pg_catalog.pg_constraint "
7236 "WHERE contypid = '%u'::pg_catalog.oid "
7238 tyinfo->dobj.catId.oid);
7241 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7242 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7243 "true as convalidated "
7244 "FROM pg_catalog.pg_constraint "
7245 "WHERE contypid = '%u'::pg_catalog.oid "
7247 tyinfo->dobj.catId.oid);
7249 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7251 ntups = PQntuples(res);
7253 i_tableoid = PQfnumber(res, "tableoid");
7254 i_oid = PQfnumber(res, "oid");
7255 i_conname = PQfnumber(res, "conname");
7256 i_consrc = PQfnumber(res, "consrc");
7258 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7260 tyinfo->nDomChecks = ntups;
7261 tyinfo->domChecks = constrinfo;
7263 for (i = 0; i < ntups; i++)
7265 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7267 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7268 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7269 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7270 AssignDumpId(&constrinfo[i].dobj);
7271 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7272 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7273 constrinfo[i].contable = NULL;
7274 constrinfo[i].condomain = tyinfo;
7275 constrinfo[i].contype = 'c';
7276 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7277 constrinfo[i].confrelid = InvalidOid;
7278 constrinfo[i].conindex = 0;
7279 constrinfo[i].condeferrable = false;
7280 constrinfo[i].condeferred = false;
7281 constrinfo[i].conislocal = true;
7283 constrinfo[i].separate = !validated;
7286 * Make the domain depend on the constraint, ensuring it won't be
7287 * output till any constraint dependencies are OK. If the constraint
7288 * has not been validated, it's going to be dumped after the domain
7289 * anyway, so this doesn't matter.
7292 addObjectDependency(&tyinfo->dobj,
7293 constrinfo[i].dobj.dumpId);
7298 destroyPQExpBuffer(query);
7303 * get basic information about every rule in the system
7305 * numRules is set to the number of rules read in
7308 getRules(Archive *fout, int *numRules)
7313 PQExpBuffer query = createPQExpBuffer();
7323 if (fout->remoteVersion >= 80300)
7325 appendPQExpBufferStr(query, "SELECT "
7326 "tableoid, oid, rulename, "
7327 "ev_class AS ruletable, ev_type, is_instead, "
7334 appendPQExpBufferStr(query, "SELECT "
7335 "tableoid, oid, rulename, "
7336 "ev_class AS ruletable, ev_type, is_instead, "
7337 "'O'::char AS ev_enabled "
7342 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7344 ntups = PQntuples(res);
7348 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7350 i_tableoid = PQfnumber(res, "tableoid");
7351 i_oid = PQfnumber(res, "oid");
7352 i_rulename = PQfnumber(res, "rulename");
7353 i_ruletable = PQfnumber(res, "ruletable");
7354 i_ev_type = PQfnumber(res, "ev_type");
7355 i_is_instead = PQfnumber(res, "is_instead");
7356 i_ev_enabled = PQfnumber(res, "ev_enabled");
7358 for (i = 0; i < ntups; i++)
7362 ruleinfo[i].dobj.objType = DO_RULE;
7363 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7364 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7365 AssignDumpId(&ruleinfo[i].dobj);
7366 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7367 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7368 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7369 if (ruleinfo[i].ruletable == NULL)
7370 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7371 ruletableoid, ruleinfo[i].dobj.catId.oid);
7372 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7373 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7374 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7375 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7376 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7377 if (ruleinfo[i].ruletable)
7380 * If the table is a view or materialized view, force its ON
7381 * SELECT rule to be sorted before the view itself --- this
7382 * ensures that any dependencies for the rule affect the table's
7383 * positioning. Other rules are forced to appear after their
7386 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7387 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7388 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7390 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7391 ruleinfo[i].dobj.dumpId);
7392 /* We'll merge the rule into CREATE VIEW, if possible */
7393 ruleinfo[i].separate = false;
7397 addObjectDependency(&ruleinfo[i].dobj,
7398 ruleinfo[i].ruletable->dobj.dumpId);
7399 ruleinfo[i].separate = true;
7403 ruleinfo[i].separate = true;
7408 destroyPQExpBuffer(query);
7415 * get information about every trigger on a dumpable table
7417 * Note: trigger data is not returned directly to the caller, but it
7418 * does get entered into the DumpableObject tables.
7421 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7425 PQExpBuffer query = createPQExpBuffer();
7427 TriggerInfo *tginfo;
7445 for (i = 0; i < numTables; i++)
7447 TableInfo *tbinfo = &tblinfo[i];
7449 if (!tbinfo->hastriggers ||
7450 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7454 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7455 tbinfo->dobj.namespace->dobj.name,
7458 resetPQExpBuffer(query);
7459 if (fout->remoteVersion >= 90000)
7462 * NB: think not to use pretty=true in pg_get_triggerdef. It
7463 * could result in non-forward-compatible dumps of WHEN clauses
7464 * due to under-parenthesization.
7466 appendPQExpBuffer(query,
7468 "tgfoid::pg_catalog.regproc AS tgfname, "
7469 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7470 "tgenabled, tableoid, oid "
7471 "FROM pg_catalog.pg_trigger t "
7472 "WHERE tgrelid = '%u'::pg_catalog.oid "
7473 "AND NOT tgisinternal",
7474 tbinfo->dobj.catId.oid);
7476 else if (fout->remoteVersion >= 80300)
7479 * We ignore triggers that are tied to a foreign-key constraint
7481 appendPQExpBuffer(query,
7483 "tgfoid::pg_catalog.regproc AS tgfname, "
7484 "tgtype, tgnargs, tgargs, tgenabled, "
7485 "tgisconstraint, tgconstrname, tgdeferrable, "
7486 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7487 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7488 "FROM pg_catalog.pg_trigger t "
7489 "WHERE tgrelid = '%u'::pg_catalog.oid "
7490 "AND tgconstraint = 0",
7491 tbinfo->dobj.catId.oid);
7496 * We ignore triggers that are tied to a foreign-key constraint,
7497 * but in these versions we have to grovel through pg_constraint
7500 appendPQExpBuffer(query,
7502 "tgfoid::pg_catalog.regproc AS tgfname, "
7503 "tgtype, tgnargs, tgargs, tgenabled, "
7504 "tgisconstraint, tgconstrname, tgdeferrable, "
7505 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7506 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7507 "FROM pg_catalog.pg_trigger t "
7508 "WHERE tgrelid = '%u'::pg_catalog.oid "
7509 "AND (NOT tgisconstraint "
7511 " (SELECT 1 FROM pg_catalog.pg_depend d "
7512 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7513 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7514 tbinfo->dobj.catId.oid);
7517 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7519 ntups = PQntuples(res);
7521 i_tableoid = PQfnumber(res, "tableoid");
7522 i_oid = PQfnumber(res, "oid");
7523 i_tgname = PQfnumber(res, "tgname");
7524 i_tgfname = PQfnumber(res, "tgfname");
7525 i_tgtype = PQfnumber(res, "tgtype");
7526 i_tgnargs = PQfnumber(res, "tgnargs");
7527 i_tgargs = PQfnumber(res, "tgargs");
7528 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7529 i_tgconstrname = PQfnumber(res, "tgconstrname");
7530 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7531 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7532 i_tgenabled = PQfnumber(res, "tgenabled");
7533 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7534 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7535 i_tgdef = PQfnumber(res, "tgdef");
7537 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7539 tbinfo->numTriggers = ntups;
7540 tbinfo->triggers = tginfo;
7542 for (j = 0; j < ntups; j++)
7544 tginfo[j].dobj.objType = DO_TRIGGER;
7545 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7546 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7547 AssignDumpId(&tginfo[j].dobj);
7548 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7549 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7550 tginfo[j].tgtable = tbinfo;
7551 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7554 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7556 /* remaining fields are not valid if we have tgdef */
7557 tginfo[j].tgfname = NULL;
7558 tginfo[j].tgtype = 0;
7559 tginfo[j].tgnargs = 0;
7560 tginfo[j].tgargs = NULL;
7561 tginfo[j].tgisconstraint = false;
7562 tginfo[j].tgdeferrable = false;
7563 tginfo[j].tginitdeferred = false;
7564 tginfo[j].tgconstrname = NULL;
7565 tginfo[j].tgconstrrelid = InvalidOid;
7566 tginfo[j].tgconstrrelname = NULL;
7570 tginfo[j].tgdef = NULL;
7572 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7573 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7574 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7575 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7576 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7577 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7578 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7580 if (tginfo[j].tgisconstraint)
7582 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7583 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7584 if (OidIsValid(tginfo[j].tgconstrrelid))
7586 if (PQgetisnull(res, j, i_tgconstrrelname))
7587 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7588 tginfo[j].dobj.name,
7590 tginfo[j].tgconstrrelid);
7591 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7594 tginfo[j].tgconstrrelname = NULL;
7598 tginfo[j].tgconstrname = NULL;
7599 tginfo[j].tgconstrrelid = InvalidOid;
7600 tginfo[j].tgconstrrelname = NULL;
7608 destroyPQExpBuffer(query);
7613 * get information about event triggers
7616 getEventTriggers(Archive *fout, int *numEventTriggers)
7621 EventTriggerInfo *evtinfo;
7632 /* Before 9.3, there are no event triggers */
7633 if (fout->remoteVersion < 90300)
7635 *numEventTriggers = 0;
7639 query = createPQExpBuffer();
7641 appendPQExpBuffer(query,
7642 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7643 "evtevent, (%s evtowner) AS evtowner, "
7644 "array_to_string(array("
7645 "select quote_literal(x) "
7646 " from unnest(evttags) as t(x)), ', ') as evttags, "
7647 "e.evtfoid::regproc as evtfname "
7648 "FROM pg_event_trigger e "
7652 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7654 ntups = PQntuples(res);
7656 *numEventTriggers = ntups;
7658 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7660 i_tableoid = PQfnumber(res, "tableoid");
7661 i_oid = PQfnumber(res, "oid");
7662 i_evtname = PQfnumber(res, "evtname");
7663 i_evtevent = PQfnumber(res, "evtevent");
7664 i_evtowner = PQfnumber(res, "evtowner");
7665 i_evttags = PQfnumber(res, "evttags");
7666 i_evtfname = PQfnumber(res, "evtfname");
7667 i_evtenabled = PQfnumber(res, "evtenabled");
7669 for (i = 0; i < ntups; i++)
7671 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7672 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7673 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7674 AssignDumpId(&evtinfo[i].dobj);
7675 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7676 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7677 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7678 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7679 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7680 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7681 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7683 /* Decide whether we want to dump it */
7684 selectDumpableObject(&(evtinfo[i].dobj), fout);
7686 /* Event Triggers do not currently have ACLs. */
7687 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7692 destroyPQExpBuffer(query);
7699 * get basic information about every procedural language in the system
7701 * numProcLangs is set to the number of langs read in
7703 * NB: this must run after getFuncs() because we assume we can do
7707 getProcLangs(Archive *fout, int *numProcLangs)
7709 DumpOptions *dopt = fout->dopt;
7713 PQExpBuffer query = createPQExpBuffer();
7714 ProcLangInfo *planginfo;
7719 int i_lanplcallfoid;
7728 if (fout->remoteVersion >= 90600)
7730 PQExpBuffer acl_subquery = createPQExpBuffer();
7731 PQExpBuffer racl_subquery = createPQExpBuffer();
7732 PQExpBuffer initacl_subquery = createPQExpBuffer();
7733 PQExpBuffer initracl_subquery = createPQExpBuffer();
7735 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7736 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7737 dopt->binary_upgrade);
7739 /* pg_language has a laninline column */
7740 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7741 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7742 "l.laninline, l.lanvalidator, "
7745 "%s AS initlanacl, "
7746 "%s AS initrlanacl, "
7747 "(%s l.lanowner) AS lanowner "
7748 "FROM pg_language l "
7749 "LEFT JOIN pg_init_privs pip ON "
7750 "(l.oid = pip.objoid "
7751 "AND pip.classoid = 'pg_language'::regclass "
7752 "AND pip.objsubid = 0) "
7756 racl_subquery->data,
7757 initacl_subquery->data,
7758 initracl_subquery->data,
7761 destroyPQExpBuffer(acl_subquery);
7762 destroyPQExpBuffer(racl_subquery);
7763 destroyPQExpBuffer(initacl_subquery);
7764 destroyPQExpBuffer(initracl_subquery);
7766 else if (fout->remoteVersion >= 90000)
7768 /* pg_language has a laninline column */
7769 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7770 "lanname, lanpltrusted, lanplcallfoid, "
7771 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7772 "NULL AS initlanacl, NULL AS initrlanacl, "
7773 "(%s lanowner) AS lanowner "
7779 else if (fout->remoteVersion >= 80300)
7781 /* pg_language has a lanowner column */
7782 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7783 "lanname, lanpltrusted, lanplcallfoid, "
7784 "0 AS laninline, lanvalidator, lanacl, "
7786 "NULL AS initlanacl, NULL AS initrlanacl, "
7787 "(%s lanowner) AS lanowner "
7793 else if (fout->remoteVersion >= 80100)
7795 /* Languages are owned by the bootstrap superuser, OID 10 */
7796 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7797 "lanname, lanpltrusted, lanplcallfoid, "
7798 "0 AS laninline, lanvalidator, lanacl, "
7800 "NULL AS initlanacl, NULL AS initrlanacl, "
7801 "(%s '10') AS lanowner "
7809 /* Languages are owned by the bootstrap superuser, sysid 1 */
7810 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7811 "lanname, lanpltrusted, lanplcallfoid, "
7812 "0 AS laninline, lanvalidator, lanacl, "
7814 "NULL AS initlanacl, NULL AS initrlanacl, "
7815 "(%s '1') AS lanowner "
7822 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7824 ntups = PQntuples(res);
7826 *numProcLangs = ntups;
7828 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7830 i_tableoid = PQfnumber(res, "tableoid");
7831 i_oid = PQfnumber(res, "oid");
7832 i_lanname = PQfnumber(res, "lanname");
7833 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7834 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7835 i_laninline = PQfnumber(res, "laninline");
7836 i_lanvalidator = PQfnumber(res, "lanvalidator");
7837 i_lanacl = PQfnumber(res, "lanacl");
7838 i_rlanacl = PQfnumber(res, "rlanacl");
7839 i_initlanacl = PQfnumber(res, "initlanacl");
7840 i_initrlanacl = PQfnumber(res, "initrlanacl");
7841 i_lanowner = PQfnumber(res, "lanowner");
7843 for (i = 0; i < ntups; i++)
7845 planginfo[i].dobj.objType = DO_PROCLANG;
7846 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7847 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7848 AssignDumpId(&planginfo[i].dobj);
7850 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7851 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7852 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7853 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7854 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7855 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7856 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7857 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7858 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7859 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7861 /* Decide whether we want to dump it */
7862 selectDumpableProcLang(&(planginfo[i]), fout);
7864 /* Do not try to dump ACL if no ACL exists. */
7865 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7866 PQgetisnull(res, i, i_initlanacl) &&
7867 PQgetisnull(res, i, i_initrlanacl))
7868 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7873 destroyPQExpBuffer(query);
7880 * get basic information about every cast in the system
7882 * numCasts is set to the number of casts read in
7885 getCasts(Archive *fout, int *numCasts)
7890 PQExpBuffer query = createPQExpBuffer();
7900 if (fout->remoteVersion >= 80400)
7902 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7903 "castsource, casttarget, castfunc, castcontext, "
7905 "FROM pg_cast ORDER BY 3,4");
7909 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7910 "castsource, casttarget, castfunc, castcontext, "
7911 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7912 "FROM pg_cast ORDER BY 3,4");
7915 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7917 ntups = PQntuples(res);
7921 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7923 i_tableoid = PQfnumber(res, "tableoid");
7924 i_oid = PQfnumber(res, "oid");
7925 i_castsource = PQfnumber(res, "castsource");
7926 i_casttarget = PQfnumber(res, "casttarget");
7927 i_castfunc = PQfnumber(res, "castfunc");
7928 i_castcontext = PQfnumber(res, "castcontext");
7929 i_castmethod = PQfnumber(res, "castmethod");
7931 for (i = 0; i < ntups; i++)
7933 PQExpBufferData namebuf;
7934 TypeInfo *sTypeInfo;
7935 TypeInfo *tTypeInfo;
7937 castinfo[i].dobj.objType = DO_CAST;
7938 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7939 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7940 AssignDumpId(&castinfo[i].dobj);
7941 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7942 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7943 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7944 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7945 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7948 * Try to name cast as concatenation of typnames. This is only used
7949 * for purposes of sorting. If we fail to find either type, the name
7950 * will be an empty string.
7952 initPQExpBuffer(&namebuf);
7953 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7954 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7955 if (sTypeInfo && tTypeInfo)
7956 appendPQExpBuffer(&namebuf, "%s %s",
7957 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7958 castinfo[i].dobj.name = namebuf.data;
7960 /* Decide whether we want to dump it */
7961 selectDumpableCast(&(castinfo[i]), fout);
7963 /* Casts do not currently have ACLs. */
7964 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7969 destroyPQExpBuffer(query);
7975 get_language_name(Archive *fout, Oid langid)
7981 query = createPQExpBuffer();
7982 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7983 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7984 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7985 destroyPQExpBuffer(query);
7993 * get basic information about every transform in the system
7995 * numTransforms is set to the number of transforms read in
7998 getTransforms(Archive *fout, int *numTransforms)
8004 TransformInfo *transforminfo;
8012 /* Transforms didn't exist pre-9.5 */
8013 if (fout->remoteVersion < 90500)
8019 query = createPQExpBuffer();
8021 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8022 "trftype, trflang, trffromsql::oid, trftosql::oid "
8023 "FROM pg_transform "
8026 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8028 ntups = PQntuples(res);
8030 *numTransforms = ntups;
8032 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8034 i_tableoid = PQfnumber(res, "tableoid");
8035 i_oid = PQfnumber(res, "oid");
8036 i_trftype = PQfnumber(res, "trftype");
8037 i_trflang = PQfnumber(res, "trflang");
8038 i_trffromsql = PQfnumber(res, "trffromsql");
8039 i_trftosql = PQfnumber(res, "trftosql");
8041 for (i = 0; i < ntups; i++)
8043 PQExpBufferData namebuf;
8047 transforminfo[i].dobj.objType = DO_TRANSFORM;
8048 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8049 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8050 AssignDumpId(&transforminfo[i].dobj);
8051 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8052 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8053 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8054 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8057 * Try to name transform as concatenation of type and language name.
8058 * This is only used for purposes of sorting. If we fail to find
8059 * either, the name will be an empty string.
8061 initPQExpBuffer(&namebuf);
8062 typeInfo = findTypeByOid(transforminfo[i].trftype);
8063 lanname = get_language_name(fout, transforminfo[i].trflang);
8064 if (typeInfo && lanname)
8065 appendPQExpBuffer(&namebuf, "%s %s",
8066 typeInfo->dobj.name, lanname);
8067 transforminfo[i].dobj.name = namebuf.data;
8070 /* Decide whether we want to dump it */
8071 selectDumpableObject(&(transforminfo[i].dobj), fout);
8076 destroyPQExpBuffer(query);
8078 return transforminfo;
8083 * for each interesting table, read info about its attributes
8084 * (names, types, default values, CHECK constraints, etc)
8086 * This is implemented in a very inefficient way right now, looping
8087 * through the tblinfo and doing a join per table to find the attrs and their
8088 * types. However, because we want type names and so forth to be named
8089 * relative to the schema of each table, we couldn't do it in just one
8090 * query. (Maybe one query per schema?)
8095 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8097 DumpOptions *dopt = fout->dopt;
8100 PQExpBuffer q = createPQExpBuffer();
8105 int i_attstattarget;
8117 int i_attfdwoptions;
8118 int i_attmissingval;
8123 for (i = 0; i < numTables; i++)
8125 TableInfo *tbinfo = &tblinfo[i];
8127 /* Don't bother to collect info for sequences */
8128 if (tbinfo->relkind == RELKIND_SEQUENCE)
8131 /* Don't bother with uninteresting tables, either */
8132 if (!tbinfo->interesting)
8135 /* find all the user attributes and their types */
8138 * we must read the attribute names in attribute number order! because
8139 * we will use the attnum to index into the attnames array later.
8142 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8143 tbinfo->dobj.namespace->dobj.name,
8146 resetPQExpBuffer(q);
8148 if (fout->remoteVersion >= 110000)
8150 /* atthasmissing and attmissingval are new in 11 */
8151 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8152 "a.attstattarget, a.attstorage, t.typstorage, "
8153 "a.attnotnull, a.atthasdef, a.attisdropped, "
8154 "a.attlen, a.attalign, a.attislocal, "
8155 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8156 "array_to_string(a.attoptions, ', ') AS attoptions, "
8157 "CASE WHEN a.attcollation <> t.typcollation "
8158 "THEN a.attcollation ELSE 0 END AS attcollation, "
8160 "pg_catalog.array_to_string(ARRAY("
8161 "SELECT pg_catalog.quote_ident(option_name) || "
8162 "' ' || pg_catalog.quote_literal(option_value) "
8163 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8164 "ORDER BY option_name"
8165 "), E',\n ') AS attfdwoptions ,"
8166 "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8167 "THEN a.attmissingval ELSE null END AS attmissingval "
8168 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8169 "ON a.atttypid = t.oid "
8170 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8171 "AND a.attnum > 0::pg_catalog.int2 "
8172 "ORDER BY a.attnum",
8173 tbinfo->dobj.catId.oid);
8175 else if (fout->remoteVersion >= 100000)
8178 * attidentity is new in version 10.
8180 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8181 "a.attstattarget, a.attstorage, t.typstorage, "
8182 "a.attnotnull, a.atthasdef, a.attisdropped, "
8183 "a.attlen, a.attalign, a.attislocal, "
8184 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8185 "array_to_string(a.attoptions, ', ') AS attoptions, "
8186 "CASE WHEN a.attcollation <> t.typcollation "
8187 "THEN a.attcollation ELSE 0 END AS attcollation, "
8189 "pg_catalog.array_to_string(ARRAY("
8190 "SELECT pg_catalog.quote_ident(option_name) || "
8191 "' ' || pg_catalog.quote_literal(option_value) "
8192 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8193 "ORDER BY option_name"
8194 "), E',\n ') AS attfdwoptions ,"
8195 "NULL as attmissingval "
8196 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8197 "ON a.atttypid = t.oid "
8198 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8199 "AND a.attnum > 0::pg_catalog.int2 "
8200 "ORDER BY a.attnum",
8201 tbinfo->dobj.catId.oid);
8203 else if (fout->remoteVersion >= 90200)
8206 * attfdwoptions is new in 9.2.
8208 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8209 "a.attstattarget, a.attstorage, t.typstorage, "
8210 "a.attnotnull, a.atthasdef, a.attisdropped, "
8211 "a.attlen, a.attalign, a.attislocal, "
8212 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8213 "array_to_string(a.attoptions, ', ') AS attoptions, "
8214 "CASE WHEN a.attcollation <> t.typcollation "
8215 "THEN a.attcollation ELSE 0 END AS attcollation, "
8216 "pg_catalog.array_to_string(ARRAY("
8217 "SELECT pg_catalog.quote_ident(option_name) || "
8218 "' ' || pg_catalog.quote_literal(option_value) "
8219 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8220 "ORDER BY option_name"
8221 "), E',\n ') AS attfdwoptions, "
8222 "NULL as attmissingval "
8223 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8224 "ON a.atttypid = t.oid "
8225 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8226 "AND a.attnum > 0::pg_catalog.int2 "
8227 "ORDER BY a.attnum",
8228 tbinfo->dobj.catId.oid);
8230 else if (fout->remoteVersion >= 90100)
8233 * attcollation is new in 9.1. Since we only want to dump COLLATE
8234 * clauses for attributes whose collation is different from their
8235 * type's default, we use a CASE here to suppress uninteresting
8236 * attcollations cheaply.
8238 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8239 "a.attstattarget, a.attstorage, t.typstorage, "
8240 "a.attnotnull, a.atthasdef, a.attisdropped, "
8241 "a.attlen, a.attalign, a.attislocal, "
8242 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8243 "array_to_string(a.attoptions, ', ') AS attoptions, "
8244 "CASE WHEN a.attcollation <> t.typcollation "
8245 "THEN a.attcollation ELSE 0 END AS attcollation, "
8246 "NULL AS attfdwoptions, "
8247 "NULL as attmissingval "
8248 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8249 "ON a.atttypid = t.oid "
8250 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8251 "AND a.attnum > 0::pg_catalog.int2 "
8252 "ORDER BY a.attnum",
8253 tbinfo->dobj.catId.oid);
8255 else if (fout->remoteVersion >= 90000)
8257 /* attoptions is new in 9.0 */
8258 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8259 "a.attstattarget, a.attstorage, t.typstorage, "
8260 "a.attnotnull, a.atthasdef, a.attisdropped, "
8261 "a.attlen, a.attalign, a.attislocal, "
8262 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8263 "array_to_string(a.attoptions, ', ') AS attoptions, "
8264 "0 AS attcollation, "
8265 "NULL AS attfdwoptions, "
8266 "NULL as attmissingval "
8267 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8268 "ON a.atttypid = t.oid "
8269 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8270 "AND a.attnum > 0::pg_catalog.int2 "
8271 "ORDER BY a.attnum",
8272 tbinfo->dobj.catId.oid);
8276 /* need left join here to not fail on dropped columns ... */
8277 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8278 "a.attstattarget, a.attstorage, t.typstorage, "
8279 "a.attnotnull, a.atthasdef, a.attisdropped, "
8280 "a.attlen, a.attalign, a.attislocal, "
8281 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8282 "'' AS attoptions, 0 AS attcollation, "
8283 "NULL AS attfdwoptions, "
8284 "NULL as attmissingval "
8285 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8286 "ON a.atttypid = t.oid "
8287 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8288 "AND a.attnum > 0::pg_catalog.int2 "
8289 "ORDER BY a.attnum",
8290 tbinfo->dobj.catId.oid);
8293 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8295 ntups = PQntuples(res);
8297 i_attnum = PQfnumber(res, "attnum");
8298 i_attname = PQfnumber(res, "attname");
8299 i_atttypname = PQfnumber(res, "atttypname");
8300 i_atttypmod = PQfnumber(res, "atttypmod");
8301 i_attstattarget = PQfnumber(res, "attstattarget");
8302 i_attstorage = PQfnumber(res, "attstorage");
8303 i_typstorage = PQfnumber(res, "typstorage");
8304 i_attnotnull = PQfnumber(res, "attnotnull");
8305 i_atthasdef = PQfnumber(res, "atthasdef");
8306 i_attidentity = PQfnumber(res, "attidentity");
8307 i_attisdropped = PQfnumber(res, "attisdropped");
8308 i_attlen = PQfnumber(res, "attlen");
8309 i_attalign = PQfnumber(res, "attalign");
8310 i_attislocal = PQfnumber(res, "attislocal");
8311 i_attoptions = PQfnumber(res, "attoptions");
8312 i_attcollation = PQfnumber(res, "attcollation");
8313 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8314 i_attmissingval = PQfnumber(res, "attmissingval");
8316 tbinfo->numatts = ntups;
8317 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8318 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8319 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8320 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8321 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8322 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8323 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8324 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8325 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8326 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8327 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8328 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8329 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8330 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8331 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8332 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8333 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8334 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8335 hasdefaults = false;
8337 for (j = 0; j < ntups; j++)
8339 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8341 "invalid column numbering in table \"%s\"\n",
8343 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8344 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8345 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8346 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8347 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8348 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8349 tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8350 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8351 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8352 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8353 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8354 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8355 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8356 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8357 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8358 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8359 tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8360 tbinfo->attrdefs[j] = NULL; /* fix below */
8361 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8363 /* these flags will be set in flagInhAttrs() */
8364 tbinfo->inhNotNull[j] = false;
8370 * Get info about column defaults
8374 AttrDefInfo *attrdefs;
8378 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8379 tbinfo->dobj.namespace->dobj.name,
8382 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8383 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8384 "FROM pg_catalog.pg_attrdef "
8385 "WHERE adrelid = '%u'::pg_catalog.oid",
8386 tbinfo->dobj.catId.oid);
8388 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8390 numDefaults = PQntuples(res);
8391 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8393 for (j = 0; j < numDefaults; j++)
8397 adnum = atoi(PQgetvalue(res, j, 2));
8399 if (adnum <= 0 || adnum > ntups)
8401 "invalid adnum value %d for table \"%s\"\n",
8402 adnum, tbinfo->dobj.name);
8405 * dropped columns shouldn't have defaults, but just in case,
8408 if (tbinfo->attisdropped[adnum - 1])
8411 attrdefs[j].dobj.objType = DO_ATTRDEF;
8412 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8413 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8414 AssignDumpId(&attrdefs[j].dobj);
8415 attrdefs[j].adtable = tbinfo;
8416 attrdefs[j].adnum = adnum;
8417 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8419 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8420 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8422 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8425 * Defaults on a VIEW must always be dumped as separate ALTER
8426 * TABLE commands. Defaults on regular tables are dumped as
8427 * part of the CREATE TABLE if possible, which it won't be if
8428 * the column is not going to be emitted explicitly.
8430 if (tbinfo->relkind == RELKIND_VIEW)
8432 attrdefs[j].separate = true;
8434 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8436 /* column will be suppressed, print default separately */
8437 attrdefs[j].separate = true;
8441 attrdefs[j].separate = false;
8444 * Mark the default as needing to appear before the table,
8445 * so that any dependencies it has must be emitted before
8446 * the CREATE TABLE. If this is not possible, we'll
8447 * change to "separate" mode while sorting dependencies.
8449 addObjectDependency(&tbinfo->dobj,
8450 attrdefs[j].dobj.dumpId);
8453 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8459 * Get info about table CHECK constraints
8461 if (tbinfo->ncheck > 0)
8463 ConstraintInfo *constrs;
8467 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8468 tbinfo->dobj.namespace->dobj.name,
8471 resetPQExpBuffer(q);
8472 if (fout->remoteVersion >= 90200)
8475 * convalidated is new in 9.2 (actually, it is there in 9.1,
8476 * but it wasn't ever false for check constraints until 9.2).
8478 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8479 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8480 "conislocal, convalidated "
8481 "FROM pg_catalog.pg_constraint "
8482 "WHERE conrelid = '%u'::pg_catalog.oid "
8483 " AND contype = 'c' "
8485 tbinfo->dobj.catId.oid);
8487 else if (fout->remoteVersion >= 80400)
8489 /* conislocal is new in 8.4 */
8490 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8491 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8492 "conislocal, true AS convalidated "
8493 "FROM pg_catalog.pg_constraint "
8494 "WHERE conrelid = '%u'::pg_catalog.oid "
8495 " AND contype = 'c' "
8497 tbinfo->dobj.catId.oid);
8501 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8502 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8503 "true AS conislocal, true AS convalidated "
8504 "FROM pg_catalog.pg_constraint "
8505 "WHERE conrelid = '%u'::pg_catalog.oid "
8506 " AND contype = 'c' "
8508 tbinfo->dobj.catId.oid);
8511 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8513 numConstrs = PQntuples(res);
8514 if (numConstrs != tbinfo->ncheck)
8516 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8517 "expected %d check constraints on table \"%s\" but found %d\n",
8519 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8520 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8524 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8525 tbinfo->checkexprs = constrs;
8527 for (j = 0; j < numConstrs; j++)
8529 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8531 constrs[j].dobj.objType = DO_CONSTRAINT;
8532 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8533 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8534 AssignDumpId(&constrs[j].dobj);
8535 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8536 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8537 constrs[j].contable = tbinfo;
8538 constrs[j].condomain = NULL;
8539 constrs[j].contype = 'c';
8540 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8541 constrs[j].confrelid = InvalidOid;
8542 constrs[j].conindex = 0;
8543 constrs[j].condeferrable = false;
8544 constrs[j].condeferred = false;
8545 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8548 * An unvalidated constraint needs to be dumped separately, so
8549 * that potentially-violating existing data is loaded before
8552 constrs[j].separate = !validated;
8554 constrs[j].dobj.dump = tbinfo->dobj.dump;
8557 * Mark the constraint as needing to appear before the table
8558 * --- this is so that any other dependencies of the
8559 * constraint will be emitted before we try to create the
8560 * table. If the constraint is to be dumped separately, it
8561 * will be dumped after data is loaded anyway, so don't do it.
8562 * (There's an automatic dependency in the opposite direction
8563 * anyway, so don't need to add one manually here.)
8565 if (!constrs[j].separate)
8566 addObjectDependency(&tbinfo->dobj,
8567 constrs[j].dobj.dumpId);
8570 * If the constraint is inherited, this will be detected later
8571 * (in pre-8.4 databases). We also detect later if the
8572 * constraint must be split out from the table definition.
8579 destroyPQExpBuffer(q);
8583 * Test whether a column should be printed as part of table's CREATE TABLE.
8584 * Column number is zero-based.
8586 * Normally this is always true, but it's false for dropped columns, as well
8587 * as those that were inherited without any local definition. (If we print
8588 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8589 * However, in binary_upgrade mode, we must print all such columns anyway and
8590 * fix the attislocal/attisdropped state later, so as to keep control of the
8591 * physical column order.
8593 * This function exists because there are scattered nonobvious places that
8594 * must be kept in sync with this decision.
8597 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8599 if (dopt->binary_upgrade)
8601 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8607 * read all text search parsers in the system catalogs and return them
8608 * in the TSParserInfo* structure
8610 * numTSParsers is set to the number of parsers read in
8613 getTSParsers(Archive *fout, int *numTSParsers)
8619 TSParserInfo *prsinfo;
8630 /* Before 8.3, there is no built-in text search support */
8631 if (fout->remoteVersion < 80300)
8637 query = createPQExpBuffer();
8640 * find all text search objects, including builtin ones; we filter out
8641 * system-defined objects at dump-out time.
8644 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8645 "prsstart::oid, prstoken::oid, "
8646 "prsend::oid, prsheadline::oid, prslextype::oid "
8647 "FROM pg_ts_parser");
8649 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8651 ntups = PQntuples(res);
8652 *numTSParsers = ntups;
8654 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8656 i_tableoid = PQfnumber(res, "tableoid");
8657 i_oid = PQfnumber(res, "oid");
8658 i_prsname = PQfnumber(res, "prsname");
8659 i_prsnamespace = PQfnumber(res, "prsnamespace");
8660 i_prsstart = PQfnumber(res, "prsstart");
8661 i_prstoken = PQfnumber(res, "prstoken");
8662 i_prsend = PQfnumber(res, "prsend");
8663 i_prsheadline = PQfnumber(res, "prsheadline");
8664 i_prslextype = PQfnumber(res, "prslextype");
8666 for (i = 0; i < ntups; i++)
8668 prsinfo[i].dobj.objType = DO_TSPARSER;
8669 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8670 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8671 AssignDumpId(&prsinfo[i].dobj);
8672 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8673 prsinfo[i].dobj.namespace =
8675 atooid(PQgetvalue(res, i, i_prsnamespace)));
8676 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8677 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8678 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8679 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8680 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8682 /* Decide whether we want to dump it */
8683 selectDumpableObject(&(prsinfo[i].dobj), fout);
8685 /* Text Search Parsers do not currently have ACLs. */
8686 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8691 destroyPQExpBuffer(query);
8697 * getTSDictionaries:
8698 * read all text search dictionaries in the system catalogs and return them
8699 * in the TSDictInfo* structure
8701 * numTSDicts is set to the number of dictionaries read in
8704 getTSDictionaries(Archive *fout, int *numTSDicts)
8710 TSDictInfo *dictinfo;
8714 int i_dictnamespace;
8717 int i_dictinitoption;
8719 /* Before 8.3, there is no built-in text search support */
8720 if (fout->remoteVersion < 80300)
8726 query = createPQExpBuffer();
8728 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8729 "dictnamespace, (%s dictowner) AS rolname, "
8730 "dicttemplate, dictinitoption "
8734 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8736 ntups = PQntuples(res);
8737 *numTSDicts = ntups;
8739 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8741 i_tableoid = PQfnumber(res, "tableoid");
8742 i_oid = PQfnumber(res, "oid");
8743 i_dictname = PQfnumber(res, "dictname");
8744 i_dictnamespace = PQfnumber(res, "dictnamespace");
8745 i_rolname = PQfnumber(res, "rolname");
8746 i_dictinitoption = PQfnumber(res, "dictinitoption");
8747 i_dicttemplate = PQfnumber(res, "dicttemplate");
8749 for (i = 0; i < ntups; i++)
8751 dictinfo[i].dobj.objType = DO_TSDICT;
8752 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8753 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8754 AssignDumpId(&dictinfo[i].dobj);
8755 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8756 dictinfo[i].dobj.namespace =
8758 atooid(PQgetvalue(res, i, i_dictnamespace)));
8759 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8760 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8761 if (PQgetisnull(res, i, i_dictinitoption))
8762 dictinfo[i].dictinitoption = NULL;
8764 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8766 /* Decide whether we want to dump it */
8767 selectDumpableObject(&(dictinfo[i].dobj), fout);
8769 /* Text Search Dictionaries do not currently have ACLs. */
8770 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8775 destroyPQExpBuffer(query);
8782 * read all text search templates in the system catalogs and return them
8783 * in the TSTemplateInfo* structure
8785 * numTSTemplates is set to the number of templates read in
8788 getTSTemplates(Archive *fout, int *numTSTemplates)
8794 TSTemplateInfo *tmplinfo;
8798 int i_tmplnamespace;
8802 /* Before 8.3, there is no built-in text search support */
8803 if (fout->remoteVersion < 80300)
8805 *numTSTemplates = 0;
8809 query = createPQExpBuffer();
8811 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8812 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8813 "FROM pg_ts_template");
8815 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8817 ntups = PQntuples(res);
8818 *numTSTemplates = ntups;
8820 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8822 i_tableoid = PQfnumber(res, "tableoid");
8823 i_oid = PQfnumber(res, "oid");
8824 i_tmplname = PQfnumber(res, "tmplname");
8825 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8826 i_tmplinit = PQfnumber(res, "tmplinit");
8827 i_tmpllexize = PQfnumber(res, "tmpllexize");
8829 for (i = 0; i < ntups; i++)
8831 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8832 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8833 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8834 AssignDumpId(&tmplinfo[i].dobj);
8835 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8836 tmplinfo[i].dobj.namespace =
8838 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8839 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8840 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8842 /* Decide whether we want to dump it */
8843 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8845 /* Text Search Templates do not currently have ACLs. */
8846 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8851 destroyPQExpBuffer(query);
8857 * getTSConfigurations:
8858 * read all text search configurations in the system catalogs and return
8859 * them in the TSConfigInfo* structure
8861 * numTSConfigs is set to the number of configurations read in
8864 getTSConfigurations(Archive *fout, int *numTSConfigs)
8870 TSConfigInfo *cfginfo;
8878 /* Before 8.3, there is no built-in text search support */
8879 if (fout->remoteVersion < 80300)
8885 query = createPQExpBuffer();
8887 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8888 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8889 "FROM pg_ts_config",
8892 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8894 ntups = PQntuples(res);
8895 *numTSConfigs = ntups;
8897 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8899 i_tableoid = PQfnumber(res, "tableoid");
8900 i_oid = PQfnumber(res, "oid");
8901 i_cfgname = PQfnumber(res, "cfgname");
8902 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8903 i_rolname = PQfnumber(res, "rolname");
8904 i_cfgparser = PQfnumber(res, "cfgparser");
8906 for (i = 0; i < ntups; i++)
8908 cfginfo[i].dobj.objType = DO_TSCONFIG;
8909 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8910 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8911 AssignDumpId(&cfginfo[i].dobj);
8912 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8913 cfginfo[i].dobj.namespace =
8915 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8916 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8917 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8919 /* Decide whether we want to dump it */
8920 selectDumpableObject(&(cfginfo[i].dobj), fout);
8922 /* Text Search Configurations do not currently have ACLs. */
8923 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8928 destroyPQExpBuffer(query);
8934 * getForeignDataWrappers:
8935 * read all foreign-data wrappers in the system catalogs and return
8936 * them in the FdwInfo* structure
8938 * numForeignDataWrappers is set to the number of fdws read in
8941 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8943 DumpOptions *dopt = fout->dopt;
8961 /* Before 8.4, there are no foreign-data wrappers */
8962 if (fout->remoteVersion < 80400)
8964 *numForeignDataWrappers = 0;
8968 query = createPQExpBuffer();
8970 if (fout->remoteVersion >= 90600)
8972 PQExpBuffer acl_subquery = createPQExpBuffer();
8973 PQExpBuffer racl_subquery = createPQExpBuffer();
8974 PQExpBuffer initacl_subquery = createPQExpBuffer();
8975 PQExpBuffer initracl_subquery = createPQExpBuffer();
8977 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8978 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8979 dopt->binary_upgrade);
8981 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8982 "(%s f.fdwowner) AS rolname, "
8983 "f.fdwhandler::pg_catalog.regproc, "
8984 "f.fdwvalidator::pg_catalog.regproc, "
8987 "%s AS initfdwacl, "
8988 "%s AS initrfdwacl, "
8989 "array_to_string(ARRAY("
8990 "SELECT quote_ident(option_name) || ' ' || "
8991 "quote_literal(option_value) "
8992 "FROM pg_options_to_table(f.fdwoptions) "
8993 "ORDER BY option_name"
8994 "), E',\n ') AS fdwoptions "
8995 "FROM pg_foreign_data_wrapper f "
8996 "LEFT JOIN pg_init_privs pip ON "
8997 "(f.oid = pip.objoid "
8998 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8999 "AND pip.objsubid = 0) ",
9002 racl_subquery->data,
9003 initacl_subquery->data,
9004 initracl_subquery->data);
9006 destroyPQExpBuffer(acl_subquery);
9007 destroyPQExpBuffer(racl_subquery);
9008 destroyPQExpBuffer(initacl_subquery);
9009 destroyPQExpBuffer(initracl_subquery);
9011 else if (fout->remoteVersion >= 90100)
9013 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9014 "(%s fdwowner) AS rolname, "
9015 "fdwhandler::pg_catalog.regproc, "
9016 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9018 "NULL as initfdwacl, NULL AS initrfdwacl, "
9019 "array_to_string(ARRAY("
9020 "SELECT quote_ident(option_name) || ' ' || "
9021 "quote_literal(option_value) "
9022 "FROM pg_options_to_table(fdwoptions) "
9023 "ORDER BY option_name"
9024 "), E',\n ') AS fdwoptions "
9025 "FROM pg_foreign_data_wrapper",
9030 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9031 "(%s fdwowner) AS rolname, "
9032 "'-' AS fdwhandler, "
9033 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9035 "NULL as initfdwacl, NULL AS initrfdwacl, "
9036 "array_to_string(ARRAY("
9037 "SELECT quote_ident(option_name) || ' ' || "
9038 "quote_literal(option_value) "
9039 "FROM pg_options_to_table(fdwoptions) "
9040 "ORDER BY option_name"
9041 "), E',\n ') AS fdwoptions "
9042 "FROM pg_foreign_data_wrapper",
9046 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9048 ntups = PQntuples(res);
9049 *numForeignDataWrappers = ntups;
9051 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9053 i_tableoid = PQfnumber(res, "tableoid");
9054 i_oid = PQfnumber(res, "oid");
9055 i_fdwname = PQfnumber(res, "fdwname");
9056 i_rolname = PQfnumber(res, "rolname");
9057 i_fdwhandler = PQfnumber(res, "fdwhandler");
9058 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9059 i_fdwacl = PQfnumber(res, "fdwacl");
9060 i_rfdwacl = PQfnumber(res, "rfdwacl");
9061 i_initfdwacl = PQfnumber(res, "initfdwacl");
9062 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9063 i_fdwoptions = PQfnumber(res, "fdwoptions");
9065 for (i = 0; i < ntups; i++)
9067 fdwinfo[i].dobj.objType = DO_FDW;
9068 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9069 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9070 AssignDumpId(&fdwinfo[i].dobj);
9071 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9072 fdwinfo[i].dobj.namespace = NULL;
9073 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9074 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9075 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9076 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9077 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9078 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9079 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9080 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9082 /* Decide whether we want to dump it */
9083 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9085 /* Do not try to dump ACL if no ACL exists. */
9086 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9087 PQgetisnull(res, i, i_initfdwacl) &&
9088 PQgetisnull(res, i, i_initrfdwacl))
9089 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9094 destroyPQExpBuffer(query);
9100 * getForeignServers:
9101 * read all foreign servers in the system catalogs and return
9102 * them in the ForeignServerInfo * structure
9104 * numForeignServers is set to the number of servers read in
9107 getForeignServers(Archive *fout, int *numForeignServers)
9109 DumpOptions *dopt = fout->dopt;
9114 ForeignServerInfo *srvinfo;
9128 /* Before 8.4, there are no foreign servers */
9129 if (fout->remoteVersion < 80400)
9131 *numForeignServers = 0;
9135 query = createPQExpBuffer();
9137 if (fout->remoteVersion >= 90600)
9139 PQExpBuffer acl_subquery = createPQExpBuffer();
9140 PQExpBuffer racl_subquery = createPQExpBuffer();
9141 PQExpBuffer initacl_subquery = createPQExpBuffer();
9142 PQExpBuffer initracl_subquery = createPQExpBuffer();
9144 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9145 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9146 dopt->binary_upgrade);
9148 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9149 "(%s f.srvowner) AS rolname, "
9150 "f.srvfdw, f.srvtype, f.srvversion, "
9153 "%s AS initsrvacl, "
9154 "%s AS initrsrvacl, "
9155 "array_to_string(ARRAY("
9156 "SELECT quote_ident(option_name) || ' ' || "
9157 "quote_literal(option_value) "
9158 "FROM pg_options_to_table(f.srvoptions) "
9159 "ORDER BY option_name"
9160 "), E',\n ') AS srvoptions "
9161 "FROM pg_foreign_server f "
9162 "LEFT JOIN pg_init_privs pip "
9163 "ON (f.oid = pip.objoid "
9164 "AND pip.classoid = 'pg_foreign_server'::regclass "
9165 "AND pip.objsubid = 0) ",
9168 racl_subquery->data,
9169 initacl_subquery->data,
9170 initracl_subquery->data);
9172 destroyPQExpBuffer(acl_subquery);
9173 destroyPQExpBuffer(racl_subquery);
9174 destroyPQExpBuffer(initacl_subquery);
9175 destroyPQExpBuffer(initracl_subquery);
9179 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9180 "(%s srvowner) AS rolname, "
9181 "srvfdw, srvtype, srvversion, srvacl, "
9183 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9184 "array_to_string(ARRAY("
9185 "SELECT quote_ident(option_name) || ' ' || "
9186 "quote_literal(option_value) "
9187 "FROM pg_options_to_table(srvoptions) "
9188 "ORDER BY option_name"
9189 "), E',\n ') AS srvoptions "
9190 "FROM pg_foreign_server",
9194 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9196 ntups = PQntuples(res);
9197 *numForeignServers = ntups;
9199 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9201 i_tableoid = PQfnumber(res, "tableoid");
9202 i_oid = PQfnumber(res, "oid");
9203 i_srvname = PQfnumber(res, "srvname");
9204 i_rolname = PQfnumber(res, "rolname");
9205 i_srvfdw = PQfnumber(res, "srvfdw");
9206 i_srvtype = PQfnumber(res, "srvtype");
9207 i_srvversion = PQfnumber(res, "srvversion");
9208 i_srvacl = PQfnumber(res, "srvacl");
9209 i_rsrvacl = PQfnumber(res, "rsrvacl");
9210 i_initsrvacl = PQfnumber(res, "initsrvacl");
9211 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9212 i_srvoptions = PQfnumber(res, "srvoptions");
9214 for (i = 0; i < ntups; i++)
9216 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9217 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9218 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9219 AssignDumpId(&srvinfo[i].dobj);
9220 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9221 srvinfo[i].dobj.namespace = NULL;
9222 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9223 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9224 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9225 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9226 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9227 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9228 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9229 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9230 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9232 /* Decide whether we want to dump it */
9233 selectDumpableObject(&(srvinfo[i].dobj), fout);
9235 /* Do not try to dump ACL if no ACL exists. */
9236 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9237 PQgetisnull(res, i, i_initsrvacl) &&
9238 PQgetisnull(res, i, i_initrsrvacl))
9239 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9244 destroyPQExpBuffer(query);
9251 * read all default ACL information in the system catalogs and return
9252 * them in the DefaultACLInfo structure
9254 * numDefaultACLs is set to the number of ACLs read in
9257 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9259 DumpOptions *dopt = fout->dopt;
9260 DefaultACLInfo *daclinfo;
9266 int i_defaclnamespace;
9267 int i_defaclobjtype;
9270 int i_initdefaclacl;
9271 int i_initrdefaclacl;
9275 if (fout->remoteVersion < 90000)
9277 *numDefaultACLs = 0;
9281 query = createPQExpBuffer();
9283 if (fout->remoteVersion >= 90600)
9285 PQExpBuffer acl_subquery = createPQExpBuffer();
9286 PQExpBuffer racl_subquery = createPQExpBuffer();
9287 PQExpBuffer initacl_subquery = createPQExpBuffer();
9288 PQExpBuffer initracl_subquery = createPQExpBuffer();
9290 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9291 initracl_subquery, "defaclacl", "defaclrole",
9292 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9293 dopt->binary_upgrade);
9295 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9296 "(%s d.defaclrole) AS defaclrole, "
9297 "d.defaclnamespace, "
9300 "%s AS rdefaclacl, "
9301 "%s AS initdefaclacl, "
9302 "%s AS initrdefaclacl "
9303 "FROM pg_default_acl d "
9304 "LEFT JOIN pg_init_privs pip ON "
9305 "(d.oid = pip.objoid "
9306 "AND pip.classoid = 'pg_default_acl'::regclass "
9307 "AND pip.objsubid = 0) ",
9310 racl_subquery->data,
9311 initacl_subquery->data,
9312 initracl_subquery->data);
9316 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9317 "(%s defaclrole) AS defaclrole, "
9321 "NULL AS rdefaclacl, "
9322 "NULL AS initdefaclacl, "
9323 "NULL AS initrdefaclacl "
9324 "FROM pg_default_acl",
9328 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9330 ntups = PQntuples(res);
9331 *numDefaultACLs = ntups;
9333 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9335 i_oid = PQfnumber(res, "oid");
9336 i_tableoid = PQfnumber(res, "tableoid");
9337 i_defaclrole = PQfnumber(res, "defaclrole");
9338 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9339 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9340 i_defaclacl = PQfnumber(res, "defaclacl");
9341 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9342 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9343 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9345 for (i = 0; i < ntups; i++)
9347 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9349 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9350 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9351 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9352 AssignDumpId(&daclinfo[i].dobj);
9353 /* cheesy ... is it worth coming up with a better object name? */
9354 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9356 if (nspid != InvalidOid)
9357 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9359 daclinfo[i].dobj.namespace = NULL;
9361 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9362 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9363 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9364 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9365 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9366 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9368 /* Decide whether we want to dump it */
9369 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9374 destroyPQExpBuffer(query);
9382 * This routine is used to dump any comments associated with the
9383 * object handed to this routine. The routine takes the object type
9384 * and object name (ready to print, except for schema decoration), plus
9385 * the namespace and owner of the object (for labeling the ArchiveEntry),
9386 * plus catalog ID and subid which are the lookup key for pg_description,
9387 * plus the dump ID for the object (for setting a dependency).
9388 * If a matching pg_description entry is found, it is dumped.
9390 * Note: in some cases, such as comments for triggers and rules, the "type"
9391 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9392 * but it doesn't seem worth complicating the API for all callers to make
9395 * Note: although this routine takes a dumpId for dependency purposes,
9396 * that purpose is just to mark the dependency in the emitted dump file
9397 * for possible future use by pg_restore. We do NOT use it for determining
9398 * ordering of the comment in the dump file, because this routine is called
9399 * after dependency sorting occurs. This routine should be called just after
9400 * calling ArchiveEntry() for the specified object.
9403 dumpComment(Archive *fout, const char *type, const char *name,
9404 const char *namespace, const char *owner,
9405 CatalogId catalogId, int subid, DumpId dumpId)
9407 DumpOptions *dopt = fout->dopt;
9408 CommentItem *comments;
9411 /* do nothing, if --no-comments is supplied */
9412 if (dopt->no_comments)
9415 /* Comments are schema not data ... except blob comments are data */
9416 if (strcmp(type, "LARGE OBJECT") != 0)
9423 /* We do dump blob comments in binary-upgrade mode */
9424 if (dopt->schemaOnly && !dopt->binary_upgrade)
9428 /* Search for comments associated with catalogId, using table */
9429 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9432 /* Is there one matching the subid? */
9433 while (ncomments > 0)
9435 if (comments->objsubid == subid)
9441 /* If a comment exists, build COMMENT ON statement */
9444 PQExpBuffer query = createPQExpBuffer();
9445 PQExpBuffer tag = createPQExpBuffer();
9447 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9448 if (namespace && *namespace)
9449 appendPQExpBuffer(query, "%s.", fmtId(namespace));
9450 appendPQExpBuffer(query, "%s IS ", name);
9451 appendStringLiteralAH(query, comments->descr, fout);
9452 appendPQExpBufferStr(query, ";\n");
9454 appendPQExpBuffer(tag, "%s %s", type, name);
9457 * We mark comments as SECTION_NONE because they really belong in the
9458 * same section as their parent, whether that is pre-data or
9461 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9462 tag->data, namespace, NULL, owner,
9463 false, "COMMENT", SECTION_NONE,
9464 query->data, "", NULL,
9468 destroyPQExpBuffer(query);
9469 destroyPQExpBuffer(tag);
9474 * dumpTableComment --
9476 * As above, but dump comments for both the specified table (or view)
9480 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9481 const char *reltypename)
9483 DumpOptions *dopt = fout->dopt;
9484 CommentItem *comments;
9489 /* do nothing, if --no-comments is supplied */
9490 if (dopt->no_comments)
9493 /* Comments are SCHEMA not data */
9497 /* Search for comments associated with relation, using table */
9498 ncomments = findComments(fout,
9499 tbinfo->dobj.catId.tableoid,
9500 tbinfo->dobj.catId.oid,
9503 /* If comments exist, build COMMENT ON statements */
9507 query = createPQExpBuffer();
9508 tag = createPQExpBuffer();
9510 while (ncomments > 0)
9512 const char *descr = comments->descr;
9513 int objsubid = comments->objsubid;
9517 resetPQExpBuffer(tag);
9518 appendPQExpBuffer(tag, "%s %s", reltypename,
9519 fmtId(tbinfo->dobj.name));
9521 resetPQExpBuffer(query);
9522 appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9523 fmtQualifiedDumpable(tbinfo));
9524 appendStringLiteralAH(query, descr, fout);
9525 appendPQExpBufferStr(query, ";\n");
9527 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9529 tbinfo->dobj.namespace->dobj.name,
9530 NULL, tbinfo->rolname,
9531 false, "COMMENT", SECTION_NONE,
9532 query->data, "", NULL,
9533 &(tbinfo->dobj.dumpId), 1,
9536 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9538 resetPQExpBuffer(tag);
9539 appendPQExpBuffer(tag, "COLUMN %s.",
9540 fmtId(tbinfo->dobj.name));
9541 appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9543 resetPQExpBuffer(query);
9544 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9545 fmtQualifiedDumpable(tbinfo));
9546 appendPQExpBuffer(query, "%s IS ",
9547 fmtId(tbinfo->attnames[objsubid - 1]));
9548 appendStringLiteralAH(query, descr, fout);
9549 appendPQExpBufferStr(query, ";\n");
9551 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9553 tbinfo->dobj.namespace->dobj.name,
9554 NULL, tbinfo->rolname,
9555 false, "COMMENT", SECTION_NONE,
9556 query->data, "", NULL,
9557 &(tbinfo->dobj.dumpId), 1,
9565 destroyPQExpBuffer(query);
9566 destroyPQExpBuffer(tag);
9572 * Find the comment(s), if any, associated with the given object. All the
9573 * objsubid values associated with the given classoid/objoid are found with
9577 findComments(Archive *fout, Oid classoid, Oid objoid,
9578 CommentItem **items)
9580 /* static storage for table of comments */
9581 static CommentItem *comments = NULL;
9582 static int ncomments = -1;
9584 CommentItem *middle = NULL;
9589 /* Get comments if we didn't already */
9591 ncomments = collectComments(fout, &comments);
9594 * Do binary search to find some item matching the object.
9597 high = &comments[ncomments - 1];
9600 middle = low + (high - low) / 2;
9602 if (classoid < middle->classoid)
9604 else if (classoid > middle->classoid)
9606 else if (objoid < middle->objoid)
9608 else if (objoid > middle->objoid)
9611 break; /* found a match */
9614 if (low > high) /* no matches */
9621 * Now determine how many items match the object. The search loop
9622 * invariant still holds: only items between low and high inclusive could
9626 while (middle > low)
9628 if (classoid != middle[-1].classoid ||
9629 objoid != middle[-1].objoid)
9638 while (middle <= high)
9640 if (classoid != middle->classoid ||
9641 objoid != middle->objoid)
9651 * collectComments --
9653 * Construct a table of all comments available for database objects.
9654 * We used to do per-object queries for the comments, but it's much faster
9655 * to pull them all over at once, and on most databases the memory cost
9658 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9661 collectComments(Archive *fout, CommentItem **items)
9671 CommentItem *comments;
9673 query = createPQExpBuffer();
9675 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9676 "FROM pg_catalog.pg_description "
9677 "ORDER BY classoid, objoid, objsubid");
9679 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9681 /* Construct lookup table containing OIDs in numeric form */
9683 i_description = PQfnumber(res, "description");
9684 i_classoid = PQfnumber(res, "classoid");
9685 i_objoid = PQfnumber(res, "objoid");
9686 i_objsubid = PQfnumber(res, "objsubid");
9688 ntups = PQntuples(res);
9690 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9692 for (i = 0; i < ntups; i++)
9694 comments[i].descr = PQgetvalue(res, i, i_description);
9695 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9696 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9697 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9700 /* Do NOT free the PGresult since we are keeping pointers into it */
9701 destroyPQExpBuffer(query);
9708 * dumpDumpableObject
9710 * This routine and its subsidiaries are responsible for creating
9711 * ArchiveEntries (TOC objects) for each object to be dumped.
9714 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9716 switch (dobj->objType)
9719 dumpNamespace(fout, (NamespaceInfo *) dobj);
9722 dumpExtension(fout, (ExtensionInfo *) dobj);
9725 dumpType(fout, (TypeInfo *) dobj);
9728 dumpShellType(fout, (ShellTypeInfo *) dobj);
9731 dumpFunc(fout, (FuncInfo *) dobj);
9734 dumpAgg(fout, (AggInfo *) dobj);
9737 dumpOpr(fout, (OprInfo *) dobj);
9739 case DO_ACCESS_METHOD:
9740 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9743 dumpOpclass(fout, (OpclassInfo *) dobj);
9746 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9749 dumpCollation(fout, (CollInfo *) dobj);
9752 dumpConversion(fout, (ConvInfo *) dobj);
9755 dumpTable(fout, (TableInfo *) dobj);
9758 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9761 dumpIndex(fout, (IndxInfo *) dobj);
9763 case DO_INDEX_ATTACH:
9764 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9767 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9769 case DO_REFRESH_MATVIEW:
9770 refreshMatViewData(fout, (TableDataInfo *) dobj);
9773 dumpRule(fout, (RuleInfo *) dobj);
9776 dumpTrigger(fout, (TriggerInfo *) dobj);
9778 case DO_EVENT_TRIGGER:
9779 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9782 dumpConstraint(fout, (ConstraintInfo *) dobj);
9784 case DO_FK_CONSTRAINT:
9785 dumpConstraint(fout, (ConstraintInfo *) dobj);
9788 dumpProcLang(fout, (ProcLangInfo *) dobj);
9791 dumpCast(fout, (CastInfo *) dobj);
9794 dumpTransform(fout, (TransformInfo *) dobj);
9796 case DO_SEQUENCE_SET:
9797 dumpSequenceData(fout, (TableDataInfo *) dobj);
9800 dumpTableData(fout, (TableDataInfo *) dobj);
9803 /* table rowtypes and array types are never dumped separately */
9806 dumpTSParser(fout, (TSParserInfo *) dobj);
9809 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9812 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9815 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9818 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9820 case DO_FOREIGN_SERVER:
9821 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9823 case DO_DEFAULT_ACL:
9824 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9827 dumpBlob(fout, (BlobInfo *) dobj);
9830 if (dobj->dump & DUMP_COMPONENT_DATA)
9831 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9832 dobj->name, NULL, NULL, "",
9833 false, "BLOBS", SECTION_DATA,
9839 dumpPolicy(fout, (PolicyInfo *) dobj);
9841 case DO_PUBLICATION:
9842 dumpPublication(fout, (PublicationInfo *) dobj);
9844 case DO_PUBLICATION_REL:
9845 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9847 case DO_SUBSCRIPTION:
9848 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9850 case DO_PRE_DATA_BOUNDARY:
9851 case DO_POST_DATA_BOUNDARY:
9852 /* never dumped, nothing to do */
9859 * writes out to fout the queries to recreate a user-defined namespace
9862 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9864 DumpOptions *dopt = fout->dopt;
9869 /* Skip if not to be dumped */
9870 if (!nspinfo->dobj.dump || dopt->dataOnly)
9873 q = createPQExpBuffer();
9874 delq = createPQExpBuffer();
9876 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9878 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9880 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9882 if (dopt->binary_upgrade)
9883 binary_upgrade_extension_member(q, &nspinfo->dobj,
9884 "SCHEMA", qnspname, NULL);
9886 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9887 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9891 false, "SCHEMA", SECTION_PRE_DATA,
9892 q->data, delq->data, NULL,
9896 /* Dump Schema Comments and Security Labels */
9897 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9898 dumpComment(fout, "SCHEMA", qnspname,
9899 NULL, nspinfo->rolname,
9900 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9902 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9903 dumpSecLabel(fout, "SCHEMA", qnspname,
9904 NULL, nspinfo->rolname,
9905 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9907 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9908 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9909 qnspname, NULL, NULL,
9910 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9911 nspinfo->initnspacl, nspinfo->initrnspacl);
9915 destroyPQExpBuffer(q);
9916 destroyPQExpBuffer(delq);
9921 * writes out to fout the queries to recreate an extension
9924 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9926 DumpOptions *dopt = fout->dopt;
9931 /* Skip if not to be dumped */
9932 if (!extinfo->dobj.dump || dopt->dataOnly)
9935 q = createPQExpBuffer();
9936 delq = createPQExpBuffer();
9938 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9940 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9942 if (!dopt->binary_upgrade)
9945 * In a regular dump, we simply create the extension, intentionally
9946 * not specifying a version, so that the destination installation's
9947 * default version is used.
9949 * Use of IF NOT EXISTS here is unlike our behavior for other object
9950 * types; but there are various scenarios in which it's convenient to
9951 * manually create the desired extension before restoring, so we
9952 * prefer to allow it to exist already.
9954 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9955 qextname, fmtId(extinfo->namespace));
9960 * In binary-upgrade mode, it's critical to reproduce the state of the
9961 * database exactly, so our procedure is to create an empty extension,
9962 * restore all the contained objects normally, and add them to the
9963 * extension one by one. This function performs just the first of
9964 * those steps. binary_upgrade_extension_member() takes care of
9965 * adding member objects as they're created.
9970 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9973 * We unconditionally create the extension, so we must drop it if it
9974 * exists. This could happen if the user deleted 'plpgsql' and then
9975 * readded it, causing its oid to be greater than g_last_builtin_oid.
9977 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9979 appendPQExpBufferStr(q,
9980 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9981 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9982 appendPQExpBufferStr(q, ", ");
9983 appendStringLiteralAH(q, extinfo->namespace, fout);
9984 appendPQExpBufferStr(q, ", ");
9985 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9986 appendStringLiteralAH(q, extinfo->extversion, fout);
9987 appendPQExpBufferStr(q, ", ");
9990 * Note that we're pushing extconfig (an OID array) back into
9991 * pg_extension exactly as-is. This is OK because pg_class OIDs are
9992 * preserved in binary upgrade.
9994 if (strlen(extinfo->extconfig) > 2)
9995 appendStringLiteralAH(q, extinfo->extconfig, fout);
9997 appendPQExpBufferStr(q, "NULL");
9998 appendPQExpBufferStr(q, ", ");
9999 if (strlen(extinfo->extcondition) > 2)
10000 appendStringLiteralAH(q, extinfo->extcondition, fout);
10002 appendPQExpBufferStr(q, "NULL");
10003 appendPQExpBufferStr(q, ", ");
10004 appendPQExpBufferStr(q, "ARRAY[");
10006 for (i = 0; i < extinfo->dobj.nDeps; i++)
10008 DumpableObject *extobj;
10010 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10011 if (extobj && extobj->objType == DO_EXTENSION)
10014 appendPQExpBufferChar(q, ',');
10015 appendStringLiteralAH(q, extobj->name, fout);
10018 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10019 appendPQExpBufferStr(q, ");\n");
10022 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10023 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10024 extinfo->dobj.name,
10027 false, "EXTENSION", SECTION_PRE_DATA,
10028 q->data, delq->data, NULL,
10032 /* Dump Extension Comments and Security Labels */
10033 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10034 dumpComment(fout, "EXTENSION", qextname,
10036 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10038 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10039 dumpSecLabel(fout, "EXTENSION", qextname,
10041 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10045 destroyPQExpBuffer(q);
10046 destroyPQExpBuffer(delq);
10051 * writes out to fout the queries to recreate a user-defined type
10054 dumpType(Archive *fout, TypeInfo *tyinfo)
10056 DumpOptions *dopt = fout->dopt;
10058 /* Skip if not to be dumped */
10059 if (!tyinfo->dobj.dump || dopt->dataOnly)
10062 /* Dump out in proper style */
10063 if (tyinfo->typtype == TYPTYPE_BASE)
10064 dumpBaseType(fout, tyinfo);
10065 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10066 dumpDomain(fout, tyinfo);
10067 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10068 dumpCompositeType(fout, tyinfo);
10069 else if (tyinfo->typtype == TYPTYPE_ENUM)
10070 dumpEnumType(fout, tyinfo);
10071 else if (tyinfo->typtype == TYPTYPE_RANGE)
10072 dumpRangeType(fout, tyinfo);
10073 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10074 dumpUndefinedType(fout, tyinfo);
10076 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10077 tyinfo->dobj.name);
10082 * writes out to fout the queries to recreate a user-defined enum type
10085 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10087 DumpOptions *dopt = fout->dopt;
10088 PQExpBuffer q = createPQExpBuffer();
10089 PQExpBuffer delq = createPQExpBuffer();
10090 PQExpBuffer query = createPQExpBuffer();
10099 if (fout->remoteVersion >= 90100)
10100 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10101 "FROM pg_catalog.pg_enum "
10102 "WHERE enumtypid = '%u'"
10103 "ORDER BY enumsortorder",
10104 tyinfo->dobj.catId.oid);
10106 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10107 "FROM pg_catalog.pg_enum "
10108 "WHERE enumtypid = '%u'"
10110 tyinfo->dobj.catId.oid);
10112 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10114 num = PQntuples(res);
10116 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10117 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10120 * CASCADE shouldn't be required here as for normal types since the I/O
10121 * functions are generic and do not get dropped.
10123 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10125 if (dopt->binary_upgrade)
10126 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10127 tyinfo->dobj.catId.oid,
10130 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10133 if (!dopt->binary_upgrade)
10135 /* Labels with server-assigned oids */
10136 for (i = 0; i < num; i++)
10138 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10140 appendPQExpBufferChar(q, ',');
10141 appendPQExpBufferStr(q, "\n ");
10142 appendStringLiteralAH(q, label, fout);
10146 appendPQExpBufferStr(q, "\n);\n");
10148 if (dopt->binary_upgrade)
10150 /* Labels with dump-assigned (preserved) oids */
10151 for (i = 0; i < num; i++)
10153 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10154 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10157 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10158 appendPQExpBuffer(q,
10159 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10161 appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10162 appendStringLiteralAH(q, label, fout);
10163 appendPQExpBufferStr(q, ";\n\n");
10167 if (dopt->binary_upgrade)
10168 binary_upgrade_extension_member(q, &tyinfo->dobj,
10170 tyinfo->dobj.namespace->dobj.name);
10172 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10173 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10175 tyinfo->dobj.namespace->dobj.name,
10177 tyinfo->rolname, false,
10178 "TYPE", SECTION_PRE_DATA,
10179 q->data, delq->data, NULL,
10183 /* Dump Type Comments and Security Labels */
10184 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10185 dumpComment(fout, "TYPE", qtypname,
10186 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10187 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10189 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10190 dumpSecLabel(fout, "TYPE", qtypname,
10191 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10192 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10194 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10195 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10197 tyinfo->dobj.namespace->dobj.name,
10198 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10199 tyinfo->inittypacl, tyinfo->initrtypacl);
10202 destroyPQExpBuffer(q);
10203 destroyPQExpBuffer(delq);
10204 destroyPQExpBuffer(query);
10211 * writes out to fout the queries to recreate a user-defined range type
10214 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10216 DumpOptions *dopt = fout->dopt;
10217 PQExpBuffer q = createPQExpBuffer();
10218 PQExpBuffer delq = createPQExpBuffer();
10219 PQExpBuffer query = createPQExpBuffer();
10226 appendPQExpBuffer(query,
10227 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10228 "opc.opcname AS opcname, "
10229 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10230 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10232 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10233 " ELSE rngcollation END AS collation, "
10234 "rngcanonical, rngsubdiff "
10235 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10236 " pg_catalog.pg_opclass opc "
10237 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10239 tyinfo->dobj.catId.oid);
10241 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10243 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10244 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10247 * CASCADE shouldn't be required here as for normal types since the I/O
10248 * functions are generic and do not get dropped.
10250 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10252 if (dopt->binary_upgrade)
10253 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10254 tyinfo->dobj.catId.oid,
10257 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10260 appendPQExpBuffer(q, "\n subtype = %s",
10261 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10263 /* print subtype_opclass only if not default for subtype */
10264 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10266 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10267 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10269 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10271 appendPQExpBufferStr(q, fmtId(opcname));
10274 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10275 if (OidIsValid(collationOid))
10277 CollInfo *coll = findCollationByOid(collationOid);
10280 appendPQExpBuffer(q, ",\n collation = %s",
10281 fmtQualifiedDumpable(coll));
10284 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10285 if (strcmp(procname, "-") != 0)
10286 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10288 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10289 if (strcmp(procname, "-") != 0)
10290 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10292 appendPQExpBufferStr(q, "\n);\n");
10294 if (dopt->binary_upgrade)
10295 binary_upgrade_extension_member(q, &tyinfo->dobj,
10297 tyinfo->dobj.namespace->dobj.name);
10299 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10300 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10302 tyinfo->dobj.namespace->dobj.name,
10304 tyinfo->rolname, false,
10305 "TYPE", SECTION_PRE_DATA,
10306 q->data, delq->data, NULL,
10310 /* Dump Type Comments and Security Labels */
10311 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10312 dumpComment(fout, "TYPE", qtypname,
10313 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10314 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10316 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10317 dumpSecLabel(fout, "TYPE", qtypname,
10318 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10319 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10321 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10322 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10324 tyinfo->dobj.namespace->dobj.name,
10325 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10326 tyinfo->inittypacl, tyinfo->initrtypacl);
10329 destroyPQExpBuffer(q);
10330 destroyPQExpBuffer(delq);
10331 destroyPQExpBuffer(query);
10337 * dumpUndefinedType
10338 * writes out to fout the queries to recreate a !typisdefined type
10340 * This is a shell type, but we use different terminology to distinguish
10341 * this case from where we have to emit a shell type definition to break
10342 * circular dependencies. An undefined type shouldn't ever have anything
10346 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10348 DumpOptions *dopt = fout->dopt;
10349 PQExpBuffer q = createPQExpBuffer();
10350 PQExpBuffer delq = createPQExpBuffer();
10354 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10355 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10357 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10359 if (dopt->binary_upgrade)
10360 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10361 tyinfo->dobj.catId.oid,
10364 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10367 if (dopt->binary_upgrade)
10368 binary_upgrade_extension_member(q, &tyinfo->dobj,
10370 tyinfo->dobj.namespace->dobj.name);
10372 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10373 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10375 tyinfo->dobj.namespace->dobj.name,
10377 tyinfo->rolname, false,
10378 "TYPE", SECTION_PRE_DATA,
10379 q->data, delq->data, NULL,
10383 /* Dump Type Comments and Security Labels */
10384 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10385 dumpComment(fout, "TYPE", qtypname,
10386 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10387 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10389 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10390 dumpSecLabel(fout, "TYPE", qtypname,
10391 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10392 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10394 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10395 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10397 tyinfo->dobj.namespace->dobj.name,
10398 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10399 tyinfo->inittypacl, tyinfo->initrtypacl);
10401 destroyPQExpBuffer(q);
10402 destroyPQExpBuffer(delq);
10409 * writes out to fout the queries to recreate a user-defined base type
10412 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10414 DumpOptions *dopt = fout->dopt;
10415 PQExpBuffer q = createPQExpBuffer();
10416 PQExpBuffer delq = createPQExpBuffer();
10417 PQExpBuffer query = createPQExpBuffer();
10435 char *typispreferred;
10440 char *typcollatable;
10442 bool typdefault_is_literal = false;
10444 /* Fetch type-specific details */
10445 if (fout->remoteVersion >= 90100)
10447 appendPQExpBuffer(query, "SELECT typlen, "
10448 "typinput, typoutput, typreceive, typsend, "
10449 "typmodin, typmodout, typanalyze, "
10450 "typreceive::pg_catalog.oid AS typreceiveoid, "
10451 "typsend::pg_catalog.oid AS typsendoid, "
10452 "typmodin::pg_catalog.oid AS typmodinoid, "
10453 "typmodout::pg_catalog.oid AS typmodoutoid, "
10454 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10455 "typcategory, typispreferred, "
10456 "typdelim, typbyval, typalign, typstorage, "
10457 "(typcollation <> 0) AS typcollatable, "
10458 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10459 "FROM pg_catalog.pg_type "
10460 "WHERE oid = '%u'::pg_catalog.oid",
10461 tyinfo->dobj.catId.oid);
10463 else if (fout->remoteVersion >= 80400)
10465 appendPQExpBuffer(query, "SELECT typlen, "
10466 "typinput, typoutput, typreceive, typsend, "
10467 "typmodin, typmodout, typanalyze, "
10468 "typreceive::pg_catalog.oid AS typreceiveoid, "
10469 "typsend::pg_catalog.oid AS typsendoid, "
10470 "typmodin::pg_catalog.oid AS typmodinoid, "
10471 "typmodout::pg_catalog.oid AS typmodoutoid, "
10472 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10473 "typcategory, typispreferred, "
10474 "typdelim, typbyval, typalign, typstorage, "
10475 "false AS typcollatable, "
10476 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10477 "FROM pg_catalog.pg_type "
10478 "WHERE oid = '%u'::pg_catalog.oid",
10479 tyinfo->dobj.catId.oid);
10481 else if (fout->remoteVersion >= 80300)
10483 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10484 appendPQExpBuffer(query, "SELECT typlen, "
10485 "typinput, typoutput, typreceive, typsend, "
10486 "typmodin, typmodout, typanalyze, "
10487 "typreceive::pg_catalog.oid AS typreceiveoid, "
10488 "typsend::pg_catalog.oid AS typsendoid, "
10489 "typmodin::pg_catalog.oid AS typmodinoid, "
10490 "typmodout::pg_catalog.oid AS typmodoutoid, "
10491 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10492 "'U' AS typcategory, false AS typispreferred, "
10493 "typdelim, typbyval, typalign, typstorage, "
10494 "false AS typcollatable, "
10495 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10496 "FROM pg_catalog.pg_type "
10497 "WHERE oid = '%u'::pg_catalog.oid",
10498 tyinfo->dobj.catId.oid);
10502 appendPQExpBuffer(query, "SELECT typlen, "
10503 "typinput, typoutput, typreceive, typsend, "
10504 "'-' AS typmodin, '-' AS typmodout, "
10506 "typreceive::pg_catalog.oid AS typreceiveoid, "
10507 "typsend::pg_catalog.oid AS typsendoid, "
10508 "0 AS typmodinoid, 0 AS typmodoutoid, "
10509 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10510 "'U' AS typcategory, false AS typispreferred, "
10511 "typdelim, typbyval, typalign, typstorage, "
10512 "false AS typcollatable, "
10513 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10514 "FROM pg_catalog.pg_type "
10515 "WHERE oid = '%u'::pg_catalog.oid",
10516 tyinfo->dobj.catId.oid);
10519 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10521 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10522 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10523 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10524 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10525 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10526 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10527 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10528 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10529 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10530 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10531 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10532 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10533 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10534 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10535 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10536 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10537 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10538 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10539 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10540 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10541 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10542 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10543 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10545 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10546 typdefault_is_literal = true; /* it needs quotes */
10551 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10552 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10555 * The reason we include CASCADE is that the circular dependency between
10556 * the type and its I/O functions makes it impossible to drop the type any
10559 appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10562 * We might already have a shell type, but setting pg_type_oid is
10563 * harmless, and in any case we'd better set the array type OID.
10565 if (dopt->binary_upgrade)
10566 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10567 tyinfo->dobj.catId.oid,
10570 appendPQExpBuffer(q,
10571 "CREATE TYPE %s (\n"
10572 " INTERNALLENGTH = %s",
10574 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10576 /* regproc result is sufficiently quoted already */
10577 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10578 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10579 if (OidIsValid(typreceiveoid))
10580 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10581 if (OidIsValid(typsendoid))
10582 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10583 if (OidIsValid(typmodinoid))
10584 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10585 if (OidIsValid(typmodoutoid))
10586 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10587 if (OidIsValid(typanalyzeoid))
10588 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10590 if (strcmp(typcollatable, "t") == 0)
10591 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10593 if (typdefault != NULL)
10595 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10596 if (typdefault_is_literal)
10597 appendStringLiteralAH(q, typdefault, fout);
10599 appendPQExpBufferStr(q, typdefault);
10602 if (OidIsValid(tyinfo->typelem))
10606 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10607 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10611 if (strcmp(typcategory, "U") != 0)
10613 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10614 appendStringLiteralAH(q, typcategory, fout);
10617 if (strcmp(typispreferred, "t") == 0)
10618 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10620 if (typdelim && strcmp(typdelim, ",") != 0)
10622 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10623 appendStringLiteralAH(q, typdelim, fout);
10626 if (strcmp(typalign, "c") == 0)
10627 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10628 else if (strcmp(typalign, "s") == 0)
10629 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10630 else if (strcmp(typalign, "i") == 0)
10631 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10632 else if (strcmp(typalign, "d") == 0)
10633 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10635 if (strcmp(typstorage, "p") == 0)
10636 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10637 else if (strcmp(typstorage, "e") == 0)
10638 appendPQExpBufferStr(q, ",\n STORAGE = external");
10639 else if (strcmp(typstorage, "x") == 0)
10640 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10641 else if (strcmp(typstorage, "m") == 0)
10642 appendPQExpBufferStr(q, ",\n STORAGE = main");
10644 if (strcmp(typbyval, "t") == 0)
10645 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10647 appendPQExpBufferStr(q, "\n);\n");
10649 if (dopt->binary_upgrade)
10650 binary_upgrade_extension_member(q, &tyinfo->dobj,
10652 tyinfo->dobj.namespace->dobj.name);
10654 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10655 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10657 tyinfo->dobj.namespace->dobj.name,
10659 tyinfo->rolname, false,
10660 "TYPE", SECTION_PRE_DATA,
10661 q->data, delq->data, NULL,
10665 /* Dump Type Comments and Security Labels */
10666 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10667 dumpComment(fout, "TYPE", qtypname,
10668 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10669 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10671 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10672 dumpSecLabel(fout, "TYPE", qtypname,
10673 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10674 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10676 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10677 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10679 tyinfo->dobj.namespace->dobj.name,
10680 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10681 tyinfo->inittypacl, tyinfo->initrtypacl);
10684 destroyPQExpBuffer(q);
10685 destroyPQExpBuffer(delq);
10686 destroyPQExpBuffer(query);
10693 * writes out to fout the queries to recreate a user-defined domain
10696 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10698 DumpOptions *dopt = fout->dopt;
10699 PQExpBuffer q = createPQExpBuffer();
10700 PQExpBuffer delq = createPQExpBuffer();
10701 PQExpBuffer query = createPQExpBuffer();
10710 bool typdefault_is_literal = false;
10712 /* Fetch domain specific details */
10713 if (fout->remoteVersion >= 90100)
10715 /* typcollation is new in 9.1 */
10716 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10717 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10718 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10720 "CASE WHEN t.typcollation <> u.typcollation "
10721 "THEN t.typcollation ELSE 0 END AS typcollation "
10722 "FROM pg_catalog.pg_type t "
10723 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10724 "WHERE t.oid = '%u'::pg_catalog.oid",
10725 tyinfo->dobj.catId.oid);
10729 appendPQExpBuffer(query, "SELECT typnotnull, "
10730 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10731 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10732 "typdefault, 0 AS typcollation "
10733 "FROM pg_catalog.pg_type "
10734 "WHERE oid = '%u'::pg_catalog.oid",
10735 tyinfo->dobj.catId.oid);
10738 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10740 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10741 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10742 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10743 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10744 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10746 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10747 typdefault_is_literal = true; /* it needs quotes */
10751 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10753 if (dopt->binary_upgrade)
10754 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10755 tyinfo->dobj.catId.oid,
10756 true); /* force array type */
10758 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10759 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10761 appendPQExpBuffer(q,
10762 "CREATE DOMAIN %s AS %s",
10766 /* Print collation only if different from base type's collation */
10767 if (OidIsValid(typcollation))
10771 coll = findCollationByOid(typcollation);
10773 appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10776 if (typnotnull[0] == 't')
10777 appendPQExpBufferStr(q, " NOT NULL");
10779 if (typdefault != NULL)
10781 appendPQExpBufferStr(q, " DEFAULT ");
10782 if (typdefault_is_literal)
10783 appendStringLiteralAH(q, typdefault, fout);
10785 appendPQExpBufferStr(q, typdefault);
10791 * Add any CHECK constraints for the domain
10793 for (i = 0; i < tyinfo->nDomChecks; i++)
10795 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10797 if (!domcheck->separate)
10798 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10799 fmtId(domcheck->dobj.name), domcheck->condef);
10802 appendPQExpBufferStr(q, ";\n");
10804 appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10806 if (dopt->binary_upgrade)
10807 binary_upgrade_extension_member(q, &tyinfo->dobj,
10808 "DOMAIN", qtypname,
10809 tyinfo->dobj.namespace->dobj.name);
10811 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10812 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10814 tyinfo->dobj.namespace->dobj.name,
10816 tyinfo->rolname, false,
10817 "DOMAIN", SECTION_PRE_DATA,
10818 q->data, delq->data, NULL,
10822 /* Dump Domain Comments and Security Labels */
10823 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10824 dumpComment(fout, "DOMAIN", qtypname,
10825 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10826 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10828 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10829 dumpSecLabel(fout, "DOMAIN", qtypname,
10830 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10831 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10833 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10834 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10836 tyinfo->dobj.namespace->dobj.name,
10837 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10838 tyinfo->inittypacl, tyinfo->initrtypacl);
10840 /* Dump any per-constraint comments */
10841 for (i = 0; i < tyinfo->nDomChecks; i++)
10843 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10844 PQExpBuffer conprefix = createPQExpBuffer();
10846 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10847 fmtId(domcheck->dobj.name));
10849 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10850 dumpComment(fout, conprefix->data, qtypname,
10851 tyinfo->dobj.namespace->dobj.name,
10853 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10855 destroyPQExpBuffer(conprefix);
10858 destroyPQExpBuffer(q);
10859 destroyPQExpBuffer(delq);
10860 destroyPQExpBuffer(query);
10866 * dumpCompositeType
10867 * writes out to fout the queries to recreate a user-defined stand-alone
10871 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10873 DumpOptions *dopt = fout->dopt;
10874 PQExpBuffer q = createPQExpBuffer();
10875 PQExpBuffer dropped = createPQExpBuffer();
10876 PQExpBuffer delq = createPQExpBuffer();
10877 PQExpBuffer query = createPQExpBuffer();
10886 int i_attisdropped;
10887 int i_attcollation;
10891 /* Fetch type specific details */
10892 if (fout->remoteVersion >= 90100)
10895 * attcollation is new in 9.1. Since we only want to dump COLLATE
10896 * clauses for attributes whose collation is different from their
10897 * type's default, we use a CASE here to suppress uninteresting
10898 * attcollations cheaply. atttypid will be 0 for dropped columns;
10899 * collation does not matter for those.
10901 appendPQExpBuffer(query, "SELECT a.attname, "
10902 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10903 "a.attlen, a.attalign, a.attisdropped, "
10904 "CASE WHEN a.attcollation <> at.typcollation "
10905 "THEN a.attcollation ELSE 0 END AS attcollation "
10906 "FROM pg_catalog.pg_type ct "
10907 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10908 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10909 "WHERE ct.oid = '%u'::pg_catalog.oid "
10910 "ORDER BY a.attnum ",
10911 tyinfo->dobj.catId.oid);
10916 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10917 * should always be false.
10919 appendPQExpBuffer(query, "SELECT a.attname, "
10920 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10921 "a.attlen, a.attalign, a.attisdropped, "
10922 "0 AS attcollation "
10923 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10924 "WHERE ct.oid = '%u'::pg_catalog.oid "
10925 "AND a.attrelid = ct.typrelid "
10926 "ORDER BY a.attnum ",
10927 tyinfo->dobj.catId.oid);
10930 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10932 ntups = PQntuples(res);
10934 i_attname = PQfnumber(res, "attname");
10935 i_atttypdefn = PQfnumber(res, "atttypdefn");
10936 i_attlen = PQfnumber(res, "attlen");
10937 i_attalign = PQfnumber(res, "attalign");
10938 i_attisdropped = PQfnumber(res, "attisdropped");
10939 i_attcollation = PQfnumber(res, "attcollation");
10941 if (dopt->binary_upgrade)
10943 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10944 tyinfo->dobj.catId.oid,
10946 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10949 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10950 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10952 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10956 for (i = 0; i < ntups; i++)
10965 attname = PQgetvalue(res, i, i_attname);
10966 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10967 attlen = PQgetvalue(res, i, i_attlen);
10968 attalign = PQgetvalue(res, i, i_attalign);
10969 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10970 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10972 if (attisdropped && !dopt->binary_upgrade)
10975 /* Format properly if not first attr */
10976 if (actual_atts++ > 0)
10977 appendPQExpBufferChar(q, ',');
10978 appendPQExpBufferStr(q, "\n\t");
10982 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10984 /* Add collation if not default for the column type */
10985 if (OidIsValid(attcollation))
10989 coll = findCollationByOid(attcollation);
10991 appendPQExpBuffer(q, " COLLATE %s",
10992 fmtQualifiedDumpable(coll));
10998 * This is a dropped attribute and we're in binary_upgrade mode.
10999 * Insert a placeholder for it in the CREATE TYPE command, and set
11000 * length and alignment with direct UPDATE to the catalogs
11001 * afterwards. See similar code in dumpTableSchema().
11003 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11005 /* stash separately for insertion after the CREATE TYPE */
11006 appendPQExpBufferStr(dropped,
11007 "\n-- For binary upgrade, recreate dropped column.\n");
11008 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11009 "SET attlen = %s, "
11010 "attalign = '%s', attbyval = false\n"
11011 "WHERE attname = ", attlen, attalign);
11012 appendStringLiteralAH(dropped, attname, fout);
11013 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
11014 appendStringLiteralAH(dropped, qualtypname, fout);
11015 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11017 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11019 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11023 appendPQExpBufferStr(q, "\n);\n");
11024 appendPQExpBufferStr(q, dropped->data);
11026 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11028 if (dopt->binary_upgrade)
11029 binary_upgrade_extension_member(q, &tyinfo->dobj,
11031 tyinfo->dobj.namespace->dobj.name);
11033 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11034 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11036 tyinfo->dobj.namespace->dobj.name,
11038 tyinfo->rolname, false,
11039 "TYPE", SECTION_PRE_DATA,
11040 q->data, delq->data, NULL,
11045 /* Dump Type Comments and Security Labels */
11046 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11047 dumpComment(fout, "TYPE", qtypname,
11048 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11049 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11051 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11052 dumpSecLabel(fout, "TYPE", qtypname,
11053 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11054 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11056 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11057 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
11059 tyinfo->dobj.namespace->dobj.name,
11060 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11061 tyinfo->inittypacl, tyinfo->initrtypacl);
11064 destroyPQExpBuffer(q);
11065 destroyPQExpBuffer(dropped);
11066 destroyPQExpBuffer(delq);
11067 destroyPQExpBuffer(query);
11071 /* Dump any per-column comments */
11072 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11073 dumpCompositeTypeColComments(fout, tyinfo);
11077 * dumpCompositeTypeColComments
11078 * writes out to fout the queries to recreate comments on the columns of
11079 * a user-defined stand-alone composite type
11082 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11084 CommentItem *comments;
11088 PQExpBuffer target;
11095 /* do nothing, if --no-comments is supplied */
11096 if (fout->dopt->no_comments)
11099 query = createPQExpBuffer();
11101 appendPQExpBuffer(query,
11102 "SELECT c.tableoid, a.attname, a.attnum "
11103 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11104 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11105 " AND NOT a.attisdropped "
11106 "ORDER BY a.attnum ",
11109 /* Fetch column attnames */
11110 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11112 ntups = PQntuples(res);
11116 destroyPQExpBuffer(query);
11120 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11122 /* Search for comments associated with type's pg_class OID */
11123 ncomments = findComments(fout,
11128 /* If no comments exist, we're done */
11129 if (ncomments <= 0)
11132 destroyPQExpBuffer(query);
11136 /* Build COMMENT ON statements */
11137 target = createPQExpBuffer();
11139 i_attnum = PQfnumber(res, "attnum");
11140 i_attname = PQfnumber(res, "attname");
11141 while (ncomments > 0)
11143 const char *attname;
11146 for (i = 0; i < ntups; i++)
11148 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11150 attname = PQgetvalue(res, i, i_attname);
11154 if (attname) /* just in case we don't find it */
11156 const char *descr = comments->descr;
11158 resetPQExpBuffer(target);
11159 appendPQExpBuffer(target, "COLUMN %s.",
11160 fmtId(tyinfo->dobj.name));
11161 appendPQExpBufferStr(target, fmtId(attname));
11163 resetPQExpBuffer(query);
11164 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11165 fmtQualifiedDumpable(tyinfo));
11166 appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11167 appendStringLiteralAH(query, descr, fout);
11168 appendPQExpBufferStr(query, ";\n");
11170 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11172 tyinfo->dobj.namespace->dobj.name,
11173 NULL, tyinfo->rolname,
11174 false, "COMMENT", SECTION_NONE,
11175 query->data, "", NULL,
11176 &(tyinfo->dobj.dumpId), 1,
11185 destroyPQExpBuffer(query);
11186 destroyPQExpBuffer(target);
11191 * writes out to fout the queries to create a shell type
11193 * We dump a shell definition in advance of the I/O functions for the type.
11196 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11198 DumpOptions *dopt = fout->dopt;
11201 /* Skip if not to be dumped */
11202 if (!stinfo->dobj.dump || dopt->dataOnly)
11205 q = createPQExpBuffer();
11208 * Note the lack of a DROP command for the shell type; any required DROP
11209 * is driven off the base type entry, instead. This interacts with
11210 * _printTocEntry()'s use of the presence of a DROP command to decide
11211 * whether an entry needs an ALTER OWNER command. We don't want to alter
11212 * the shell type's owner immediately on creation; that should happen only
11213 * after it's filled in, otherwise the backend complains.
11216 if (dopt->binary_upgrade)
11217 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11218 stinfo->baseType->dobj.catId.oid,
11221 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11222 fmtQualifiedDumpable(stinfo));
11224 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11225 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11227 stinfo->dobj.namespace->dobj.name,
11229 stinfo->baseType->rolname, false,
11230 "SHELL TYPE", SECTION_PRE_DATA,
11235 destroyPQExpBuffer(q);
11240 * writes out to fout the queries to recreate a user-defined
11241 * procedural language
11244 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11246 DumpOptions *dopt = fout->dopt;
11247 PQExpBuffer defqry;
11248 PQExpBuffer delqry;
11251 FuncInfo *funcInfo;
11252 FuncInfo *inlineInfo = NULL;
11253 FuncInfo *validatorInfo = NULL;
11255 /* Skip if not to be dumped */
11256 if (!plang->dobj.dump || dopt->dataOnly)
11260 * Try to find the support function(s). It is not an error if we don't
11261 * find them --- if the functions are in the pg_catalog schema, as is
11262 * standard in 8.1 and up, then we won't have loaded them. (In this case
11263 * we will emit a parameterless CREATE LANGUAGE command, which will
11264 * require PL template knowledge in the backend to reload.)
11267 funcInfo = findFuncByOid(plang->lanplcallfoid);
11268 if (funcInfo != NULL && !funcInfo->dobj.dump)
11269 funcInfo = NULL; /* treat not-dumped same as not-found */
11271 if (OidIsValid(plang->laninline))
11273 inlineInfo = findFuncByOid(plang->laninline);
11274 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11278 if (OidIsValid(plang->lanvalidator))
11280 validatorInfo = findFuncByOid(plang->lanvalidator);
11281 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11282 validatorInfo = NULL;
11286 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11287 * with parameters. Otherwise, we'll write a parameterless command, which
11288 * will rely on data from pg_pltemplate.
11290 useParams = (funcInfo != NULL &&
11291 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11292 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11294 defqry = createPQExpBuffer();
11295 delqry = createPQExpBuffer();
11297 qlanname = pg_strdup(fmtId(plang->dobj.name));
11299 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11304 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11305 plang->lanpltrusted ? "TRUSTED " : "",
11307 appendPQExpBuffer(defqry, " HANDLER %s",
11308 fmtQualifiedDumpable(funcInfo));
11309 if (OidIsValid(plang->laninline))
11310 appendPQExpBuffer(defqry, " INLINE %s",
11311 fmtQualifiedDumpable(inlineInfo));
11312 if (OidIsValid(plang->lanvalidator))
11313 appendPQExpBuffer(defqry, " VALIDATOR %s",
11314 fmtQualifiedDumpable(validatorInfo));
11319 * If not dumping parameters, then use CREATE OR REPLACE so that the
11320 * command will not fail if the language is preinstalled in the target
11321 * database. We restrict the use of REPLACE to this case so as to
11322 * eliminate the risk of replacing a language with incompatible
11323 * parameter settings: this command will only succeed at all if there
11324 * is a pg_pltemplate entry, and if there is one, the existing entry
11325 * must match it too.
11327 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11330 appendPQExpBufferStr(defqry, ";\n");
11332 if (dopt->binary_upgrade)
11333 binary_upgrade_extension_member(defqry, &plang->dobj,
11334 "LANGUAGE", qlanname, NULL);
11336 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11337 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11339 NULL, NULL, plang->lanowner,
11340 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11341 defqry->data, delqry->data, NULL,
11345 /* Dump Proc Lang Comments and Security Labels */
11346 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11347 dumpComment(fout, "LANGUAGE", qlanname,
11348 NULL, plang->lanowner,
11349 plang->dobj.catId, 0, plang->dobj.dumpId);
11351 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11352 dumpSecLabel(fout, "LANGUAGE", qlanname,
11353 NULL, plang->lanowner,
11354 plang->dobj.catId, 0, plang->dobj.dumpId);
11356 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11357 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11358 qlanname, NULL, NULL,
11359 plang->lanowner, plang->lanacl, plang->rlanacl,
11360 plang->initlanacl, plang->initrlanacl);
11364 destroyPQExpBuffer(defqry);
11365 destroyPQExpBuffer(delqry);
11369 * format_function_arguments: generate function name and argument list
11371 * This is used when we can rely on pg_get_function_arguments to format
11372 * the argument list. Note, however, that pg_get_function_arguments
11373 * does not special-case zero-argument aggregates.
11376 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11378 PQExpBufferData fn;
11380 initPQExpBuffer(&fn);
11381 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11382 if (is_agg && finfo->nargs == 0)
11383 appendPQExpBufferStr(&fn, "(*)");
11385 appendPQExpBuffer(&fn, "(%s)", funcargs);
11390 * format_function_arguments_old: generate function name and argument list
11392 * The argument type names are qualified if needed. The function name
11393 * is never qualified.
11395 * This is used only with pre-8.4 servers, so we aren't expecting to see
11396 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11398 * Any or all of allargtypes, argmodes, argnames may be NULL.
11401 format_function_arguments_old(Archive *fout,
11402 FuncInfo *finfo, int nallargs,
11403 char **allargtypes,
11407 PQExpBufferData fn;
11410 initPQExpBuffer(&fn);
11411 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11412 for (j = 0; j < nallargs; j++)
11416 const char *argmode;
11417 const char *argname;
11419 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11420 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11424 switch (argmodes[j][0])
11426 case PROARGMODE_IN:
11429 case PROARGMODE_OUT:
11432 case PROARGMODE_INOUT:
11433 argmode = "INOUT ";
11436 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11444 argname = argnames ? argnames[j] : (char *) NULL;
11445 if (argname && argname[0] == '\0')
11448 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11449 (j > 0) ? ", " : "",
11451 argname ? fmtId(argname) : "",
11452 argname ? " " : "",
11456 appendPQExpBufferChar(&fn, ')');
11461 * format_function_signature: generate function name and argument list
11463 * This is like format_function_arguments_old except that only a minimal
11464 * list of input argument types is generated; this is sufficient to
11465 * reference the function, but not to define it.
11467 * If honor_quotes is false then the function name is never quoted.
11468 * This is appropriate for use in TOC tags, but not in SQL commands.
11471 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11473 PQExpBufferData fn;
11476 initPQExpBuffer(&fn);
11478 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11480 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11481 for (j = 0; j < finfo->nargs; j++)
11486 appendPQExpBufferStr(&fn, ", ");
11488 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11490 appendPQExpBufferStr(&fn, typname);
11493 appendPQExpBufferChar(&fn, ')');
11500 * dump out one function
11503 dumpFunc(Archive *fout, FuncInfo *finfo)
11505 DumpOptions *dopt = fout->dopt;
11508 PQExpBuffer delqry;
11509 PQExpBuffer asPart;
11511 char *funcsig; /* identity signature */
11512 char *funcfullsig = NULL; /* full signature */
11520 char *proallargtypes;
11528 char *proleakproof;
11536 char **allargtypes = NULL;
11537 char **argmodes = NULL;
11538 char **argnames = NULL;
11539 char **configitems = NULL;
11540 int nconfigitems = 0;
11541 const char *keyword;
11544 /* Skip if not to be dumped */
11545 if (!finfo->dobj.dump || dopt->dataOnly)
11548 query = createPQExpBuffer();
11549 q = createPQExpBuffer();
11550 delqry = createPQExpBuffer();
11551 asPart = createPQExpBuffer();
11553 /* Fetch function-specific details */
11554 if (fout->remoteVersion >= 110000)
11557 * prokind was added in 11
11559 appendPQExpBuffer(query,
11560 "SELECT proretset, prosrc, probin, "
11561 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11562 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11563 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11564 "array_to_string(protrftypes, ' ') AS protrftypes, "
11565 "prokind, provolatile, proisstrict, prosecdef, "
11566 "proleakproof, proconfig, procost, prorows, "
11568 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11569 "FROM pg_catalog.pg_proc "
11570 "WHERE oid = '%u'::pg_catalog.oid",
11571 finfo->dobj.catId.oid);
11573 else if (fout->remoteVersion >= 90600)
11576 * proparallel was added in 9.6
11578 appendPQExpBuffer(query,
11579 "SELECT proretset, prosrc, probin, "
11580 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11581 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11582 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11583 "array_to_string(protrftypes, ' ') AS protrftypes, "
11584 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11585 "provolatile, proisstrict, prosecdef, "
11586 "proleakproof, proconfig, procost, prorows, "
11588 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11589 "FROM pg_catalog.pg_proc "
11590 "WHERE oid = '%u'::pg_catalog.oid",
11591 finfo->dobj.catId.oid);
11593 else if (fout->remoteVersion >= 90500)
11596 * protrftypes was added in 9.5
11598 appendPQExpBuffer(query,
11599 "SELECT proretset, prosrc, probin, "
11600 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11601 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11602 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11603 "array_to_string(protrftypes, ' ') AS protrftypes, "
11604 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11605 "provolatile, proisstrict, prosecdef, "
11606 "proleakproof, proconfig, procost, prorows, "
11607 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11608 "FROM pg_catalog.pg_proc "
11609 "WHERE oid = '%u'::pg_catalog.oid",
11610 finfo->dobj.catId.oid);
11612 else if (fout->remoteVersion >= 90200)
11615 * proleakproof was added in 9.2
11617 appendPQExpBuffer(query,
11618 "SELECT proretset, prosrc, probin, "
11619 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11620 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11621 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11622 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11623 "provolatile, proisstrict, prosecdef, "
11624 "proleakproof, proconfig, procost, prorows, "
11625 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11626 "FROM pg_catalog.pg_proc "
11627 "WHERE oid = '%u'::pg_catalog.oid",
11628 finfo->dobj.catId.oid);
11630 else if (fout->remoteVersion >= 80400)
11633 * In 8.4 and up we rely on pg_get_function_arguments and
11634 * pg_get_function_result instead of examining proallargtypes etc.
11636 appendPQExpBuffer(query,
11637 "SELECT proretset, prosrc, probin, "
11638 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11639 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11640 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11641 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11642 "provolatile, proisstrict, prosecdef, "
11643 "false AS proleakproof, "
11644 " proconfig, procost, prorows, "
11645 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11646 "FROM pg_catalog.pg_proc "
11647 "WHERE oid = '%u'::pg_catalog.oid",
11648 finfo->dobj.catId.oid);
11650 else if (fout->remoteVersion >= 80300)
11652 appendPQExpBuffer(query,
11653 "SELECT proretset, prosrc, probin, "
11654 "proallargtypes, proargmodes, proargnames, "
11656 "provolatile, proisstrict, prosecdef, "
11657 "false AS proleakproof, "
11658 "proconfig, procost, prorows, "
11659 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11660 "FROM pg_catalog.pg_proc "
11661 "WHERE oid = '%u'::pg_catalog.oid",
11662 finfo->dobj.catId.oid);
11664 else if (fout->remoteVersion >= 80100)
11666 appendPQExpBuffer(query,
11667 "SELECT proretset, prosrc, probin, "
11668 "proallargtypes, proargmodes, proargnames, "
11670 "provolatile, proisstrict, prosecdef, "
11671 "false AS proleakproof, "
11672 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11673 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11674 "FROM pg_catalog.pg_proc "
11675 "WHERE oid = '%u'::pg_catalog.oid",
11676 finfo->dobj.catId.oid);
11680 appendPQExpBuffer(query,
11681 "SELECT proretset, prosrc, probin, "
11682 "null AS proallargtypes, "
11683 "null AS proargmodes, "
11686 "provolatile, proisstrict, prosecdef, "
11687 "false AS proleakproof, "
11688 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11689 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11690 "FROM pg_catalog.pg_proc "
11691 "WHERE oid = '%u'::pg_catalog.oid",
11692 finfo->dobj.catId.oid);
11695 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11697 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11698 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11699 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11700 if (fout->remoteVersion >= 80400)
11702 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11703 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11704 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11705 proallargtypes = proargmodes = proargnames = NULL;
11709 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11710 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11711 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11712 funcargs = funciargs = funcresult = NULL;
11714 if (PQfnumber(res, "protrftypes") != -1)
11715 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11717 protrftypes = NULL;
11718 prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11719 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11720 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11721 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11722 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11723 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11724 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11725 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11727 if (PQfnumber(res, "proparallel") != -1)
11728 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11730 proparallel = NULL;
11732 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11735 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11736 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11737 * versions would set it to "-". There are no known cases in which prosrc
11738 * is unused, so the tests below for "-" are probably useless.
11740 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11742 appendPQExpBufferStr(asPart, "AS ");
11743 appendStringLiteralAH(asPart, probin, fout);
11744 if (strcmp(prosrc, "-") != 0)
11746 appendPQExpBufferStr(asPart, ", ");
11749 * where we have bin, use dollar quoting if allowed and src
11750 * contains quote or backslash; else use regular quoting.
11752 if (dopt->disable_dollar_quoting ||
11753 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11754 appendStringLiteralAH(asPart, prosrc, fout);
11756 appendStringLiteralDQ(asPart, prosrc, NULL);
11761 if (strcmp(prosrc, "-") != 0)
11763 appendPQExpBufferStr(asPart, "AS ");
11764 /* with no bin, dollar quote src unconditionally if allowed */
11765 if (dopt->disable_dollar_quoting)
11766 appendStringLiteralAH(asPart, prosrc, fout);
11768 appendStringLiteralDQ(asPart, prosrc, NULL);
11772 nallargs = finfo->nargs; /* unless we learn different from allargs */
11774 if (proallargtypes && *proallargtypes)
11778 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11779 nitems < finfo->nargs)
11781 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11784 allargtypes = NULL;
11790 if (proargmodes && *proargmodes)
11794 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11795 nitems != nallargs)
11797 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11804 if (proargnames && *proargnames)
11808 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11809 nitems != nallargs)
11811 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11818 if (proconfig && *proconfig)
11820 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11822 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11825 configitems = NULL;
11832 /* 8.4 or later; we rely on server-side code for most of the work */
11833 funcfullsig = format_function_arguments(finfo, funcargs, false);
11834 funcsig = format_function_arguments(finfo, funciargs, false);
11837 /* pre-8.4, do it ourselves */
11838 funcsig = format_function_arguments_old(fout,
11839 finfo, nallargs, allargtypes,
11840 argmodes, argnames);
11842 funcsig_tag = format_function_signature(fout, finfo, false);
11844 if (prokind[0] == PROKIND_PROCEDURE)
11845 keyword = "PROCEDURE";
11847 keyword = "FUNCTION"; /* works for window functions too */
11849 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11851 fmtId(finfo->dobj.namespace->dobj.name),
11854 appendPQExpBuffer(q, "CREATE %s %s.%s",
11856 fmtId(finfo->dobj.namespace->dobj.name),
11857 funcfullsig ? funcfullsig :
11860 if (prokind[0] == PROKIND_PROCEDURE)
11861 /* no result type to output */ ;
11862 else if (funcresult)
11863 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11866 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11868 appendPQExpBuffer(q, " RETURNS %s%s",
11869 (proretset[0] == 't') ? "SETOF " : "",
11874 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11876 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11878 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11881 appendPQExpBufferStr(q, " TRANSFORM ");
11882 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11883 for (i = 0; typeids[i]; i++)
11886 appendPQExpBufferStr(q, ", ");
11887 appendPQExpBuffer(q, "FOR TYPE %s",
11888 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11892 if (prokind[0] == PROKIND_WINDOW)
11893 appendPQExpBufferStr(q, " WINDOW");
11895 if (provolatile[0] != PROVOLATILE_VOLATILE)
11897 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11898 appendPQExpBufferStr(q, " IMMUTABLE");
11899 else if (provolatile[0] == PROVOLATILE_STABLE)
11900 appendPQExpBufferStr(q, " STABLE");
11901 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11902 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11906 if (proisstrict[0] == 't')
11907 appendPQExpBufferStr(q, " STRICT");
11909 if (prosecdef[0] == 't')
11910 appendPQExpBufferStr(q, " SECURITY DEFINER");
11912 if (proleakproof[0] == 't')
11913 appendPQExpBufferStr(q, " LEAKPROOF");
11916 * COST and ROWS are emitted only if present and not default, so as not to
11917 * break backwards-compatibility of the dump without need. Keep this code
11918 * in sync with the defaults in functioncmds.c.
11920 if (strcmp(procost, "0") != 0)
11922 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11924 /* default cost is 1 */
11925 if (strcmp(procost, "1") != 0)
11926 appendPQExpBuffer(q, " COST %s", procost);
11930 /* default cost is 100 */
11931 if (strcmp(procost, "100") != 0)
11932 appendPQExpBuffer(q, " COST %s", procost);
11935 if (proretset[0] == 't' &&
11936 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11937 appendPQExpBuffer(q, " ROWS %s", prorows);
11939 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11941 if (proparallel[0] == PROPARALLEL_SAFE)
11942 appendPQExpBufferStr(q, " PARALLEL SAFE");
11943 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11944 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11945 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11946 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11950 for (i = 0; i < nconfigitems; i++)
11952 /* we feel free to scribble on configitems[] here */
11953 char *configitem = configitems[i];
11956 pos = strchr(configitem, '=');
11960 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
11963 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11964 * by flatten_set_variable_args() before they were put into the
11965 * proconfig array. However, because the quoting rules used there
11966 * aren't exactly like SQL's, we have to break the list value apart
11967 * and then quote the elements as string literals. (The elements may
11968 * be double-quoted as-is, but we can't just feed them to the SQL
11969 * parser; it would do the wrong thing with elements that are
11970 * zero-length or longer than NAMEDATALEN.)
11972 * Variables that are not so marked should just be emitted as simple
11973 * string literals. If the variable is not known to
11974 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
11975 * to use GUC_LIST_QUOTE for extension variables.
11977 if (variable_is_guc_list_quote(configitem))
11982 /* Parse string into list of identifiers */
11983 /* this shouldn't fail really */
11984 if (SplitGUCList(pos, ',', &namelist))
11986 for (nameptr = namelist; *nameptr; nameptr++)
11988 if (nameptr != namelist)
11989 appendPQExpBufferStr(q, ", ");
11990 appendStringLiteralAH(q, *nameptr, fout);
11996 appendStringLiteralAH(q, pos, fout);
11999 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
12001 if (dopt->binary_upgrade)
12002 binary_upgrade_extension_member(q, &finfo->dobj,
12004 finfo->dobj.namespace->dobj.name);
12006 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12007 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12009 finfo->dobj.namespace->dobj.name,
12011 finfo->rolname, false,
12012 keyword, SECTION_PRE_DATA,
12013 q->data, delqry->data, NULL,
12017 /* Dump Function Comments and Security Labels */
12018 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12019 dumpComment(fout, keyword, funcsig,
12020 finfo->dobj.namespace->dobj.name, finfo->rolname,
12021 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12023 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12024 dumpSecLabel(fout, keyword, funcsig,
12025 finfo->dobj.namespace->dobj.name, finfo->rolname,
12026 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12028 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12029 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
12031 finfo->dobj.namespace->dobj.name,
12032 finfo->rolname, finfo->proacl, finfo->rproacl,
12033 finfo->initproacl, finfo->initrproacl);
12037 destroyPQExpBuffer(query);
12038 destroyPQExpBuffer(q);
12039 destroyPQExpBuffer(delqry);
12040 destroyPQExpBuffer(asPart);
12057 * Dump a user-defined cast
12060 dumpCast(Archive *fout, CastInfo *cast)
12062 DumpOptions *dopt = fout->dopt;
12063 PQExpBuffer defqry;
12064 PQExpBuffer delqry;
12065 PQExpBuffer labelq;
12066 PQExpBuffer castargs;
12067 FuncInfo *funcInfo = NULL;
12071 /* Skip if not to be dumped */
12072 if (!cast->dobj.dump || dopt->dataOnly)
12075 /* Cannot dump if we don't have the cast function's info */
12076 if (OidIsValid(cast->castfunc))
12078 funcInfo = findFuncByOid(cast->castfunc);
12079 if (funcInfo == NULL)
12080 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12084 defqry = createPQExpBuffer();
12085 delqry = createPQExpBuffer();
12086 labelq = createPQExpBuffer();
12087 castargs = createPQExpBuffer();
12089 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12090 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12091 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12092 sourceType, targetType);
12094 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12095 sourceType, targetType);
12097 switch (cast->castmethod)
12099 case COERCION_METHOD_BINARY:
12100 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12102 case COERCION_METHOD_INOUT:
12103 appendPQExpBufferStr(defqry, "WITH INOUT");
12105 case COERCION_METHOD_FUNCTION:
12108 char *fsig = format_function_signature(fout, funcInfo, true);
12111 * Always qualify the function name (format_function_signature
12112 * won't qualify it).
12114 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12115 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12119 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12122 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12125 if (cast->castcontext == 'a')
12126 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12127 else if (cast->castcontext == 'i')
12128 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12129 appendPQExpBufferStr(defqry, ";\n");
12131 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12132 sourceType, targetType);
12134 appendPQExpBuffer(castargs, "(%s AS %s)",
12135 sourceType, targetType);
12137 if (dopt->binary_upgrade)
12138 binary_upgrade_extension_member(defqry, &cast->dobj,
12139 "CAST", castargs->data, NULL);
12141 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12142 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12145 false, "CAST", SECTION_PRE_DATA,
12146 defqry->data, delqry->data, NULL,
12150 /* Dump Cast Comments */
12151 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12152 dumpComment(fout, "CAST", castargs->data,
12154 cast->dobj.catId, 0, cast->dobj.dumpId);
12159 destroyPQExpBuffer(defqry);
12160 destroyPQExpBuffer(delqry);
12161 destroyPQExpBuffer(labelq);
12162 destroyPQExpBuffer(castargs);
12169 dumpTransform(Archive *fout, TransformInfo *transform)
12171 DumpOptions *dopt = fout->dopt;
12172 PQExpBuffer defqry;
12173 PQExpBuffer delqry;
12174 PQExpBuffer labelq;
12175 PQExpBuffer transformargs;
12176 FuncInfo *fromsqlFuncInfo = NULL;
12177 FuncInfo *tosqlFuncInfo = NULL;
12179 char *transformType;
12181 /* Skip if not to be dumped */
12182 if (!transform->dobj.dump || dopt->dataOnly)
12185 /* Cannot dump if we don't have the transform functions' info */
12186 if (OidIsValid(transform->trffromsql))
12188 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12189 if (fromsqlFuncInfo == NULL)
12190 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12191 transform->trffromsql);
12193 if (OidIsValid(transform->trftosql))
12195 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12196 if (tosqlFuncInfo == NULL)
12197 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12198 transform->trftosql);
12201 defqry = createPQExpBuffer();
12202 delqry = createPQExpBuffer();
12203 labelq = createPQExpBuffer();
12204 transformargs = createPQExpBuffer();
12206 lanname = get_language_name(fout, transform->trflang);
12207 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12209 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12210 transformType, lanname);
12212 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12213 transformType, lanname);
12215 if (!transform->trffromsql && !transform->trftosql)
12216 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12218 if (transform->trffromsql)
12220 if (fromsqlFuncInfo)
12222 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12225 * Always qualify the function name (format_function_signature
12226 * won't qualify it).
12228 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12229 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12233 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12236 if (transform->trftosql)
12238 if (transform->trffromsql)
12239 appendPQExpBuffer(defqry, ", ");
12243 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12246 * Always qualify the function name (format_function_signature
12247 * won't qualify it).
12249 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12250 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12254 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12257 appendPQExpBuffer(defqry, ");\n");
12259 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12260 transformType, lanname);
12262 appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12263 transformType, lanname);
12265 if (dopt->binary_upgrade)
12266 binary_upgrade_extension_member(defqry, &transform->dobj,
12267 "TRANSFORM", transformargs->data, NULL);
12269 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12270 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12273 false, "TRANSFORM", SECTION_PRE_DATA,
12274 defqry->data, delqry->data, NULL,
12275 transform->dobj.dependencies, transform->dobj.nDeps,
12278 /* Dump Transform Comments */
12279 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12280 dumpComment(fout, "TRANSFORM", transformargs->data,
12282 transform->dobj.catId, 0, transform->dobj.dumpId);
12285 free(transformType);
12286 destroyPQExpBuffer(defqry);
12287 destroyPQExpBuffer(delqry);
12288 destroyPQExpBuffer(labelq);
12289 destroyPQExpBuffer(transformargs);
12295 * write out a single operator definition
12298 dumpOpr(Archive *fout, OprInfo *oprinfo)
12300 DumpOptions *dopt = fout->dopt;
12305 PQExpBuffer details;
12330 /* Skip if not to be dumped */
12331 if (!oprinfo->dobj.dump || dopt->dataOnly)
12335 * some operators are invalid because they were the result of user
12336 * defining operators before commutators exist
12338 if (!OidIsValid(oprinfo->oprcode))
12341 query = createPQExpBuffer();
12342 q = createPQExpBuffer();
12343 delq = createPQExpBuffer();
12344 oprid = createPQExpBuffer();
12345 details = createPQExpBuffer();
12347 if (fout->remoteVersion >= 80300)
12349 appendPQExpBuffer(query, "SELECT oprkind, "
12350 "oprcode::pg_catalog.regprocedure, "
12351 "oprleft::pg_catalog.regtype, "
12352 "oprright::pg_catalog.regtype, "
12355 "oprrest::pg_catalog.regprocedure, "
12356 "oprjoin::pg_catalog.regprocedure, "
12357 "oprcanmerge, oprcanhash "
12358 "FROM pg_catalog.pg_operator "
12359 "WHERE oid = '%u'::pg_catalog.oid",
12360 oprinfo->dobj.catId.oid);
12364 appendPQExpBuffer(query, "SELECT oprkind, "
12365 "oprcode::pg_catalog.regprocedure, "
12366 "oprleft::pg_catalog.regtype, "
12367 "oprright::pg_catalog.regtype, "
12370 "oprrest::pg_catalog.regprocedure, "
12371 "oprjoin::pg_catalog.regprocedure, "
12372 "(oprlsortop != 0) AS oprcanmerge, "
12374 "FROM pg_catalog.pg_operator "
12375 "WHERE oid = '%u'::pg_catalog.oid",
12376 oprinfo->dobj.catId.oid);
12379 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12381 i_oprkind = PQfnumber(res, "oprkind");
12382 i_oprcode = PQfnumber(res, "oprcode");
12383 i_oprleft = PQfnumber(res, "oprleft");
12384 i_oprright = PQfnumber(res, "oprright");
12385 i_oprcom = PQfnumber(res, "oprcom");
12386 i_oprnegate = PQfnumber(res, "oprnegate");
12387 i_oprrest = PQfnumber(res, "oprrest");
12388 i_oprjoin = PQfnumber(res, "oprjoin");
12389 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12390 i_oprcanhash = PQfnumber(res, "oprcanhash");
12392 oprkind = PQgetvalue(res, 0, i_oprkind);
12393 oprcode = PQgetvalue(res, 0, i_oprcode);
12394 oprleft = PQgetvalue(res, 0, i_oprleft);
12395 oprright = PQgetvalue(res, 0, i_oprright);
12396 oprcom = PQgetvalue(res, 0, i_oprcom);
12397 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12398 oprrest = PQgetvalue(res, 0, i_oprrest);
12399 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12400 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12401 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12403 oprregproc = convertRegProcReference(fout, oprcode);
12406 appendPQExpBuffer(details, " PROCEDURE = %s", oprregproc);
12410 appendPQExpBuffer(oprid, "%s (",
12411 oprinfo->dobj.name);
12414 * right unary means there's a left arg and left unary means there's a
12417 if (strcmp(oprkind, "r") == 0 ||
12418 strcmp(oprkind, "b") == 0)
12420 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12421 appendPQExpBufferStr(oprid, oprleft);
12424 appendPQExpBufferStr(oprid, "NONE");
12426 if (strcmp(oprkind, "l") == 0 ||
12427 strcmp(oprkind, "b") == 0)
12429 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12430 appendPQExpBuffer(oprid, ", %s)", oprright);
12433 appendPQExpBufferStr(oprid, ", NONE)");
12435 oprref = getFormattedOperatorName(fout, oprcom);
12438 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12442 oprref = getFormattedOperatorName(fout, oprnegate);
12445 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12449 if (strcmp(oprcanmerge, "t") == 0)
12450 appendPQExpBufferStr(details, ",\n MERGES");
12452 if (strcmp(oprcanhash, "t") == 0)
12453 appendPQExpBufferStr(details, ",\n HASHES");
12455 oprregproc = convertRegProcReference(fout, oprrest);
12458 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12462 oprregproc = convertRegProcReference(fout, oprjoin);
12465 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12469 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12470 fmtId(oprinfo->dobj.namespace->dobj.name),
12473 appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12474 fmtId(oprinfo->dobj.namespace->dobj.name),
12475 oprinfo->dobj.name, details->data);
12477 if (dopt->binary_upgrade)
12478 binary_upgrade_extension_member(q, &oprinfo->dobj,
12479 "OPERATOR", oprid->data,
12480 oprinfo->dobj.namespace->dobj.name);
12482 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12483 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12484 oprinfo->dobj.name,
12485 oprinfo->dobj.namespace->dobj.name,
12488 false, "OPERATOR", SECTION_PRE_DATA,
12489 q->data, delq->data, NULL,
12493 /* Dump Operator Comments */
12494 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12495 dumpComment(fout, "OPERATOR", oprid->data,
12496 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12497 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12501 destroyPQExpBuffer(query);
12502 destroyPQExpBuffer(q);
12503 destroyPQExpBuffer(delq);
12504 destroyPQExpBuffer(oprid);
12505 destroyPQExpBuffer(details);
12509 * Convert a function reference obtained from pg_operator
12511 * Returns allocated string of what to print, or NULL if function references
12512 * is InvalidOid. Returned string is expected to be free'd by the caller.
12514 * The input is a REGPROCEDURE display; we have to strip the argument-types
12518 convertRegProcReference(Archive *fout, const char *proc)
12524 /* In all cases "-" means a null reference */
12525 if (strcmp(proc, "-") == 0)
12528 name = pg_strdup(proc);
12529 /* find non-double-quoted left paren */
12531 for (paren = name; *paren; paren++)
12533 if (*paren == '(' && !inquote)
12539 inquote = !inquote;
12545 * getFormattedOperatorName - retrieve the operator name for the
12546 * given operator OID (presented in string form).
12548 * Returns an allocated string, or NULL if the given OID is invalid.
12549 * Caller is responsible for free'ing result string.
12551 * What we produce has the format "OPERATOR(schema.oprname)". This is only
12552 * useful in commands where the operator's argument types can be inferred from
12553 * context. We always schema-qualify the name, though. The predecessor to
12554 * this code tried to skip the schema qualification if possible, but that led
12555 * to wrong results in corner cases, such as if an operator and its negator
12556 * are in different schemas.
12559 getFormattedOperatorName(Archive *fout, const char *oproid)
12563 /* In all cases "0" means a null reference */
12564 if (strcmp(oproid, "0") == 0)
12567 oprInfo = findOprByOid(atooid(oproid));
12568 if (oprInfo == NULL)
12570 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12575 return psprintf("OPERATOR(%s.%s)",
12576 fmtId(oprInfo->dobj.namespace->dobj.name),
12577 oprInfo->dobj.name);
12581 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12583 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12584 * argument lists of these functions are predetermined. Note that the
12585 * caller should ensure we are in the proper schema, because the results
12586 * are search path dependent!
12589 convertTSFunction(Archive *fout, Oid funcOid)
12595 snprintf(query, sizeof(query),
12596 "SELECT '%u'::pg_catalog.regproc", funcOid);
12597 res = ExecuteSqlQueryForSingleRow(fout, query);
12599 result = pg_strdup(PQgetvalue(res, 0, 0));
12608 * write out a single access method definition
12611 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12613 DumpOptions *dopt = fout->dopt;
12618 /* Skip if not to be dumped */
12619 if (!aminfo->dobj.dump || dopt->dataOnly)
12622 q = createPQExpBuffer();
12623 delq = createPQExpBuffer();
12625 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12627 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12629 switch (aminfo->amtype)
12632 appendPQExpBuffer(q, "TYPE INDEX ");
12635 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12636 aminfo->amtype, qamname);
12637 destroyPQExpBuffer(q);
12638 destroyPQExpBuffer(delq);
12643 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12645 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12648 if (dopt->binary_upgrade)
12649 binary_upgrade_extension_member(q, &aminfo->dobj,
12650 "ACCESS METHOD", qamname, NULL);
12652 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12653 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12658 false, "ACCESS METHOD", SECTION_PRE_DATA,
12659 q->data, delq->data, NULL,
12663 /* Dump Access Method Comments */
12664 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12665 dumpComment(fout, "ACCESS METHOD", qamname,
12667 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12669 destroyPQExpBuffer(q);
12670 destroyPQExpBuffer(delq);
12676 * write out a single operator class definition
12679 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12681 DumpOptions *dopt = fout->dopt;
12685 PQExpBuffer nameusing;
12692 int i_opcfamilyname;
12693 int i_opcfamilynsp;
12695 int i_amopstrategy;
12696 int i_amopreqcheck;
12699 int i_sortfamilynsp;
12702 int i_amproclefttype;
12703 int i_amprocrighttype;
12708 char *opcfamilyname;
12709 char *opcfamilynsp;
12711 char *amopstrategy;
12712 char *amopreqcheck;
12715 char *sortfamilynsp;
12718 char *amproclefttype;
12719 char *amprocrighttype;
12723 /* Skip if not to be dumped */
12724 if (!opcinfo->dobj.dump || dopt->dataOnly)
12727 query = createPQExpBuffer();
12728 q = createPQExpBuffer();
12729 delq = createPQExpBuffer();
12730 nameusing = createPQExpBuffer();
12732 /* Get additional fields from the pg_opclass row */
12733 if (fout->remoteVersion >= 80300)
12735 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12736 "opckeytype::pg_catalog.regtype, "
12737 "opcdefault, opcfamily, "
12738 "opfname AS opcfamilyname, "
12739 "nspname AS opcfamilynsp, "
12740 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12741 "FROM pg_catalog.pg_opclass c "
12742 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12743 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12744 "WHERE c.oid = '%u'::pg_catalog.oid",
12745 opcinfo->dobj.catId.oid);
12749 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12750 "opckeytype::pg_catalog.regtype, "
12751 "opcdefault, NULL AS opcfamily, "
12752 "NULL AS opcfamilyname, "
12753 "NULL AS opcfamilynsp, "
12754 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12755 "FROM pg_catalog.pg_opclass "
12756 "WHERE oid = '%u'::pg_catalog.oid",
12757 opcinfo->dobj.catId.oid);
12760 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12762 i_opcintype = PQfnumber(res, "opcintype");
12763 i_opckeytype = PQfnumber(res, "opckeytype");
12764 i_opcdefault = PQfnumber(res, "opcdefault");
12765 i_opcfamily = PQfnumber(res, "opcfamily");
12766 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12767 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12768 i_amname = PQfnumber(res, "amname");
12770 /* opcintype may still be needed after we PQclear res */
12771 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12772 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12773 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12774 /* opcfamily will still be needed after we PQclear res */
12775 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12776 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12777 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12778 /* amname will still be needed after we PQclear res */
12779 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12781 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12782 fmtQualifiedDumpable(opcinfo));
12783 appendPQExpBuffer(delq, " USING %s;\n",
12786 /* Build the fixed portion of the CREATE command */
12787 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12788 fmtQualifiedDumpable(opcinfo));
12789 if (strcmp(opcdefault, "t") == 0)
12790 appendPQExpBufferStr(q, "DEFAULT ");
12791 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12794 if (strlen(opcfamilyname) > 0)
12796 appendPQExpBufferStr(q, " FAMILY ");
12797 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12798 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12800 appendPQExpBufferStr(q, " AS\n ");
12804 if (strcmp(opckeytype, "-") != 0)
12806 appendPQExpBuffer(q, "STORAGE %s",
12814 * Now fetch and print the OPERATOR entries (pg_amop rows).
12816 * Print only those opfamily members that are tied to the opclass by
12817 * pg_depend entries.
12819 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12820 * older server's opclass in which it is used. This is to avoid
12821 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12822 * older server and then reload into that old version. This can go away
12823 * once 8.3 is so old as to not be of interest to anyone.
12825 resetPQExpBuffer(query);
12827 if (fout->remoteVersion >= 90100)
12829 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12830 "amopopr::pg_catalog.regoperator, "
12831 "opfname AS sortfamily, "
12832 "nspname AS sortfamilynsp "
12833 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12834 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12835 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12836 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12837 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12838 "AND refobjid = '%u'::pg_catalog.oid "
12839 "AND amopfamily = '%s'::pg_catalog.oid "
12840 "ORDER BY amopstrategy",
12841 opcinfo->dobj.catId.oid,
12844 else if (fout->remoteVersion >= 80400)
12846 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12847 "amopopr::pg_catalog.regoperator, "
12848 "NULL AS sortfamily, "
12849 "NULL AS sortfamilynsp "
12850 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12851 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12852 "AND refobjid = '%u'::pg_catalog.oid "
12853 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12854 "AND objid = ao.oid "
12855 "ORDER BY amopstrategy",
12856 opcinfo->dobj.catId.oid);
12858 else if (fout->remoteVersion >= 80300)
12860 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12861 "amopopr::pg_catalog.regoperator, "
12862 "NULL AS sortfamily, "
12863 "NULL AS sortfamilynsp "
12864 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12865 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12866 "AND refobjid = '%u'::pg_catalog.oid "
12867 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12868 "AND objid = ao.oid "
12869 "ORDER BY amopstrategy",
12870 opcinfo->dobj.catId.oid);
12875 * Here, we print all entries since there are no opfamilies and hence
12876 * no loose operators to worry about.
12878 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12879 "amopopr::pg_catalog.regoperator, "
12880 "NULL AS sortfamily, "
12881 "NULL AS sortfamilynsp "
12882 "FROM pg_catalog.pg_amop "
12883 "WHERE amopclaid = '%u'::pg_catalog.oid "
12884 "ORDER BY amopstrategy",
12885 opcinfo->dobj.catId.oid);
12888 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12890 ntups = PQntuples(res);
12892 i_amopstrategy = PQfnumber(res, "amopstrategy");
12893 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12894 i_amopopr = PQfnumber(res, "amopopr");
12895 i_sortfamily = PQfnumber(res, "sortfamily");
12896 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12898 for (i = 0; i < ntups; i++)
12900 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12901 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12902 amopopr = PQgetvalue(res, i, i_amopopr);
12903 sortfamily = PQgetvalue(res, i, i_sortfamily);
12904 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12907 appendPQExpBufferStr(q, " ,\n ");
12909 appendPQExpBuffer(q, "OPERATOR %s %s",
12910 amopstrategy, amopopr);
12912 if (strlen(sortfamily) > 0)
12914 appendPQExpBufferStr(q, " FOR ORDER BY ");
12915 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12916 appendPQExpBufferStr(q, fmtId(sortfamily));
12919 if (strcmp(amopreqcheck, "t") == 0)
12920 appendPQExpBufferStr(q, " RECHECK");
12928 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12930 * Print only those opfamily members that are tied to the opclass by
12931 * pg_depend entries.
12933 * We print the amproclefttype/amprocrighttype even though in most cases
12934 * the backend could deduce the right values, because of the corner case
12935 * of a btree sort support function for a cross-type comparison. That's
12936 * only allowed in 9.2 and later, but for simplicity print them in all
12937 * versions that have the columns.
12939 resetPQExpBuffer(query);
12941 if (fout->remoteVersion >= 80300)
12943 appendPQExpBuffer(query, "SELECT amprocnum, "
12944 "amproc::pg_catalog.regprocedure, "
12945 "amproclefttype::pg_catalog.regtype, "
12946 "amprocrighttype::pg_catalog.regtype "
12947 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12948 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12949 "AND refobjid = '%u'::pg_catalog.oid "
12950 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12951 "AND objid = ap.oid "
12952 "ORDER BY amprocnum",
12953 opcinfo->dobj.catId.oid);
12957 appendPQExpBuffer(query, "SELECT amprocnum, "
12958 "amproc::pg_catalog.regprocedure, "
12959 "'' AS amproclefttype, "
12960 "'' AS amprocrighttype "
12961 "FROM pg_catalog.pg_amproc "
12962 "WHERE amopclaid = '%u'::pg_catalog.oid "
12963 "ORDER BY amprocnum",
12964 opcinfo->dobj.catId.oid);
12967 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12969 ntups = PQntuples(res);
12971 i_amprocnum = PQfnumber(res, "amprocnum");
12972 i_amproc = PQfnumber(res, "amproc");
12973 i_amproclefttype = PQfnumber(res, "amproclefttype");
12974 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12976 for (i = 0; i < ntups; i++)
12978 amprocnum = PQgetvalue(res, i, i_amprocnum);
12979 amproc = PQgetvalue(res, i, i_amproc);
12980 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12981 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12984 appendPQExpBufferStr(q, " ,\n ");
12986 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12988 if (*amproclefttype && *amprocrighttype)
12989 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12991 appendPQExpBuffer(q, " %s", amproc);
12999 * If needComma is still false it means we haven't added anything after
13000 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13001 * clause with the same datatype. This isn't sanctioned by the
13002 * documentation, but actually DefineOpClass will treat it as a no-op.
13005 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13007 appendPQExpBufferStr(q, ";\n");
13009 appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13010 appendPQExpBuffer(nameusing, " USING %s",
13013 if (dopt->binary_upgrade)
13014 binary_upgrade_extension_member(q, &opcinfo->dobj,
13015 "OPERATOR CLASS", nameusing->data,
13016 opcinfo->dobj.namespace->dobj.name);
13018 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13019 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13020 opcinfo->dobj.name,
13021 opcinfo->dobj.namespace->dobj.name,
13024 false, "OPERATOR CLASS", SECTION_PRE_DATA,
13025 q->data, delq->data, NULL,
13029 /* Dump Operator Class Comments */
13030 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13031 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13032 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13033 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13038 destroyPQExpBuffer(query);
13039 destroyPQExpBuffer(q);
13040 destroyPQExpBuffer(delq);
13041 destroyPQExpBuffer(nameusing);
13046 * write out a single operator family definition
13048 * Note: this also dumps any "loose" operator members that aren't bound to a
13049 * specific opclass within the opfamily.
13052 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13054 DumpOptions *dopt = fout->dopt;
13058 PQExpBuffer nameusing;
13061 PGresult *res_procs;
13064 int i_amopstrategy;
13065 int i_amopreqcheck;
13068 int i_sortfamilynsp;
13071 int i_amproclefttype;
13072 int i_amprocrighttype;
13074 char *amopstrategy;
13075 char *amopreqcheck;
13078 char *sortfamilynsp;
13081 char *amproclefttype;
13082 char *amprocrighttype;
13086 /* Skip if not to be dumped */
13087 if (!opfinfo->dobj.dump || dopt->dataOnly)
13090 query = createPQExpBuffer();
13091 q = createPQExpBuffer();
13092 delq = createPQExpBuffer();
13093 nameusing = createPQExpBuffer();
13096 * Fetch only those opfamily members that are tied directly to the
13097 * opfamily by pg_depend entries.
13099 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13100 * older server's opclass in which it is used. This is to avoid
13101 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13102 * older server and then reload into that old version. This can go away
13103 * once 8.3 is so old as to not be of interest to anyone.
13105 if (fout->remoteVersion >= 90100)
13107 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13108 "amopopr::pg_catalog.regoperator, "
13109 "opfname AS sortfamily, "
13110 "nspname AS sortfamilynsp "
13111 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13112 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13113 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13114 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13115 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13116 "AND refobjid = '%u'::pg_catalog.oid "
13117 "AND amopfamily = '%u'::pg_catalog.oid "
13118 "ORDER BY amopstrategy",
13119 opfinfo->dobj.catId.oid,
13120 opfinfo->dobj.catId.oid);
13122 else if (fout->remoteVersion >= 80400)
13124 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13125 "amopopr::pg_catalog.regoperator, "
13126 "NULL AS sortfamily, "
13127 "NULL AS sortfamilynsp "
13128 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13129 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13130 "AND refobjid = '%u'::pg_catalog.oid "
13131 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13132 "AND objid = ao.oid "
13133 "ORDER BY amopstrategy",
13134 opfinfo->dobj.catId.oid);
13138 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13139 "amopopr::pg_catalog.regoperator, "
13140 "NULL AS sortfamily, "
13141 "NULL AS sortfamilynsp "
13142 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13143 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13144 "AND refobjid = '%u'::pg_catalog.oid "
13145 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13146 "AND objid = ao.oid "
13147 "ORDER BY amopstrategy",
13148 opfinfo->dobj.catId.oid);
13151 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13153 resetPQExpBuffer(query);
13155 appendPQExpBuffer(query, "SELECT amprocnum, "
13156 "amproc::pg_catalog.regprocedure, "
13157 "amproclefttype::pg_catalog.regtype, "
13158 "amprocrighttype::pg_catalog.regtype "
13159 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13160 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13161 "AND refobjid = '%u'::pg_catalog.oid "
13162 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13163 "AND objid = ap.oid "
13164 "ORDER BY amprocnum",
13165 opfinfo->dobj.catId.oid);
13167 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13169 /* Get additional fields from the pg_opfamily row */
13170 resetPQExpBuffer(query);
13172 appendPQExpBuffer(query, "SELECT "
13173 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13174 "FROM pg_catalog.pg_opfamily "
13175 "WHERE oid = '%u'::pg_catalog.oid",
13176 opfinfo->dobj.catId.oid);
13178 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13180 i_amname = PQfnumber(res, "amname");
13182 /* amname will still be needed after we PQclear res */
13183 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13185 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13186 fmtQualifiedDumpable(opfinfo));
13187 appendPQExpBuffer(delq, " USING %s;\n",
13190 /* Build the fixed portion of the CREATE command */
13191 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13192 fmtQualifiedDumpable(opfinfo));
13193 appendPQExpBuffer(q, " USING %s;\n",
13198 /* Do we need an ALTER to add loose members? */
13199 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13201 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13202 fmtQualifiedDumpable(opfinfo));
13203 appendPQExpBuffer(q, " USING %s ADD\n ",
13209 * Now fetch and print the OPERATOR entries (pg_amop rows).
13211 ntups = PQntuples(res_ops);
13213 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13214 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13215 i_amopopr = PQfnumber(res_ops, "amopopr");
13216 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13217 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13219 for (i = 0; i < ntups; i++)
13221 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13222 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13223 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13224 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13225 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13228 appendPQExpBufferStr(q, " ,\n ");
13230 appendPQExpBuffer(q, "OPERATOR %s %s",
13231 amopstrategy, amopopr);
13233 if (strlen(sortfamily) > 0)
13235 appendPQExpBufferStr(q, " FOR ORDER BY ");
13236 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13237 appendPQExpBufferStr(q, fmtId(sortfamily));
13240 if (strcmp(amopreqcheck, "t") == 0)
13241 appendPQExpBufferStr(q, " RECHECK");
13247 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13249 ntups = PQntuples(res_procs);
13251 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13252 i_amproc = PQfnumber(res_procs, "amproc");
13253 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13254 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13256 for (i = 0; i < ntups; i++)
13258 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13259 amproc = PQgetvalue(res_procs, i, i_amproc);
13260 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13261 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13264 appendPQExpBufferStr(q, " ,\n ");
13266 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13267 amprocnum, amproclefttype, amprocrighttype,
13273 appendPQExpBufferStr(q, ";\n");
13276 appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13277 appendPQExpBuffer(nameusing, " USING %s",
13280 if (dopt->binary_upgrade)
13281 binary_upgrade_extension_member(q, &opfinfo->dobj,
13282 "OPERATOR FAMILY", nameusing->data,
13283 opfinfo->dobj.namespace->dobj.name);
13285 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13286 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13287 opfinfo->dobj.name,
13288 opfinfo->dobj.namespace->dobj.name,
13291 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13292 q->data, delq->data, NULL,
13296 /* Dump Operator Family Comments */
13297 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13298 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13299 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13300 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13304 PQclear(res_procs);
13305 destroyPQExpBuffer(query);
13306 destroyPQExpBuffer(q);
13307 destroyPQExpBuffer(delq);
13308 destroyPQExpBuffer(nameusing);
13313 * write out a single collation definition
13316 dumpCollation(Archive *fout, CollInfo *collinfo)
13318 DumpOptions *dopt = fout->dopt;
13324 int i_collprovider;
13327 const char *collprovider;
13328 const char *collcollate;
13329 const char *collctype;
13331 /* Skip if not to be dumped */
13332 if (!collinfo->dobj.dump || dopt->dataOnly)
13335 query = createPQExpBuffer();
13336 q = createPQExpBuffer();
13337 delq = createPQExpBuffer();
13339 qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13341 /* Get collation-specific details */
13342 if (fout->remoteVersion >= 100000)
13343 appendPQExpBuffer(query, "SELECT "
13348 "FROM pg_catalog.pg_collation c "
13349 "WHERE c.oid = '%u'::pg_catalog.oid",
13350 collinfo->dobj.catId.oid);
13352 appendPQExpBuffer(query, "SELECT "
13353 "'c' AS collprovider, "
13356 "NULL AS collversion "
13357 "FROM pg_catalog.pg_collation c "
13358 "WHERE c.oid = '%u'::pg_catalog.oid",
13359 collinfo->dobj.catId.oid);
13361 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13363 i_collprovider = PQfnumber(res, "collprovider");
13364 i_collcollate = PQfnumber(res, "collcollate");
13365 i_collctype = PQfnumber(res, "collctype");
13367 collprovider = PQgetvalue(res, 0, i_collprovider);
13368 collcollate = PQgetvalue(res, 0, i_collcollate);
13369 collctype = PQgetvalue(res, 0, i_collctype);
13371 appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13372 fmtQualifiedDumpable(collinfo));
13374 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13375 fmtQualifiedDumpable(collinfo));
13377 appendPQExpBufferStr(q, "provider = ");
13378 if (collprovider[0] == 'c')
13379 appendPQExpBufferStr(q, "libc");
13380 else if (collprovider[0] == 'i')
13381 appendPQExpBufferStr(q, "icu");
13382 else if (collprovider[0] == 'd')
13383 /* to allow dumping pg_catalog; not accepted on input */
13384 appendPQExpBufferStr(q, "default");
13386 exit_horribly(NULL,
13387 "unrecognized collation provider: %s\n",
13390 if (strcmp(collcollate, collctype) == 0)
13392 appendPQExpBufferStr(q, ", locale = ");
13393 appendStringLiteralAH(q, collcollate, fout);
13397 appendPQExpBufferStr(q, ", lc_collate = ");
13398 appendStringLiteralAH(q, collcollate, fout);
13399 appendPQExpBufferStr(q, ", lc_ctype = ");
13400 appendStringLiteralAH(q, collctype, fout);
13404 * For binary upgrade, carry over the collation version. For normal
13405 * dump/restore, omit the version, so that it is computed upon restore.
13407 if (dopt->binary_upgrade)
13411 i_collversion = PQfnumber(res, "collversion");
13412 if (!PQgetisnull(res, 0, i_collversion))
13414 appendPQExpBufferStr(q, ", version = ");
13415 appendStringLiteralAH(q,
13416 PQgetvalue(res, 0, i_collversion),
13421 appendPQExpBufferStr(q, ");\n");
13423 if (dopt->binary_upgrade)
13424 binary_upgrade_extension_member(q, &collinfo->dobj,
13425 "COLLATION", qcollname,
13426 collinfo->dobj.namespace->dobj.name);
13428 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13429 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13430 collinfo->dobj.name,
13431 collinfo->dobj.namespace->dobj.name,
13434 false, "COLLATION", SECTION_PRE_DATA,
13435 q->data, delq->data, NULL,
13439 /* Dump Collation Comments */
13440 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13441 dumpComment(fout, "COLLATION", qcollname,
13442 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13443 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13447 destroyPQExpBuffer(query);
13448 destroyPQExpBuffer(q);
13449 destroyPQExpBuffer(delq);
13455 * write out a single conversion definition
13458 dumpConversion(Archive *fout, ConvInfo *convinfo)
13460 DumpOptions *dopt = fout->dopt;
13466 int i_conforencoding;
13467 int i_contoencoding;
13470 const char *conforencoding;
13471 const char *contoencoding;
13472 const char *conproc;
13475 /* Skip if not to be dumped */
13476 if (!convinfo->dobj.dump || dopt->dataOnly)
13479 query = createPQExpBuffer();
13480 q = createPQExpBuffer();
13481 delq = createPQExpBuffer();
13483 qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13485 /* Get conversion-specific details */
13486 appendPQExpBuffer(query, "SELECT "
13487 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13488 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13489 "conproc, condefault "
13490 "FROM pg_catalog.pg_conversion c "
13491 "WHERE c.oid = '%u'::pg_catalog.oid",
13492 convinfo->dobj.catId.oid);
13494 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13496 i_conforencoding = PQfnumber(res, "conforencoding");
13497 i_contoencoding = PQfnumber(res, "contoencoding");
13498 i_conproc = PQfnumber(res, "conproc");
13499 i_condefault = PQfnumber(res, "condefault");
13501 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13502 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13503 conproc = PQgetvalue(res, 0, i_conproc);
13504 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13506 appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13507 fmtQualifiedDumpable(convinfo));
13509 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13510 (condefault) ? "DEFAULT " : "",
13511 fmtQualifiedDumpable(convinfo));
13512 appendStringLiteralAH(q, conforencoding, fout);
13513 appendPQExpBufferStr(q, " TO ");
13514 appendStringLiteralAH(q, contoencoding, fout);
13515 /* regproc output is already sufficiently quoted */
13516 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13518 if (dopt->binary_upgrade)
13519 binary_upgrade_extension_member(q, &convinfo->dobj,
13520 "CONVERSION", qconvname,
13521 convinfo->dobj.namespace->dobj.name);
13523 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13524 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13525 convinfo->dobj.name,
13526 convinfo->dobj.namespace->dobj.name,
13529 false, "CONVERSION", SECTION_PRE_DATA,
13530 q->data, delq->data, NULL,
13534 /* Dump Conversion Comments */
13535 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13536 dumpComment(fout, "CONVERSION", qconvname,
13537 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13538 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13542 destroyPQExpBuffer(query);
13543 destroyPQExpBuffer(q);
13544 destroyPQExpBuffer(delq);
13549 * format_aggregate_signature: generate aggregate name and argument list
13551 * The argument type names are qualified if needed. The aggregate name
13552 * is never qualified.
13555 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13557 PQExpBufferData buf;
13560 initPQExpBuffer(&buf);
13562 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13564 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13566 if (agginfo->aggfn.nargs == 0)
13567 appendPQExpBuffer(&buf, "(*)");
13570 appendPQExpBufferChar(&buf, '(');
13571 for (j = 0; j < agginfo->aggfn.nargs; j++)
13575 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13578 appendPQExpBuffer(&buf, "%s%s",
13579 (j > 0) ? ", " : "",
13583 appendPQExpBufferChar(&buf, ')');
13590 * write out a single aggregate definition
13593 dumpAgg(Archive *fout, AggInfo *agginfo)
13595 DumpOptions *dopt = fout->dopt;
13599 PQExpBuffer details;
13600 char *aggsig; /* identity signature */
13601 char *aggfullsig = NULL; /* full signature */
13606 int i_aggcombinefn;
13608 int i_aggdeserialfn;
13610 int i_aggminvtransfn;
13612 int i_aggfinalextra;
13613 int i_aggmfinalextra;
13614 int i_aggfinalmodify;
13615 int i_aggmfinalmodify;
13618 int i_aggtranstype;
13619 int i_aggtransspace;
13620 int i_aggmtranstype;
13621 int i_aggmtransspace;
13626 const char *aggtransfn;
13627 const char *aggfinalfn;
13628 const char *aggcombinefn;
13629 const char *aggserialfn;
13630 const char *aggdeserialfn;
13631 const char *aggmtransfn;
13632 const char *aggminvtransfn;
13633 const char *aggmfinalfn;
13634 bool aggfinalextra;
13635 bool aggmfinalextra;
13636 char aggfinalmodify;
13637 char aggmfinalmodify;
13638 const char *aggsortop;
13639 char *aggsortconvop;
13641 const char *aggtranstype;
13642 const char *aggtransspace;
13643 const char *aggmtranstype;
13644 const char *aggmtransspace;
13645 const char *agginitval;
13646 const char *aggminitval;
13648 const char *proparallel;
13649 char defaultfinalmodify;
13651 /* Skip if not to be dumped */
13652 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13655 query = createPQExpBuffer();
13656 q = createPQExpBuffer();
13657 delq = createPQExpBuffer();
13658 details = createPQExpBuffer();
13660 /* Get aggregate-specific details */
13661 if (fout->remoteVersion >= 110000)
13663 appendPQExpBuffer(query, "SELECT aggtransfn, "
13664 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13665 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13666 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13667 "aggfinalextra, aggmfinalextra, "
13668 "aggfinalmodify, aggmfinalmodify, "
13671 "aggtransspace, agginitval, "
13672 "aggmtransspace, aggminitval, "
13673 "true AS convertok, "
13674 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13675 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13677 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13678 "WHERE a.aggfnoid = p.oid "
13679 "AND p.oid = '%u'::pg_catalog.oid",
13680 agginfo->aggfn.dobj.catId.oid);
13682 else if (fout->remoteVersion >= 90600)
13684 appendPQExpBuffer(query, "SELECT aggtransfn, "
13685 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13686 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13687 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13688 "aggfinalextra, aggmfinalextra, "
13689 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13692 "aggtransspace, agginitval, "
13693 "aggmtransspace, aggminitval, "
13694 "true AS convertok, "
13695 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13696 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13698 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13699 "WHERE a.aggfnoid = p.oid "
13700 "AND p.oid = '%u'::pg_catalog.oid",
13701 agginfo->aggfn.dobj.catId.oid);
13703 else if (fout->remoteVersion >= 90400)
13705 appendPQExpBuffer(query, "SELECT aggtransfn, "
13706 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13707 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13708 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13709 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13710 "aggfinalextra, aggmfinalextra, "
13711 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13714 "aggtransspace, agginitval, "
13715 "aggmtransspace, aggminitval, "
13716 "true AS convertok, "
13717 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13718 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13719 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13720 "WHERE a.aggfnoid = p.oid "
13721 "AND p.oid = '%u'::pg_catalog.oid",
13722 agginfo->aggfn.dobj.catId.oid);
13724 else if (fout->remoteVersion >= 80400)
13726 appendPQExpBuffer(query, "SELECT aggtransfn, "
13727 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13728 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13729 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13730 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13731 "0 AS aggmtranstype, false AS aggfinalextra, "
13732 "false AS aggmfinalextra, "
13733 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13736 "0 AS aggtransspace, agginitval, "
13737 "0 AS aggmtransspace, NULL AS aggminitval, "
13738 "true AS convertok, "
13739 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13740 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13741 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13742 "WHERE a.aggfnoid = p.oid "
13743 "AND p.oid = '%u'::pg_catalog.oid",
13744 agginfo->aggfn.dobj.catId.oid);
13746 else if (fout->remoteVersion >= 80100)
13748 appendPQExpBuffer(query, "SELECT aggtransfn, "
13749 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13750 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13751 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13752 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13753 "0 AS aggmtranstype, false AS aggfinalextra, "
13754 "false AS aggmfinalextra, "
13755 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13758 "0 AS aggtransspace, agginitval, "
13759 "0 AS aggmtransspace, NULL AS aggminitval, "
13760 "true AS convertok "
13761 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13762 "WHERE a.aggfnoid = p.oid "
13763 "AND p.oid = '%u'::pg_catalog.oid",
13764 agginfo->aggfn.dobj.catId.oid);
13768 appendPQExpBuffer(query, "SELECT aggtransfn, "
13769 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13770 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13771 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13772 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13773 "0 AS aggmtranstype, false AS aggfinalextra, "
13774 "false AS aggmfinalextra, "
13775 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13778 "0 AS aggtransspace, agginitval, "
13779 "0 AS aggmtransspace, NULL AS aggminitval, "
13780 "true AS convertok "
13781 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13782 "WHERE a.aggfnoid = p.oid "
13783 "AND p.oid = '%u'::pg_catalog.oid",
13784 agginfo->aggfn.dobj.catId.oid);
13787 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13789 i_aggtransfn = PQfnumber(res, "aggtransfn");
13790 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13791 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13792 i_aggserialfn = PQfnumber(res, "aggserialfn");
13793 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13794 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13795 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13796 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13797 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13798 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13799 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13800 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13801 i_aggsortop = PQfnumber(res, "aggsortop");
13802 i_aggkind = PQfnumber(res, "aggkind");
13803 i_aggtranstype = PQfnumber(res, "aggtranstype");
13804 i_aggtransspace = PQfnumber(res, "aggtransspace");
13805 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13806 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13807 i_agginitval = PQfnumber(res, "agginitval");
13808 i_aggminitval = PQfnumber(res, "aggminitval");
13809 i_convertok = PQfnumber(res, "convertok");
13810 i_proparallel = PQfnumber(res, "proparallel");
13812 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13813 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13814 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13815 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13816 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13817 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13818 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13819 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13820 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13821 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13822 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13823 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13824 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13825 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13826 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13827 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13828 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13829 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13830 agginitval = PQgetvalue(res, 0, i_agginitval);
13831 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13832 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13834 if (fout->remoteVersion >= 80400)
13836 /* 8.4 or later; we rely on server-side code for most of the work */
13840 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13841 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13842 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13843 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13846 /* pre-8.4, do it ourselves */
13847 aggsig = format_aggregate_signature(agginfo, fout, true);
13849 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13851 if (i_proparallel != -1)
13852 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13854 proparallel = NULL;
13858 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13869 /* identify default modify flag for aggkind (must match DefineAggregate) */
13870 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13871 /* replace omitted flags for old versions */
13872 if (aggfinalmodify == '0')
13873 aggfinalmodify = defaultfinalmodify;
13874 if (aggmfinalmodify == '0')
13875 aggmfinalmodify = defaultfinalmodify;
13877 /* regproc and regtype output is already sufficiently quoted */
13878 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13879 aggtransfn, aggtranstype);
13881 if (strcmp(aggtransspace, "0") != 0)
13883 appendPQExpBuffer(details, ",\n SSPACE = %s",
13887 if (!PQgetisnull(res, 0, i_agginitval))
13889 appendPQExpBufferStr(details, ",\n INITCOND = ");
13890 appendStringLiteralAH(details, agginitval, fout);
13893 if (strcmp(aggfinalfn, "-") != 0)
13895 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13898 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13899 if (aggfinalmodify != defaultfinalmodify)
13901 switch (aggfinalmodify)
13903 case AGGMODIFY_READ_ONLY:
13904 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
13906 case AGGMODIFY_SHAREABLE:
13907 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
13909 case AGGMODIFY_READ_WRITE:
13910 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
13913 exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13914 agginfo->aggfn.dobj.name);
13920 if (strcmp(aggcombinefn, "-") != 0)
13921 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
13923 if (strcmp(aggserialfn, "-") != 0)
13924 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
13926 if (strcmp(aggdeserialfn, "-") != 0)
13927 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
13929 if (strcmp(aggmtransfn, "-") != 0)
13931 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
13937 if (strcmp(aggmtransspace, "0") != 0)
13939 appendPQExpBuffer(details, ",\n MSSPACE = %s",
13943 if (!PQgetisnull(res, 0, i_aggminitval))
13945 appendPQExpBufferStr(details, ",\n MINITCOND = ");
13946 appendStringLiteralAH(details, aggminitval, fout);
13949 if (strcmp(aggmfinalfn, "-") != 0)
13951 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
13953 if (aggmfinalextra)
13954 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
13955 if (aggmfinalmodify != defaultfinalmodify)
13957 switch (aggmfinalmodify)
13959 case AGGMODIFY_READ_ONLY:
13960 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
13962 case AGGMODIFY_SHAREABLE:
13963 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
13965 case AGGMODIFY_READ_WRITE:
13966 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
13969 exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13970 agginfo->aggfn.dobj.name);
13976 aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13979 appendPQExpBuffer(details, ",\n SORTOP = %s",
13981 free(aggsortconvop);
13984 if (aggkind == AGGKIND_HYPOTHETICAL)
13985 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
13987 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13989 if (proparallel[0] == PROPARALLEL_SAFE)
13990 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
13991 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13992 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
13993 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13994 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13995 agginfo->aggfn.dobj.name);
13998 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13999 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14002 appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14003 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14004 aggfullsig ? aggfullsig : aggsig, details->data);
14006 if (dopt->binary_upgrade)
14007 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14008 "AGGREGATE", aggsig,
14009 agginfo->aggfn.dobj.namespace->dobj.name);
14011 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14012 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14013 agginfo->aggfn.dobj.dumpId,
14015 agginfo->aggfn.dobj.namespace->dobj.name,
14017 agginfo->aggfn.rolname,
14018 false, "AGGREGATE", SECTION_PRE_DATA,
14019 q->data, delq->data, NULL,
14023 /* Dump Aggregate Comments */
14024 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14025 dumpComment(fout, "AGGREGATE", aggsig,
14026 agginfo->aggfn.dobj.namespace->dobj.name,
14027 agginfo->aggfn.rolname,
14028 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14030 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14031 dumpSecLabel(fout, "AGGREGATE", aggsig,
14032 agginfo->aggfn.dobj.namespace->dobj.name,
14033 agginfo->aggfn.rolname,
14034 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14037 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14038 * command look like a function's GRANT; in particular this affects the
14039 * syntax for zero-argument aggregates and ordered-set aggregates.
14043 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14045 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14046 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
14047 "FUNCTION", aggsig, NULL,
14048 agginfo->aggfn.dobj.namespace->dobj.name,
14049 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14050 agginfo->aggfn.rproacl,
14051 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14060 destroyPQExpBuffer(query);
14061 destroyPQExpBuffer(q);
14062 destroyPQExpBuffer(delq);
14063 destroyPQExpBuffer(details);
14068 * write out a single text search parser
14071 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14073 DumpOptions *dopt = fout->dopt;
14078 /* Skip if not to be dumped */
14079 if (!prsinfo->dobj.dump || dopt->dataOnly)
14082 q = createPQExpBuffer();
14083 delq = createPQExpBuffer();
14085 qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14087 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14088 fmtQualifiedDumpable(prsinfo));
14090 appendPQExpBuffer(q, " START = %s,\n",
14091 convertTSFunction(fout, prsinfo->prsstart));
14092 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14093 convertTSFunction(fout, prsinfo->prstoken));
14094 appendPQExpBuffer(q, " END = %s,\n",
14095 convertTSFunction(fout, prsinfo->prsend));
14096 if (prsinfo->prsheadline != InvalidOid)
14097 appendPQExpBuffer(q, " HEADLINE = %s,\n",
14098 convertTSFunction(fout, prsinfo->prsheadline));
14099 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14100 convertTSFunction(fout, prsinfo->prslextype));
14102 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14103 fmtQualifiedDumpable(prsinfo));
14105 if (dopt->binary_upgrade)
14106 binary_upgrade_extension_member(q, &prsinfo->dobj,
14107 "TEXT SEARCH PARSER", qprsname,
14108 prsinfo->dobj.namespace->dobj.name);
14110 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14111 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14112 prsinfo->dobj.name,
14113 prsinfo->dobj.namespace->dobj.name,
14116 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14117 q->data, delq->data, NULL,
14121 /* Dump Parser Comments */
14122 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14123 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14124 prsinfo->dobj.namespace->dobj.name, "",
14125 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14127 destroyPQExpBuffer(q);
14128 destroyPQExpBuffer(delq);
14134 * write out a single text search dictionary
14137 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14139 DumpOptions *dopt = fout->dopt;
14148 /* Skip if not to be dumped */
14149 if (!dictinfo->dobj.dump || dopt->dataOnly)
14152 q = createPQExpBuffer();
14153 delq = createPQExpBuffer();
14154 query = createPQExpBuffer();
14156 qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14158 /* Fetch name and namespace of the dictionary's template */
14159 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14160 "FROM pg_ts_template p, pg_namespace n "
14161 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14162 dictinfo->dicttemplate);
14163 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14164 nspname = PQgetvalue(res, 0, 0);
14165 tmplname = PQgetvalue(res, 0, 1);
14167 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14168 fmtQualifiedDumpable(dictinfo));
14170 appendPQExpBufferStr(q, " TEMPLATE = ");
14171 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14172 appendPQExpBufferStr(q, fmtId(tmplname));
14176 /* the dictinitoption can be dumped straight into the command */
14177 if (dictinfo->dictinitoption)
14178 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14180 appendPQExpBufferStr(q, " );\n");
14182 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14183 fmtQualifiedDumpable(dictinfo));
14185 if (dopt->binary_upgrade)
14186 binary_upgrade_extension_member(q, &dictinfo->dobj,
14187 "TEXT SEARCH DICTIONARY", qdictname,
14188 dictinfo->dobj.namespace->dobj.name);
14190 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14191 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14192 dictinfo->dobj.name,
14193 dictinfo->dobj.namespace->dobj.name,
14196 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14197 q->data, delq->data, NULL,
14201 /* Dump Dictionary Comments */
14202 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14203 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14204 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14205 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14207 destroyPQExpBuffer(q);
14208 destroyPQExpBuffer(delq);
14209 destroyPQExpBuffer(query);
14215 * write out a single text search template
14218 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14220 DumpOptions *dopt = fout->dopt;
14225 /* Skip if not to be dumped */
14226 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14229 q = createPQExpBuffer();
14230 delq = createPQExpBuffer();
14232 qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14234 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14235 fmtQualifiedDumpable(tmplinfo));
14237 if (tmplinfo->tmplinit != InvalidOid)
14238 appendPQExpBuffer(q, " INIT = %s,\n",
14239 convertTSFunction(fout, tmplinfo->tmplinit));
14240 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14241 convertTSFunction(fout, tmplinfo->tmpllexize));
14243 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14244 fmtQualifiedDumpable(tmplinfo));
14246 if (dopt->binary_upgrade)
14247 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14248 "TEXT SEARCH TEMPLATE", qtmplname,
14249 tmplinfo->dobj.namespace->dobj.name);
14251 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14252 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14253 tmplinfo->dobj.name,
14254 tmplinfo->dobj.namespace->dobj.name,
14257 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14258 q->data, delq->data, NULL,
14262 /* Dump Template Comments */
14263 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14264 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14265 tmplinfo->dobj.namespace->dobj.name, "",
14266 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14268 destroyPQExpBuffer(q);
14269 destroyPQExpBuffer(delq);
14275 * write out a single text search configuration
14278 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14280 DumpOptions *dopt = fout->dopt;
14293 /* Skip if not to be dumped */
14294 if (!cfginfo->dobj.dump || dopt->dataOnly)
14297 q = createPQExpBuffer();
14298 delq = createPQExpBuffer();
14299 query = createPQExpBuffer();
14301 qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14303 /* Fetch name and namespace of the config's parser */
14304 appendPQExpBuffer(query, "SELECT nspname, prsname "
14305 "FROM pg_ts_parser p, pg_namespace n "
14306 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14307 cfginfo->cfgparser);
14308 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14309 nspname = PQgetvalue(res, 0, 0);
14310 prsname = PQgetvalue(res, 0, 1);
14312 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14313 fmtQualifiedDumpable(cfginfo));
14315 appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14316 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14320 resetPQExpBuffer(query);
14321 appendPQExpBuffer(query,
14323 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14324 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14325 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14326 "FROM pg_catalog.pg_ts_config_map AS m\n"
14327 "WHERE m.mapcfg = '%u'\n"
14328 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14329 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14331 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14332 ntups = PQntuples(res);
14334 i_tokenname = PQfnumber(res, "tokenname");
14335 i_dictname = PQfnumber(res, "dictname");
14337 for (i = 0; i < ntups; i++)
14339 char *tokenname = PQgetvalue(res, i, i_tokenname);
14340 char *dictname = PQgetvalue(res, i, i_dictname);
14343 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14345 /* starting a new token type, so start a new command */
14347 appendPQExpBufferStr(q, ";\n");
14348 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14349 fmtQualifiedDumpable(cfginfo));
14350 /* tokenname needs quoting, dictname does NOT */
14351 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14352 fmtId(tokenname), dictname);
14355 appendPQExpBuffer(q, ", %s", dictname);
14359 appendPQExpBufferStr(q, ";\n");
14363 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14364 fmtQualifiedDumpable(cfginfo));
14366 if (dopt->binary_upgrade)
14367 binary_upgrade_extension_member(q, &cfginfo->dobj,
14368 "TEXT SEARCH CONFIGURATION", qcfgname,
14369 cfginfo->dobj.namespace->dobj.name);
14371 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14372 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14373 cfginfo->dobj.name,
14374 cfginfo->dobj.namespace->dobj.name,
14377 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14378 q->data, delq->data, NULL,
14382 /* Dump Configuration Comments */
14383 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14384 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14385 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14386 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14388 destroyPQExpBuffer(q);
14389 destroyPQExpBuffer(delq);
14390 destroyPQExpBuffer(query);
14395 * dumpForeignDataWrapper
14396 * write out a single foreign-data wrapper definition
14399 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14401 DumpOptions *dopt = fout->dopt;
14406 /* Skip if not to be dumped */
14407 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14410 q = createPQExpBuffer();
14411 delq = createPQExpBuffer();
14413 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14415 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14418 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14419 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14421 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14422 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14424 if (strlen(fdwinfo->fdwoptions) > 0)
14425 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14427 appendPQExpBufferStr(q, ";\n");
14429 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14432 if (dopt->binary_upgrade)
14433 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14434 "FOREIGN DATA WRAPPER", qfdwname,
14437 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14438 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14439 fdwinfo->dobj.name,
14443 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14444 q->data, delq->data, NULL,
14448 /* Dump Foreign Data Wrapper Comments */
14449 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14450 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14451 NULL, fdwinfo->rolname,
14452 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14454 /* Handle the ACL */
14455 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14456 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14457 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14458 NULL, fdwinfo->rolname,
14459 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14460 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14464 destroyPQExpBuffer(q);
14465 destroyPQExpBuffer(delq);
14469 * dumpForeignServer
14470 * write out a foreign server definition
14473 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14475 DumpOptions *dopt = fout->dopt;
14483 /* Skip if not to be dumped */
14484 if (!srvinfo->dobj.dump || dopt->dataOnly)
14487 q = createPQExpBuffer();
14488 delq = createPQExpBuffer();
14489 query = createPQExpBuffer();
14491 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14493 /* look up the foreign-data wrapper */
14494 appendPQExpBuffer(query, "SELECT fdwname "
14495 "FROM pg_foreign_data_wrapper w "
14496 "WHERE w.oid = '%u'",
14498 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14499 fdwname = PQgetvalue(res, 0, 0);
14501 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14502 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14504 appendPQExpBufferStr(q, " TYPE ");
14505 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14507 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14509 appendPQExpBufferStr(q, " VERSION ");
14510 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14513 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14514 appendPQExpBufferStr(q, fmtId(fdwname));
14516 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14517 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14519 appendPQExpBufferStr(q, ";\n");
14521 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14524 if (dopt->binary_upgrade)
14525 binary_upgrade_extension_member(q, &srvinfo->dobj,
14526 "SERVER", qsrvname, NULL);
14528 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14529 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14530 srvinfo->dobj.name,
14534 false, "SERVER", SECTION_PRE_DATA,
14535 q->data, delq->data, NULL,
14539 /* Dump Foreign Server Comments */
14540 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14541 dumpComment(fout, "SERVER", qsrvname,
14542 NULL, srvinfo->rolname,
14543 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14545 /* Handle the ACL */
14546 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14547 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14548 "FOREIGN SERVER", qsrvname, NULL,
14549 NULL, srvinfo->rolname,
14550 srvinfo->srvacl, srvinfo->rsrvacl,
14551 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14553 /* Dump user mappings */
14554 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14555 dumpUserMappings(fout,
14556 srvinfo->dobj.name, NULL,
14558 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14562 destroyPQExpBuffer(q);
14563 destroyPQExpBuffer(delq);
14564 destroyPQExpBuffer(query);
14570 * This routine is used to dump any user mappings associated with the
14571 * server handed to this routine. Should be called after ArchiveEntry()
14575 dumpUserMappings(Archive *fout,
14576 const char *servername, const char *namespace,
14578 CatalogId catalogId, DumpId dumpId)
14590 q = createPQExpBuffer();
14591 tag = createPQExpBuffer();
14592 delq = createPQExpBuffer();
14593 query = createPQExpBuffer();
14596 * We read from the publicly accessible view pg_user_mappings, so as not
14597 * to fail if run by a non-superuser. Note that the view will show
14598 * umoptions as null if the user hasn't got privileges for the associated
14599 * server; this means that pg_dump will dump such a mapping, but with no
14600 * OPTIONS clause. A possible alternative is to skip such mappings
14601 * altogether, but it's not clear that that's an improvement.
14603 appendPQExpBuffer(query,
14605 "array_to_string(ARRAY("
14606 "SELECT quote_ident(option_name) || ' ' || "
14607 "quote_literal(option_value) "
14608 "FROM pg_options_to_table(umoptions) "
14609 "ORDER BY option_name"
14610 "), E',\n ') AS umoptions "
14611 "FROM pg_user_mappings "
14612 "WHERE srvid = '%u' "
14613 "ORDER BY usename",
14616 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14618 ntups = PQntuples(res);
14619 i_usename = PQfnumber(res, "usename");
14620 i_umoptions = PQfnumber(res, "umoptions");
14622 for (i = 0; i < ntups; i++)
14627 usename = PQgetvalue(res, i, i_usename);
14628 umoptions = PQgetvalue(res, i, i_umoptions);
14630 resetPQExpBuffer(q);
14631 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14632 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14634 if (umoptions && strlen(umoptions) > 0)
14635 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14637 appendPQExpBufferStr(q, ";\n");
14639 resetPQExpBuffer(delq);
14640 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14641 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14643 resetPQExpBuffer(tag);
14644 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14645 usename, servername);
14647 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14652 "USER MAPPING", SECTION_PRE_DATA,
14653 q->data, delq->data, NULL,
14660 destroyPQExpBuffer(query);
14661 destroyPQExpBuffer(delq);
14662 destroyPQExpBuffer(tag);
14663 destroyPQExpBuffer(q);
14667 * Write out default privileges information
14670 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14672 DumpOptions *dopt = fout->dopt;
14677 /* Skip if not to be dumped */
14678 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14681 q = createPQExpBuffer();
14682 tag = createPQExpBuffer();
14684 switch (daclinfo->defaclobjtype)
14686 case DEFACLOBJ_RELATION:
14689 case DEFACLOBJ_SEQUENCE:
14690 type = "SEQUENCES";
14692 case DEFACLOBJ_FUNCTION:
14693 type = "FUNCTIONS";
14695 case DEFACLOBJ_TYPE:
14698 case DEFACLOBJ_NAMESPACE:
14702 /* shouldn't get here */
14703 exit_horribly(NULL,
14704 "unrecognized object type in default privileges: %d\n",
14705 (int) daclinfo->defaclobjtype);
14706 type = ""; /* keep compiler quiet */
14709 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14711 /* build the actual command(s) for this tuple */
14712 if (!buildDefaultACLCommands(type,
14713 daclinfo->dobj.namespace != NULL ?
14714 daclinfo->dobj.namespace->dobj.name : NULL,
14715 daclinfo->defaclacl,
14716 daclinfo->rdefaclacl,
14717 daclinfo->initdefaclacl,
14718 daclinfo->initrdefaclacl,
14719 daclinfo->defaclrole,
14720 fout->remoteVersion,
14722 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14723 daclinfo->defaclacl);
14725 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14726 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14728 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14730 daclinfo->defaclrole,
14731 false, "DEFAULT ACL", SECTION_POST_DATA,
14736 destroyPQExpBuffer(tag);
14737 destroyPQExpBuffer(q);
14741 * Write out grant/revoke information
14743 * 'objCatId' is the catalog ID of the underlying object.
14744 * 'objDumpId' is the dump ID of the underlying object.
14745 * 'type' must be one of
14746 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14747 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14748 * 'name' is the formatted name of the object. Must be quoted etc. already.
14749 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14750 * (Currently we assume that subname is only provided for table columns.)
14751 * 'nspname' is the namespace the object is in (NULL if none).
14752 * 'owner' is the owner, NULL if there is no owner (for languages).
14753 * 'acls' contains the ACL string of the object from the appropriate system
14754 * catalog field; it will be passed to buildACLCommands for building the
14755 * appropriate GRANT commands.
14756 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14757 * object; it will be passed to buildACLCommands for building the
14758 * appropriate REVOKE commands.
14759 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14760 * privileges, to be recorded into pg_init_privs
14761 * 'initracls' In binary-upgrade mode, ACL string of the object's
14762 * revoked-from-default privileges, to be recorded into pg_init_privs
14764 * NB: initacls/initracls are needed because extensions can set privileges on
14765 * an object during the extension's script file and we record those into
14766 * pg_init_privs as that object's initial privileges.
14770 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14771 const char *type, const char *name, const char *subname,
14772 const char *nspname, const char *owner,
14773 const char *acls, const char *racls,
14774 const char *initacls, const char *initracls)
14776 DumpOptions *dopt = fout->dopt;
14779 /* Do nothing if ACL dump is not enabled */
14780 if (dopt->aclsSkip)
14783 /* --data-only skips ACLs *except* BLOB ACLs */
14784 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14787 sql = createPQExpBuffer();
14790 * Check to see if this object has had any initial ACLs included for it.
14791 * If so, we are in binary upgrade mode and these are the ACLs to turn
14792 * into GRANT and REVOKE statements to set and record the initial
14793 * privileges for an extension object. Let the backend know that these
14794 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14795 * before and after.
14797 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14799 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14800 if (!buildACLCommands(name, subname, nspname, type,
14801 initacls, initracls, owner,
14802 "", fout->remoteVersion, sql))
14803 exit_horribly(NULL,
14804 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14805 initacls, initracls, name, type);
14806 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14809 if (!buildACLCommands(name, subname, nspname, type,
14810 acls, racls, owner,
14811 "", fout->remoteVersion, sql))
14812 exit_horribly(NULL,
14813 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14814 acls, racls, name, type);
14818 PQExpBuffer tag = createPQExpBuffer();
14821 appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14823 appendPQExpBuffer(tag, "%s %s", type, name);
14825 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14826 tag->data, nspname,
14828 owner ? owner : "",
14829 false, "ACL", SECTION_NONE,
14830 sql->data, "", NULL,
14833 destroyPQExpBuffer(tag);
14836 destroyPQExpBuffer(sql);
14842 * This routine is used to dump any security labels associated with the
14843 * object handed to this routine. The routine takes the object type
14844 * and object name (ready to print, except for schema decoration), plus
14845 * the namespace and owner of the object (for labeling the ArchiveEntry),
14846 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14847 * plus the dump ID for the object (for setting a dependency).
14848 * If a matching pg_seclabel entry is found, it is dumped.
14850 * Note: although this routine takes a dumpId for dependency purposes,
14851 * that purpose is just to mark the dependency in the emitted dump file
14852 * for possible future use by pg_restore. We do NOT use it for determining
14853 * ordering of the label in the dump file, because this routine is called
14854 * after dependency sorting occurs. This routine should be called just after
14855 * calling ArchiveEntry() for the specified object.
14858 dumpSecLabel(Archive *fout, const char *type, const char *name,
14859 const char *namespace, const char *owner,
14860 CatalogId catalogId, int subid, DumpId dumpId)
14862 DumpOptions *dopt = fout->dopt;
14863 SecLabelItem *labels;
14868 /* do nothing, if --no-security-labels is supplied */
14869 if (dopt->no_security_labels)
14872 /* Security labels are schema not data ... except blob labels are data */
14873 if (strcmp(type, "LARGE OBJECT") != 0)
14875 if (dopt->dataOnly)
14880 /* We do dump blob security labels in binary-upgrade mode */
14881 if (dopt->schemaOnly && !dopt->binary_upgrade)
14885 /* Search for security labels associated with catalogId, using table */
14886 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14888 query = createPQExpBuffer();
14890 for (i = 0; i < nlabels; i++)
14893 * Ignore label entries for which the subid doesn't match.
14895 if (labels[i].objsubid != subid)
14898 appendPQExpBuffer(query,
14899 "SECURITY LABEL FOR %s ON %s ",
14900 fmtId(labels[i].provider), type);
14901 if (namespace && *namespace)
14902 appendPQExpBuffer(query, "%s.", fmtId(namespace));
14903 appendPQExpBuffer(query, "%s IS ", name);
14904 appendStringLiteralAH(query, labels[i].label, fout);
14905 appendPQExpBufferStr(query, ";\n");
14908 if (query->len > 0)
14910 PQExpBuffer tag = createPQExpBuffer();
14912 appendPQExpBuffer(tag, "%s %s", type, name);
14913 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14914 tag->data, namespace, NULL, owner,
14915 false, "SECURITY LABEL", SECTION_NONE,
14916 query->data, "", NULL,
14919 destroyPQExpBuffer(tag);
14922 destroyPQExpBuffer(query);
14926 * dumpTableSecLabel
14928 * As above, but dump security label for both the specified table (or view)
14932 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14934 DumpOptions *dopt = fout->dopt;
14935 SecLabelItem *labels;
14939 PQExpBuffer target;
14941 /* do nothing, if --no-security-labels is supplied */
14942 if (dopt->no_security_labels)
14945 /* SecLabel are SCHEMA not data */
14946 if (dopt->dataOnly)
14949 /* Search for comments associated with relation, using table */
14950 nlabels = findSecLabels(fout,
14951 tbinfo->dobj.catId.tableoid,
14952 tbinfo->dobj.catId.oid,
14955 /* If security labels exist, build SECURITY LABEL statements */
14959 query = createPQExpBuffer();
14960 target = createPQExpBuffer();
14962 for (i = 0; i < nlabels; i++)
14964 const char *colname;
14965 const char *provider = labels[i].provider;
14966 const char *label = labels[i].label;
14967 int objsubid = labels[i].objsubid;
14969 resetPQExpBuffer(target);
14972 appendPQExpBuffer(target, "%s %s", reltypename,
14973 fmtQualifiedDumpable(tbinfo));
14977 colname = getAttrName(objsubid, tbinfo);
14978 /* first fmtXXX result must be consumed before calling again */
14979 appendPQExpBuffer(target, "COLUMN %s",
14980 fmtQualifiedDumpable(tbinfo));
14981 appendPQExpBuffer(target, ".%s", fmtId(colname));
14983 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14984 fmtId(provider), target->data);
14985 appendStringLiteralAH(query, label, fout);
14986 appendPQExpBufferStr(query, ";\n");
14988 if (query->len > 0)
14990 resetPQExpBuffer(target);
14991 appendPQExpBuffer(target, "%s %s", reltypename,
14992 fmtId(tbinfo->dobj.name));
14993 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14995 tbinfo->dobj.namespace->dobj.name,
14996 NULL, tbinfo->rolname,
14997 false, "SECURITY LABEL", SECTION_NONE,
14998 query->data, "", NULL,
14999 &(tbinfo->dobj.dumpId), 1,
15002 destroyPQExpBuffer(query);
15003 destroyPQExpBuffer(target);
15009 * Find the security label(s), if any, associated with the given object.
15010 * All the objsubid values associated with the given classoid/objoid are
15011 * found with one search.
15014 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15016 /* static storage for table of security labels */
15017 static SecLabelItem *labels = NULL;
15018 static int nlabels = -1;
15020 SecLabelItem *middle = NULL;
15022 SecLabelItem *high;
15025 /* Get security labels if we didn't already */
15027 nlabels = collectSecLabels(fout, &labels);
15029 if (nlabels <= 0) /* no labels, so no match is possible */
15036 * Do binary search to find some item matching the object.
15039 high = &labels[nlabels - 1];
15040 while (low <= high)
15042 middle = low + (high - low) / 2;
15044 if (classoid < middle->classoid)
15046 else if (classoid > middle->classoid)
15048 else if (objoid < middle->objoid)
15050 else if (objoid > middle->objoid)
15053 break; /* found a match */
15056 if (low > high) /* no matches */
15063 * Now determine how many items match the object. The search loop
15064 * invariant still holds: only items between low and high inclusive could
15068 while (middle > low)
15070 if (classoid != middle[-1].classoid ||
15071 objoid != middle[-1].objoid)
15080 while (middle <= high)
15082 if (classoid != middle->classoid ||
15083 objoid != middle->objoid)
15095 * Construct a table of all security labels available for database objects.
15096 * It's much faster to pull them all at once.
15098 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15101 collectSecLabels(Archive *fout, SecLabelItem **items)
15112 SecLabelItem *labels;
15114 query = createPQExpBuffer();
15116 appendPQExpBufferStr(query,
15117 "SELECT label, provider, classoid, objoid, objsubid "
15118 "FROM pg_catalog.pg_seclabel "
15119 "ORDER BY classoid, objoid, objsubid");
15121 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15123 /* Construct lookup table containing OIDs in numeric form */
15124 i_label = PQfnumber(res, "label");
15125 i_provider = PQfnumber(res, "provider");
15126 i_classoid = PQfnumber(res, "classoid");
15127 i_objoid = PQfnumber(res, "objoid");
15128 i_objsubid = PQfnumber(res, "objsubid");
15130 ntups = PQntuples(res);
15132 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15134 for (i = 0; i < ntups; i++)
15136 labels[i].label = PQgetvalue(res, i, i_label);
15137 labels[i].provider = PQgetvalue(res, i, i_provider);
15138 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15139 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15140 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15143 /* Do NOT free the PGresult since we are keeping pointers into it */
15144 destroyPQExpBuffer(query);
15152 * write out to fout the declarations (not data) of a user-defined table
15155 dumpTable(Archive *fout, TableInfo *tbinfo)
15157 DumpOptions *dopt = fout->dopt;
15161 * noop if we are not dumping anything about this table, or if we are
15162 * doing a data-only dump
15164 if (!tbinfo->dobj.dump || dopt->dataOnly)
15167 if (tbinfo->relkind == RELKIND_SEQUENCE)
15168 dumpSequence(fout, tbinfo);
15170 dumpTableSchema(fout, tbinfo);
15172 /* Handle the ACL here */
15173 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15174 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15176 const char *objtype =
15177 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15179 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15180 objtype, namecopy, NULL,
15181 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15182 tbinfo->relacl, tbinfo->rrelacl,
15183 tbinfo->initrelacl, tbinfo->initrrelacl);
15187 * Handle column ACLs, if any. Note: we pull these with a separate query
15188 * rather than trying to fetch them during getTableAttrs, so that we won't
15189 * miss ACLs on system columns.
15191 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15193 PQExpBuffer query = createPQExpBuffer();
15197 if (fout->remoteVersion >= 90600)
15199 PQExpBuffer acl_subquery = createPQExpBuffer();
15200 PQExpBuffer racl_subquery = createPQExpBuffer();
15201 PQExpBuffer initacl_subquery = createPQExpBuffer();
15202 PQExpBuffer initracl_subquery = createPQExpBuffer();
15204 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15205 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15206 dopt->binary_upgrade);
15208 appendPQExpBuffer(query,
15209 "SELECT at.attname, "
15212 "%s AS initattacl, "
15213 "%s AS initrattacl "
15214 "FROM pg_catalog.pg_attribute at "
15215 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15216 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15217 "(at.attrelid = pip.objoid "
15218 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15219 "AND at.attnum = pip.objsubid) "
15220 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15221 "NOT at.attisdropped "
15223 "%s IS NOT NULL OR "
15224 "%s IS NOT NULL OR "
15225 "%s IS NOT NULL OR "
15227 "ORDER BY at.attnum",
15228 acl_subquery->data,
15229 racl_subquery->data,
15230 initacl_subquery->data,
15231 initracl_subquery->data,
15232 tbinfo->dobj.catId.oid,
15233 acl_subquery->data,
15234 racl_subquery->data,
15235 initacl_subquery->data,
15236 initracl_subquery->data);
15238 destroyPQExpBuffer(acl_subquery);
15239 destroyPQExpBuffer(racl_subquery);
15240 destroyPQExpBuffer(initacl_subquery);
15241 destroyPQExpBuffer(initracl_subquery);
15245 appendPQExpBuffer(query,
15246 "SELECT attname, attacl, NULL as rattacl, "
15247 "NULL AS initattacl, NULL AS initrattacl "
15248 "FROM pg_catalog.pg_attribute "
15249 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15250 "AND attacl IS NOT NULL "
15252 tbinfo->dobj.catId.oid);
15255 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15257 for (i = 0; i < PQntuples(res); i++)
15259 char *attname = PQgetvalue(res, i, 0);
15260 char *attacl = PQgetvalue(res, i, 1);
15261 char *rattacl = PQgetvalue(res, i, 2);
15262 char *initattacl = PQgetvalue(res, i, 3);
15263 char *initrattacl = PQgetvalue(res, i, 4);
15266 attnamecopy = pg_strdup(fmtId(attname));
15267 /* Column's GRANT type is always TABLE */
15268 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15269 "TABLE", namecopy, attnamecopy,
15270 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15271 attacl, rattacl, initattacl, initrattacl);
15275 destroyPQExpBuffer(query);
15284 * Create the AS clause for a view or materialized view. The semicolon is
15285 * stripped because a materialized view must add a WITH NO DATA clause.
15287 * This returns a new buffer which must be freed by the caller.
15290 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15292 PQExpBuffer query = createPQExpBuffer();
15293 PQExpBuffer result = createPQExpBuffer();
15297 /* Fetch the view definition */
15298 appendPQExpBuffer(query,
15299 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15300 tbinfo->dobj.catId.oid);
15302 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15304 if (PQntuples(res) != 1)
15306 if (PQntuples(res) < 1)
15307 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15308 tbinfo->dobj.name);
15310 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15311 tbinfo->dobj.name);
15314 len = PQgetlength(res, 0, 0);
15317 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15318 tbinfo->dobj.name);
15320 /* Strip off the trailing semicolon so that other things may follow. */
15321 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15322 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15325 destroyPQExpBuffer(query);
15331 * Create a dummy AS clause for a view. This is used when the real view
15332 * definition has to be postponed because of circular dependencies.
15333 * We must duplicate the view's external properties -- column names and types
15334 * (including collation) -- so that it works for subsequent references.
15336 * This returns a new buffer which must be freed by the caller.
15339 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15341 PQExpBuffer result = createPQExpBuffer();
15344 appendPQExpBufferStr(result, "SELECT");
15346 for (j = 0; j < tbinfo->numatts; j++)
15349 appendPQExpBufferChar(result, ',');
15350 appendPQExpBufferStr(result, "\n ");
15352 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15355 * Must add collation if not default for the type, because CREATE OR
15356 * REPLACE VIEW won't change it
15358 if (OidIsValid(tbinfo->attcollation[j]))
15362 coll = findCollationByOid(tbinfo->attcollation[j]);
15364 appendPQExpBuffer(result, " COLLATE %s",
15365 fmtQualifiedDumpable(coll));
15368 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15376 * write the declaration (not data) of one user-defined table or view
15379 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15381 DumpOptions *dopt = fout->dopt;
15382 PQExpBuffer q = createPQExpBuffer();
15383 PQExpBuffer delq = createPQExpBuffer();
15387 TableInfo **parents;
15388 int actual_atts; /* number of attrs in this CREATE statement */
15389 const char *reltypename;
15396 qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15397 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15399 if (dopt->binary_upgrade)
15400 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15401 tbinfo->dobj.catId.oid);
15403 /* Is it a table or a view? */
15404 if (tbinfo->relkind == RELKIND_VIEW)
15406 PQExpBuffer result;
15409 * Note: keep this code in sync with the is_view case in dumpRule()
15412 reltypename = "VIEW";
15414 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15416 if (dopt->binary_upgrade)
15417 binary_upgrade_set_pg_class_oids(fout, q,
15418 tbinfo->dobj.catId.oid, false);
15420 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15422 if (tbinfo->dummy_view)
15423 result = createDummyViewAsClause(fout, tbinfo);
15426 if (nonemptyReloptions(tbinfo->reloptions))
15428 appendPQExpBufferStr(q, " WITH (");
15429 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15430 appendPQExpBufferChar(q, ')');
15432 result = createViewAsClause(fout, tbinfo);
15434 appendPQExpBuffer(q, " AS\n%s", result->data);
15435 destroyPQExpBuffer(result);
15437 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15438 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15439 appendPQExpBufferStr(q, ";\n");
15443 switch (tbinfo->relkind)
15445 case RELKIND_FOREIGN_TABLE:
15447 PQExpBuffer query = createPQExpBuffer();
15452 reltypename = "FOREIGN TABLE";
15454 /* retrieve name of foreign server and generic options */
15455 appendPQExpBuffer(query,
15456 "SELECT fs.srvname, "
15457 "pg_catalog.array_to_string(ARRAY("
15458 "SELECT pg_catalog.quote_ident(option_name) || "
15459 "' ' || pg_catalog.quote_literal(option_value) "
15460 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15461 "ORDER BY option_name"
15462 "), E',\n ') AS ftoptions "
15463 "FROM pg_catalog.pg_foreign_table ft "
15464 "JOIN pg_catalog.pg_foreign_server fs "
15465 "ON (fs.oid = ft.ftserver) "
15466 "WHERE ft.ftrelid = '%u'",
15467 tbinfo->dobj.catId.oid);
15468 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15469 i_srvname = PQfnumber(res, "srvname");
15470 i_ftoptions = PQfnumber(res, "ftoptions");
15471 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15472 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15474 destroyPQExpBuffer(query);
15477 case RELKIND_MATVIEW:
15478 reltypename = "MATERIALIZED VIEW";
15483 reltypename = "TABLE";
15488 numParents = tbinfo->numParents;
15489 parents = tbinfo->parents;
15491 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15493 if (dopt->binary_upgrade)
15494 binary_upgrade_set_pg_class_oids(fout, q,
15495 tbinfo->dobj.catId.oid, false);
15497 appendPQExpBuffer(q, "CREATE %s%s %s",
15498 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15504 * Attach to type, if reloftype; except in case of a binary upgrade,
15505 * we dump the table normally and attach it to the type afterward.
15507 if (tbinfo->reloftype && !dopt->binary_upgrade)
15508 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15511 * If the table is a partition, dump it as such; except in the case of
15512 * a binary upgrade, we dump the table normally and attach it to the
15513 * parent afterward.
15515 if (tbinfo->ispartition && !dopt->binary_upgrade)
15517 TableInfo *parentRel = tbinfo->parents[0];
15520 * With partitions, unlike inheritance, there can only be one
15523 if (tbinfo->numParents != 1)
15524 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15525 tbinfo->numParents, tbinfo->dobj.name);
15527 appendPQExpBuffer(q, " PARTITION OF %s",
15528 fmtQualifiedDumpable(parentRel));
15531 if (tbinfo->relkind != RELKIND_MATVIEW)
15533 /* Dump the attributes */
15535 for (j = 0; j < tbinfo->numatts; j++)
15538 * Normally, dump if it's locally defined in this table, and
15539 * not dropped. But for binary upgrade, we'll dump all the
15540 * columns, and then fix up the dropped and nonlocal cases
15543 if (shouldPrintColumn(dopt, tbinfo, j))
15546 * Default value --- suppress if to be printed separately.
15548 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15549 !tbinfo->attrdefs[j]->separate);
15552 * Not Null constraint --- suppress if inherited, except
15553 * in binary-upgrade case where that won't work.
15555 bool has_notnull = (tbinfo->notnull[j] &&
15556 (!tbinfo->inhNotNull[j] ||
15557 dopt->binary_upgrade));
15560 * Skip column if fully defined by reloftype or the
15561 * partition parent.
15563 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15564 !has_default && !has_notnull && !dopt->binary_upgrade)
15567 /* Format properly if not first attr */
15568 if (actual_atts == 0)
15569 appendPQExpBufferStr(q, " (");
15571 appendPQExpBufferChar(q, ',');
15572 appendPQExpBufferStr(q, "\n ");
15575 /* Attribute name */
15576 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15578 if (tbinfo->attisdropped[j])
15581 * ALTER TABLE DROP COLUMN clears
15582 * pg_attribute.atttypid, so we will not have gotten a
15583 * valid type name; insert INTEGER as a stopgap. We'll
15584 * clean things up later.
15586 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15587 /* Skip all the rest, too */
15594 * In binary-upgrade mode, we always include the type. If
15595 * we aren't in binary-upgrade mode, then we skip the type
15596 * when creating a typed table ('OF type_name') or a
15597 * partition ('PARTITION OF'), since the type comes from
15598 * the parent/partitioned table.
15600 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15602 appendPQExpBuffer(q, " %s",
15603 tbinfo->atttypnames[j]);
15606 /* Add collation if not default for the type */
15607 if (OidIsValid(tbinfo->attcollation[j]))
15611 coll = findCollationByOid(tbinfo->attcollation[j]);
15613 appendPQExpBuffer(q, " COLLATE %s",
15614 fmtQualifiedDumpable(coll));
15618 appendPQExpBuffer(q, " DEFAULT %s",
15619 tbinfo->attrdefs[j]->adef_expr);
15622 appendPQExpBufferStr(q, " NOT NULL");
15627 * Add non-inherited CHECK constraints, if any.
15629 for (j = 0; j < tbinfo->ncheck; j++)
15631 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15633 if (constr->separate || !constr->conislocal)
15636 if (actual_atts == 0)
15637 appendPQExpBufferStr(q, " (\n ");
15639 appendPQExpBufferStr(q, ",\n ");
15641 appendPQExpBuffer(q, "CONSTRAINT %s ",
15642 fmtId(constr->dobj.name));
15643 appendPQExpBufferStr(q, constr->condef);
15649 appendPQExpBufferStr(q, "\n)");
15650 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15651 !dopt->binary_upgrade))
15654 * We must have a parenthesized attribute list, even though
15655 * empty, when not using the OF TYPE or PARTITION OF syntax.
15657 appendPQExpBufferStr(q, " (\n)");
15660 if (tbinfo->ispartition && !dopt->binary_upgrade)
15662 appendPQExpBufferChar(q, '\n');
15663 appendPQExpBufferStr(q, tbinfo->partbound);
15666 /* Emit the INHERITS clause, except if this is a partition. */
15667 if (numParents > 0 &&
15668 !tbinfo->ispartition &&
15669 !dopt->binary_upgrade)
15671 appendPQExpBufferStr(q, "\nINHERITS (");
15672 for (k = 0; k < numParents; k++)
15674 TableInfo *parentRel = parents[k];
15677 appendPQExpBufferStr(q, ", ");
15678 appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15680 appendPQExpBufferChar(q, ')');
15683 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15684 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15686 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15687 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15690 if (nonemptyReloptions(tbinfo->reloptions) ||
15691 nonemptyReloptions(tbinfo->toast_reloptions))
15693 bool addcomma = false;
15695 appendPQExpBufferStr(q, "\nWITH (");
15696 if (nonemptyReloptions(tbinfo->reloptions))
15699 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15701 if (nonemptyReloptions(tbinfo->toast_reloptions))
15704 appendPQExpBufferStr(q, ", ");
15705 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15708 appendPQExpBufferChar(q, ')');
15711 /* Dump generic options if any */
15712 if (ftoptions && ftoptions[0])
15713 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15716 * For materialized views, create the AS clause just like a view. At
15717 * this point, we always mark the view as not populated.
15719 if (tbinfo->relkind == RELKIND_MATVIEW)
15721 PQExpBuffer result;
15723 result = createViewAsClause(fout, tbinfo);
15724 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15726 destroyPQExpBuffer(result);
15729 appendPQExpBufferStr(q, ";\n");
15732 * in binary upgrade mode, update the catalog with any missing values
15733 * that might be present.
15735 if (dopt->binary_upgrade)
15737 for (j = 0; j < tbinfo->numatts; j++)
15739 if (tbinfo->attmissingval[j][0] != '\0')
15741 appendPQExpBufferStr(q, "\n-- set missing value.\n");
15742 appendPQExpBufferStr(q,
15743 "SELECT pg_catalog.binary_upgrade_set_missing_value(");
15744 appendStringLiteralAH(q, qualrelname, fout);
15745 appendPQExpBufferStr(q, "::pg_catalog.regclass,");
15746 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15747 appendPQExpBufferStr(q, ",");
15748 appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
15749 appendPQExpBufferStr(q, ");\n\n");
15755 * To create binary-compatible heap files, we have to ensure the same
15756 * physical column order, including dropped columns, as in the
15757 * original. Therefore, we create dropped columns above and drop them
15758 * here, also updating their attlen/attalign values so that the
15759 * dropped column can be skipped properly. (We do not bother with
15760 * restoring the original attbyval setting.) Also, inheritance
15761 * relationships are set up by doing ALTER TABLE INHERIT rather than
15762 * using an INHERITS clause --- the latter would possibly mess up the
15763 * column order. That also means we have to take care about setting
15764 * attislocal correctly, plus fix up any inherited CHECK constraints.
15765 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15767 * We process foreign and partitioned tables here, even though they
15768 * lack heap storage, because they can participate in inheritance
15769 * relationships and we want this stuff to be consistent across the
15770 * inheritance tree. We can exclude indexes, toast tables, sequences
15771 * and matviews, even though they have storage, because we don't
15772 * support altering or dropping columns in them, nor can they be part
15773 * of inheritance trees.
15775 if (dopt->binary_upgrade &&
15776 (tbinfo->relkind == RELKIND_RELATION ||
15777 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15778 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15780 for (j = 0; j < tbinfo->numatts; j++)
15782 if (tbinfo->attisdropped[j])
15784 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15785 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15786 "SET attlen = %d, "
15787 "attalign = '%c', attbyval = false\n"
15788 "WHERE attname = ",
15790 tbinfo->attalign[j]);
15791 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15792 appendPQExpBufferStr(q, "\n AND attrelid = ");
15793 appendStringLiteralAH(q, qualrelname, fout);
15794 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15796 if (tbinfo->relkind == RELKIND_RELATION ||
15797 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15798 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15801 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15803 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15804 fmtId(tbinfo->attnames[j]));
15806 else if (!tbinfo->attislocal[j])
15808 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15809 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15810 "SET attislocal = false\n"
15811 "WHERE attname = ");
15812 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15813 appendPQExpBufferStr(q, "\n AND attrelid = ");
15814 appendStringLiteralAH(q, qualrelname, fout);
15815 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15819 for (k = 0; k < tbinfo->ncheck; k++)
15821 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15823 if (constr->separate || constr->conislocal)
15826 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15827 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15829 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15830 fmtId(constr->dobj.name));
15831 appendPQExpBuffer(q, "%s;\n", constr->condef);
15832 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15833 "SET conislocal = false\n"
15834 "WHERE contype = 'c' AND conname = ");
15835 appendStringLiteralAH(q, constr->dobj.name, fout);
15836 appendPQExpBufferStr(q, "\n AND conrelid = ");
15837 appendStringLiteralAH(q, qualrelname, fout);
15838 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15841 if (numParents > 0)
15843 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15844 for (k = 0; k < numParents; k++)
15846 TableInfo *parentRel = parents[k];
15848 /* In the partitioning case, we alter the parent */
15849 if (tbinfo->ispartition)
15850 appendPQExpBuffer(q,
15851 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15852 fmtQualifiedDumpable(parentRel));
15854 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15857 /* Partition needs specifying the bounds */
15858 if (tbinfo->ispartition)
15859 appendPQExpBuffer(q, "%s %s;\n",
15861 tbinfo->partbound);
15863 appendPQExpBuffer(q, "%s;\n",
15864 fmtQualifiedDumpable(parentRel));
15868 if (tbinfo->reloftype)
15870 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15871 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15873 tbinfo->reloftype);
15878 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15879 * relminmxid of all vacuumable relations. (While vacuum.c processes
15880 * TOAST tables semi-independently, here we see them only as children
15881 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15882 * child toast table is handled below.)
15884 if (dopt->binary_upgrade &&
15885 (tbinfo->relkind == RELKIND_RELATION ||
15886 tbinfo->relkind == RELKIND_MATVIEW))
15888 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15889 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15890 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15892 tbinfo->frozenxid, tbinfo->minmxid);
15893 appendStringLiteralAH(q, qualrelname, fout);
15894 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15896 if (tbinfo->toast_oid)
15899 * The toast table will have the same OID at restore, so we
15900 * can safely target it by OID.
15902 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15903 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15904 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15905 "WHERE oid = '%u';\n",
15906 tbinfo->toast_frozenxid,
15907 tbinfo->toast_minmxid, tbinfo->toast_oid);
15912 * In binary_upgrade mode, restore matviews' populated status by
15913 * poking pg_class directly. This is pretty ugly, but we can't use
15914 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15915 * matview is not populated even though this matview is; in any case,
15916 * we want to transfer the matview's heap storage, not run REFRESH.
15918 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15919 tbinfo->relispopulated)
15921 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15922 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15923 "SET relispopulated = 't'\n"
15925 appendStringLiteralAH(q, qualrelname, fout);
15926 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15930 * Dump additional per-column properties that we can't handle in the
15931 * main CREATE TABLE command.
15933 for (j = 0; j < tbinfo->numatts; j++)
15935 /* None of this applies to dropped columns */
15936 if (tbinfo->attisdropped[j])
15940 * If we didn't dump the column definition explicitly above, and
15941 * it is NOT NULL and did not inherit that property from a parent,
15942 * we have to mark it separately.
15944 if (!shouldPrintColumn(dopt, tbinfo, j) &&
15945 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15947 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15949 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15950 fmtId(tbinfo->attnames[j]));
15954 * Dump per-column statistics information. We only issue an ALTER
15955 * TABLE statement if the attstattarget entry for this column is
15956 * non-negative (i.e. it's not the default value)
15958 if (tbinfo->attstattarget[j] >= 0)
15960 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15962 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15963 fmtId(tbinfo->attnames[j]));
15964 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15965 tbinfo->attstattarget[j]);
15969 * Dump per-column storage information. The statement is only
15970 * dumped if the storage has been changed from the type's default.
15972 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15974 switch (tbinfo->attstorage[j])
15980 storage = "EXTERNAL";
15986 storage = "EXTENDED";
15993 * Only dump the statement if it's a storage type we recognize
15995 if (storage != NULL)
15997 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15999 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16000 fmtId(tbinfo->attnames[j]));
16001 appendPQExpBuffer(q, "SET STORAGE %s;\n",
16007 * Dump per-column attributes.
16009 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
16011 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16013 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16014 fmtId(tbinfo->attnames[j]));
16015 appendPQExpBuffer(q, "SET (%s);\n",
16016 tbinfo->attoptions[j]);
16020 * Dump per-column fdw options.
16022 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16023 tbinfo->attfdwoptions[j] &&
16024 tbinfo->attfdwoptions[j][0] != '\0')
16026 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16028 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16029 fmtId(tbinfo->attnames[j]));
16030 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
16031 tbinfo->attfdwoptions[j]);
16037 * dump properties we only have ALTER TABLE syntax for
16039 if ((tbinfo->relkind == RELKIND_RELATION ||
16040 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16041 tbinfo->relkind == RELKIND_MATVIEW) &&
16042 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16044 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16046 /* nothing to do, will be set when the index is dumped */
16048 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16050 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16053 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16055 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16060 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
16061 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
16064 if (tbinfo->forcerowsec)
16065 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16068 if (dopt->binary_upgrade)
16069 binary_upgrade_extension_member(q, &tbinfo->dobj,
16070 reltypename, qrelname,
16071 tbinfo->dobj.namespace->dobj.name);
16073 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16074 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16076 tbinfo->dobj.namespace->dobj.name,
16077 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16079 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
16081 tbinfo->postponed_def ?
16082 SECTION_POST_DATA : SECTION_PRE_DATA,
16083 q->data, delq->data, NULL,
16088 /* Dump Table Comments */
16089 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16090 dumpTableComment(fout, tbinfo, reltypename);
16092 /* Dump Table Security Labels */
16093 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16094 dumpTableSecLabel(fout, tbinfo, reltypename);
16096 /* Dump comments on inlined table constraints */
16097 for (j = 0; j < tbinfo->ncheck; j++)
16099 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16101 if (constr->separate || !constr->conislocal)
16104 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16105 dumpTableConstraintComment(fout, constr);
16108 destroyPQExpBuffer(q);
16109 destroyPQExpBuffer(delq);
16115 * dumpAttrDef --- dump an attribute's default-value declaration
16118 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16120 DumpOptions *dopt = fout->dopt;
16121 TableInfo *tbinfo = adinfo->adtable;
16122 int adnum = adinfo->adnum;
16128 /* Skip if table definition not to be dumped */
16129 if (!tbinfo->dobj.dump || dopt->dataOnly)
16132 /* Skip if not "separate"; it was dumped in the table's definition */
16133 if (!adinfo->separate)
16136 q = createPQExpBuffer();
16137 delq = createPQExpBuffer();
16139 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16141 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16143 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16144 fmtId(tbinfo->attnames[adnum - 1]),
16145 adinfo->adef_expr);
16147 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16149 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16150 fmtId(tbinfo->attnames[adnum - 1]));
16152 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16154 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16155 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16157 tbinfo->dobj.namespace->dobj.name,
16160 false, "DEFAULT", SECTION_PRE_DATA,
16161 q->data, delq->data, NULL,
16166 destroyPQExpBuffer(q);
16167 destroyPQExpBuffer(delq);
16172 * getAttrName: extract the correct name for an attribute
16174 * The array tblInfo->attnames[] only provides names of user attributes;
16175 * if a system attribute number is supplied, we have to fake it.
16176 * We also do a little bit of bounds checking for safety's sake.
16178 static const char *
16179 getAttrName(int attrnum, TableInfo *tblInfo)
16181 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16182 return tblInfo->attnames[attrnum - 1];
16185 case SelfItemPointerAttributeNumber:
16187 case ObjectIdAttributeNumber:
16189 case MinTransactionIdAttributeNumber:
16191 case MinCommandIdAttributeNumber:
16193 case MaxTransactionIdAttributeNumber:
16195 case MaxCommandIdAttributeNumber:
16197 case TableOidAttributeNumber:
16200 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16201 attrnum, tblInfo->dobj.name);
16202 return NULL; /* keep compiler quiet */
16207 * write out to fout a user-defined index
16210 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16212 DumpOptions *dopt = fout->dopt;
16213 TableInfo *tbinfo = indxinfo->indextable;
16214 bool is_constraint = (indxinfo->indexconstraint != 0);
16219 if (dopt->dataOnly)
16222 q = createPQExpBuffer();
16223 delq = createPQExpBuffer();
16225 qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16228 * If there's an associated constraint, don't dump the index per se, but
16229 * do dump any comment for it. (This is safe because dependency ordering
16230 * will have ensured the constraint is emitted first.) Note that the
16231 * emitted comment has to be shown as depending on the constraint, not the
16232 * index, in such cases.
16234 if (!is_constraint)
16236 if (dopt->binary_upgrade)
16237 binary_upgrade_set_pg_class_oids(fout, q,
16238 indxinfo->dobj.catId.oid, true);
16240 /* Plain secondary index */
16241 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16244 * Append ALTER TABLE commands as needed to set properties that we
16245 * only have ALTER TABLE syntax for. Keep this in sync with the
16246 * similar code in dumpConstraint!
16249 /* If the index is clustered, we need to record that. */
16250 if (indxinfo->indisclustered)
16252 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16253 fmtQualifiedDumpable(tbinfo));
16254 /* index name is not qualified in this syntax */
16255 appendPQExpBuffer(q, " ON %s;\n",
16259 /* If the index defines identity, we need to record that. */
16260 if (indxinfo->indisreplident)
16262 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16263 fmtQualifiedDumpable(tbinfo));
16264 /* index name is not qualified in this syntax */
16265 appendPQExpBuffer(q, " INDEX %s;\n",
16269 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16270 fmtQualifiedDumpable(indxinfo));
16272 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16273 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16274 indxinfo->dobj.name,
16275 tbinfo->dobj.namespace->dobj.name,
16276 indxinfo->tablespace,
16277 tbinfo->rolname, false,
16278 "INDEX", SECTION_POST_DATA,
16279 q->data, delq->data, NULL,
16284 /* Dump Index Comments */
16285 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16286 dumpComment(fout, "INDEX", qindxname,
16287 tbinfo->dobj.namespace->dobj.name,
16289 indxinfo->dobj.catId, 0,
16290 is_constraint ? indxinfo->indexconstraint :
16291 indxinfo->dobj.dumpId);
16293 destroyPQExpBuffer(q);
16294 destroyPQExpBuffer(delq);
16300 * write out to fout a partitioned-index attachment clause
16303 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16305 if (fout->dopt->dataOnly)
16308 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16310 PQExpBuffer q = createPQExpBuffer();
16312 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16313 fmtQualifiedDumpable(attachinfo->parentIdx));
16314 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16315 fmtQualifiedDumpable(attachinfo->partitionIdx));
16317 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16318 attachinfo->dobj.name,
16321 false, "INDEX ATTACH", SECTION_POST_DATA,
16326 destroyPQExpBuffer(q);
16331 * dumpStatisticsExt
16332 * write out to fout an extended statistics object
16335 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16337 DumpOptions *dopt = fout->dopt;
16341 char *qstatsextname;
16345 /* Skip if not to be dumped */
16346 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16349 q = createPQExpBuffer();
16350 delq = createPQExpBuffer();
16351 query = createPQExpBuffer();
16353 qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16355 appendPQExpBuffer(query, "SELECT "
16356 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16357 statsextinfo->dobj.catId.oid);
16359 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16361 stxdef = PQgetvalue(res, 0, 0);
16363 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16364 appendPQExpBuffer(q, "%s;\n", stxdef);
16366 appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16367 fmtQualifiedDumpable(statsextinfo));
16369 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16370 ArchiveEntry(fout, statsextinfo->dobj.catId,
16371 statsextinfo->dobj.dumpId,
16372 statsextinfo->dobj.name,
16373 statsextinfo->dobj.namespace->dobj.name,
16375 statsextinfo->rolname, false,
16376 "STATISTICS", SECTION_POST_DATA,
16377 q->data, delq->data, NULL,
16381 /* Dump Statistics Comments */
16382 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16383 dumpComment(fout, "STATISTICS", qstatsextname,
16384 statsextinfo->dobj.namespace->dobj.name,
16385 statsextinfo->rolname,
16386 statsextinfo->dobj.catId, 0,
16387 statsextinfo->dobj.dumpId);
16390 destroyPQExpBuffer(q);
16391 destroyPQExpBuffer(delq);
16392 destroyPQExpBuffer(query);
16393 free(qstatsextname);
16398 * write out to fout a user-defined constraint
16401 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16403 DumpOptions *dopt = fout->dopt;
16404 TableInfo *tbinfo = coninfo->contable;
16409 /* Skip if not to be dumped */
16410 if (!coninfo->dobj.dump || dopt->dataOnly)
16413 q = createPQExpBuffer();
16414 delq = createPQExpBuffer();
16416 if (coninfo->contype == 'p' ||
16417 coninfo->contype == 'u' ||
16418 coninfo->contype == 'x')
16420 /* Index-related constraint */
16421 IndxInfo *indxinfo;
16424 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16426 if (indxinfo == NULL)
16427 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16428 coninfo->dobj.name);
16430 if (dopt->binary_upgrade)
16431 binary_upgrade_set_pg_class_oids(fout, q,
16432 indxinfo->dobj.catId.oid, true);
16434 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16435 fmtQualifiedDumpable(tbinfo));
16436 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16437 fmtId(coninfo->dobj.name));
16439 if (coninfo->condef)
16441 /* pg_get_constraintdef should have provided everything */
16442 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16446 appendPQExpBuffer(q, "%s (",
16447 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16448 for (k = 0; k < indxinfo->indnkeyattrs; k++)
16450 int indkey = (int) indxinfo->indkeys[k];
16451 const char *attname;
16453 if (indkey == InvalidAttrNumber)
16455 attname = getAttrName(indkey, tbinfo);
16457 appendPQExpBuffer(q, "%s%s",
16458 (k == 0) ? "" : ", ",
16462 if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
16463 appendPQExpBuffer(q, ") INCLUDE (");
16465 for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
16467 int indkey = (int) indxinfo->indkeys[k];
16468 const char *attname;
16470 if (indkey == InvalidAttrNumber)
16472 attname = getAttrName(indkey, tbinfo);
16474 appendPQExpBuffer(q, "%s%s",
16475 (k == indxinfo->indnkeyattrs) ? "" : ", ",
16479 appendPQExpBufferChar(q, ')');
16481 if (nonemptyReloptions(indxinfo->indreloptions))
16483 appendPQExpBufferStr(q, " WITH (");
16484 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16485 appendPQExpBufferChar(q, ')');
16488 if (coninfo->condeferrable)
16490 appendPQExpBufferStr(q, " DEFERRABLE");
16491 if (coninfo->condeferred)
16492 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16495 appendPQExpBufferStr(q, ";\n");
16499 * Append ALTER TABLE commands as needed to set properties that we
16500 * only have ALTER TABLE syntax for. Keep this in sync with the
16501 * similar code in dumpIndex!
16504 /* If the index is clustered, we need to record that. */
16505 if (indxinfo->indisclustered)
16507 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16508 fmtQualifiedDumpable(tbinfo));
16509 /* index name is not qualified in this syntax */
16510 appendPQExpBuffer(q, " ON %s;\n",
16511 fmtId(indxinfo->dobj.name));
16514 /* If the index defines identity, we need to record that. */
16515 if (indxinfo->indisreplident)
16517 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16518 fmtQualifiedDumpable(tbinfo));
16519 /* index name is not qualified in this syntax */
16520 appendPQExpBuffer(q, " INDEX %s;\n",
16521 fmtId(indxinfo->dobj.name));
16524 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16525 fmtQualifiedDumpable(tbinfo));
16526 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16527 fmtId(coninfo->dobj.name));
16529 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16531 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16532 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16534 tbinfo->dobj.namespace->dobj.name,
16535 indxinfo->tablespace,
16536 tbinfo->rolname, false,
16537 "CONSTRAINT", SECTION_POST_DATA,
16538 q->data, delq->data, NULL,
16542 else if (coninfo->contype == 'f')
16547 * Foreign keys on partitioned tables are always declared as
16548 * inheriting to partitions; for all other cases, emit them as
16549 * applying ONLY directly to the named table, because that's how they
16550 * work for regular inherited tables.
16552 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
16555 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16556 * current table data is not processed
16558 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
16559 only, fmtQualifiedDumpable(tbinfo));
16560 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16561 fmtId(coninfo->dobj.name),
16564 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
16565 only, fmtQualifiedDumpable(tbinfo));
16566 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16567 fmtId(coninfo->dobj.name));
16569 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16571 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16572 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16574 tbinfo->dobj.namespace->dobj.name,
16576 tbinfo->rolname, false,
16577 "FK CONSTRAINT", SECTION_POST_DATA,
16578 q->data, delq->data, NULL,
16582 else if (coninfo->contype == 'c' && tbinfo)
16584 /* CHECK constraint on a table */
16586 /* Ignore if not to be dumped separately, or if it was inherited */
16587 if (coninfo->separate && coninfo->conislocal)
16589 /* not ONLY since we want it to propagate to children */
16590 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16591 fmtQualifiedDumpable(tbinfo));
16592 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16593 fmtId(coninfo->dobj.name),
16596 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16597 fmtQualifiedDumpable(tbinfo));
16598 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16599 fmtId(coninfo->dobj.name));
16601 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16603 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16604 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16606 tbinfo->dobj.namespace->dobj.name,
16608 tbinfo->rolname, false,
16609 "CHECK CONSTRAINT", SECTION_POST_DATA,
16610 q->data, delq->data, NULL,
16615 else if (coninfo->contype == 'c' && tbinfo == NULL)
16617 /* CHECK constraint on a domain */
16618 TypeInfo *tyinfo = coninfo->condomain;
16620 /* Ignore if not to be dumped separately */
16621 if (coninfo->separate)
16623 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16624 fmtQualifiedDumpable(tyinfo));
16625 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16626 fmtId(coninfo->dobj.name),
16629 appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16630 fmtQualifiedDumpable(tyinfo));
16631 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16632 fmtId(coninfo->dobj.name));
16634 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16636 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16637 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16639 tyinfo->dobj.namespace->dobj.name,
16641 tyinfo->rolname, false,
16642 "CHECK CONSTRAINT", SECTION_POST_DATA,
16643 q->data, delq->data, NULL,
16650 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16654 /* Dump Constraint Comments --- only works for table constraints */
16655 if (tbinfo && coninfo->separate &&
16656 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16657 dumpTableConstraintComment(fout, coninfo);
16660 destroyPQExpBuffer(q);
16661 destroyPQExpBuffer(delq);
16665 * dumpTableConstraintComment --- dump a constraint's comment if any
16667 * This is split out because we need the function in two different places
16668 * depending on whether the constraint is dumped as part of CREATE TABLE
16669 * or as a separate ALTER command.
16672 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16674 TableInfo *tbinfo = coninfo->contable;
16675 PQExpBuffer conprefix = createPQExpBuffer();
16678 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16680 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16681 fmtId(coninfo->dobj.name));
16683 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16684 dumpComment(fout, conprefix->data, qtabname,
16685 tbinfo->dobj.namespace->dobj.name,
16687 coninfo->dobj.catId, 0,
16688 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16690 destroyPQExpBuffer(conprefix);
16695 * findLastBuiltinOid_V71 -
16697 * find the last built in oid
16699 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16700 * pg_database entry for the current database. (Note: current_database()
16701 * requires 7.3; pg_dump requires 8.0 now.)
16704 findLastBuiltinOid_V71(Archive *fout)
16709 res = ExecuteSqlQueryForSingleRow(fout,
16710 "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
16711 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16719 * write the declaration (not data) of one user-defined sequence
16722 dumpSequence(Archive *fout, TableInfo *tbinfo)
16724 DumpOptions *dopt = fout->dopt;
16734 int64 default_minv,
16738 PQExpBuffer query = createPQExpBuffer();
16739 PQExpBuffer delqry = createPQExpBuffer();
16742 qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16744 if (fout->remoteVersion >= 100000)
16746 appendPQExpBuffer(query,
16747 "SELECT format_type(seqtypid, NULL), "
16748 "seqstart, seqincrement, "
16750 "seqcache, seqcycle "
16751 "FROM pg_catalog.pg_sequence "
16752 "WHERE seqrelid = '%u'::oid",
16753 tbinfo->dobj.catId.oid);
16755 else if (fout->remoteVersion >= 80400)
16758 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16760 * Note: it might seem that 'bigint' potentially needs to be
16761 * schema-qualified, but actually that's a keyword.
16763 appendPQExpBuffer(query,
16764 "SELECT 'bigint' AS sequence_type, "
16765 "start_value, increment_by, max_value, min_value, "
16766 "cache_value, is_cycled FROM %s",
16767 fmtQualifiedDumpable(tbinfo));
16771 appendPQExpBuffer(query,
16772 "SELECT 'bigint' AS sequence_type, "
16773 "0 AS start_value, increment_by, max_value, min_value, "
16774 "cache_value, is_cycled FROM %s",
16775 fmtQualifiedDumpable(tbinfo));
16778 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16780 if (PQntuples(res) != 1)
16782 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16783 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16785 tbinfo->dobj.name, PQntuples(res));
16789 seqtype = PQgetvalue(res, 0, 0);
16790 startv = PQgetvalue(res, 0, 1);
16791 incby = PQgetvalue(res, 0, 2);
16792 maxv = PQgetvalue(res, 0, 3);
16793 minv = PQgetvalue(res, 0, 4);
16794 cache = PQgetvalue(res, 0, 5);
16795 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16797 /* Calculate default limits for a sequence of this type */
16798 is_ascending = (incby[0] != '-');
16799 if (strcmp(seqtype, "smallint") == 0)
16801 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16802 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16804 else if (strcmp(seqtype, "integer") == 0)
16806 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16807 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16809 else if (strcmp(seqtype, "bigint") == 0)
16811 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16812 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16816 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16817 default_minv = default_maxv = 0; /* keep compiler quiet */
16821 * 64-bit strtol() isn't very portable, so convert the limits to strings
16822 * and compare that way.
16824 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16825 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16827 /* Don't print minv/maxv if they match the respective default limit */
16828 if (strcmp(minv, bufm) == 0)
16830 if (strcmp(maxv, bufx) == 0)
16834 * Identity sequences are not to be dropped separately.
16836 if (!tbinfo->is_identity_sequence)
16838 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16839 fmtQualifiedDumpable(tbinfo));
16842 resetPQExpBuffer(query);
16844 if (dopt->binary_upgrade)
16846 binary_upgrade_set_pg_class_oids(fout, query,
16847 tbinfo->dobj.catId.oid, false);
16848 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16849 tbinfo->dobj.catId.oid);
16852 if (tbinfo->is_identity_sequence)
16854 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16856 appendPQExpBuffer(query,
16858 fmtQualifiedDumpable(owning_tab));
16859 appendPQExpBuffer(query,
16860 "ALTER COLUMN %s ADD GENERATED ",
16861 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16862 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16863 appendPQExpBuffer(query, "ALWAYS");
16864 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16865 appendPQExpBuffer(query, "BY DEFAULT");
16866 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16867 fmtQualifiedDumpable(tbinfo));
16871 appendPQExpBuffer(query,
16872 "CREATE SEQUENCE %s\n",
16873 fmtQualifiedDumpable(tbinfo));
16875 if (strcmp(seqtype, "bigint") != 0)
16876 appendPQExpBuffer(query, " AS %s\n", seqtype);
16879 if (fout->remoteVersion >= 80400)
16880 appendPQExpBuffer(query, " START WITH %s\n", startv);
16882 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
16885 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
16887 appendPQExpBufferStr(query, " NO MINVALUE\n");
16890 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
16892 appendPQExpBufferStr(query, " NO MAXVALUE\n");
16894 appendPQExpBuffer(query,
16896 cache, (cycled ? "\n CYCLE" : ""));
16898 if (tbinfo->is_identity_sequence)
16899 appendPQExpBufferStr(query, "\n);\n");
16901 appendPQExpBufferStr(query, ";\n");
16903 /* binary_upgrade: no need to clear TOAST table oid */
16905 if (dopt->binary_upgrade)
16906 binary_upgrade_extension_member(query, &tbinfo->dobj,
16907 "SEQUENCE", qseqname,
16908 tbinfo->dobj.namespace->dobj.name);
16910 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16911 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16913 tbinfo->dobj.namespace->dobj.name,
16916 false, "SEQUENCE", SECTION_PRE_DATA,
16917 query->data, delqry->data, NULL,
16922 * If the sequence is owned by a table column, emit the ALTER for it as a
16923 * separate TOC entry immediately following the sequence's own entry. It's
16924 * OK to do this rather than using full sorting logic, because the
16925 * dependency that tells us it's owned will have forced the table to be
16926 * created first. We can't just include the ALTER in the TOC entry
16927 * because it will fail if we haven't reassigned the sequence owner to
16928 * match the table's owner.
16930 * We need not schema-qualify the table reference because both sequence
16931 * and table must be in the same schema.
16933 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16935 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16937 if (owning_tab == NULL)
16938 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16939 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16941 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16943 resetPQExpBuffer(query);
16944 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16945 fmtQualifiedDumpable(tbinfo));
16946 appendPQExpBuffer(query, " OWNED BY %s",
16947 fmtQualifiedDumpable(owning_tab));
16948 appendPQExpBuffer(query, ".%s;\n",
16949 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16951 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16952 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16954 tbinfo->dobj.namespace->dobj.name,
16957 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16958 query->data, "", NULL,
16959 &(tbinfo->dobj.dumpId), 1,
16964 /* Dump Sequence Comments and Security Labels */
16965 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16966 dumpComment(fout, "SEQUENCE", qseqname,
16967 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16968 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16970 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16971 dumpSecLabel(fout, "SEQUENCE", qseqname,
16972 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16973 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16977 destroyPQExpBuffer(query);
16978 destroyPQExpBuffer(delqry);
16984 * write the data of one user-defined sequence
16987 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16989 TableInfo *tbinfo = tdinfo->tdtable;
16993 PQExpBuffer query = createPQExpBuffer();
16995 appendPQExpBuffer(query,
16996 "SELECT last_value, is_called FROM %s",
16997 fmtQualifiedDumpable(tbinfo));
16999 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17001 if (PQntuples(res) != 1)
17003 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
17004 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
17006 tbinfo->dobj.name, PQntuples(res));
17010 last = PQgetvalue(res, 0, 0);
17011 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17013 resetPQExpBuffer(query);
17014 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17015 appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
17016 appendPQExpBuffer(query, ", %s, %s);\n",
17017 last, (called ? "true" : "false"));
17019 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17020 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17022 tbinfo->dobj.namespace->dobj.name,
17025 false, "SEQUENCE SET", SECTION_DATA,
17026 query->data, "", NULL,
17027 &(tbinfo->dobj.dumpId), 1,
17032 destroyPQExpBuffer(query);
17037 * write the declaration of one user-defined table trigger
17040 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17042 DumpOptions *dopt = fout->dopt;
17043 TableInfo *tbinfo = tginfo->tgtable;
17045 PQExpBuffer delqry;
17046 PQExpBuffer trigprefix;
17055 * we needn't check dobj.dump because TriggerInfo wouldn't have been
17056 * created in the first place for non-dumpable triggers
17058 if (dopt->dataOnly)
17061 query = createPQExpBuffer();
17062 delqry = createPQExpBuffer();
17063 trigprefix = createPQExpBuffer();
17065 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17067 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17068 fmtId(tginfo->dobj.name));
17069 appendPQExpBuffer(delqry, "ON %s;\n",
17070 fmtQualifiedDumpable(tbinfo));
17074 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17078 if (tginfo->tgisconstraint)
17080 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17081 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17085 appendPQExpBufferStr(query, "CREATE TRIGGER ");
17086 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17088 appendPQExpBufferStr(query, "\n ");
17091 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17092 appendPQExpBufferStr(query, "BEFORE");
17093 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17094 appendPQExpBufferStr(query, "AFTER");
17095 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17096 appendPQExpBufferStr(query, "INSTEAD OF");
17099 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17104 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17106 appendPQExpBufferStr(query, " INSERT");
17109 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17112 appendPQExpBufferStr(query, " OR DELETE");
17114 appendPQExpBufferStr(query, " DELETE");
17117 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17120 appendPQExpBufferStr(query, " OR UPDATE");
17122 appendPQExpBufferStr(query, " UPDATE");
17125 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17128 appendPQExpBufferStr(query, " OR TRUNCATE");
17130 appendPQExpBufferStr(query, " TRUNCATE");
17133 appendPQExpBuffer(query, " ON %s\n",
17134 fmtQualifiedDumpable(tbinfo));
17136 if (tginfo->tgisconstraint)
17138 if (OidIsValid(tginfo->tgconstrrelid))
17140 /* regclass output is already quoted */
17141 appendPQExpBuffer(query, " FROM %s\n ",
17142 tginfo->tgconstrrelname);
17144 if (!tginfo->tgdeferrable)
17145 appendPQExpBufferStr(query, "NOT ");
17146 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17147 if (tginfo->tginitdeferred)
17148 appendPQExpBufferStr(query, "DEFERRED\n");
17150 appendPQExpBufferStr(query, "IMMEDIATE\n");
17153 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17154 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
17156 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
17158 /* regproc output is already sufficiently quoted */
17159 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17162 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17165 for (findx = 0; findx < tginfo->tgnargs; findx++)
17167 /* find the embedded null that terminates this trigger argument */
17168 size_t tlen = strlen(p);
17170 if (p + tlen >= tgargs + lentgargs)
17172 /* hm, not found before end of bytea value... */
17173 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17176 tbinfo->dobj.name);
17181 appendPQExpBufferStr(query, ", ");
17182 appendStringLiteralAH(query, p, fout);
17186 appendPQExpBufferStr(query, ");\n");
17189 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17191 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17192 fmtQualifiedDumpable(tbinfo));
17193 switch (tginfo->tgenabled)
17197 appendPQExpBufferStr(query, "DISABLE");
17200 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17203 appendPQExpBufferStr(query, "ENABLE REPLICA");
17206 appendPQExpBufferStr(query, "ENABLE");
17209 appendPQExpBuffer(query, " TRIGGER %s;\n",
17210 fmtId(tginfo->dobj.name));
17213 appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17214 fmtId(tginfo->dobj.name));
17216 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17218 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17219 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17221 tbinfo->dobj.namespace->dobj.name,
17223 tbinfo->rolname, false,
17224 "TRIGGER", SECTION_POST_DATA,
17225 query->data, delqry->data, NULL,
17229 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17230 dumpComment(fout, trigprefix->data, qtabname,
17231 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17232 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17235 destroyPQExpBuffer(query);
17236 destroyPQExpBuffer(delqry);
17237 destroyPQExpBuffer(trigprefix);
17243 * write the declaration of one user-defined event trigger
17246 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17248 DumpOptions *dopt = fout->dopt;
17250 PQExpBuffer delqry;
17253 /* Skip if not to be dumped */
17254 if (!evtinfo->dobj.dump || dopt->dataOnly)
17257 query = createPQExpBuffer();
17258 delqry = createPQExpBuffer();
17260 qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17262 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17263 appendPQExpBufferStr(query, qevtname);
17264 appendPQExpBufferStr(query, " ON ");
17265 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17267 if (strcmp("", evtinfo->evttags) != 0)
17269 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17270 appendPQExpBufferStr(query, evtinfo->evttags);
17271 appendPQExpBufferChar(query, ')');
17274 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
17275 appendPQExpBufferStr(query, evtinfo->evtfname);
17276 appendPQExpBufferStr(query, "();\n");
17278 if (evtinfo->evtenabled != 'O')
17280 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17282 switch (evtinfo->evtenabled)
17285 appendPQExpBufferStr(query, "DISABLE");
17288 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17291 appendPQExpBufferStr(query, "ENABLE REPLICA");
17294 appendPQExpBufferStr(query, "ENABLE");
17297 appendPQExpBufferStr(query, ";\n");
17300 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17303 if (dopt->binary_upgrade)
17304 binary_upgrade_extension_member(query, &evtinfo->dobj,
17305 "EVENT TRIGGER", qevtname, NULL);
17307 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17308 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17309 evtinfo->dobj.name, NULL, NULL,
17310 evtinfo->evtowner, false,
17311 "EVENT TRIGGER", SECTION_POST_DATA,
17312 query->data, delqry->data, NULL,
17316 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17317 dumpComment(fout, "EVENT TRIGGER", qevtname,
17318 NULL, evtinfo->evtowner,
17319 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17321 destroyPQExpBuffer(query);
17322 destroyPQExpBuffer(delqry);
17331 dumpRule(Archive *fout, RuleInfo *rinfo)
17333 DumpOptions *dopt = fout->dopt;
17334 TableInfo *tbinfo = rinfo->ruletable;
17338 PQExpBuffer delcmd;
17339 PQExpBuffer ruleprefix;
17344 /* Skip if not to be dumped */
17345 if (!rinfo->dobj.dump || dopt->dataOnly)
17349 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17350 * we do not want to dump it as a separate object.
17352 if (!rinfo->separate)
17356 * If it's an ON SELECT rule, we want to print it as a view definition,
17357 * instead of a rule.
17359 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17361 query = createPQExpBuffer();
17362 cmd = createPQExpBuffer();
17363 delcmd = createPQExpBuffer();
17364 ruleprefix = createPQExpBuffer();
17366 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17370 PQExpBuffer result;
17373 * We need OR REPLACE here because we'll be replacing a dummy view.
17374 * Otherwise this should look largely like the regular view dump code.
17376 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17377 fmtQualifiedDumpable(tbinfo));
17378 if (nonemptyReloptions(tbinfo->reloptions))
17380 appendPQExpBufferStr(cmd, " WITH (");
17381 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17382 appendPQExpBufferChar(cmd, ')');
17384 result = createViewAsClause(fout, tbinfo);
17385 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17386 destroyPQExpBuffer(result);
17387 if (tbinfo->checkoption != NULL)
17388 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
17389 tbinfo->checkoption);
17390 appendPQExpBufferStr(cmd, ";\n");
17394 /* In the rule case, just print pg_get_ruledef's result verbatim */
17395 appendPQExpBuffer(query,
17396 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17397 rinfo->dobj.catId.oid);
17399 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17401 if (PQntuples(res) != 1)
17403 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17404 rinfo->dobj.name, tbinfo->dobj.name);
17408 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17414 * Add the command to alter the rules replication firing semantics if it
17415 * differs from the default.
17417 if (rinfo->ev_enabled != 'O')
17419 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17420 switch (rinfo->ev_enabled)
17423 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17424 fmtId(rinfo->dobj.name));
17427 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17428 fmtId(rinfo->dobj.name));
17431 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17432 fmtId(rinfo->dobj.name));
17440 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17441 * REPLACE VIEW to replace the rule with something with minimal
17444 PQExpBuffer result;
17446 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17447 fmtQualifiedDumpable(tbinfo));
17448 result = createDummyViewAsClause(fout, tbinfo);
17449 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17450 destroyPQExpBuffer(result);
17454 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17455 fmtId(rinfo->dobj.name));
17456 appendPQExpBuffer(delcmd, "ON %s;\n",
17457 fmtQualifiedDumpable(tbinfo));
17460 appendPQExpBuffer(ruleprefix, "RULE %s ON",
17461 fmtId(rinfo->dobj.name));
17463 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17465 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17466 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17468 tbinfo->dobj.namespace->dobj.name,
17470 tbinfo->rolname, false,
17471 "RULE", SECTION_POST_DATA,
17472 cmd->data, delcmd->data, NULL,
17476 /* Dump rule comments */
17477 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17478 dumpComment(fout, ruleprefix->data, qtabname,
17479 tbinfo->dobj.namespace->dobj.name,
17481 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17484 destroyPQExpBuffer(query);
17485 destroyPQExpBuffer(cmd);
17486 destroyPQExpBuffer(delcmd);
17487 destroyPQExpBuffer(ruleprefix);
17492 * getExtensionMembership --- obtain extension membership data
17494 * We need to identify objects that are extension members as soon as they're
17495 * loaded, so that we can correctly determine whether they need to be dumped.
17496 * Generally speaking, extension member objects will get marked as *not* to
17497 * be dumped, as they will be recreated by the single CREATE EXTENSION
17498 * command. However, in binary upgrade mode we still need to dump the members
17502 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17513 ExtensionMemberId *extmembers;
17514 ExtensionInfo *ext;
17516 /* Nothing to do if no extensions */
17517 if (numExtensions == 0)
17520 query = createPQExpBuffer();
17522 /* refclassid constraint is redundant but may speed the search */
17523 appendPQExpBufferStr(query, "SELECT "
17524 "classid, objid, refobjid "
17526 "WHERE refclassid = 'pg_extension'::regclass "
17527 "AND deptype = 'e' "
17530 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17532 ntups = PQntuples(res);
17534 i_classid = PQfnumber(res, "classid");
17535 i_objid = PQfnumber(res, "objid");
17536 i_refobjid = PQfnumber(res, "refobjid");
17538 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17542 * Accumulate data into extmembers[].
17544 * Since we ordered the SELECT by referenced ID, we can expect that
17545 * multiple entries for the same extension will appear together; this
17546 * saves on searches.
17550 for (i = 0; i < ntups; i++)
17555 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17556 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17557 extId = atooid(PQgetvalue(res, i, i_refobjid));
17560 ext->dobj.catId.oid != extId)
17561 ext = findExtensionByOid(extId);
17565 /* shouldn't happen */
17566 fprintf(stderr, "could not find referenced extension %u\n", extId);
17570 extmembers[nextmembers].catId = objId;
17571 extmembers[nextmembers].ext = ext;
17577 /* Remember the data for use later */
17578 setExtensionMembership(extmembers, nextmembers);
17580 destroyPQExpBuffer(query);
17584 * processExtensionTables --- deal with extension configuration tables
17586 * There are two parts to this process:
17588 * 1. Identify and create dump records for extension configuration tables.
17590 * Extensions can mark tables as "configuration", which means that the user
17591 * is able and expected to modify those tables after the extension has been
17592 * loaded. For these tables, we dump out only the data- the structure is
17593 * expected to be handled at CREATE EXTENSION time, including any indexes or
17594 * foreign keys, which brings us to-
17596 * 2. Record FK dependencies between configuration tables.
17598 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17599 * the data is loaded, we have to work out what the best order for reloading
17600 * the data is, to avoid FK violations when the tables are restored. This is
17601 * not perfect- we can't handle circular dependencies and if any exist they
17602 * will cause an invalid dump to be produced (though at least all of the data
17603 * is included for a user to manually restore). This is currently documented
17604 * but perhaps we can provide a better solution in the future.
17607 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17610 DumpOptions *dopt = fout->dopt;
17618 /* Nothing to do if no extensions */
17619 if (numExtensions == 0)
17623 * Identify extension configuration tables and create TableDataInfo
17624 * objects for them, ensuring their data will be dumped even though the
17625 * tables themselves won't be.
17627 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17628 * user data in a configuration table is treated like schema data. This
17629 * seems appropriate since system data in a config table would get
17630 * reloaded by CREATE EXTENSION.
17632 for (i = 0; i < numExtensions; i++)
17634 ExtensionInfo *curext = &(extinfo[i]);
17635 char *extconfig = curext->extconfig;
17636 char *extcondition = curext->extcondition;
17637 char **extconfigarray = NULL;
17638 char **extconditionarray = NULL;
17640 int nconditionitems;
17642 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17643 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17644 nconfigitems == nconditionitems)
17648 for (j = 0; j < nconfigitems; j++)
17650 TableInfo *configtbl;
17651 Oid configtbloid = atooid(extconfigarray[j]);
17653 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17655 configtbl = findTableByOid(configtbloid);
17656 if (configtbl == NULL)
17660 * Tables of not-to-be-dumped extensions shouldn't be dumped
17661 * unless the table or its schema is explicitly included
17663 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17665 /* check table explicitly requested */
17666 if (table_include_oids.head != NULL &&
17667 simple_oid_list_member(&table_include_oids,
17671 /* check table's schema explicitly requested */
17672 if (configtbl->dobj.namespace->dobj.dump &
17673 DUMP_COMPONENT_DATA)
17677 /* check table excluded by an exclusion switch */
17678 if (table_exclude_oids.head != NULL &&
17679 simple_oid_list_member(&table_exclude_oids,
17683 /* check schema excluded by an exclusion switch */
17684 if (simple_oid_list_member(&schema_exclude_oids,
17685 configtbl->dobj.namespace->dobj.catId.oid))
17691 * Note: config tables are dumped without OIDs regardless
17692 * of the --oids setting. This is because row filtering
17693 * conditions aren't compatible with dumping OIDs.
17695 makeTableDataInfo(dopt, configtbl, false);
17696 if (configtbl->dataObj != NULL)
17698 if (strlen(extconditionarray[j]) > 0)
17699 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17704 if (extconfigarray)
17705 free(extconfigarray);
17706 if (extconditionarray)
17707 free(extconditionarray);
17711 * Now that all the TableInfoData objects have been created for all the
17712 * extensions, check their FK dependencies and register them to try and
17713 * dump the data out in an order that they can be restored in.
17715 * Note that this is not a problem for user tables as their FKs are
17716 * recreated after the data has been loaded.
17719 query = createPQExpBuffer();
17721 printfPQExpBuffer(query,
17722 "SELECT conrelid, confrelid "
17723 "FROM pg_constraint "
17724 "JOIN pg_depend ON (objid = confrelid) "
17725 "WHERE contype = 'f' "
17726 "AND refclassid = 'pg_extension'::regclass "
17727 "AND classid = 'pg_class'::regclass;");
17729 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17730 ntups = PQntuples(res);
17732 i_conrelid = PQfnumber(res, "conrelid");
17733 i_confrelid = PQfnumber(res, "confrelid");
17735 /* Now get the dependencies and register them */
17736 for (i = 0; i < ntups; i++)
17740 TableInfo *reftable,
17743 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17744 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17745 contable = findTableByOid(conrelid);
17746 reftable = findTableByOid(confrelid);
17748 if (reftable == NULL ||
17749 reftable->dataObj == NULL ||
17750 contable == NULL ||
17751 contable->dataObj == NULL)
17755 * Make referencing TABLE_DATA object depend on the referenced table's
17756 * TABLE_DATA object.
17758 addObjectDependency(&contable->dataObj->dobj,
17759 reftable->dataObj->dobj.dumpId);
17762 destroyPQExpBuffer(query);
17766 * getDependencies --- obtain available dependency data
17769 getDependencies(Archive *fout)
17780 DumpableObject *dobj,
17784 write_msg(NULL, "reading dependency data\n");
17786 query = createPQExpBuffer();
17789 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17790 * already processed by getExtensionMembership.
17792 appendPQExpBufferStr(query, "SELECT "
17793 "classid, objid, refclassid, refobjid, deptype "
17795 "WHERE deptype != 'p' AND deptype != 'e' "
17798 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17800 ntups = PQntuples(res);
17802 i_classid = PQfnumber(res, "classid");
17803 i_objid = PQfnumber(res, "objid");
17804 i_refclassid = PQfnumber(res, "refclassid");
17805 i_refobjid = PQfnumber(res, "refobjid");
17806 i_deptype = PQfnumber(res, "deptype");
17809 * Since we ordered the SELECT by referencing ID, we can expect that
17810 * multiple entries for the same object will appear together; this saves
17815 for (i = 0; i < ntups; i++)
17818 CatalogId refobjId;
17821 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17822 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17823 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17824 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17825 deptype = *(PQgetvalue(res, i, i_deptype));
17827 if (dobj == NULL ||
17828 dobj->catId.tableoid != objId.tableoid ||
17829 dobj->catId.oid != objId.oid)
17830 dobj = findObjectByCatalogId(objId);
17833 * Failure to find objects mentioned in pg_depend is not unexpected,
17834 * since for example we don't collect info about TOAST tables.
17839 fprintf(stderr, "no referencing object %u %u\n",
17840 objId.tableoid, objId.oid);
17845 refdobj = findObjectByCatalogId(refobjId);
17847 if (refdobj == NULL)
17850 fprintf(stderr, "no referenced object %u %u\n",
17851 refobjId.tableoid, refobjId.oid);
17857 * Ordinarily, table rowtypes have implicit dependencies on their
17858 * tables. However, for a composite type the implicit dependency goes
17859 * the other way in pg_depend; which is the right thing for DROP but
17860 * it doesn't produce the dependency ordering we need. So in that one
17861 * case, we reverse the direction of the dependency.
17863 if (deptype == 'i' &&
17864 dobj->objType == DO_TABLE &&
17865 refdobj->objType == DO_TYPE)
17866 addObjectDependency(refdobj, dobj->dumpId);
17869 addObjectDependency(dobj, refdobj->dumpId);
17874 destroyPQExpBuffer(query);
17879 * createBoundaryObjects - create dummy DumpableObjects to represent
17880 * dump section boundaries.
17882 static DumpableObject *
17883 createBoundaryObjects(void)
17885 DumpableObject *dobjs;
17887 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17889 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17890 dobjs[0].catId = nilCatalogId;
17891 AssignDumpId(dobjs + 0);
17892 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17894 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17895 dobjs[1].catId = nilCatalogId;
17896 AssignDumpId(dobjs + 1);
17897 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17903 * addBoundaryDependencies - add dependencies as needed to enforce the dump
17904 * section boundaries.
17907 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17908 DumpableObject *boundaryObjs)
17910 DumpableObject *preDataBound = boundaryObjs + 0;
17911 DumpableObject *postDataBound = boundaryObjs + 1;
17914 for (i = 0; i < numObjs; i++)
17916 DumpableObject *dobj = dobjs[i];
17919 * The classification of object types here must match the SECTION_xxx
17920 * values assigned during subsequent ArchiveEntry calls!
17922 switch (dobj->objType)
17927 case DO_SHELL_TYPE:
17931 case DO_ACCESS_METHOD:
17935 case DO_CONVERSION:
17940 case DO_DUMMY_TYPE:
17943 case DO_TSTEMPLATE:
17946 case DO_FOREIGN_SERVER:
17949 /* Pre-data objects: must come before the pre-data boundary */
17950 addObjectDependency(preDataBound, dobj->dumpId);
17952 case DO_TABLE_DATA:
17953 case DO_SEQUENCE_SET:
17955 /* Data objects: must come between the boundaries */
17956 addObjectDependency(dobj, preDataBound->dumpId);
17957 addObjectDependency(postDataBound, dobj->dumpId);
17960 case DO_INDEX_ATTACH:
17962 case DO_REFRESH_MATVIEW:
17964 case DO_EVENT_TRIGGER:
17965 case DO_DEFAULT_ACL:
17967 case DO_PUBLICATION:
17968 case DO_PUBLICATION_REL:
17969 case DO_SUBSCRIPTION:
17970 /* Post-data objects: must come after the post-data boundary */
17971 addObjectDependency(dobj, postDataBound->dumpId);
17974 /* Rules are post-data, but only if dumped separately */
17975 if (((RuleInfo *) dobj)->separate)
17976 addObjectDependency(dobj, postDataBound->dumpId);
17978 case DO_CONSTRAINT:
17979 case DO_FK_CONSTRAINT:
17980 /* Constraints are post-data, but only if dumped separately */
17981 if (((ConstraintInfo *) dobj)->separate)
17982 addObjectDependency(dobj, postDataBound->dumpId);
17984 case DO_PRE_DATA_BOUNDARY:
17985 /* nothing to do */
17987 case DO_POST_DATA_BOUNDARY:
17988 /* must come after the pre-data boundary */
17989 addObjectDependency(dobj, preDataBound->dumpId);
17997 * BuildArchiveDependencies - create dependency data for archive TOC entries
17999 * The raw dependency data obtained by getDependencies() is not terribly
18000 * useful in an archive dump, because in many cases there are dependency
18001 * chains linking through objects that don't appear explicitly in the dump.
18002 * For example, a view will depend on its _RETURN rule while the _RETURN rule
18003 * will depend on other objects --- but the rule will not appear as a separate
18004 * object in the dump. We need to adjust the view's dependencies to include
18005 * whatever the rule depends on that is included in the dump.
18007 * Just to make things more complicated, there are also "special" dependencies
18008 * such as the dependency of a TABLE DATA item on its TABLE, which we must
18009 * not rearrange because pg_restore knows that TABLE DATA only depends on
18010 * its table. In these cases we must leave the dependencies strictly as-is
18011 * even if they refer to not-to-be-dumped objects.
18013 * To handle this, the convention is that "special" dependencies are created
18014 * during ArchiveEntry calls, and an archive TOC item that has any such
18015 * entries will not be touched here. Otherwise, we recursively search the
18016 * DumpableObject data structures to build the correct dependencies for each
18017 * archive TOC item.
18020 BuildArchiveDependencies(Archive *fout)
18022 ArchiveHandle *AH = (ArchiveHandle *) fout;
18025 /* Scan all TOC entries in the archive */
18026 for (te = AH->toc->next; te != AH->toc; te = te->next)
18028 DumpableObject *dobj;
18029 DumpId *dependencies;
18033 /* No need to process entries that will not be dumped */
18036 /* Ignore entries that already have "special" dependencies */
18039 /* Otherwise, look up the item's original DumpableObject, if any */
18040 dobj = findObjectByDumpId(te->dumpId);
18043 /* No work if it has no dependencies */
18044 if (dobj->nDeps <= 0)
18046 /* Set up work array */
18048 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18050 /* Recursively find all dumpable dependencies */
18051 findDumpableDependencies(AH, dobj,
18052 &dependencies, &nDeps, &allocDeps);
18053 /* And save 'em ... */
18056 dependencies = (DumpId *) pg_realloc(dependencies,
18057 nDeps * sizeof(DumpId));
18058 te->dependencies = dependencies;
18062 free(dependencies);
18066 /* Recursive search subroutine for BuildArchiveDependencies */
18068 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18069 DumpId **dependencies, int *nDeps, int *allocDeps)
18074 * Ignore section boundary objects: if we search through them, we'll
18075 * report lots of bogus dependencies.
18077 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18078 dobj->objType == DO_POST_DATA_BOUNDARY)
18081 for (i = 0; i < dobj->nDeps; i++)
18083 DumpId depid = dobj->dependencies[i];
18085 if (TocIDRequired(AH, depid) != 0)
18087 /* Object will be dumped, so just reference it as a dependency */
18088 if (*nDeps >= *allocDeps)
18091 *dependencies = (DumpId *) pg_realloc(*dependencies,
18092 *allocDeps * sizeof(DumpId));
18094 (*dependencies)[*nDeps] = depid;
18100 * Object will not be dumped, so recursively consider its deps. We
18101 * rely on the assumption that sortDumpableObjects already broke
18102 * any dependency loops, else we might recurse infinitely.
18104 DumpableObject *otherdobj = findObjectByDumpId(depid);
18107 findDumpableDependencies(AH, otherdobj,
18108 dependencies, nDeps, allocDeps);
18115 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18118 * This does not guarantee to schema-qualify the output, so it should not
18119 * be used to create the target object name for CREATE or ALTER commands.
18121 * TODO: there might be some value in caching the results.
18124 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18132 if ((opts & zeroAsOpaque) != 0)
18133 return pg_strdup(g_opaque_type);
18134 else if ((opts & zeroAsAny) != 0)
18135 return pg_strdup("'any'");
18136 else if ((opts & zeroAsStar) != 0)
18137 return pg_strdup("*");
18138 else if ((opts & zeroAsNone) != 0)
18139 return pg_strdup("NONE");
18142 query = createPQExpBuffer();
18143 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18146 res = ExecuteSqlQueryForSingleRow(fout, query->data);
18148 /* result of format_type is already quoted */
18149 result = pg_strdup(PQgetvalue(res, 0, 0));
18152 destroyPQExpBuffer(query);
18158 * Return a column list clause for the given relation.
18160 * Special case: if there are no undropped columns in the relation, return
18161 * "", not an invalid "()" column list.
18163 static const char *
18164 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18166 int numatts = ti->numatts;
18167 char **attnames = ti->attnames;
18168 bool *attisdropped = ti->attisdropped;
18172 appendPQExpBufferChar(buffer, '(');
18174 for (i = 0; i < numatts; i++)
18176 if (attisdropped[i])
18179 appendPQExpBufferStr(buffer, ", ");
18180 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18185 return ""; /* no undropped columns */
18187 appendPQExpBufferChar(buffer, ')');
18188 return buffer->data;
18192 * Check if a reloptions array is nonempty.
18195 nonemptyReloptions(const char *reloptions)
18197 /* Don't want to print it if it's just "{}" */
18198 return (reloptions != NULL && strlen(reloptions) > 2);
18202 * Format a reloptions array and append it to the given buffer.
18204 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18207 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18208 const char *prefix, Archive *fout)
18212 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18213 fout->std_strings);
18215 write_msg(NULL, "WARNING: could not parse reloptions array\n");