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 * Only dump identity sequences if we're going to dump the table that
6642 if (owning_tab->dobj.dump == DUMP_COMPONENT_NONE &&
6643 seqinfo->is_identity_sequence)
6645 seqinfo->dobj.dump = DUMP_COMPONENT_NONE;
6650 * Otherwise we need to dump the components that are being dumped for
6651 * the table and any components which the sequence is explicitly
6654 * We can't simply use the set of components which are being dumped
6655 * for the table as the table might be in an extension (and only the
6656 * non-extension components, eg: ACLs if changed, security labels, and
6657 * policies, are being dumped) while the sequence is not (and
6658 * therefore the definition and other components should also be
6661 * If the sequence is part of the extension then it should be properly
6662 * marked by checkExtensionMembership() and this will be a no-op as
6663 * the table will be equivalently marked.
6665 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6667 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6668 seqinfo->interesting = true;
6674 * read all the inheritance information
6675 * from the system catalogs return them in the InhInfo* structure
6677 * numInherits is set to the number of pairs read in
6680 getInherits(Archive *fout, int *numInherits)
6685 PQExpBuffer query = createPQExpBuffer();
6692 * Find all the inheritance information, excluding implicit inheritance
6693 * via partitioning. We handle that case using getPartitions(), because
6694 * we want more information about partitions than just the parent-child
6697 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6699 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6701 ntups = PQntuples(res);
6703 *numInherits = ntups;
6705 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6707 i_inhrelid = PQfnumber(res, "inhrelid");
6708 i_inhparent = PQfnumber(res, "inhparent");
6710 for (i = 0; i < ntups; i++)
6712 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6713 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6718 destroyPQExpBuffer(query);
6725 * get information about every index on a dumpable table
6727 * Note: index data is not returned directly to the caller, but it
6728 * does get entered into the DumpableObject tables.
6731 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6735 PQExpBuffer query = createPQExpBuffer();
6738 ConstraintInfo *constrinfo;
6761 for (i = 0; i < numTables; i++)
6763 TableInfo *tbinfo = &tblinfo[i];
6765 if (!tbinfo->hasindex)
6769 * Ignore indexes of tables whose definitions are not to be dumped.
6771 * We also need indexes on partitioned tables which have partitions to
6772 * be dumped, in order to dump the indexes on the partitions.
6774 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6775 !tbinfo->interesting)
6779 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6780 tbinfo->dobj.namespace->dobj.name,
6784 * The point of the messy-looking outer join is to find a constraint
6785 * that is related by an internal dependency link to the index. If we
6786 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6787 * assume an index won't have more than one internal dependency.
6789 * As of 9.0 we don't need to look at pg_depend but can check for a
6790 * match to pg_constraint.conindid. The check on conrelid is
6791 * redundant but useful because that column is indexed while conindid
6794 resetPQExpBuffer(query);
6795 if (fout->remoteVersion >= 110000)
6797 appendPQExpBuffer(query,
6798 "SELECT t.tableoid, t.oid, "
6799 "t.relname AS indexname, "
6800 "inh.inhparent AS parentidx, "
6801 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6802 "i.indnkeyatts AS indnkeyatts, "
6803 "i.indnatts AS indnatts, "
6804 "i.indkey, i.indisclustered, "
6805 "i.indisreplident, t.relpages, "
6806 "c.contype, c.conname, "
6807 "c.condeferrable, c.condeferred, "
6808 "c.tableoid AS contableoid, "
6810 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6811 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6812 "t.reloptions AS indreloptions "
6813 "FROM pg_catalog.pg_index i "
6814 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6815 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6816 "LEFT JOIN pg_catalog.pg_constraint c "
6817 "ON (i.indrelid = c.conrelid AND "
6818 "i.indexrelid = c.conindid AND "
6819 "c.contype IN ('p','u','x')) "
6820 "LEFT JOIN pg_catalog.pg_inherits inh "
6821 "ON (inh.inhrelid = indexrelid) "
6822 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6823 "AND (i.indisvalid OR t2.relkind = 'p') "
6825 "ORDER BY indexname",
6826 tbinfo->dobj.catId.oid);
6828 else if (fout->remoteVersion >= 90400)
6831 * the test on indisready is necessary in 9.2, and harmless in
6832 * earlier/later versions
6834 appendPQExpBuffer(query,
6835 "SELECT t.tableoid, t.oid, "
6836 "t.relname AS indexname, "
6838 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6839 "i.indnatts AS indnkeyatts, "
6840 "i.indnatts AS indnatts, "
6841 "i.indkey, i.indisclustered, "
6842 "i.indisreplident, t.relpages, "
6843 "c.contype, c.conname, "
6844 "c.condeferrable, c.condeferred, "
6845 "c.tableoid AS contableoid, "
6847 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6848 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6849 "t.reloptions AS indreloptions "
6850 "FROM pg_catalog.pg_index i "
6851 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6852 "LEFT JOIN pg_catalog.pg_constraint c "
6853 "ON (i.indrelid = c.conrelid AND "
6854 "i.indexrelid = c.conindid AND "
6855 "c.contype IN ('p','u','x')) "
6856 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6857 "AND i.indisvalid AND i.indisready "
6858 "ORDER BY indexname",
6859 tbinfo->dobj.catId.oid);
6861 else if (fout->remoteVersion >= 90000)
6864 * the test on indisready is necessary in 9.2, and harmless in
6865 * earlier/later versions
6867 appendPQExpBuffer(query,
6868 "SELECT t.tableoid, t.oid, "
6869 "t.relname AS indexname, "
6871 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6872 "i.indnatts AS indnkeyatts, "
6873 "i.indnatts AS indnatts, "
6874 "i.indkey, i.indisclustered, "
6875 "false AS indisreplident, t.relpages, "
6876 "c.contype, c.conname, "
6877 "c.condeferrable, c.condeferred, "
6878 "c.tableoid AS contableoid, "
6880 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6881 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6882 "t.reloptions AS indreloptions "
6883 "FROM pg_catalog.pg_index i "
6884 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6885 "LEFT JOIN pg_catalog.pg_constraint c "
6886 "ON (i.indrelid = c.conrelid AND "
6887 "i.indexrelid = c.conindid AND "
6888 "c.contype IN ('p','u','x')) "
6889 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6890 "AND i.indisvalid AND i.indisready "
6891 "ORDER BY indexname",
6892 tbinfo->dobj.catId.oid);
6894 else if (fout->remoteVersion >= 80200)
6896 appendPQExpBuffer(query,
6897 "SELECT t.tableoid, t.oid, "
6898 "t.relname AS indexname, "
6900 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6901 "i.indnatts AS indnkeyatts, "
6902 "i.indnatts AS indnatts, "
6903 "i.indkey, i.indisclustered, "
6904 "false AS indisreplident, t.relpages, "
6905 "c.contype, c.conname, "
6906 "c.condeferrable, c.condeferred, "
6907 "c.tableoid AS contableoid, "
6910 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6911 "t.reloptions AS indreloptions "
6912 "FROM pg_catalog.pg_index i "
6913 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6914 "LEFT JOIN pg_catalog.pg_depend d "
6915 "ON (d.classid = t.tableoid "
6916 "AND d.objid = t.oid "
6917 "AND d.deptype = 'i') "
6918 "LEFT JOIN pg_catalog.pg_constraint c "
6919 "ON (d.refclassid = c.tableoid "
6920 "AND d.refobjid = c.oid) "
6921 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6923 "ORDER BY indexname",
6924 tbinfo->dobj.catId.oid);
6928 appendPQExpBuffer(query,
6929 "SELECT t.tableoid, t.oid, "
6930 "t.relname AS indexname, "
6932 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6933 "t.relnatts AS indnkeyatts, "
6934 "t.relnatts AS indnatts, "
6935 "i.indkey, i.indisclustered, "
6936 "false AS indisreplident, t.relpages, "
6937 "c.contype, c.conname, "
6938 "c.condeferrable, c.condeferred, "
6939 "c.tableoid AS contableoid, "
6942 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6943 "null AS indreloptions "
6944 "FROM pg_catalog.pg_index i "
6945 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6946 "LEFT JOIN pg_catalog.pg_depend d "
6947 "ON (d.classid = t.tableoid "
6948 "AND d.objid = t.oid "
6949 "AND d.deptype = 'i') "
6950 "LEFT JOIN pg_catalog.pg_constraint c "
6951 "ON (d.refclassid = c.tableoid "
6952 "AND d.refobjid = c.oid) "
6953 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6954 "ORDER BY indexname",
6955 tbinfo->dobj.catId.oid);
6958 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6960 ntups = PQntuples(res);
6962 i_tableoid = PQfnumber(res, "tableoid");
6963 i_oid = PQfnumber(res, "oid");
6964 i_indexname = PQfnumber(res, "indexname");
6965 i_parentidx = PQfnumber(res, "parentidx");
6966 i_indexdef = PQfnumber(res, "indexdef");
6967 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
6968 i_indnatts = PQfnumber(res, "indnatts");
6969 i_indkey = PQfnumber(res, "indkey");
6970 i_indisclustered = PQfnumber(res, "indisclustered");
6971 i_indisreplident = PQfnumber(res, "indisreplident");
6972 i_relpages = PQfnumber(res, "relpages");
6973 i_contype = PQfnumber(res, "contype");
6974 i_conname = PQfnumber(res, "conname");
6975 i_condeferrable = PQfnumber(res, "condeferrable");
6976 i_condeferred = PQfnumber(res, "condeferred");
6977 i_contableoid = PQfnumber(res, "contableoid");
6978 i_conoid = PQfnumber(res, "conoid");
6979 i_condef = PQfnumber(res, "condef");
6980 i_tablespace = PQfnumber(res, "tablespace");
6981 i_indreloptions = PQfnumber(res, "indreloptions");
6983 tbinfo->indexes = indxinfo =
6984 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6985 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6986 tbinfo->numIndexes = ntups;
6988 for (j = 0; j < ntups; j++)
6992 indxinfo[j].dobj.objType = DO_INDEX;
6993 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6994 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6995 AssignDumpId(&indxinfo[j].dobj);
6996 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6997 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6998 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6999 indxinfo[j].indextable = tbinfo;
7000 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
7001 indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
7002 indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
7003 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
7004 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
7005 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
7006 parseOidArray(PQgetvalue(res, j, i_indkey),
7007 indxinfo[j].indkeys, indxinfo[j].indnattrs);
7008 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
7009 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
7010 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
7011 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
7012 contype = *(PQgetvalue(res, j, i_contype));
7014 if (contype == 'p' || contype == 'u' || contype == 'x')
7017 * If we found a constraint matching the index, create an
7020 constrinfo[j].dobj.objType = DO_CONSTRAINT;
7021 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7022 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7023 AssignDumpId(&constrinfo[j].dobj);
7024 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
7025 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7026 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7027 constrinfo[j].contable = tbinfo;
7028 constrinfo[j].condomain = NULL;
7029 constrinfo[j].contype = contype;
7031 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7033 constrinfo[j].condef = NULL;
7034 constrinfo[j].confrelid = InvalidOid;
7035 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7036 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7037 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7038 constrinfo[j].conislocal = true;
7039 constrinfo[j].separate = true;
7041 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7045 /* Plain secondary index */
7046 indxinfo[j].indexconstraint = 0;
7053 destroyPQExpBuffer(query);
7057 * getExtendedStatistics
7058 * get information about extended-statistics objects.
7060 * Note: extended statistics data is not returned directly to the caller, but
7061 * it does get entered into the DumpableObject tables.
7064 getExtendedStatistics(Archive *fout)
7068 StatsExtInfo *statsextinfo;
7077 /* Extended statistics were new in v10 */
7078 if (fout->remoteVersion < 100000)
7081 query = createPQExpBuffer();
7083 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7084 "stxnamespace, (%s stxowner) AS rolname "
7085 "FROM pg_catalog.pg_statistic_ext",
7088 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7090 ntups = PQntuples(res);
7092 i_tableoid = PQfnumber(res, "tableoid");
7093 i_oid = PQfnumber(res, "oid");
7094 i_stxname = PQfnumber(res, "stxname");
7095 i_stxnamespace = PQfnumber(res, "stxnamespace");
7096 i_rolname = PQfnumber(res, "rolname");
7098 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7100 for (i = 0; i < ntups; i++)
7102 statsextinfo[i].dobj.objType = DO_STATSEXT;
7103 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7104 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7105 AssignDumpId(&statsextinfo[i].dobj);
7106 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7107 statsextinfo[i].dobj.namespace =
7109 atooid(PQgetvalue(res, i, i_stxnamespace)));
7110 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7112 /* Decide whether we want to dump it */
7113 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7115 /* Stats objects do not currently have ACLs. */
7116 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7120 destroyPQExpBuffer(query);
7126 * Get info about constraints on dumpable tables.
7128 * Currently handles foreign keys only.
7129 * Unique and primary key constraints are handled with indexes,
7130 * while check constraints are processed in getTableAttrs().
7133 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7137 ConstraintInfo *constrinfo;
7147 query = createPQExpBuffer();
7149 for (i = 0; i < numTables; i++)
7151 TableInfo *tbinfo = &tblinfo[i];
7154 * For partitioned tables, foreign keys have no triggers so they must
7155 * be included anyway in case some foreign keys are defined.
7157 if ((!tbinfo->hastriggers &&
7158 tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7159 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7163 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7164 tbinfo->dobj.namespace->dobj.name,
7167 resetPQExpBuffer(query);
7168 if (fout->remoteVersion >= 110000)
7169 appendPQExpBuffer(query,
7170 "SELECT tableoid, oid, conname, confrelid, "
7171 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7172 "FROM pg_catalog.pg_constraint "
7173 "WHERE conrelid = '%u'::pg_catalog.oid "
7174 "AND conparentid = 0 "
7175 "AND contype = 'f'",
7176 tbinfo->dobj.catId.oid);
7178 appendPQExpBuffer(query,
7179 "SELECT tableoid, oid, conname, confrelid, "
7180 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7181 "FROM pg_catalog.pg_constraint "
7182 "WHERE conrelid = '%u'::pg_catalog.oid "
7183 "AND contype = 'f'",
7184 tbinfo->dobj.catId.oid);
7185 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7187 ntups = PQntuples(res);
7189 i_contableoid = PQfnumber(res, "tableoid");
7190 i_conoid = PQfnumber(res, "oid");
7191 i_conname = PQfnumber(res, "conname");
7192 i_confrelid = PQfnumber(res, "confrelid");
7193 i_condef = PQfnumber(res, "condef");
7195 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7197 for (j = 0; j < ntups; j++)
7199 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7200 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7201 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7202 AssignDumpId(&constrinfo[j].dobj);
7203 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7204 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7205 constrinfo[j].contable = tbinfo;
7206 constrinfo[j].condomain = NULL;
7207 constrinfo[j].contype = 'f';
7208 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7209 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7210 constrinfo[j].conindex = 0;
7211 constrinfo[j].condeferrable = false;
7212 constrinfo[j].condeferred = false;
7213 constrinfo[j].conislocal = true;
7214 constrinfo[j].separate = true;
7220 destroyPQExpBuffer(query);
7224 * getDomainConstraints
7226 * Get info about constraints on a domain.
7229 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7232 ConstraintInfo *constrinfo;
7241 query = createPQExpBuffer();
7243 if (fout->remoteVersion >= 90100)
7244 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7245 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7247 "FROM pg_catalog.pg_constraint "
7248 "WHERE contypid = '%u'::pg_catalog.oid "
7250 tyinfo->dobj.catId.oid);
7253 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7254 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7255 "true as convalidated "
7256 "FROM pg_catalog.pg_constraint "
7257 "WHERE contypid = '%u'::pg_catalog.oid "
7259 tyinfo->dobj.catId.oid);
7261 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7263 ntups = PQntuples(res);
7265 i_tableoid = PQfnumber(res, "tableoid");
7266 i_oid = PQfnumber(res, "oid");
7267 i_conname = PQfnumber(res, "conname");
7268 i_consrc = PQfnumber(res, "consrc");
7270 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7272 tyinfo->nDomChecks = ntups;
7273 tyinfo->domChecks = constrinfo;
7275 for (i = 0; i < ntups; i++)
7277 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7279 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7280 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7281 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7282 AssignDumpId(&constrinfo[i].dobj);
7283 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7284 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7285 constrinfo[i].contable = NULL;
7286 constrinfo[i].condomain = tyinfo;
7287 constrinfo[i].contype = 'c';
7288 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7289 constrinfo[i].confrelid = InvalidOid;
7290 constrinfo[i].conindex = 0;
7291 constrinfo[i].condeferrable = false;
7292 constrinfo[i].condeferred = false;
7293 constrinfo[i].conislocal = true;
7295 constrinfo[i].separate = !validated;
7298 * Make the domain depend on the constraint, ensuring it won't be
7299 * output till any constraint dependencies are OK. If the constraint
7300 * has not been validated, it's going to be dumped after the domain
7301 * anyway, so this doesn't matter.
7304 addObjectDependency(&tyinfo->dobj,
7305 constrinfo[i].dobj.dumpId);
7310 destroyPQExpBuffer(query);
7315 * get basic information about every rule in the system
7317 * numRules is set to the number of rules read in
7320 getRules(Archive *fout, int *numRules)
7325 PQExpBuffer query = createPQExpBuffer();
7335 if (fout->remoteVersion >= 80300)
7337 appendPQExpBufferStr(query, "SELECT "
7338 "tableoid, oid, rulename, "
7339 "ev_class AS ruletable, ev_type, is_instead, "
7346 appendPQExpBufferStr(query, "SELECT "
7347 "tableoid, oid, rulename, "
7348 "ev_class AS ruletable, ev_type, is_instead, "
7349 "'O'::char AS ev_enabled "
7354 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7356 ntups = PQntuples(res);
7360 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7362 i_tableoid = PQfnumber(res, "tableoid");
7363 i_oid = PQfnumber(res, "oid");
7364 i_rulename = PQfnumber(res, "rulename");
7365 i_ruletable = PQfnumber(res, "ruletable");
7366 i_ev_type = PQfnumber(res, "ev_type");
7367 i_is_instead = PQfnumber(res, "is_instead");
7368 i_ev_enabled = PQfnumber(res, "ev_enabled");
7370 for (i = 0; i < ntups; i++)
7374 ruleinfo[i].dobj.objType = DO_RULE;
7375 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7376 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7377 AssignDumpId(&ruleinfo[i].dobj);
7378 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7379 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7380 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7381 if (ruleinfo[i].ruletable == NULL)
7382 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7383 ruletableoid, ruleinfo[i].dobj.catId.oid);
7384 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7385 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7386 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7387 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7388 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7389 if (ruleinfo[i].ruletable)
7392 * If the table is a view or materialized view, force its ON
7393 * SELECT rule to be sorted before the view itself --- this
7394 * ensures that any dependencies for the rule affect the table's
7395 * positioning. Other rules are forced to appear after their
7398 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7399 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7400 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7402 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7403 ruleinfo[i].dobj.dumpId);
7404 /* We'll merge the rule into CREATE VIEW, if possible */
7405 ruleinfo[i].separate = false;
7409 addObjectDependency(&ruleinfo[i].dobj,
7410 ruleinfo[i].ruletable->dobj.dumpId);
7411 ruleinfo[i].separate = true;
7415 ruleinfo[i].separate = true;
7420 destroyPQExpBuffer(query);
7427 * get information about every trigger on a dumpable table
7429 * Note: trigger data is not returned directly to the caller, but it
7430 * does get entered into the DumpableObject tables.
7433 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7437 PQExpBuffer query = createPQExpBuffer();
7439 TriggerInfo *tginfo;
7457 for (i = 0; i < numTables; i++)
7459 TableInfo *tbinfo = &tblinfo[i];
7461 if (!tbinfo->hastriggers ||
7462 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7466 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7467 tbinfo->dobj.namespace->dobj.name,
7470 resetPQExpBuffer(query);
7471 if (fout->remoteVersion >= 90000)
7474 * NB: think not to use pretty=true in pg_get_triggerdef. It
7475 * could result in non-forward-compatible dumps of WHEN clauses
7476 * due to under-parenthesization.
7478 appendPQExpBuffer(query,
7480 "tgfoid::pg_catalog.regproc AS tgfname, "
7481 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7482 "tgenabled, tableoid, oid "
7483 "FROM pg_catalog.pg_trigger t "
7484 "WHERE tgrelid = '%u'::pg_catalog.oid "
7485 "AND NOT tgisinternal",
7486 tbinfo->dobj.catId.oid);
7488 else if (fout->remoteVersion >= 80300)
7491 * We ignore triggers that are tied to a foreign-key constraint
7493 appendPQExpBuffer(query,
7495 "tgfoid::pg_catalog.regproc AS tgfname, "
7496 "tgtype, tgnargs, tgargs, tgenabled, "
7497 "tgisconstraint, tgconstrname, tgdeferrable, "
7498 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7499 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7500 "FROM pg_catalog.pg_trigger t "
7501 "WHERE tgrelid = '%u'::pg_catalog.oid "
7502 "AND tgconstraint = 0",
7503 tbinfo->dobj.catId.oid);
7508 * We ignore triggers that are tied to a foreign-key constraint,
7509 * but in these versions we have to grovel through pg_constraint
7512 appendPQExpBuffer(query,
7514 "tgfoid::pg_catalog.regproc AS tgfname, "
7515 "tgtype, tgnargs, tgargs, tgenabled, "
7516 "tgisconstraint, tgconstrname, tgdeferrable, "
7517 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7518 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7519 "FROM pg_catalog.pg_trigger t "
7520 "WHERE tgrelid = '%u'::pg_catalog.oid "
7521 "AND (NOT tgisconstraint "
7523 " (SELECT 1 FROM pg_catalog.pg_depend d "
7524 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7525 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7526 tbinfo->dobj.catId.oid);
7529 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7531 ntups = PQntuples(res);
7533 i_tableoid = PQfnumber(res, "tableoid");
7534 i_oid = PQfnumber(res, "oid");
7535 i_tgname = PQfnumber(res, "tgname");
7536 i_tgfname = PQfnumber(res, "tgfname");
7537 i_tgtype = PQfnumber(res, "tgtype");
7538 i_tgnargs = PQfnumber(res, "tgnargs");
7539 i_tgargs = PQfnumber(res, "tgargs");
7540 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7541 i_tgconstrname = PQfnumber(res, "tgconstrname");
7542 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7543 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7544 i_tgenabled = PQfnumber(res, "tgenabled");
7545 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7546 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7547 i_tgdef = PQfnumber(res, "tgdef");
7549 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7551 tbinfo->numTriggers = ntups;
7552 tbinfo->triggers = tginfo;
7554 for (j = 0; j < ntups; j++)
7556 tginfo[j].dobj.objType = DO_TRIGGER;
7557 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7558 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7559 AssignDumpId(&tginfo[j].dobj);
7560 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7561 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7562 tginfo[j].tgtable = tbinfo;
7563 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7566 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7568 /* remaining fields are not valid if we have tgdef */
7569 tginfo[j].tgfname = NULL;
7570 tginfo[j].tgtype = 0;
7571 tginfo[j].tgnargs = 0;
7572 tginfo[j].tgargs = NULL;
7573 tginfo[j].tgisconstraint = false;
7574 tginfo[j].tgdeferrable = false;
7575 tginfo[j].tginitdeferred = false;
7576 tginfo[j].tgconstrname = NULL;
7577 tginfo[j].tgconstrrelid = InvalidOid;
7578 tginfo[j].tgconstrrelname = NULL;
7582 tginfo[j].tgdef = NULL;
7584 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7585 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7586 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7587 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7588 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7589 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7590 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7592 if (tginfo[j].tgisconstraint)
7594 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7595 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7596 if (OidIsValid(tginfo[j].tgconstrrelid))
7598 if (PQgetisnull(res, j, i_tgconstrrelname))
7599 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7600 tginfo[j].dobj.name,
7602 tginfo[j].tgconstrrelid);
7603 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7606 tginfo[j].tgconstrrelname = NULL;
7610 tginfo[j].tgconstrname = NULL;
7611 tginfo[j].tgconstrrelid = InvalidOid;
7612 tginfo[j].tgconstrrelname = NULL;
7620 destroyPQExpBuffer(query);
7625 * get information about event triggers
7628 getEventTriggers(Archive *fout, int *numEventTriggers)
7633 EventTriggerInfo *evtinfo;
7644 /* Before 9.3, there are no event triggers */
7645 if (fout->remoteVersion < 90300)
7647 *numEventTriggers = 0;
7651 query = createPQExpBuffer();
7653 appendPQExpBuffer(query,
7654 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7655 "evtevent, (%s evtowner) AS evtowner, "
7656 "array_to_string(array("
7657 "select quote_literal(x) "
7658 " from unnest(evttags) as t(x)), ', ') as evttags, "
7659 "e.evtfoid::regproc as evtfname "
7660 "FROM pg_event_trigger e "
7664 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7666 ntups = PQntuples(res);
7668 *numEventTriggers = ntups;
7670 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7672 i_tableoid = PQfnumber(res, "tableoid");
7673 i_oid = PQfnumber(res, "oid");
7674 i_evtname = PQfnumber(res, "evtname");
7675 i_evtevent = PQfnumber(res, "evtevent");
7676 i_evtowner = PQfnumber(res, "evtowner");
7677 i_evttags = PQfnumber(res, "evttags");
7678 i_evtfname = PQfnumber(res, "evtfname");
7679 i_evtenabled = PQfnumber(res, "evtenabled");
7681 for (i = 0; i < ntups; i++)
7683 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7684 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7685 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7686 AssignDumpId(&evtinfo[i].dobj);
7687 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7688 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7689 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7690 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7691 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7692 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7693 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7695 /* Decide whether we want to dump it */
7696 selectDumpableObject(&(evtinfo[i].dobj), fout);
7698 /* Event Triggers do not currently have ACLs. */
7699 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7704 destroyPQExpBuffer(query);
7711 * get basic information about every procedural language in the system
7713 * numProcLangs is set to the number of langs read in
7715 * NB: this must run after getFuncs() because we assume we can do
7719 getProcLangs(Archive *fout, int *numProcLangs)
7721 DumpOptions *dopt = fout->dopt;
7725 PQExpBuffer query = createPQExpBuffer();
7726 ProcLangInfo *planginfo;
7731 int i_lanplcallfoid;
7740 if (fout->remoteVersion >= 90600)
7742 PQExpBuffer acl_subquery = createPQExpBuffer();
7743 PQExpBuffer racl_subquery = createPQExpBuffer();
7744 PQExpBuffer initacl_subquery = createPQExpBuffer();
7745 PQExpBuffer initracl_subquery = createPQExpBuffer();
7747 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7748 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7749 dopt->binary_upgrade);
7751 /* pg_language has a laninline column */
7752 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7753 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7754 "l.laninline, l.lanvalidator, "
7757 "%s AS initlanacl, "
7758 "%s AS initrlanacl, "
7759 "(%s l.lanowner) AS lanowner "
7760 "FROM pg_language l "
7761 "LEFT JOIN pg_init_privs pip ON "
7762 "(l.oid = pip.objoid "
7763 "AND pip.classoid = 'pg_language'::regclass "
7764 "AND pip.objsubid = 0) "
7768 racl_subquery->data,
7769 initacl_subquery->data,
7770 initracl_subquery->data,
7773 destroyPQExpBuffer(acl_subquery);
7774 destroyPQExpBuffer(racl_subquery);
7775 destroyPQExpBuffer(initacl_subquery);
7776 destroyPQExpBuffer(initracl_subquery);
7778 else if (fout->remoteVersion >= 90000)
7780 /* pg_language has a laninline column */
7781 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7782 "lanname, lanpltrusted, lanplcallfoid, "
7783 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7784 "NULL AS initlanacl, NULL AS initrlanacl, "
7785 "(%s lanowner) AS lanowner "
7791 else if (fout->remoteVersion >= 80300)
7793 /* pg_language has a lanowner column */
7794 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7795 "lanname, lanpltrusted, lanplcallfoid, "
7796 "0 AS laninline, lanvalidator, lanacl, "
7798 "NULL AS initlanacl, NULL AS initrlanacl, "
7799 "(%s lanowner) AS lanowner "
7805 else if (fout->remoteVersion >= 80100)
7807 /* Languages are owned by the bootstrap superuser, OID 10 */
7808 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7809 "lanname, lanpltrusted, lanplcallfoid, "
7810 "0 AS laninline, lanvalidator, lanacl, "
7812 "NULL AS initlanacl, NULL AS initrlanacl, "
7813 "(%s '10') AS lanowner "
7821 /* Languages are owned by the bootstrap superuser, sysid 1 */
7822 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7823 "lanname, lanpltrusted, lanplcallfoid, "
7824 "0 AS laninline, lanvalidator, lanacl, "
7826 "NULL AS initlanacl, NULL AS initrlanacl, "
7827 "(%s '1') AS lanowner "
7834 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7836 ntups = PQntuples(res);
7838 *numProcLangs = ntups;
7840 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7842 i_tableoid = PQfnumber(res, "tableoid");
7843 i_oid = PQfnumber(res, "oid");
7844 i_lanname = PQfnumber(res, "lanname");
7845 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7846 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7847 i_laninline = PQfnumber(res, "laninline");
7848 i_lanvalidator = PQfnumber(res, "lanvalidator");
7849 i_lanacl = PQfnumber(res, "lanacl");
7850 i_rlanacl = PQfnumber(res, "rlanacl");
7851 i_initlanacl = PQfnumber(res, "initlanacl");
7852 i_initrlanacl = PQfnumber(res, "initrlanacl");
7853 i_lanowner = PQfnumber(res, "lanowner");
7855 for (i = 0; i < ntups; i++)
7857 planginfo[i].dobj.objType = DO_PROCLANG;
7858 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7859 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7860 AssignDumpId(&planginfo[i].dobj);
7862 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7863 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7864 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7865 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7866 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7867 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7868 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7869 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7870 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7871 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7873 /* Decide whether we want to dump it */
7874 selectDumpableProcLang(&(planginfo[i]), fout);
7876 /* Do not try to dump ACL if no ACL exists. */
7877 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7878 PQgetisnull(res, i, i_initlanacl) &&
7879 PQgetisnull(res, i, i_initrlanacl))
7880 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7885 destroyPQExpBuffer(query);
7892 * get basic information about every cast in the system
7894 * numCasts is set to the number of casts read in
7897 getCasts(Archive *fout, int *numCasts)
7902 PQExpBuffer query = createPQExpBuffer();
7912 if (fout->remoteVersion >= 80400)
7914 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7915 "castsource, casttarget, castfunc, castcontext, "
7917 "FROM pg_cast ORDER BY 3,4");
7921 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7922 "castsource, casttarget, castfunc, castcontext, "
7923 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7924 "FROM pg_cast ORDER BY 3,4");
7927 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7929 ntups = PQntuples(res);
7933 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7935 i_tableoid = PQfnumber(res, "tableoid");
7936 i_oid = PQfnumber(res, "oid");
7937 i_castsource = PQfnumber(res, "castsource");
7938 i_casttarget = PQfnumber(res, "casttarget");
7939 i_castfunc = PQfnumber(res, "castfunc");
7940 i_castcontext = PQfnumber(res, "castcontext");
7941 i_castmethod = PQfnumber(res, "castmethod");
7943 for (i = 0; i < ntups; i++)
7945 PQExpBufferData namebuf;
7946 TypeInfo *sTypeInfo;
7947 TypeInfo *tTypeInfo;
7949 castinfo[i].dobj.objType = DO_CAST;
7950 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7951 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7952 AssignDumpId(&castinfo[i].dobj);
7953 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7954 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7955 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7956 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7957 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7960 * Try to name cast as concatenation of typnames. This is only used
7961 * for purposes of sorting. If we fail to find either type, the name
7962 * will be an empty string.
7964 initPQExpBuffer(&namebuf);
7965 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7966 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7967 if (sTypeInfo && tTypeInfo)
7968 appendPQExpBuffer(&namebuf, "%s %s",
7969 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7970 castinfo[i].dobj.name = namebuf.data;
7972 /* Decide whether we want to dump it */
7973 selectDumpableCast(&(castinfo[i]), fout);
7975 /* Casts do not currently have ACLs. */
7976 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7981 destroyPQExpBuffer(query);
7987 get_language_name(Archive *fout, Oid langid)
7993 query = createPQExpBuffer();
7994 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7995 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7996 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7997 destroyPQExpBuffer(query);
8005 * get basic information about every transform in the system
8007 * numTransforms is set to the number of transforms read in
8010 getTransforms(Archive *fout, int *numTransforms)
8016 TransformInfo *transforminfo;
8024 /* Transforms didn't exist pre-9.5 */
8025 if (fout->remoteVersion < 90500)
8031 query = createPQExpBuffer();
8033 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8034 "trftype, trflang, trffromsql::oid, trftosql::oid "
8035 "FROM pg_transform "
8038 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8040 ntups = PQntuples(res);
8042 *numTransforms = ntups;
8044 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8046 i_tableoid = PQfnumber(res, "tableoid");
8047 i_oid = PQfnumber(res, "oid");
8048 i_trftype = PQfnumber(res, "trftype");
8049 i_trflang = PQfnumber(res, "trflang");
8050 i_trffromsql = PQfnumber(res, "trffromsql");
8051 i_trftosql = PQfnumber(res, "trftosql");
8053 for (i = 0; i < ntups; i++)
8055 PQExpBufferData namebuf;
8059 transforminfo[i].dobj.objType = DO_TRANSFORM;
8060 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8061 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8062 AssignDumpId(&transforminfo[i].dobj);
8063 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8064 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8065 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8066 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8069 * Try to name transform as concatenation of type and language name.
8070 * This is only used for purposes of sorting. If we fail to find
8071 * either, the name will be an empty string.
8073 initPQExpBuffer(&namebuf);
8074 typeInfo = findTypeByOid(transforminfo[i].trftype);
8075 lanname = get_language_name(fout, transforminfo[i].trflang);
8076 if (typeInfo && lanname)
8077 appendPQExpBuffer(&namebuf, "%s %s",
8078 typeInfo->dobj.name, lanname);
8079 transforminfo[i].dobj.name = namebuf.data;
8082 /* Decide whether we want to dump it */
8083 selectDumpableObject(&(transforminfo[i].dobj), fout);
8088 destroyPQExpBuffer(query);
8090 return transforminfo;
8095 * for each interesting table, read info about its attributes
8096 * (names, types, default values, CHECK constraints, etc)
8098 * This is implemented in a very inefficient way right now, looping
8099 * through the tblinfo and doing a join per table to find the attrs and their
8100 * types. However, because we want type names and so forth to be named
8101 * relative to the schema of each table, we couldn't do it in just one
8102 * query. (Maybe one query per schema?)
8107 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8109 DumpOptions *dopt = fout->dopt;
8112 PQExpBuffer q = createPQExpBuffer();
8117 int i_attstattarget;
8129 int i_attfdwoptions;
8130 int i_attmissingval;
8135 for (i = 0; i < numTables; i++)
8137 TableInfo *tbinfo = &tblinfo[i];
8139 /* Don't bother to collect info for sequences */
8140 if (tbinfo->relkind == RELKIND_SEQUENCE)
8143 /* Don't bother with uninteresting tables, either */
8144 if (!tbinfo->interesting)
8147 /* find all the user attributes and their types */
8150 * we must read the attribute names in attribute number order! because
8151 * we will use the attnum to index into the attnames array later.
8154 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8155 tbinfo->dobj.namespace->dobj.name,
8158 resetPQExpBuffer(q);
8160 if (fout->remoteVersion >= 110000)
8162 /* atthasmissing and attmissingval are new in 11 */
8163 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8164 "a.attstattarget, a.attstorage, t.typstorage, "
8165 "a.attnotnull, a.atthasdef, a.attisdropped, "
8166 "a.attlen, a.attalign, a.attislocal, "
8167 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8168 "array_to_string(a.attoptions, ', ') AS attoptions, "
8169 "CASE WHEN a.attcollation <> t.typcollation "
8170 "THEN a.attcollation ELSE 0 END AS attcollation, "
8172 "pg_catalog.array_to_string(ARRAY("
8173 "SELECT pg_catalog.quote_ident(option_name) || "
8174 "' ' || pg_catalog.quote_literal(option_value) "
8175 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8176 "ORDER BY option_name"
8177 "), E',\n ') AS attfdwoptions ,"
8178 "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8179 "THEN a.attmissingval ELSE null END AS attmissingval "
8180 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8181 "ON a.atttypid = t.oid "
8182 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8183 "AND a.attnum > 0::pg_catalog.int2 "
8184 "ORDER BY a.attnum",
8185 tbinfo->dobj.catId.oid);
8187 else if (fout->remoteVersion >= 100000)
8190 * attidentity is new in version 10.
8192 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8193 "a.attstattarget, a.attstorage, t.typstorage, "
8194 "a.attnotnull, a.atthasdef, a.attisdropped, "
8195 "a.attlen, a.attalign, a.attislocal, "
8196 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8197 "array_to_string(a.attoptions, ', ') AS attoptions, "
8198 "CASE WHEN a.attcollation <> t.typcollation "
8199 "THEN a.attcollation ELSE 0 END AS attcollation, "
8201 "pg_catalog.array_to_string(ARRAY("
8202 "SELECT pg_catalog.quote_ident(option_name) || "
8203 "' ' || pg_catalog.quote_literal(option_value) "
8204 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8205 "ORDER BY option_name"
8206 "), E',\n ') AS attfdwoptions ,"
8207 "NULL as attmissingval "
8208 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8209 "ON a.atttypid = t.oid "
8210 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8211 "AND a.attnum > 0::pg_catalog.int2 "
8212 "ORDER BY a.attnum",
8213 tbinfo->dobj.catId.oid);
8215 else if (fout->remoteVersion >= 90200)
8218 * attfdwoptions is new in 9.2.
8220 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8221 "a.attstattarget, a.attstorage, t.typstorage, "
8222 "a.attnotnull, a.atthasdef, a.attisdropped, "
8223 "a.attlen, a.attalign, a.attislocal, "
8224 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8225 "array_to_string(a.attoptions, ', ') AS attoptions, "
8226 "CASE WHEN a.attcollation <> t.typcollation "
8227 "THEN a.attcollation ELSE 0 END AS attcollation, "
8228 "pg_catalog.array_to_string(ARRAY("
8229 "SELECT pg_catalog.quote_ident(option_name) || "
8230 "' ' || pg_catalog.quote_literal(option_value) "
8231 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8232 "ORDER BY option_name"
8233 "), E',\n ') AS attfdwoptions, "
8234 "NULL as attmissingval "
8235 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8236 "ON a.atttypid = t.oid "
8237 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8238 "AND a.attnum > 0::pg_catalog.int2 "
8239 "ORDER BY a.attnum",
8240 tbinfo->dobj.catId.oid);
8242 else if (fout->remoteVersion >= 90100)
8245 * attcollation is new in 9.1. Since we only want to dump COLLATE
8246 * clauses for attributes whose collation is different from their
8247 * type's default, we use a CASE here to suppress uninteresting
8248 * attcollations cheaply.
8250 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8251 "a.attstattarget, a.attstorage, t.typstorage, "
8252 "a.attnotnull, a.atthasdef, a.attisdropped, "
8253 "a.attlen, a.attalign, a.attislocal, "
8254 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8255 "array_to_string(a.attoptions, ', ') AS attoptions, "
8256 "CASE WHEN a.attcollation <> t.typcollation "
8257 "THEN a.attcollation ELSE 0 END AS attcollation, "
8258 "NULL AS attfdwoptions, "
8259 "NULL as attmissingval "
8260 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8261 "ON a.atttypid = t.oid "
8262 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8263 "AND a.attnum > 0::pg_catalog.int2 "
8264 "ORDER BY a.attnum",
8265 tbinfo->dobj.catId.oid);
8267 else if (fout->remoteVersion >= 90000)
8269 /* attoptions is new in 9.0 */
8270 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8271 "a.attstattarget, a.attstorage, t.typstorage, "
8272 "a.attnotnull, a.atthasdef, a.attisdropped, "
8273 "a.attlen, a.attalign, a.attislocal, "
8274 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8275 "array_to_string(a.attoptions, ', ') AS attoptions, "
8276 "0 AS attcollation, "
8277 "NULL AS attfdwoptions, "
8278 "NULL as attmissingval "
8279 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8280 "ON a.atttypid = t.oid "
8281 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8282 "AND a.attnum > 0::pg_catalog.int2 "
8283 "ORDER BY a.attnum",
8284 tbinfo->dobj.catId.oid);
8288 /* need left join here to not fail on dropped columns ... */
8289 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8290 "a.attstattarget, a.attstorage, t.typstorage, "
8291 "a.attnotnull, a.atthasdef, a.attisdropped, "
8292 "a.attlen, a.attalign, a.attislocal, "
8293 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8294 "'' AS attoptions, 0 AS attcollation, "
8295 "NULL AS attfdwoptions, "
8296 "NULL as attmissingval "
8297 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8298 "ON a.atttypid = t.oid "
8299 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8300 "AND a.attnum > 0::pg_catalog.int2 "
8301 "ORDER BY a.attnum",
8302 tbinfo->dobj.catId.oid);
8305 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8307 ntups = PQntuples(res);
8309 i_attnum = PQfnumber(res, "attnum");
8310 i_attname = PQfnumber(res, "attname");
8311 i_atttypname = PQfnumber(res, "atttypname");
8312 i_atttypmod = PQfnumber(res, "atttypmod");
8313 i_attstattarget = PQfnumber(res, "attstattarget");
8314 i_attstorage = PQfnumber(res, "attstorage");
8315 i_typstorage = PQfnumber(res, "typstorage");
8316 i_attnotnull = PQfnumber(res, "attnotnull");
8317 i_atthasdef = PQfnumber(res, "atthasdef");
8318 i_attidentity = PQfnumber(res, "attidentity");
8319 i_attisdropped = PQfnumber(res, "attisdropped");
8320 i_attlen = PQfnumber(res, "attlen");
8321 i_attalign = PQfnumber(res, "attalign");
8322 i_attislocal = PQfnumber(res, "attislocal");
8323 i_attoptions = PQfnumber(res, "attoptions");
8324 i_attcollation = PQfnumber(res, "attcollation");
8325 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8326 i_attmissingval = PQfnumber(res, "attmissingval");
8328 tbinfo->numatts = ntups;
8329 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8330 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8331 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8332 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8333 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8334 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8335 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8336 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8337 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8338 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8339 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8340 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8341 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8342 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8343 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8344 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8345 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8346 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8347 hasdefaults = false;
8349 for (j = 0; j < ntups; j++)
8351 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8353 "invalid column numbering in table \"%s\"\n",
8355 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8356 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8357 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8358 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8359 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8360 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8361 tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8362 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8363 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8364 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8365 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8366 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8367 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8368 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8369 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8370 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8371 tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8372 tbinfo->attrdefs[j] = NULL; /* fix below */
8373 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8375 /* these flags will be set in flagInhAttrs() */
8376 tbinfo->inhNotNull[j] = false;
8382 * Get info about column defaults
8386 AttrDefInfo *attrdefs;
8390 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8391 tbinfo->dobj.namespace->dobj.name,
8394 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8395 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8396 "FROM pg_catalog.pg_attrdef "
8397 "WHERE adrelid = '%u'::pg_catalog.oid",
8398 tbinfo->dobj.catId.oid);
8400 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8402 numDefaults = PQntuples(res);
8403 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8405 for (j = 0; j < numDefaults; j++)
8409 adnum = atoi(PQgetvalue(res, j, 2));
8411 if (adnum <= 0 || adnum > ntups)
8413 "invalid adnum value %d for table \"%s\"\n",
8414 adnum, tbinfo->dobj.name);
8417 * dropped columns shouldn't have defaults, but just in case,
8420 if (tbinfo->attisdropped[adnum - 1])
8423 attrdefs[j].dobj.objType = DO_ATTRDEF;
8424 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8425 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8426 AssignDumpId(&attrdefs[j].dobj);
8427 attrdefs[j].adtable = tbinfo;
8428 attrdefs[j].adnum = adnum;
8429 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8431 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8432 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8434 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8437 * Defaults on a VIEW must always be dumped as separate ALTER
8438 * TABLE commands. Defaults on regular tables are dumped as
8439 * part of the CREATE TABLE if possible, which it won't be if
8440 * the column is not going to be emitted explicitly.
8442 if (tbinfo->relkind == RELKIND_VIEW)
8444 attrdefs[j].separate = true;
8446 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8448 /* column will be suppressed, print default separately */
8449 attrdefs[j].separate = true;
8453 attrdefs[j].separate = false;
8456 * Mark the default as needing to appear before the table,
8457 * so that any dependencies it has must be emitted before
8458 * the CREATE TABLE. If this is not possible, we'll
8459 * change to "separate" mode while sorting dependencies.
8461 addObjectDependency(&tbinfo->dobj,
8462 attrdefs[j].dobj.dumpId);
8465 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8471 * Get info about table CHECK constraints
8473 if (tbinfo->ncheck > 0)
8475 ConstraintInfo *constrs;
8479 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8480 tbinfo->dobj.namespace->dobj.name,
8483 resetPQExpBuffer(q);
8484 if (fout->remoteVersion >= 90200)
8487 * convalidated is new in 9.2 (actually, it is there in 9.1,
8488 * but it wasn't ever false for check constraints until 9.2).
8490 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8491 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8492 "conislocal, convalidated "
8493 "FROM pg_catalog.pg_constraint "
8494 "WHERE conrelid = '%u'::pg_catalog.oid "
8495 " AND contype = 'c' "
8497 tbinfo->dobj.catId.oid);
8499 else if (fout->remoteVersion >= 80400)
8501 /* conislocal is new in 8.4 */
8502 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8503 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8504 "conislocal, true AS convalidated "
8505 "FROM pg_catalog.pg_constraint "
8506 "WHERE conrelid = '%u'::pg_catalog.oid "
8507 " AND contype = 'c' "
8509 tbinfo->dobj.catId.oid);
8513 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8514 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8515 "true AS conislocal, true AS convalidated "
8516 "FROM pg_catalog.pg_constraint "
8517 "WHERE conrelid = '%u'::pg_catalog.oid "
8518 " AND contype = 'c' "
8520 tbinfo->dobj.catId.oid);
8523 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8525 numConstrs = PQntuples(res);
8526 if (numConstrs != tbinfo->ncheck)
8528 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8529 "expected %d check constraints on table \"%s\" but found %d\n",
8531 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8532 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8536 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8537 tbinfo->checkexprs = constrs;
8539 for (j = 0; j < numConstrs; j++)
8541 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8543 constrs[j].dobj.objType = DO_CONSTRAINT;
8544 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8545 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8546 AssignDumpId(&constrs[j].dobj);
8547 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8548 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8549 constrs[j].contable = tbinfo;
8550 constrs[j].condomain = NULL;
8551 constrs[j].contype = 'c';
8552 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8553 constrs[j].confrelid = InvalidOid;
8554 constrs[j].conindex = 0;
8555 constrs[j].condeferrable = false;
8556 constrs[j].condeferred = false;
8557 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8560 * An unvalidated constraint needs to be dumped separately, so
8561 * that potentially-violating existing data is loaded before
8564 constrs[j].separate = !validated;
8566 constrs[j].dobj.dump = tbinfo->dobj.dump;
8569 * Mark the constraint as needing to appear before the table
8570 * --- this is so that any other dependencies of the
8571 * constraint will be emitted before we try to create the
8572 * table. If the constraint is to be dumped separately, it
8573 * will be dumped after data is loaded anyway, so don't do it.
8574 * (There's an automatic dependency in the opposite direction
8575 * anyway, so don't need to add one manually here.)
8577 if (!constrs[j].separate)
8578 addObjectDependency(&tbinfo->dobj,
8579 constrs[j].dobj.dumpId);
8582 * If the constraint is inherited, this will be detected later
8583 * (in pre-8.4 databases). We also detect later if the
8584 * constraint must be split out from the table definition.
8591 destroyPQExpBuffer(q);
8595 * Test whether a column should be printed as part of table's CREATE TABLE.
8596 * Column number is zero-based.
8598 * Normally this is always true, but it's false for dropped columns, as well
8599 * as those that were inherited without any local definition. (If we print
8600 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8601 * However, in binary_upgrade mode, we must print all such columns anyway and
8602 * fix the attislocal/attisdropped state later, so as to keep control of the
8603 * physical column order.
8605 * This function exists because there are scattered nonobvious places that
8606 * must be kept in sync with this decision.
8609 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8611 if (dopt->binary_upgrade)
8613 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8619 * read all text search parsers in the system catalogs and return them
8620 * in the TSParserInfo* structure
8622 * numTSParsers is set to the number of parsers read in
8625 getTSParsers(Archive *fout, int *numTSParsers)
8631 TSParserInfo *prsinfo;
8642 /* Before 8.3, there is no built-in text search support */
8643 if (fout->remoteVersion < 80300)
8649 query = createPQExpBuffer();
8652 * find all text search objects, including builtin ones; we filter out
8653 * system-defined objects at dump-out time.
8656 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8657 "prsstart::oid, prstoken::oid, "
8658 "prsend::oid, prsheadline::oid, prslextype::oid "
8659 "FROM pg_ts_parser");
8661 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8663 ntups = PQntuples(res);
8664 *numTSParsers = ntups;
8666 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8668 i_tableoid = PQfnumber(res, "tableoid");
8669 i_oid = PQfnumber(res, "oid");
8670 i_prsname = PQfnumber(res, "prsname");
8671 i_prsnamespace = PQfnumber(res, "prsnamespace");
8672 i_prsstart = PQfnumber(res, "prsstart");
8673 i_prstoken = PQfnumber(res, "prstoken");
8674 i_prsend = PQfnumber(res, "prsend");
8675 i_prsheadline = PQfnumber(res, "prsheadline");
8676 i_prslextype = PQfnumber(res, "prslextype");
8678 for (i = 0; i < ntups; i++)
8680 prsinfo[i].dobj.objType = DO_TSPARSER;
8681 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8682 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8683 AssignDumpId(&prsinfo[i].dobj);
8684 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8685 prsinfo[i].dobj.namespace =
8687 atooid(PQgetvalue(res, i, i_prsnamespace)));
8688 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8689 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8690 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8691 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8692 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8694 /* Decide whether we want to dump it */
8695 selectDumpableObject(&(prsinfo[i].dobj), fout);
8697 /* Text Search Parsers do not currently have ACLs. */
8698 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8703 destroyPQExpBuffer(query);
8709 * getTSDictionaries:
8710 * read all text search dictionaries in the system catalogs and return them
8711 * in the TSDictInfo* structure
8713 * numTSDicts is set to the number of dictionaries read in
8716 getTSDictionaries(Archive *fout, int *numTSDicts)
8722 TSDictInfo *dictinfo;
8726 int i_dictnamespace;
8729 int i_dictinitoption;
8731 /* Before 8.3, there is no built-in text search support */
8732 if (fout->remoteVersion < 80300)
8738 query = createPQExpBuffer();
8740 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8741 "dictnamespace, (%s dictowner) AS rolname, "
8742 "dicttemplate, dictinitoption "
8746 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8748 ntups = PQntuples(res);
8749 *numTSDicts = ntups;
8751 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8753 i_tableoid = PQfnumber(res, "tableoid");
8754 i_oid = PQfnumber(res, "oid");
8755 i_dictname = PQfnumber(res, "dictname");
8756 i_dictnamespace = PQfnumber(res, "dictnamespace");
8757 i_rolname = PQfnumber(res, "rolname");
8758 i_dictinitoption = PQfnumber(res, "dictinitoption");
8759 i_dicttemplate = PQfnumber(res, "dicttemplate");
8761 for (i = 0; i < ntups; i++)
8763 dictinfo[i].dobj.objType = DO_TSDICT;
8764 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8765 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8766 AssignDumpId(&dictinfo[i].dobj);
8767 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8768 dictinfo[i].dobj.namespace =
8770 atooid(PQgetvalue(res, i, i_dictnamespace)));
8771 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8772 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8773 if (PQgetisnull(res, i, i_dictinitoption))
8774 dictinfo[i].dictinitoption = NULL;
8776 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8778 /* Decide whether we want to dump it */
8779 selectDumpableObject(&(dictinfo[i].dobj), fout);
8781 /* Text Search Dictionaries do not currently have ACLs. */
8782 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8787 destroyPQExpBuffer(query);
8794 * read all text search templates in the system catalogs and return them
8795 * in the TSTemplateInfo* structure
8797 * numTSTemplates is set to the number of templates read in
8800 getTSTemplates(Archive *fout, int *numTSTemplates)
8806 TSTemplateInfo *tmplinfo;
8810 int i_tmplnamespace;
8814 /* Before 8.3, there is no built-in text search support */
8815 if (fout->remoteVersion < 80300)
8817 *numTSTemplates = 0;
8821 query = createPQExpBuffer();
8823 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8824 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8825 "FROM pg_ts_template");
8827 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8829 ntups = PQntuples(res);
8830 *numTSTemplates = ntups;
8832 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8834 i_tableoid = PQfnumber(res, "tableoid");
8835 i_oid = PQfnumber(res, "oid");
8836 i_tmplname = PQfnumber(res, "tmplname");
8837 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8838 i_tmplinit = PQfnumber(res, "tmplinit");
8839 i_tmpllexize = PQfnumber(res, "tmpllexize");
8841 for (i = 0; i < ntups; i++)
8843 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8844 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8845 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8846 AssignDumpId(&tmplinfo[i].dobj);
8847 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8848 tmplinfo[i].dobj.namespace =
8850 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8851 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8852 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8854 /* Decide whether we want to dump it */
8855 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8857 /* Text Search Templates do not currently have ACLs. */
8858 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8863 destroyPQExpBuffer(query);
8869 * getTSConfigurations:
8870 * read all text search configurations in the system catalogs and return
8871 * them in the TSConfigInfo* structure
8873 * numTSConfigs is set to the number of configurations read in
8876 getTSConfigurations(Archive *fout, int *numTSConfigs)
8882 TSConfigInfo *cfginfo;
8890 /* Before 8.3, there is no built-in text search support */
8891 if (fout->remoteVersion < 80300)
8897 query = createPQExpBuffer();
8899 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8900 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8901 "FROM pg_ts_config",
8904 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8906 ntups = PQntuples(res);
8907 *numTSConfigs = ntups;
8909 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8911 i_tableoid = PQfnumber(res, "tableoid");
8912 i_oid = PQfnumber(res, "oid");
8913 i_cfgname = PQfnumber(res, "cfgname");
8914 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8915 i_rolname = PQfnumber(res, "rolname");
8916 i_cfgparser = PQfnumber(res, "cfgparser");
8918 for (i = 0; i < ntups; i++)
8920 cfginfo[i].dobj.objType = DO_TSCONFIG;
8921 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8922 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8923 AssignDumpId(&cfginfo[i].dobj);
8924 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8925 cfginfo[i].dobj.namespace =
8927 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8928 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8929 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8931 /* Decide whether we want to dump it */
8932 selectDumpableObject(&(cfginfo[i].dobj), fout);
8934 /* Text Search Configurations do not currently have ACLs. */
8935 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8940 destroyPQExpBuffer(query);
8946 * getForeignDataWrappers:
8947 * read all foreign-data wrappers in the system catalogs and return
8948 * them in the FdwInfo* structure
8950 * numForeignDataWrappers is set to the number of fdws read in
8953 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8955 DumpOptions *dopt = fout->dopt;
8973 /* Before 8.4, there are no foreign-data wrappers */
8974 if (fout->remoteVersion < 80400)
8976 *numForeignDataWrappers = 0;
8980 query = createPQExpBuffer();
8982 if (fout->remoteVersion >= 90600)
8984 PQExpBuffer acl_subquery = createPQExpBuffer();
8985 PQExpBuffer racl_subquery = createPQExpBuffer();
8986 PQExpBuffer initacl_subquery = createPQExpBuffer();
8987 PQExpBuffer initracl_subquery = createPQExpBuffer();
8989 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8990 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8991 dopt->binary_upgrade);
8993 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8994 "(%s f.fdwowner) AS rolname, "
8995 "f.fdwhandler::pg_catalog.regproc, "
8996 "f.fdwvalidator::pg_catalog.regproc, "
8999 "%s AS initfdwacl, "
9000 "%s AS initrfdwacl, "
9001 "array_to_string(ARRAY("
9002 "SELECT quote_ident(option_name) || ' ' || "
9003 "quote_literal(option_value) "
9004 "FROM pg_options_to_table(f.fdwoptions) "
9005 "ORDER BY option_name"
9006 "), E',\n ') AS fdwoptions "
9007 "FROM pg_foreign_data_wrapper f "
9008 "LEFT JOIN pg_init_privs pip ON "
9009 "(f.oid = pip.objoid "
9010 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
9011 "AND pip.objsubid = 0) ",
9014 racl_subquery->data,
9015 initacl_subquery->data,
9016 initracl_subquery->data);
9018 destroyPQExpBuffer(acl_subquery);
9019 destroyPQExpBuffer(racl_subquery);
9020 destroyPQExpBuffer(initacl_subquery);
9021 destroyPQExpBuffer(initracl_subquery);
9023 else if (fout->remoteVersion >= 90100)
9025 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9026 "(%s fdwowner) AS rolname, "
9027 "fdwhandler::pg_catalog.regproc, "
9028 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9030 "NULL as initfdwacl, NULL AS initrfdwacl, "
9031 "array_to_string(ARRAY("
9032 "SELECT quote_ident(option_name) || ' ' || "
9033 "quote_literal(option_value) "
9034 "FROM pg_options_to_table(fdwoptions) "
9035 "ORDER BY option_name"
9036 "), E',\n ') AS fdwoptions "
9037 "FROM pg_foreign_data_wrapper",
9042 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9043 "(%s fdwowner) AS rolname, "
9044 "'-' AS fdwhandler, "
9045 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9047 "NULL as initfdwacl, NULL AS initrfdwacl, "
9048 "array_to_string(ARRAY("
9049 "SELECT quote_ident(option_name) || ' ' || "
9050 "quote_literal(option_value) "
9051 "FROM pg_options_to_table(fdwoptions) "
9052 "ORDER BY option_name"
9053 "), E',\n ') AS fdwoptions "
9054 "FROM pg_foreign_data_wrapper",
9058 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9060 ntups = PQntuples(res);
9061 *numForeignDataWrappers = ntups;
9063 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9065 i_tableoid = PQfnumber(res, "tableoid");
9066 i_oid = PQfnumber(res, "oid");
9067 i_fdwname = PQfnumber(res, "fdwname");
9068 i_rolname = PQfnumber(res, "rolname");
9069 i_fdwhandler = PQfnumber(res, "fdwhandler");
9070 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9071 i_fdwacl = PQfnumber(res, "fdwacl");
9072 i_rfdwacl = PQfnumber(res, "rfdwacl");
9073 i_initfdwacl = PQfnumber(res, "initfdwacl");
9074 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9075 i_fdwoptions = PQfnumber(res, "fdwoptions");
9077 for (i = 0; i < ntups; i++)
9079 fdwinfo[i].dobj.objType = DO_FDW;
9080 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9081 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9082 AssignDumpId(&fdwinfo[i].dobj);
9083 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9084 fdwinfo[i].dobj.namespace = NULL;
9085 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9086 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9087 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9088 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9089 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9090 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9091 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9092 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9094 /* Decide whether we want to dump it */
9095 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9097 /* Do not try to dump ACL if no ACL exists. */
9098 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9099 PQgetisnull(res, i, i_initfdwacl) &&
9100 PQgetisnull(res, i, i_initrfdwacl))
9101 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9106 destroyPQExpBuffer(query);
9112 * getForeignServers:
9113 * read all foreign servers in the system catalogs and return
9114 * them in the ForeignServerInfo * structure
9116 * numForeignServers is set to the number of servers read in
9119 getForeignServers(Archive *fout, int *numForeignServers)
9121 DumpOptions *dopt = fout->dopt;
9126 ForeignServerInfo *srvinfo;
9140 /* Before 8.4, there are no foreign servers */
9141 if (fout->remoteVersion < 80400)
9143 *numForeignServers = 0;
9147 query = createPQExpBuffer();
9149 if (fout->remoteVersion >= 90600)
9151 PQExpBuffer acl_subquery = createPQExpBuffer();
9152 PQExpBuffer racl_subquery = createPQExpBuffer();
9153 PQExpBuffer initacl_subquery = createPQExpBuffer();
9154 PQExpBuffer initracl_subquery = createPQExpBuffer();
9156 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9157 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9158 dopt->binary_upgrade);
9160 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9161 "(%s f.srvowner) AS rolname, "
9162 "f.srvfdw, f.srvtype, f.srvversion, "
9165 "%s AS initsrvacl, "
9166 "%s AS initrsrvacl, "
9167 "array_to_string(ARRAY("
9168 "SELECT quote_ident(option_name) || ' ' || "
9169 "quote_literal(option_value) "
9170 "FROM pg_options_to_table(f.srvoptions) "
9171 "ORDER BY option_name"
9172 "), E',\n ') AS srvoptions "
9173 "FROM pg_foreign_server f "
9174 "LEFT JOIN pg_init_privs pip "
9175 "ON (f.oid = pip.objoid "
9176 "AND pip.classoid = 'pg_foreign_server'::regclass "
9177 "AND pip.objsubid = 0) ",
9180 racl_subquery->data,
9181 initacl_subquery->data,
9182 initracl_subquery->data);
9184 destroyPQExpBuffer(acl_subquery);
9185 destroyPQExpBuffer(racl_subquery);
9186 destroyPQExpBuffer(initacl_subquery);
9187 destroyPQExpBuffer(initracl_subquery);
9191 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9192 "(%s srvowner) AS rolname, "
9193 "srvfdw, srvtype, srvversion, srvacl, "
9195 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9196 "array_to_string(ARRAY("
9197 "SELECT quote_ident(option_name) || ' ' || "
9198 "quote_literal(option_value) "
9199 "FROM pg_options_to_table(srvoptions) "
9200 "ORDER BY option_name"
9201 "), E',\n ') AS srvoptions "
9202 "FROM pg_foreign_server",
9206 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9208 ntups = PQntuples(res);
9209 *numForeignServers = ntups;
9211 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9213 i_tableoid = PQfnumber(res, "tableoid");
9214 i_oid = PQfnumber(res, "oid");
9215 i_srvname = PQfnumber(res, "srvname");
9216 i_rolname = PQfnumber(res, "rolname");
9217 i_srvfdw = PQfnumber(res, "srvfdw");
9218 i_srvtype = PQfnumber(res, "srvtype");
9219 i_srvversion = PQfnumber(res, "srvversion");
9220 i_srvacl = PQfnumber(res, "srvacl");
9221 i_rsrvacl = PQfnumber(res, "rsrvacl");
9222 i_initsrvacl = PQfnumber(res, "initsrvacl");
9223 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9224 i_srvoptions = PQfnumber(res, "srvoptions");
9226 for (i = 0; i < ntups; i++)
9228 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9229 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9230 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9231 AssignDumpId(&srvinfo[i].dobj);
9232 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9233 srvinfo[i].dobj.namespace = NULL;
9234 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9235 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9236 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9237 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9238 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9239 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9240 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9241 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9242 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9244 /* Decide whether we want to dump it */
9245 selectDumpableObject(&(srvinfo[i].dobj), fout);
9247 /* Do not try to dump ACL if no ACL exists. */
9248 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9249 PQgetisnull(res, i, i_initsrvacl) &&
9250 PQgetisnull(res, i, i_initrsrvacl))
9251 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9256 destroyPQExpBuffer(query);
9263 * read all default ACL information in the system catalogs and return
9264 * them in the DefaultACLInfo structure
9266 * numDefaultACLs is set to the number of ACLs read in
9269 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9271 DumpOptions *dopt = fout->dopt;
9272 DefaultACLInfo *daclinfo;
9278 int i_defaclnamespace;
9279 int i_defaclobjtype;
9282 int i_initdefaclacl;
9283 int i_initrdefaclacl;
9287 if (fout->remoteVersion < 90000)
9289 *numDefaultACLs = 0;
9293 query = createPQExpBuffer();
9295 if (fout->remoteVersion >= 90600)
9297 PQExpBuffer acl_subquery = createPQExpBuffer();
9298 PQExpBuffer racl_subquery = createPQExpBuffer();
9299 PQExpBuffer initacl_subquery = createPQExpBuffer();
9300 PQExpBuffer initracl_subquery = createPQExpBuffer();
9302 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9303 initracl_subquery, "defaclacl", "defaclrole",
9304 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9305 dopt->binary_upgrade);
9307 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9308 "(%s d.defaclrole) AS defaclrole, "
9309 "d.defaclnamespace, "
9312 "%s AS rdefaclacl, "
9313 "%s AS initdefaclacl, "
9314 "%s AS initrdefaclacl "
9315 "FROM pg_default_acl d "
9316 "LEFT JOIN pg_init_privs pip ON "
9317 "(d.oid = pip.objoid "
9318 "AND pip.classoid = 'pg_default_acl'::regclass "
9319 "AND pip.objsubid = 0) ",
9322 racl_subquery->data,
9323 initacl_subquery->data,
9324 initracl_subquery->data);
9328 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9329 "(%s defaclrole) AS defaclrole, "
9333 "NULL AS rdefaclacl, "
9334 "NULL AS initdefaclacl, "
9335 "NULL AS initrdefaclacl "
9336 "FROM pg_default_acl",
9340 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9342 ntups = PQntuples(res);
9343 *numDefaultACLs = ntups;
9345 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9347 i_oid = PQfnumber(res, "oid");
9348 i_tableoid = PQfnumber(res, "tableoid");
9349 i_defaclrole = PQfnumber(res, "defaclrole");
9350 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9351 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9352 i_defaclacl = PQfnumber(res, "defaclacl");
9353 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9354 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9355 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9357 for (i = 0; i < ntups; i++)
9359 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9361 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9362 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9363 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9364 AssignDumpId(&daclinfo[i].dobj);
9365 /* cheesy ... is it worth coming up with a better object name? */
9366 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9368 if (nspid != InvalidOid)
9369 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9371 daclinfo[i].dobj.namespace = NULL;
9373 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9374 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9375 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9376 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9377 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9378 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9380 /* Decide whether we want to dump it */
9381 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9386 destroyPQExpBuffer(query);
9394 * This routine is used to dump any comments associated with the
9395 * object handed to this routine. The routine takes the object type
9396 * and object name (ready to print, except for schema decoration), plus
9397 * the namespace and owner of the object (for labeling the ArchiveEntry),
9398 * plus catalog ID and subid which are the lookup key for pg_description,
9399 * plus the dump ID for the object (for setting a dependency).
9400 * If a matching pg_description entry is found, it is dumped.
9402 * Note: in some cases, such as comments for triggers and rules, the "type"
9403 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9404 * but it doesn't seem worth complicating the API for all callers to make
9407 * Note: although this routine takes a dumpId for dependency purposes,
9408 * that purpose is just to mark the dependency in the emitted dump file
9409 * for possible future use by pg_restore. We do NOT use it for determining
9410 * ordering of the comment in the dump file, because this routine is called
9411 * after dependency sorting occurs. This routine should be called just after
9412 * calling ArchiveEntry() for the specified object.
9415 dumpComment(Archive *fout, const char *type, const char *name,
9416 const char *namespace, const char *owner,
9417 CatalogId catalogId, int subid, DumpId dumpId)
9419 DumpOptions *dopt = fout->dopt;
9420 CommentItem *comments;
9423 /* do nothing, if --no-comments is supplied */
9424 if (dopt->no_comments)
9427 /* Comments are schema not data ... except blob comments are data */
9428 if (strcmp(type, "LARGE OBJECT") != 0)
9435 /* We do dump blob comments in binary-upgrade mode */
9436 if (dopt->schemaOnly && !dopt->binary_upgrade)
9440 /* Search for comments associated with catalogId, using table */
9441 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9444 /* Is there one matching the subid? */
9445 while (ncomments > 0)
9447 if (comments->objsubid == subid)
9453 /* If a comment exists, build COMMENT ON statement */
9456 PQExpBuffer query = createPQExpBuffer();
9457 PQExpBuffer tag = createPQExpBuffer();
9459 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9460 if (namespace && *namespace)
9461 appendPQExpBuffer(query, "%s.", fmtId(namespace));
9462 appendPQExpBuffer(query, "%s IS ", name);
9463 appendStringLiteralAH(query, comments->descr, fout);
9464 appendPQExpBufferStr(query, ";\n");
9466 appendPQExpBuffer(tag, "%s %s", type, name);
9469 * We mark comments as SECTION_NONE because they really belong in the
9470 * same section as their parent, whether that is pre-data or
9473 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9474 tag->data, namespace, NULL, owner,
9475 false, "COMMENT", SECTION_NONE,
9476 query->data, "", NULL,
9480 destroyPQExpBuffer(query);
9481 destroyPQExpBuffer(tag);
9486 * dumpTableComment --
9488 * As above, but dump comments for both the specified table (or view)
9492 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9493 const char *reltypename)
9495 DumpOptions *dopt = fout->dopt;
9496 CommentItem *comments;
9501 /* do nothing, if --no-comments is supplied */
9502 if (dopt->no_comments)
9505 /* Comments are SCHEMA not data */
9509 /* Search for comments associated with relation, using table */
9510 ncomments = findComments(fout,
9511 tbinfo->dobj.catId.tableoid,
9512 tbinfo->dobj.catId.oid,
9515 /* If comments exist, build COMMENT ON statements */
9519 query = createPQExpBuffer();
9520 tag = createPQExpBuffer();
9522 while (ncomments > 0)
9524 const char *descr = comments->descr;
9525 int objsubid = comments->objsubid;
9529 resetPQExpBuffer(tag);
9530 appendPQExpBuffer(tag, "%s %s", reltypename,
9531 fmtId(tbinfo->dobj.name));
9533 resetPQExpBuffer(query);
9534 appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9535 fmtQualifiedDumpable(tbinfo));
9536 appendStringLiteralAH(query, descr, fout);
9537 appendPQExpBufferStr(query, ";\n");
9539 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9541 tbinfo->dobj.namespace->dobj.name,
9542 NULL, tbinfo->rolname,
9543 false, "COMMENT", SECTION_NONE,
9544 query->data, "", NULL,
9545 &(tbinfo->dobj.dumpId), 1,
9548 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9550 resetPQExpBuffer(tag);
9551 appendPQExpBuffer(tag, "COLUMN %s.",
9552 fmtId(tbinfo->dobj.name));
9553 appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9555 resetPQExpBuffer(query);
9556 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9557 fmtQualifiedDumpable(tbinfo));
9558 appendPQExpBuffer(query, "%s IS ",
9559 fmtId(tbinfo->attnames[objsubid - 1]));
9560 appendStringLiteralAH(query, descr, fout);
9561 appendPQExpBufferStr(query, ";\n");
9563 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9565 tbinfo->dobj.namespace->dobj.name,
9566 NULL, tbinfo->rolname,
9567 false, "COMMENT", SECTION_NONE,
9568 query->data, "", NULL,
9569 &(tbinfo->dobj.dumpId), 1,
9577 destroyPQExpBuffer(query);
9578 destroyPQExpBuffer(tag);
9584 * Find the comment(s), if any, associated with the given object. All the
9585 * objsubid values associated with the given classoid/objoid are found with
9589 findComments(Archive *fout, Oid classoid, Oid objoid,
9590 CommentItem **items)
9592 /* static storage for table of comments */
9593 static CommentItem *comments = NULL;
9594 static int ncomments = -1;
9596 CommentItem *middle = NULL;
9601 /* Get comments if we didn't already */
9603 ncomments = collectComments(fout, &comments);
9606 * Do binary search to find some item matching the object.
9609 high = &comments[ncomments - 1];
9612 middle = low + (high - low) / 2;
9614 if (classoid < middle->classoid)
9616 else if (classoid > middle->classoid)
9618 else if (objoid < middle->objoid)
9620 else if (objoid > middle->objoid)
9623 break; /* found a match */
9626 if (low > high) /* no matches */
9633 * Now determine how many items match the object. The search loop
9634 * invariant still holds: only items between low and high inclusive could
9638 while (middle > low)
9640 if (classoid != middle[-1].classoid ||
9641 objoid != middle[-1].objoid)
9650 while (middle <= high)
9652 if (classoid != middle->classoid ||
9653 objoid != middle->objoid)
9663 * collectComments --
9665 * Construct a table of all comments available for database objects.
9666 * We used to do per-object queries for the comments, but it's much faster
9667 * to pull them all over at once, and on most databases the memory cost
9670 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9673 collectComments(Archive *fout, CommentItem **items)
9683 CommentItem *comments;
9685 query = createPQExpBuffer();
9687 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9688 "FROM pg_catalog.pg_description "
9689 "ORDER BY classoid, objoid, objsubid");
9691 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9693 /* Construct lookup table containing OIDs in numeric form */
9695 i_description = PQfnumber(res, "description");
9696 i_classoid = PQfnumber(res, "classoid");
9697 i_objoid = PQfnumber(res, "objoid");
9698 i_objsubid = PQfnumber(res, "objsubid");
9700 ntups = PQntuples(res);
9702 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9704 for (i = 0; i < ntups; i++)
9706 comments[i].descr = PQgetvalue(res, i, i_description);
9707 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9708 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9709 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9712 /* Do NOT free the PGresult since we are keeping pointers into it */
9713 destroyPQExpBuffer(query);
9720 * dumpDumpableObject
9722 * This routine and its subsidiaries are responsible for creating
9723 * ArchiveEntries (TOC objects) for each object to be dumped.
9726 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9728 switch (dobj->objType)
9731 dumpNamespace(fout, (NamespaceInfo *) dobj);
9734 dumpExtension(fout, (ExtensionInfo *) dobj);
9737 dumpType(fout, (TypeInfo *) dobj);
9740 dumpShellType(fout, (ShellTypeInfo *) dobj);
9743 dumpFunc(fout, (FuncInfo *) dobj);
9746 dumpAgg(fout, (AggInfo *) dobj);
9749 dumpOpr(fout, (OprInfo *) dobj);
9751 case DO_ACCESS_METHOD:
9752 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9755 dumpOpclass(fout, (OpclassInfo *) dobj);
9758 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9761 dumpCollation(fout, (CollInfo *) dobj);
9764 dumpConversion(fout, (ConvInfo *) dobj);
9767 dumpTable(fout, (TableInfo *) dobj);
9770 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9773 dumpIndex(fout, (IndxInfo *) dobj);
9775 case DO_INDEX_ATTACH:
9776 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9779 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9781 case DO_REFRESH_MATVIEW:
9782 refreshMatViewData(fout, (TableDataInfo *) dobj);
9785 dumpRule(fout, (RuleInfo *) dobj);
9788 dumpTrigger(fout, (TriggerInfo *) dobj);
9790 case DO_EVENT_TRIGGER:
9791 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9794 dumpConstraint(fout, (ConstraintInfo *) dobj);
9796 case DO_FK_CONSTRAINT:
9797 dumpConstraint(fout, (ConstraintInfo *) dobj);
9800 dumpProcLang(fout, (ProcLangInfo *) dobj);
9803 dumpCast(fout, (CastInfo *) dobj);
9806 dumpTransform(fout, (TransformInfo *) dobj);
9808 case DO_SEQUENCE_SET:
9809 dumpSequenceData(fout, (TableDataInfo *) dobj);
9812 dumpTableData(fout, (TableDataInfo *) dobj);
9815 /* table rowtypes and array types are never dumped separately */
9818 dumpTSParser(fout, (TSParserInfo *) dobj);
9821 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9824 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9827 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9830 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9832 case DO_FOREIGN_SERVER:
9833 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9835 case DO_DEFAULT_ACL:
9836 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9839 dumpBlob(fout, (BlobInfo *) dobj);
9842 if (dobj->dump & DUMP_COMPONENT_DATA)
9843 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9844 dobj->name, NULL, NULL, "",
9845 false, "BLOBS", SECTION_DATA,
9851 dumpPolicy(fout, (PolicyInfo *) dobj);
9853 case DO_PUBLICATION:
9854 dumpPublication(fout, (PublicationInfo *) dobj);
9856 case DO_PUBLICATION_REL:
9857 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9859 case DO_SUBSCRIPTION:
9860 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9862 case DO_PRE_DATA_BOUNDARY:
9863 case DO_POST_DATA_BOUNDARY:
9864 /* never dumped, nothing to do */
9871 * writes out to fout the queries to recreate a user-defined namespace
9874 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9876 DumpOptions *dopt = fout->dopt;
9881 /* Skip if not to be dumped */
9882 if (!nspinfo->dobj.dump || dopt->dataOnly)
9885 q = createPQExpBuffer();
9886 delq = createPQExpBuffer();
9888 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9890 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9892 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9894 if (dopt->binary_upgrade)
9895 binary_upgrade_extension_member(q, &nspinfo->dobj,
9896 "SCHEMA", qnspname, NULL);
9898 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9899 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9903 false, "SCHEMA", SECTION_PRE_DATA,
9904 q->data, delq->data, NULL,
9908 /* Dump Schema Comments and Security Labels */
9909 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9910 dumpComment(fout, "SCHEMA", qnspname,
9911 NULL, nspinfo->rolname,
9912 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9914 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9915 dumpSecLabel(fout, "SCHEMA", qnspname,
9916 NULL, nspinfo->rolname,
9917 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9919 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9920 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9921 qnspname, NULL, NULL,
9922 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9923 nspinfo->initnspacl, nspinfo->initrnspacl);
9927 destroyPQExpBuffer(q);
9928 destroyPQExpBuffer(delq);
9933 * writes out to fout the queries to recreate an extension
9936 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9938 DumpOptions *dopt = fout->dopt;
9943 /* Skip if not to be dumped */
9944 if (!extinfo->dobj.dump || dopt->dataOnly)
9947 q = createPQExpBuffer();
9948 delq = createPQExpBuffer();
9950 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9952 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9954 if (!dopt->binary_upgrade)
9957 * In a regular dump, we simply create the extension, intentionally
9958 * not specifying a version, so that the destination installation's
9959 * default version is used.
9961 * Use of IF NOT EXISTS here is unlike our behavior for other object
9962 * types; but there are various scenarios in which it's convenient to
9963 * manually create the desired extension before restoring, so we
9964 * prefer to allow it to exist already.
9966 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9967 qextname, fmtId(extinfo->namespace));
9972 * In binary-upgrade mode, it's critical to reproduce the state of the
9973 * database exactly, so our procedure is to create an empty extension,
9974 * restore all the contained objects normally, and add them to the
9975 * extension one by one. This function performs just the first of
9976 * those steps. binary_upgrade_extension_member() takes care of
9977 * adding member objects as they're created.
9982 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9985 * We unconditionally create the extension, so we must drop it if it
9986 * exists. This could happen if the user deleted 'plpgsql' and then
9987 * readded it, causing its oid to be greater than g_last_builtin_oid.
9989 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9991 appendPQExpBufferStr(q,
9992 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9993 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9994 appendPQExpBufferStr(q, ", ");
9995 appendStringLiteralAH(q, extinfo->namespace, fout);
9996 appendPQExpBufferStr(q, ", ");
9997 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9998 appendStringLiteralAH(q, extinfo->extversion, fout);
9999 appendPQExpBufferStr(q, ", ");
10002 * Note that we're pushing extconfig (an OID array) back into
10003 * pg_extension exactly as-is. This is OK because pg_class OIDs are
10004 * preserved in binary upgrade.
10006 if (strlen(extinfo->extconfig) > 2)
10007 appendStringLiteralAH(q, extinfo->extconfig, fout);
10009 appendPQExpBufferStr(q, "NULL");
10010 appendPQExpBufferStr(q, ", ");
10011 if (strlen(extinfo->extcondition) > 2)
10012 appendStringLiteralAH(q, extinfo->extcondition, fout);
10014 appendPQExpBufferStr(q, "NULL");
10015 appendPQExpBufferStr(q, ", ");
10016 appendPQExpBufferStr(q, "ARRAY[");
10018 for (i = 0; i < extinfo->dobj.nDeps; i++)
10020 DumpableObject *extobj;
10022 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10023 if (extobj && extobj->objType == DO_EXTENSION)
10026 appendPQExpBufferChar(q, ',');
10027 appendStringLiteralAH(q, extobj->name, fout);
10030 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10031 appendPQExpBufferStr(q, ");\n");
10034 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10035 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10036 extinfo->dobj.name,
10039 false, "EXTENSION", SECTION_PRE_DATA,
10040 q->data, delq->data, NULL,
10044 /* Dump Extension Comments and Security Labels */
10045 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10046 dumpComment(fout, "EXTENSION", qextname,
10048 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10050 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10051 dumpSecLabel(fout, "EXTENSION", qextname,
10053 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10057 destroyPQExpBuffer(q);
10058 destroyPQExpBuffer(delq);
10063 * writes out to fout the queries to recreate a user-defined type
10066 dumpType(Archive *fout, TypeInfo *tyinfo)
10068 DumpOptions *dopt = fout->dopt;
10070 /* Skip if not to be dumped */
10071 if (!tyinfo->dobj.dump || dopt->dataOnly)
10074 /* Dump out in proper style */
10075 if (tyinfo->typtype == TYPTYPE_BASE)
10076 dumpBaseType(fout, tyinfo);
10077 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10078 dumpDomain(fout, tyinfo);
10079 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10080 dumpCompositeType(fout, tyinfo);
10081 else if (tyinfo->typtype == TYPTYPE_ENUM)
10082 dumpEnumType(fout, tyinfo);
10083 else if (tyinfo->typtype == TYPTYPE_RANGE)
10084 dumpRangeType(fout, tyinfo);
10085 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10086 dumpUndefinedType(fout, tyinfo);
10088 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10089 tyinfo->dobj.name);
10094 * writes out to fout the queries to recreate a user-defined enum type
10097 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10099 DumpOptions *dopt = fout->dopt;
10100 PQExpBuffer q = createPQExpBuffer();
10101 PQExpBuffer delq = createPQExpBuffer();
10102 PQExpBuffer query = createPQExpBuffer();
10111 if (fout->remoteVersion >= 90100)
10112 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10113 "FROM pg_catalog.pg_enum "
10114 "WHERE enumtypid = '%u'"
10115 "ORDER BY enumsortorder",
10116 tyinfo->dobj.catId.oid);
10118 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10119 "FROM pg_catalog.pg_enum "
10120 "WHERE enumtypid = '%u'"
10122 tyinfo->dobj.catId.oid);
10124 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10126 num = PQntuples(res);
10128 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10129 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10132 * CASCADE shouldn't be required here as for normal types since the I/O
10133 * functions are generic and do not get dropped.
10135 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10137 if (dopt->binary_upgrade)
10138 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10139 tyinfo->dobj.catId.oid,
10142 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10145 if (!dopt->binary_upgrade)
10147 /* Labels with server-assigned oids */
10148 for (i = 0; i < num; i++)
10150 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10152 appendPQExpBufferChar(q, ',');
10153 appendPQExpBufferStr(q, "\n ");
10154 appendStringLiteralAH(q, label, fout);
10158 appendPQExpBufferStr(q, "\n);\n");
10160 if (dopt->binary_upgrade)
10162 /* Labels with dump-assigned (preserved) oids */
10163 for (i = 0; i < num; i++)
10165 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10166 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10169 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10170 appendPQExpBuffer(q,
10171 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10173 appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10174 appendStringLiteralAH(q, label, fout);
10175 appendPQExpBufferStr(q, ";\n\n");
10179 if (dopt->binary_upgrade)
10180 binary_upgrade_extension_member(q, &tyinfo->dobj,
10182 tyinfo->dobj.namespace->dobj.name);
10184 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10185 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10187 tyinfo->dobj.namespace->dobj.name,
10189 tyinfo->rolname, false,
10190 "TYPE", SECTION_PRE_DATA,
10191 q->data, delq->data, NULL,
10195 /* Dump Type Comments and Security Labels */
10196 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10197 dumpComment(fout, "TYPE", qtypname,
10198 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10199 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10201 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10202 dumpSecLabel(fout, "TYPE", qtypname,
10203 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10204 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10206 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10207 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10209 tyinfo->dobj.namespace->dobj.name,
10210 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10211 tyinfo->inittypacl, tyinfo->initrtypacl);
10214 destroyPQExpBuffer(q);
10215 destroyPQExpBuffer(delq);
10216 destroyPQExpBuffer(query);
10223 * writes out to fout the queries to recreate a user-defined range type
10226 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10228 DumpOptions *dopt = fout->dopt;
10229 PQExpBuffer q = createPQExpBuffer();
10230 PQExpBuffer delq = createPQExpBuffer();
10231 PQExpBuffer query = createPQExpBuffer();
10238 appendPQExpBuffer(query,
10239 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10240 "opc.opcname AS opcname, "
10241 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10242 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10244 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10245 " ELSE rngcollation END AS collation, "
10246 "rngcanonical, rngsubdiff "
10247 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10248 " pg_catalog.pg_opclass opc "
10249 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10251 tyinfo->dobj.catId.oid);
10253 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10255 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10256 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10259 * CASCADE shouldn't be required here as for normal types since the I/O
10260 * functions are generic and do not get dropped.
10262 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10264 if (dopt->binary_upgrade)
10265 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10266 tyinfo->dobj.catId.oid,
10269 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10272 appendPQExpBuffer(q, "\n subtype = %s",
10273 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10275 /* print subtype_opclass only if not default for subtype */
10276 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10278 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10279 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10281 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10283 appendPQExpBufferStr(q, fmtId(opcname));
10286 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10287 if (OidIsValid(collationOid))
10289 CollInfo *coll = findCollationByOid(collationOid);
10292 appendPQExpBuffer(q, ",\n collation = %s",
10293 fmtQualifiedDumpable(coll));
10296 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10297 if (strcmp(procname, "-") != 0)
10298 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10300 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10301 if (strcmp(procname, "-") != 0)
10302 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10304 appendPQExpBufferStr(q, "\n);\n");
10306 if (dopt->binary_upgrade)
10307 binary_upgrade_extension_member(q, &tyinfo->dobj,
10309 tyinfo->dobj.namespace->dobj.name);
10311 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10312 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10314 tyinfo->dobj.namespace->dobj.name,
10316 tyinfo->rolname, false,
10317 "TYPE", SECTION_PRE_DATA,
10318 q->data, delq->data, NULL,
10322 /* Dump Type Comments and Security Labels */
10323 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10324 dumpComment(fout, "TYPE", qtypname,
10325 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10326 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10328 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10329 dumpSecLabel(fout, "TYPE", qtypname,
10330 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10331 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10333 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10334 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10336 tyinfo->dobj.namespace->dobj.name,
10337 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10338 tyinfo->inittypacl, tyinfo->initrtypacl);
10341 destroyPQExpBuffer(q);
10342 destroyPQExpBuffer(delq);
10343 destroyPQExpBuffer(query);
10349 * dumpUndefinedType
10350 * writes out to fout the queries to recreate a !typisdefined type
10352 * This is a shell type, but we use different terminology to distinguish
10353 * this case from where we have to emit a shell type definition to break
10354 * circular dependencies. An undefined type shouldn't ever have anything
10358 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10360 DumpOptions *dopt = fout->dopt;
10361 PQExpBuffer q = createPQExpBuffer();
10362 PQExpBuffer delq = createPQExpBuffer();
10366 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10367 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10369 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10371 if (dopt->binary_upgrade)
10372 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10373 tyinfo->dobj.catId.oid,
10376 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10379 if (dopt->binary_upgrade)
10380 binary_upgrade_extension_member(q, &tyinfo->dobj,
10382 tyinfo->dobj.namespace->dobj.name);
10384 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10385 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10387 tyinfo->dobj.namespace->dobj.name,
10389 tyinfo->rolname, false,
10390 "TYPE", SECTION_PRE_DATA,
10391 q->data, delq->data, NULL,
10395 /* Dump Type Comments and Security Labels */
10396 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10397 dumpComment(fout, "TYPE", qtypname,
10398 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10399 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10401 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10402 dumpSecLabel(fout, "TYPE", qtypname,
10403 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10404 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10406 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10407 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10409 tyinfo->dobj.namespace->dobj.name,
10410 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10411 tyinfo->inittypacl, tyinfo->initrtypacl);
10413 destroyPQExpBuffer(q);
10414 destroyPQExpBuffer(delq);
10421 * writes out to fout the queries to recreate a user-defined base type
10424 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10426 DumpOptions *dopt = fout->dopt;
10427 PQExpBuffer q = createPQExpBuffer();
10428 PQExpBuffer delq = createPQExpBuffer();
10429 PQExpBuffer query = createPQExpBuffer();
10447 char *typispreferred;
10452 char *typcollatable;
10454 bool typdefault_is_literal = false;
10456 /* Fetch type-specific details */
10457 if (fout->remoteVersion >= 90100)
10459 appendPQExpBuffer(query, "SELECT typlen, "
10460 "typinput, typoutput, typreceive, typsend, "
10461 "typmodin, typmodout, typanalyze, "
10462 "typreceive::pg_catalog.oid AS typreceiveoid, "
10463 "typsend::pg_catalog.oid AS typsendoid, "
10464 "typmodin::pg_catalog.oid AS typmodinoid, "
10465 "typmodout::pg_catalog.oid AS typmodoutoid, "
10466 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10467 "typcategory, typispreferred, "
10468 "typdelim, typbyval, typalign, typstorage, "
10469 "(typcollation <> 0) AS typcollatable, "
10470 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10471 "FROM pg_catalog.pg_type "
10472 "WHERE oid = '%u'::pg_catalog.oid",
10473 tyinfo->dobj.catId.oid);
10475 else if (fout->remoteVersion >= 80400)
10477 appendPQExpBuffer(query, "SELECT typlen, "
10478 "typinput, typoutput, typreceive, typsend, "
10479 "typmodin, typmodout, typanalyze, "
10480 "typreceive::pg_catalog.oid AS typreceiveoid, "
10481 "typsend::pg_catalog.oid AS typsendoid, "
10482 "typmodin::pg_catalog.oid AS typmodinoid, "
10483 "typmodout::pg_catalog.oid AS typmodoutoid, "
10484 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10485 "typcategory, typispreferred, "
10486 "typdelim, typbyval, typalign, typstorage, "
10487 "false AS typcollatable, "
10488 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10489 "FROM pg_catalog.pg_type "
10490 "WHERE oid = '%u'::pg_catalog.oid",
10491 tyinfo->dobj.catId.oid);
10493 else if (fout->remoteVersion >= 80300)
10495 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10496 appendPQExpBuffer(query, "SELECT typlen, "
10497 "typinput, typoutput, typreceive, typsend, "
10498 "typmodin, typmodout, typanalyze, "
10499 "typreceive::pg_catalog.oid AS typreceiveoid, "
10500 "typsend::pg_catalog.oid AS typsendoid, "
10501 "typmodin::pg_catalog.oid AS typmodinoid, "
10502 "typmodout::pg_catalog.oid AS typmodoutoid, "
10503 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10504 "'U' AS typcategory, false AS typispreferred, "
10505 "typdelim, typbyval, typalign, typstorage, "
10506 "false AS typcollatable, "
10507 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10508 "FROM pg_catalog.pg_type "
10509 "WHERE oid = '%u'::pg_catalog.oid",
10510 tyinfo->dobj.catId.oid);
10514 appendPQExpBuffer(query, "SELECT typlen, "
10515 "typinput, typoutput, typreceive, typsend, "
10516 "'-' AS typmodin, '-' AS typmodout, "
10518 "typreceive::pg_catalog.oid AS typreceiveoid, "
10519 "typsend::pg_catalog.oid AS typsendoid, "
10520 "0 AS typmodinoid, 0 AS typmodoutoid, "
10521 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10522 "'U' AS typcategory, false AS typispreferred, "
10523 "typdelim, typbyval, typalign, typstorage, "
10524 "false AS typcollatable, "
10525 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10526 "FROM pg_catalog.pg_type "
10527 "WHERE oid = '%u'::pg_catalog.oid",
10528 tyinfo->dobj.catId.oid);
10531 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10533 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10534 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10535 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10536 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10537 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10538 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10539 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10540 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10541 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10542 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10543 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10544 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10545 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10546 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10547 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10548 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10549 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10550 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10551 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10552 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10553 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10554 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10555 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10557 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10558 typdefault_is_literal = true; /* it needs quotes */
10563 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10564 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10567 * The reason we include CASCADE is that the circular dependency between
10568 * the type and its I/O functions makes it impossible to drop the type any
10571 appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10574 * We might already have a shell type, but setting pg_type_oid is
10575 * harmless, and in any case we'd better set the array type OID.
10577 if (dopt->binary_upgrade)
10578 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10579 tyinfo->dobj.catId.oid,
10582 appendPQExpBuffer(q,
10583 "CREATE TYPE %s (\n"
10584 " INTERNALLENGTH = %s",
10586 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10588 /* regproc result is sufficiently quoted already */
10589 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10590 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10591 if (OidIsValid(typreceiveoid))
10592 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10593 if (OidIsValid(typsendoid))
10594 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10595 if (OidIsValid(typmodinoid))
10596 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10597 if (OidIsValid(typmodoutoid))
10598 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10599 if (OidIsValid(typanalyzeoid))
10600 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10602 if (strcmp(typcollatable, "t") == 0)
10603 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10605 if (typdefault != NULL)
10607 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10608 if (typdefault_is_literal)
10609 appendStringLiteralAH(q, typdefault, fout);
10611 appendPQExpBufferStr(q, typdefault);
10614 if (OidIsValid(tyinfo->typelem))
10618 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10619 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10623 if (strcmp(typcategory, "U") != 0)
10625 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10626 appendStringLiteralAH(q, typcategory, fout);
10629 if (strcmp(typispreferred, "t") == 0)
10630 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10632 if (typdelim && strcmp(typdelim, ",") != 0)
10634 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10635 appendStringLiteralAH(q, typdelim, fout);
10638 if (strcmp(typalign, "c") == 0)
10639 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10640 else if (strcmp(typalign, "s") == 0)
10641 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10642 else if (strcmp(typalign, "i") == 0)
10643 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10644 else if (strcmp(typalign, "d") == 0)
10645 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10647 if (strcmp(typstorage, "p") == 0)
10648 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10649 else if (strcmp(typstorage, "e") == 0)
10650 appendPQExpBufferStr(q, ",\n STORAGE = external");
10651 else if (strcmp(typstorage, "x") == 0)
10652 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10653 else if (strcmp(typstorage, "m") == 0)
10654 appendPQExpBufferStr(q, ",\n STORAGE = main");
10656 if (strcmp(typbyval, "t") == 0)
10657 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10659 appendPQExpBufferStr(q, "\n);\n");
10661 if (dopt->binary_upgrade)
10662 binary_upgrade_extension_member(q, &tyinfo->dobj,
10664 tyinfo->dobj.namespace->dobj.name);
10666 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10667 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10669 tyinfo->dobj.namespace->dobj.name,
10671 tyinfo->rolname, false,
10672 "TYPE", SECTION_PRE_DATA,
10673 q->data, delq->data, NULL,
10677 /* Dump Type Comments and Security Labels */
10678 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10679 dumpComment(fout, "TYPE", qtypname,
10680 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10681 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10683 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10684 dumpSecLabel(fout, "TYPE", qtypname,
10685 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10686 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10688 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10689 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10691 tyinfo->dobj.namespace->dobj.name,
10692 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10693 tyinfo->inittypacl, tyinfo->initrtypacl);
10696 destroyPQExpBuffer(q);
10697 destroyPQExpBuffer(delq);
10698 destroyPQExpBuffer(query);
10705 * writes out to fout the queries to recreate a user-defined domain
10708 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10710 DumpOptions *dopt = fout->dopt;
10711 PQExpBuffer q = createPQExpBuffer();
10712 PQExpBuffer delq = createPQExpBuffer();
10713 PQExpBuffer query = createPQExpBuffer();
10722 bool typdefault_is_literal = false;
10724 /* Fetch domain specific details */
10725 if (fout->remoteVersion >= 90100)
10727 /* typcollation is new in 9.1 */
10728 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10729 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10730 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10732 "CASE WHEN t.typcollation <> u.typcollation "
10733 "THEN t.typcollation ELSE 0 END AS typcollation "
10734 "FROM pg_catalog.pg_type t "
10735 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10736 "WHERE t.oid = '%u'::pg_catalog.oid",
10737 tyinfo->dobj.catId.oid);
10741 appendPQExpBuffer(query, "SELECT typnotnull, "
10742 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10743 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10744 "typdefault, 0 AS typcollation "
10745 "FROM pg_catalog.pg_type "
10746 "WHERE oid = '%u'::pg_catalog.oid",
10747 tyinfo->dobj.catId.oid);
10750 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10752 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10753 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10754 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10755 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10756 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10758 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10759 typdefault_is_literal = true; /* it needs quotes */
10763 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10765 if (dopt->binary_upgrade)
10766 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10767 tyinfo->dobj.catId.oid,
10768 true); /* force array type */
10770 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10771 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10773 appendPQExpBuffer(q,
10774 "CREATE DOMAIN %s AS %s",
10778 /* Print collation only if different from base type's collation */
10779 if (OidIsValid(typcollation))
10783 coll = findCollationByOid(typcollation);
10785 appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10788 if (typnotnull[0] == 't')
10789 appendPQExpBufferStr(q, " NOT NULL");
10791 if (typdefault != NULL)
10793 appendPQExpBufferStr(q, " DEFAULT ");
10794 if (typdefault_is_literal)
10795 appendStringLiteralAH(q, typdefault, fout);
10797 appendPQExpBufferStr(q, typdefault);
10803 * Add any CHECK constraints for the domain
10805 for (i = 0; i < tyinfo->nDomChecks; i++)
10807 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10809 if (!domcheck->separate)
10810 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10811 fmtId(domcheck->dobj.name), domcheck->condef);
10814 appendPQExpBufferStr(q, ";\n");
10816 appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10818 if (dopt->binary_upgrade)
10819 binary_upgrade_extension_member(q, &tyinfo->dobj,
10820 "DOMAIN", qtypname,
10821 tyinfo->dobj.namespace->dobj.name);
10823 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10824 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10826 tyinfo->dobj.namespace->dobj.name,
10828 tyinfo->rolname, false,
10829 "DOMAIN", SECTION_PRE_DATA,
10830 q->data, delq->data, NULL,
10834 /* Dump Domain Comments and Security Labels */
10835 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10836 dumpComment(fout, "DOMAIN", qtypname,
10837 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10838 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10840 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10841 dumpSecLabel(fout, "DOMAIN", qtypname,
10842 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10843 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10845 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10846 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10848 tyinfo->dobj.namespace->dobj.name,
10849 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10850 tyinfo->inittypacl, tyinfo->initrtypacl);
10852 /* Dump any per-constraint comments */
10853 for (i = 0; i < tyinfo->nDomChecks; i++)
10855 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10856 PQExpBuffer conprefix = createPQExpBuffer();
10858 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10859 fmtId(domcheck->dobj.name));
10861 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10862 dumpComment(fout, conprefix->data, qtypname,
10863 tyinfo->dobj.namespace->dobj.name,
10865 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10867 destroyPQExpBuffer(conprefix);
10870 destroyPQExpBuffer(q);
10871 destroyPQExpBuffer(delq);
10872 destroyPQExpBuffer(query);
10878 * dumpCompositeType
10879 * writes out to fout the queries to recreate a user-defined stand-alone
10883 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10885 DumpOptions *dopt = fout->dopt;
10886 PQExpBuffer q = createPQExpBuffer();
10887 PQExpBuffer dropped = createPQExpBuffer();
10888 PQExpBuffer delq = createPQExpBuffer();
10889 PQExpBuffer query = createPQExpBuffer();
10898 int i_attisdropped;
10899 int i_attcollation;
10903 /* Fetch type specific details */
10904 if (fout->remoteVersion >= 90100)
10907 * attcollation is new in 9.1. Since we only want to dump COLLATE
10908 * clauses for attributes whose collation is different from their
10909 * type's default, we use a CASE here to suppress uninteresting
10910 * attcollations cheaply. atttypid will be 0 for dropped columns;
10911 * collation does not matter for those.
10913 appendPQExpBuffer(query, "SELECT a.attname, "
10914 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10915 "a.attlen, a.attalign, a.attisdropped, "
10916 "CASE WHEN a.attcollation <> at.typcollation "
10917 "THEN a.attcollation ELSE 0 END AS attcollation "
10918 "FROM pg_catalog.pg_type ct "
10919 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10920 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10921 "WHERE ct.oid = '%u'::pg_catalog.oid "
10922 "ORDER BY a.attnum ",
10923 tyinfo->dobj.catId.oid);
10928 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10929 * should always be false.
10931 appendPQExpBuffer(query, "SELECT a.attname, "
10932 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10933 "a.attlen, a.attalign, a.attisdropped, "
10934 "0 AS attcollation "
10935 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10936 "WHERE ct.oid = '%u'::pg_catalog.oid "
10937 "AND a.attrelid = ct.typrelid "
10938 "ORDER BY a.attnum ",
10939 tyinfo->dobj.catId.oid);
10942 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10944 ntups = PQntuples(res);
10946 i_attname = PQfnumber(res, "attname");
10947 i_atttypdefn = PQfnumber(res, "atttypdefn");
10948 i_attlen = PQfnumber(res, "attlen");
10949 i_attalign = PQfnumber(res, "attalign");
10950 i_attisdropped = PQfnumber(res, "attisdropped");
10951 i_attcollation = PQfnumber(res, "attcollation");
10953 if (dopt->binary_upgrade)
10955 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10956 tyinfo->dobj.catId.oid,
10958 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10961 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10962 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10964 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10968 for (i = 0; i < ntups; i++)
10977 attname = PQgetvalue(res, i, i_attname);
10978 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10979 attlen = PQgetvalue(res, i, i_attlen);
10980 attalign = PQgetvalue(res, i, i_attalign);
10981 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10982 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10984 if (attisdropped && !dopt->binary_upgrade)
10987 /* Format properly if not first attr */
10988 if (actual_atts++ > 0)
10989 appendPQExpBufferChar(q, ',');
10990 appendPQExpBufferStr(q, "\n\t");
10994 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10996 /* Add collation if not default for the column type */
10997 if (OidIsValid(attcollation))
11001 coll = findCollationByOid(attcollation);
11003 appendPQExpBuffer(q, " COLLATE %s",
11004 fmtQualifiedDumpable(coll));
11010 * This is a dropped attribute and we're in binary_upgrade mode.
11011 * Insert a placeholder for it in the CREATE TYPE command, and set
11012 * length and alignment with direct UPDATE to the catalogs
11013 * afterwards. See similar code in dumpTableSchema().
11015 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11017 /* stash separately for insertion after the CREATE TYPE */
11018 appendPQExpBufferStr(dropped,
11019 "\n-- For binary upgrade, recreate dropped column.\n");
11020 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11021 "SET attlen = %s, "
11022 "attalign = '%s', attbyval = false\n"
11023 "WHERE attname = ", attlen, attalign);
11024 appendStringLiteralAH(dropped, attname, fout);
11025 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
11026 appendStringLiteralAH(dropped, qualtypname, fout);
11027 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11029 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11031 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11035 appendPQExpBufferStr(q, "\n);\n");
11036 appendPQExpBufferStr(q, dropped->data);
11038 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11040 if (dopt->binary_upgrade)
11041 binary_upgrade_extension_member(q, &tyinfo->dobj,
11043 tyinfo->dobj.namespace->dobj.name);
11045 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11046 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11048 tyinfo->dobj.namespace->dobj.name,
11050 tyinfo->rolname, false,
11051 "TYPE", SECTION_PRE_DATA,
11052 q->data, delq->data, NULL,
11057 /* Dump Type Comments and Security Labels */
11058 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11059 dumpComment(fout, "TYPE", qtypname,
11060 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11061 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11063 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11064 dumpSecLabel(fout, "TYPE", qtypname,
11065 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11066 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11068 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11069 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
11071 tyinfo->dobj.namespace->dobj.name,
11072 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11073 tyinfo->inittypacl, tyinfo->initrtypacl);
11076 destroyPQExpBuffer(q);
11077 destroyPQExpBuffer(dropped);
11078 destroyPQExpBuffer(delq);
11079 destroyPQExpBuffer(query);
11083 /* Dump any per-column comments */
11084 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11085 dumpCompositeTypeColComments(fout, tyinfo);
11089 * dumpCompositeTypeColComments
11090 * writes out to fout the queries to recreate comments on the columns of
11091 * a user-defined stand-alone composite type
11094 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11096 CommentItem *comments;
11100 PQExpBuffer target;
11107 /* do nothing, if --no-comments is supplied */
11108 if (fout->dopt->no_comments)
11111 query = createPQExpBuffer();
11113 appendPQExpBuffer(query,
11114 "SELECT c.tableoid, a.attname, a.attnum "
11115 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11116 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11117 " AND NOT a.attisdropped "
11118 "ORDER BY a.attnum ",
11121 /* Fetch column attnames */
11122 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11124 ntups = PQntuples(res);
11128 destroyPQExpBuffer(query);
11132 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11134 /* Search for comments associated with type's pg_class OID */
11135 ncomments = findComments(fout,
11140 /* If no comments exist, we're done */
11141 if (ncomments <= 0)
11144 destroyPQExpBuffer(query);
11148 /* Build COMMENT ON statements */
11149 target = createPQExpBuffer();
11151 i_attnum = PQfnumber(res, "attnum");
11152 i_attname = PQfnumber(res, "attname");
11153 while (ncomments > 0)
11155 const char *attname;
11158 for (i = 0; i < ntups; i++)
11160 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11162 attname = PQgetvalue(res, i, i_attname);
11166 if (attname) /* just in case we don't find it */
11168 const char *descr = comments->descr;
11170 resetPQExpBuffer(target);
11171 appendPQExpBuffer(target, "COLUMN %s.",
11172 fmtId(tyinfo->dobj.name));
11173 appendPQExpBufferStr(target, fmtId(attname));
11175 resetPQExpBuffer(query);
11176 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11177 fmtQualifiedDumpable(tyinfo));
11178 appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11179 appendStringLiteralAH(query, descr, fout);
11180 appendPQExpBufferStr(query, ";\n");
11182 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11184 tyinfo->dobj.namespace->dobj.name,
11185 NULL, tyinfo->rolname,
11186 false, "COMMENT", SECTION_NONE,
11187 query->data, "", NULL,
11188 &(tyinfo->dobj.dumpId), 1,
11197 destroyPQExpBuffer(query);
11198 destroyPQExpBuffer(target);
11203 * writes out to fout the queries to create a shell type
11205 * We dump a shell definition in advance of the I/O functions for the type.
11208 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11210 DumpOptions *dopt = fout->dopt;
11213 /* Skip if not to be dumped */
11214 if (!stinfo->dobj.dump || dopt->dataOnly)
11217 q = createPQExpBuffer();
11220 * Note the lack of a DROP command for the shell type; any required DROP
11221 * is driven off the base type entry, instead. This interacts with
11222 * _printTocEntry()'s use of the presence of a DROP command to decide
11223 * whether an entry needs an ALTER OWNER command. We don't want to alter
11224 * the shell type's owner immediately on creation; that should happen only
11225 * after it's filled in, otherwise the backend complains.
11228 if (dopt->binary_upgrade)
11229 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11230 stinfo->baseType->dobj.catId.oid,
11233 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11234 fmtQualifiedDumpable(stinfo));
11236 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11237 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11239 stinfo->dobj.namespace->dobj.name,
11241 stinfo->baseType->rolname, false,
11242 "SHELL TYPE", SECTION_PRE_DATA,
11247 destroyPQExpBuffer(q);
11252 * writes out to fout the queries to recreate a user-defined
11253 * procedural language
11256 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11258 DumpOptions *dopt = fout->dopt;
11259 PQExpBuffer defqry;
11260 PQExpBuffer delqry;
11263 FuncInfo *funcInfo;
11264 FuncInfo *inlineInfo = NULL;
11265 FuncInfo *validatorInfo = NULL;
11267 /* Skip if not to be dumped */
11268 if (!plang->dobj.dump || dopt->dataOnly)
11272 * Try to find the support function(s). It is not an error if we don't
11273 * find them --- if the functions are in the pg_catalog schema, as is
11274 * standard in 8.1 and up, then we won't have loaded them. (In this case
11275 * we will emit a parameterless CREATE LANGUAGE command, which will
11276 * require PL template knowledge in the backend to reload.)
11279 funcInfo = findFuncByOid(plang->lanplcallfoid);
11280 if (funcInfo != NULL && !funcInfo->dobj.dump)
11281 funcInfo = NULL; /* treat not-dumped same as not-found */
11283 if (OidIsValid(plang->laninline))
11285 inlineInfo = findFuncByOid(plang->laninline);
11286 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11290 if (OidIsValid(plang->lanvalidator))
11292 validatorInfo = findFuncByOid(plang->lanvalidator);
11293 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11294 validatorInfo = NULL;
11298 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11299 * with parameters. Otherwise, we'll write a parameterless command, which
11300 * will rely on data from pg_pltemplate.
11302 useParams = (funcInfo != NULL &&
11303 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11304 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11306 defqry = createPQExpBuffer();
11307 delqry = createPQExpBuffer();
11309 qlanname = pg_strdup(fmtId(plang->dobj.name));
11311 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11316 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11317 plang->lanpltrusted ? "TRUSTED " : "",
11319 appendPQExpBuffer(defqry, " HANDLER %s",
11320 fmtQualifiedDumpable(funcInfo));
11321 if (OidIsValid(plang->laninline))
11322 appendPQExpBuffer(defqry, " INLINE %s",
11323 fmtQualifiedDumpable(inlineInfo));
11324 if (OidIsValid(plang->lanvalidator))
11325 appendPQExpBuffer(defqry, " VALIDATOR %s",
11326 fmtQualifiedDumpable(validatorInfo));
11331 * If not dumping parameters, then use CREATE OR REPLACE so that the
11332 * command will not fail if the language is preinstalled in the target
11333 * database. We restrict the use of REPLACE to this case so as to
11334 * eliminate the risk of replacing a language with incompatible
11335 * parameter settings: this command will only succeed at all if there
11336 * is a pg_pltemplate entry, and if there is one, the existing entry
11337 * must match it too.
11339 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11342 appendPQExpBufferStr(defqry, ";\n");
11344 if (dopt->binary_upgrade)
11345 binary_upgrade_extension_member(defqry, &plang->dobj,
11346 "LANGUAGE", qlanname, NULL);
11348 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11349 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11351 NULL, NULL, plang->lanowner,
11352 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11353 defqry->data, delqry->data, NULL,
11357 /* Dump Proc Lang Comments and Security Labels */
11358 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11359 dumpComment(fout, "LANGUAGE", qlanname,
11360 NULL, plang->lanowner,
11361 plang->dobj.catId, 0, plang->dobj.dumpId);
11363 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11364 dumpSecLabel(fout, "LANGUAGE", qlanname,
11365 NULL, plang->lanowner,
11366 plang->dobj.catId, 0, plang->dobj.dumpId);
11368 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11369 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11370 qlanname, NULL, NULL,
11371 plang->lanowner, plang->lanacl, plang->rlanacl,
11372 plang->initlanacl, plang->initrlanacl);
11376 destroyPQExpBuffer(defqry);
11377 destroyPQExpBuffer(delqry);
11381 * format_function_arguments: generate function name and argument list
11383 * This is used when we can rely on pg_get_function_arguments to format
11384 * the argument list. Note, however, that pg_get_function_arguments
11385 * does not special-case zero-argument aggregates.
11388 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11390 PQExpBufferData fn;
11392 initPQExpBuffer(&fn);
11393 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11394 if (is_agg && finfo->nargs == 0)
11395 appendPQExpBufferStr(&fn, "(*)");
11397 appendPQExpBuffer(&fn, "(%s)", funcargs);
11402 * format_function_arguments_old: generate function name and argument list
11404 * The argument type names are qualified if needed. The function name
11405 * is never qualified.
11407 * This is used only with pre-8.4 servers, so we aren't expecting to see
11408 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11410 * Any or all of allargtypes, argmodes, argnames may be NULL.
11413 format_function_arguments_old(Archive *fout,
11414 FuncInfo *finfo, int nallargs,
11415 char **allargtypes,
11419 PQExpBufferData fn;
11422 initPQExpBuffer(&fn);
11423 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11424 for (j = 0; j < nallargs; j++)
11428 const char *argmode;
11429 const char *argname;
11431 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11432 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11436 switch (argmodes[j][0])
11438 case PROARGMODE_IN:
11441 case PROARGMODE_OUT:
11444 case PROARGMODE_INOUT:
11445 argmode = "INOUT ";
11448 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11456 argname = argnames ? argnames[j] : (char *) NULL;
11457 if (argname && argname[0] == '\0')
11460 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11461 (j > 0) ? ", " : "",
11463 argname ? fmtId(argname) : "",
11464 argname ? " " : "",
11468 appendPQExpBufferChar(&fn, ')');
11473 * format_function_signature: generate function name and argument list
11475 * This is like format_function_arguments_old except that only a minimal
11476 * list of input argument types is generated; this is sufficient to
11477 * reference the function, but not to define it.
11479 * If honor_quotes is false then the function name is never quoted.
11480 * This is appropriate for use in TOC tags, but not in SQL commands.
11483 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11485 PQExpBufferData fn;
11488 initPQExpBuffer(&fn);
11490 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11492 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11493 for (j = 0; j < finfo->nargs; j++)
11498 appendPQExpBufferStr(&fn, ", ");
11500 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11502 appendPQExpBufferStr(&fn, typname);
11505 appendPQExpBufferChar(&fn, ')');
11512 * dump out one function
11515 dumpFunc(Archive *fout, FuncInfo *finfo)
11517 DumpOptions *dopt = fout->dopt;
11520 PQExpBuffer delqry;
11521 PQExpBuffer asPart;
11523 char *funcsig; /* identity signature */
11524 char *funcfullsig = NULL; /* full signature */
11532 char *proallargtypes;
11540 char *proleakproof;
11548 char **allargtypes = NULL;
11549 char **argmodes = NULL;
11550 char **argnames = NULL;
11551 char **configitems = NULL;
11552 int nconfigitems = 0;
11553 const char *keyword;
11556 /* Skip if not to be dumped */
11557 if (!finfo->dobj.dump || dopt->dataOnly)
11560 query = createPQExpBuffer();
11561 q = createPQExpBuffer();
11562 delqry = createPQExpBuffer();
11563 asPart = createPQExpBuffer();
11565 /* Fetch function-specific details */
11566 if (fout->remoteVersion >= 110000)
11569 * prokind was added in 11
11571 appendPQExpBuffer(query,
11572 "SELECT proretset, prosrc, probin, "
11573 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11574 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11575 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11576 "array_to_string(protrftypes, ' ') AS protrftypes, "
11577 "prokind, provolatile, proisstrict, prosecdef, "
11578 "proleakproof, proconfig, procost, prorows, "
11580 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11581 "FROM pg_catalog.pg_proc "
11582 "WHERE oid = '%u'::pg_catalog.oid",
11583 finfo->dobj.catId.oid);
11585 else if (fout->remoteVersion >= 90600)
11588 * proparallel was added in 9.6
11590 appendPQExpBuffer(query,
11591 "SELECT proretset, prosrc, probin, "
11592 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11593 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11594 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11595 "array_to_string(protrftypes, ' ') AS protrftypes, "
11596 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11597 "provolatile, proisstrict, prosecdef, "
11598 "proleakproof, proconfig, procost, prorows, "
11600 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11601 "FROM pg_catalog.pg_proc "
11602 "WHERE oid = '%u'::pg_catalog.oid",
11603 finfo->dobj.catId.oid);
11605 else if (fout->remoteVersion >= 90500)
11608 * protrftypes was added in 9.5
11610 appendPQExpBuffer(query,
11611 "SELECT proretset, prosrc, probin, "
11612 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11613 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11614 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11615 "array_to_string(protrftypes, ' ') AS protrftypes, "
11616 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11617 "provolatile, proisstrict, prosecdef, "
11618 "proleakproof, proconfig, procost, prorows, "
11619 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11620 "FROM pg_catalog.pg_proc "
11621 "WHERE oid = '%u'::pg_catalog.oid",
11622 finfo->dobj.catId.oid);
11624 else if (fout->remoteVersion >= 90200)
11627 * proleakproof was added in 9.2
11629 appendPQExpBuffer(query,
11630 "SELECT proretset, prosrc, probin, "
11631 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11632 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11633 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11634 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11635 "provolatile, proisstrict, prosecdef, "
11636 "proleakproof, proconfig, procost, prorows, "
11637 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11638 "FROM pg_catalog.pg_proc "
11639 "WHERE oid = '%u'::pg_catalog.oid",
11640 finfo->dobj.catId.oid);
11642 else if (fout->remoteVersion >= 80400)
11645 * In 8.4 and up we rely on pg_get_function_arguments and
11646 * pg_get_function_result instead of examining proallargtypes etc.
11648 appendPQExpBuffer(query,
11649 "SELECT proretset, prosrc, probin, "
11650 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11651 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11652 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11653 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11654 "provolatile, proisstrict, prosecdef, "
11655 "false AS proleakproof, "
11656 " proconfig, procost, prorows, "
11657 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11658 "FROM pg_catalog.pg_proc "
11659 "WHERE oid = '%u'::pg_catalog.oid",
11660 finfo->dobj.catId.oid);
11662 else if (fout->remoteVersion >= 80300)
11664 appendPQExpBuffer(query,
11665 "SELECT proretset, prosrc, probin, "
11666 "proallargtypes, proargmodes, proargnames, "
11668 "provolatile, proisstrict, prosecdef, "
11669 "false AS proleakproof, "
11670 "proconfig, procost, prorows, "
11671 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11672 "FROM pg_catalog.pg_proc "
11673 "WHERE oid = '%u'::pg_catalog.oid",
11674 finfo->dobj.catId.oid);
11676 else if (fout->remoteVersion >= 80100)
11678 appendPQExpBuffer(query,
11679 "SELECT proretset, prosrc, probin, "
11680 "proallargtypes, proargmodes, proargnames, "
11682 "provolatile, proisstrict, prosecdef, "
11683 "false AS proleakproof, "
11684 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11685 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11686 "FROM pg_catalog.pg_proc "
11687 "WHERE oid = '%u'::pg_catalog.oid",
11688 finfo->dobj.catId.oid);
11692 appendPQExpBuffer(query,
11693 "SELECT proretset, prosrc, probin, "
11694 "null AS proallargtypes, "
11695 "null AS proargmodes, "
11698 "provolatile, proisstrict, prosecdef, "
11699 "false AS proleakproof, "
11700 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11701 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11702 "FROM pg_catalog.pg_proc "
11703 "WHERE oid = '%u'::pg_catalog.oid",
11704 finfo->dobj.catId.oid);
11707 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11709 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11710 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11711 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11712 if (fout->remoteVersion >= 80400)
11714 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11715 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11716 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11717 proallargtypes = proargmodes = proargnames = NULL;
11721 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11722 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11723 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11724 funcargs = funciargs = funcresult = NULL;
11726 if (PQfnumber(res, "protrftypes") != -1)
11727 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11729 protrftypes = NULL;
11730 prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11731 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11732 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11733 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11734 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11735 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11736 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11737 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11739 if (PQfnumber(res, "proparallel") != -1)
11740 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11742 proparallel = NULL;
11744 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11747 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11748 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11749 * versions would set it to "-". There are no known cases in which prosrc
11750 * is unused, so the tests below for "-" are probably useless.
11752 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11754 appendPQExpBufferStr(asPart, "AS ");
11755 appendStringLiteralAH(asPart, probin, fout);
11756 if (strcmp(prosrc, "-") != 0)
11758 appendPQExpBufferStr(asPart, ", ");
11761 * where we have bin, use dollar quoting if allowed and src
11762 * contains quote or backslash; else use regular quoting.
11764 if (dopt->disable_dollar_quoting ||
11765 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11766 appendStringLiteralAH(asPart, prosrc, fout);
11768 appendStringLiteralDQ(asPart, prosrc, NULL);
11773 if (strcmp(prosrc, "-") != 0)
11775 appendPQExpBufferStr(asPart, "AS ");
11776 /* with no bin, dollar quote src unconditionally if allowed */
11777 if (dopt->disable_dollar_quoting)
11778 appendStringLiteralAH(asPart, prosrc, fout);
11780 appendStringLiteralDQ(asPart, prosrc, NULL);
11784 nallargs = finfo->nargs; /* unless we learn different from allargs */
11786 if (proallargtypes && *proallargtypes)
11790 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11791 nitems < finfo->nargs)
11793 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11796 allargtypes = NULL;
11802 if (proargmodes && *proargmodes)
11806 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11807 nitems != nallargs)
11809 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11816 if (proargnames && *proargnames)
11820 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11821 nitems != nallargs)
11823 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11830 if (proconfig && *proconfig)
11832 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11834 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11837 configitems = NULL;
11844 /* 8.4 or later; we rely on server-side code for most of the work */
11845 funcfullsig = format_function_arguments(finfo, funcargs, false);
11846 funcsig = format_function_arguments(finfo, funciargs, false);
11849 /* pre-8.4, do it ourselves */
11850 funcsig = format_function_arguments_old(fout,
11851 finfo, nallargs, allargtypes,
11852 argmodes, argnames);
11854 funcsig_tag = format_function_signature(fout, finfo, false);
11856 if (prokind[0] == PROKIND_PROCEDURE)
11857 keyword = "PROCEDURE";
11859 keyword = "FUNCTION"; /* works for window functions too */
11861 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11863 fmtId(finfo->dobj.namespace->dobj.name),
11866 appendPQExpBuffer(q, "CREATE %s %s.%s",
11868 fmtId(finfo->dobj.namespace->dobj.name),
11869 funcfullsig ? funcfullsig :
11872 if (prokind[0] == PROKIND_PROCEDURE)
11873 /* no result type to output */ ;
11874 else if (funcresult)
11875 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11878 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11880 appendPQExpBuffer(q, " RETURNS %s%s",
11881 (proretset[0] == 't') ? "SETOF " : "",
11886 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11888 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11890 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11893 appendPQExpBufferStr(q, " TRANSFORM ");
11894 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11895 for (i = 0; typeids[i]; i++)
11898 appendPQExpBufferStr(q, ", ");
11899 appendPQExpBuffer(q, "FOR TYPE %s",
11900 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11904 if (prokind[0] == PROKIND_WINDOW)
11905 appendPQExpBufferStr(q, " WINDOW");
11907 if (provolatile[0] != PROVOLATILE_VOLATILE)
11909 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11910 appendPQExpBufferStr(q, " IMMUTABLE");
11911 else if (provolatile[0] == PROVOLATILE_STABLE)
11912 appendPQExpBufferStr(q, " STABLE");
11913 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11914 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11918 if (proisstrict[0] == 't')
11919 appendPQExpBufferStr(q, " STRICT");
11921 if (prosecdef[0] == 't')
11922 appendPQExpBufferStr(q, " SECURITY DEFINER");
11924 if (proleakproof[0] == 't')
11925 appendPQExpBufferStr(q, " LEAKPROOF");
11928 * COST and ROWS are emitted only if present and not default, so as not to
11929 * break backwards-compatibility of the dump without need. Keep this code
11930 * in sync with the defaults in functioncmds.c.
11932 if (strcmp(procost, "0") != 0)
11934 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11936 /* default cost is 1 */
11937 if (strcmp(procost, "1") != 0)
11938 appendPQExpBuffer(q, " COST %s", procost);
11942 /* default cost is 100 */
11943 if (strcmp(procost, "100") != 0)
11944 appendPQExpBuffer(q, " COST %s", procost);
11947 if (proretset[0] == 't' &&
11948 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11949 appendPQExpBuffer(q, " ROWS %s", prorows);
11951 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11953 if (proparallel[0] == PROPARALLEL_SAFE)
11954 appendPQExpBufferStr(q, " PARALLEL SAFE");
11955 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11956 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11957 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11958 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11962 for (i = 0; i < nconfigitems; i++)
11964 /* we feel free to scribble on configitems[] here */
11965 char *configitem = configitems[i];
11968 pos = strchr(configitem, '=');
11972 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
11975 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11976 * by flatten_set_variable_args() before they were put into the
11977 * proconfig array. However, because the quoting rules used there
11978 * aren't exactly like SQL's, we have to break the list value apart
11979 * and then quote the elements as string literals. (The elements may
11980 * be double-quoted as-is, but we can't just feed them to the SQL
11981 * parser; it would do the wrong thing with elements that are
11982 * zero-length or longer than NAMEDATALEN.)
11984 * Variables that are not so marked should just be emitted as simple
11985 * string literals. If the variable is not known to
11986 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
11987 * to use GUC_LIST_QUOTE for extension variables.
11989 if (variable_is_guc_list_quote(configitem))
11994 /* Parse string into list of identifiers */
11995 /* this shouldn't fail really */
11996 if (SplitGUCList(pos, ',', &namelist))
11998 for (nameptr = namelist; *nameptr; nameptr++)
12000 if (nameptr != namelist)
12001 appendPQExpBufferStr(q, ", ");
12002 appendStringLiteralAH(q, *nameptr, fout);
12008 appendStringLiteralAH(q, pos, fout);
12011 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
12013 if (dopt->binary_upgrade)
12014 binary_upgrade_extension_member(q, &finfo->dobj,
12016 finfo->dobj.namespace->dobj.name);
12018 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12019 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12021 finfo->dobj.namespace->dobj.name,
12023 finfo->rolname, false,
12024 keyword, SECTION_PRE_DATA,
12025 q->data, delqry->data, NULL,
12029 /* Dump Function Comments and Security Labels */
12030 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12031 dumpComment(fout, keyword, funcsig,
12032 finfo->dobj.namespace->dobj.name, finfo->rolname,
12033 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12035 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12036 dumpSecLabel(fout, keyword, funcsig,
12037 finfo->dobj.namespace->dobj.name, finfo->rolname,
12038 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12040 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12041 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
12043 finfo->dobj.namespace->dobj.name,
12044 finfo->rolname, finfo->proacl, finfo->rproacl,
12045 finfo->initproacl, finfo->initrproacl);
12049 destroyPQExpBuffer(query);
12050 destroyPQExpBuffer(q);
12051 destroyPQExpBuffer(delqry);
12052 destroyPQExpBuffer(asPart);
12069 * Dump a user-defined cast
12072 dumpCast(Archive *fout, CastInfo *cast)
12074 DumpOptions *dopt = fout->dopt;
12075 PQExpBuffer defqry;
12076 PQExpBuffer delqry;
12077 PQExpBuffer labelq;
12078 PQExpBuffer castargs;
12079 FuncInfo *funcInfo = NULL;
12083 /* Skip if not to be dumped */
12084 if (!cast->dobj.dump || dopt->dataOnly)
12087 /* Cannot dump if we don't have the cast function's info */
12088 if (OidIsValid(cast->castfunc))
12090 funcInfo = findFuncByOid(cast->castfunc);
12091 if (funcInfo == NULL)
12092 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12096 defqry = createPQExpBuffer();
12097 delqry = createPQExpBuffer();
12098 labelq = createPQExpBuffer();
12099 castargs = createPQExpBuffer();
12101 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12102 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12103 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12104 sourceType, targetType);
12106 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12107 sourceType, targetType);
12109 switch (cast->castmethod)
12111 case COERCION_METHOD_BINARY:
12112 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12114 case COERCION_METHOD_INOUT:
12115 appendPQExpBufferStr(defqry, "WITH INOUT");
12117 case COERCION_METHOD_FUNCTION:
12120 char *fsig = format_function_signature(fout, funcInfo, true);
12123 * Always qualify the function name (format_function_signature
12124 * won't qualify it).
12126 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12127 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12131 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12134 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12137 if (cast->castcontext == 'a')
12138 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12139 else if (cast->castcontext == 'i')
12140 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12141 appendPQExpBufferStr(defqry, ";\n");
12143 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12144 sourceType, targetType);
12146 appendPQExpBuffer(castargs, "(%s AS %s)",
12147 sourceType, targetType);
12149 if (dopt->binary_upgrade)
12150 binary_upgrade_extension_member(defqry, &cast->dobj,
12151 "CAST", castargs->data, NULL);
12153 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12154 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12157 false, "CAST", SECTION_PRE_DATA,
12158 defqry->data, delqry->data, NULL,
12162 /* Dump Cast Comments */
12163 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12164 dumpComment(fout, "CAST", castargs->data,
12166 cast->dobj.catId, 0, cast->dobj.dumpId);
12171 destroyPQExpBuffer(defqry);
12172 destroyPQExpBuffer(delqry);
12173 destroyPQExpBuffer(labelq);
12174 destroyPQExpBuffer(castargs);
12181 dumpTransform(Archive *fout, TransformInfo *transform)
12183 DumpOptions *dopt = fout->dopt;
12184 PQExpBuffer defqry;
12185 PQExpBuffer delqry;
12186 PQExpBuffer labelq;
12187 PQExpBuffer transformargs;
12188 FuncInfo *fromsqlFuncInfo = NULL;
12189 FuncInfo *tosqlFuncInfo = NULL;
12191 char *transformType;
12193 /* Skip if not to be dumped */
12194 if (!transform->dobj.dump || dopt->dataOnly)
12197 /* Cannot dump if we don't have the transform functions' info */
12198 if (OidIsValid(transform->trffromsql))
12200 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12201 if (fromsqlFuncInfo == NULL)
12202 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12203 transform->trffromsql);
12205 if (OidIsValid(transform->trftosql))
12207 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12208 if (tosqlFuncInfo == NULL)
12209 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12210 transform->trftosql);
12213 defqry = createPQExpBuffer();
12214 delqry = createPQExpBuffer();
12215 labelq = createPQExpBuffer();
12216 transformargs = createPQExpBuffer();
12218 lanname = get_language_name(fout, transform->trflang);
12219 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12221 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12222 transformType, lanname);
12224 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12225 transformType, lanname);
12227 if (!transform->trffromsql && !transform->trftosql)
12228 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12230 if (transform->trffromsql)
12232 if (fromsqlFuncInfo)
12234 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12237 * Always qualify the function name (format_function_signature
12238 * won't qualify it).
12240 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12241 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12245 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12248 if (transform->trftosql)
12250 if (transform->trffromsql)
12251 appendPQExpBuffer(defqry, ", ");
12255 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12258 * Always qualify the function name (format_function_signature
12259 * won't qualify it).
12261 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12262 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12266 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12269 appendPQExpBuffer(defqry, ");\n");
12271 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12272 transformType, lanname);
12274 appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12275 transformType, lanname);
12277 if (dopt->binary_upgrade)
12278 binary_upgrade_extension_member(defqry, &transform->dobj,
12279 "TRANSFORM", transformargs->data, NULL);
12281 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12282 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12285 false, "TRANSFORM", SECTION_PRE_DATA,
12286 defqry->data, delqry->data, NULL,
12287 transform->dobj.dependencies, transform->dobj.nDeps,
12290 /* Dump Transform Comments */
12291 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12292 dumpComment(fout, "TRANSFORM", transformargs->data,
12294 transform->dobj.catId, 0, transform->dobj.dumpId);
12297 free(transformType);
12298 destroyPQExpBuffer(defqry);
12299 destroyPQExpBuffer(delqry);
12300 destroyPQExpBuffer(labelq);
12301 destroyPQExpBuffer(transformargs);
12307 * write out a single operator definition
12310 dumpOpr(Archive *fout, OprInfo *oprinfo)
12312 DumpOptions *dopt = fout->dopt;
12317 PQExpBuffer details;
12342 /* Skip if not to be dumped */
12343 if (!oprinfo->dobj.dump || dopt->dataOnly)
12347 * some operators are invalid because they were the result of user
12348 * defining operators before commutators exist
12350 if (!OidIsValid(oprinfo->oprcode))
12353 query = createPQExpBuffer();
12354 q = createPQExpBuffer();
12355 delq = createPQExpBuffer();
12356 oprid = createPQExpBuffer();
12357 details = createPQExpBuffer();
12359 if (fout->remoteVersion >= 80300)
12361 appendPQExpBuffer(query, "SELECT oprkind, "
12362 "oprcode::pg_catalog.regprocedure, "
12363 "oprleft::pg_catalog.regtype, "
12364 "oprright::pg_catalog.regtype, "
12367 "oprrest::pg_catalog.regprocedure, "
12368 "oprjoin::pg_catalog.regprocedure, "
12369 "oprcanmerge, oprcanhash "
12370 "FROM pg_catalog.pg_operator "
12371 "WHERE oid = '%u'::pg_catalog.oid",
12372 oprinfo->dobj.catId.oid);
12376 appendPQExpBuffer(query, "SELECT oprkind, "
12377 "oprcode::pg_catalog.regprocedure, "
12378 "oprleft::pg_catalog.regtype, "
12379 "oprright::pg_catalog.regtype, "
12382 "oprrest::pg_catalog.regprocedure, "
12383 "oprjoin::pg_catalog.regprocedure, "
12384 "(oprlsortop != 0) AS oprcanmerge, "
12386 "FROM pg_catalog.pg_operator "
12387 "WHERE oid = '%u'::pg_catalog.oid",
12388 oprinfo->dobj.catId.oid);
12391 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12393 i_oprkind = PQfnumber(res, "oprkind");
12394 i_oprcode = PQfnumber(res, "oprcode");
12395 i_oprleft = PQfnumber(res, "oprleft");
12396 i_oprright = PQfnumber(res, "oprright");
12397 i_oprcom = PQfnumber(res, "oprcom");
12398 i_oprnegate = PQfnumber(res, "oprnegate");
12399 i_oprrest = PQfnumber(res, "oprrest");
12400 i_oprjoin = PQfnumber(res, "oprjoin");
12401 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12402 i_oprcanhash = PQfnumber(res, "oprcanhash");
12404 oprkind = PQgetvalue(res, 0, i_oprkind);
12405 oprcode = PQgetvalue(res, 0, i_oprcode);
12406 oprleft = PQgetvalue(res, 0, i_oprleft);
12407 oprright = PQgetvalue(res, 0, i_oprright);
12408 oprcom = PQgetvalue(res, 0, i_oprcom);
12409 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12410 oprrest = PQgetvalue(res, 0, i_oprrest);
12411 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12412 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12413 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12415 oprregproc = convertRegProcReference(fout, oprcode);
12418 appendPQExpBuffer(details, " FUNCTION = %s", oprregproc);
12422 appendPQExpBuffer(oprid, "%s (",
12423 oprinfo->dobj.name);
12426 * right unary means there's a left arg and left unary means there's a
12429 if (strcmp(oprkind, "r") == 0 ||
12430 strcmp(oprkind, "b") == 0)
12432 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12433 appendPQExpBufferStr(oprid, oprleft);
12436 appendPQExpBufferStr(oprid, "NONE");
12438 if (strcmp(oprkind, "l") == 0 ||
12439 strcmp(oprkind, "b") == 0)
12441 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12442 appendPQExpBuffer(oprid, ", %s)", oprright);
12445 appendPQExpBufferStr(oprid, ", NONE)");
12447 oprref = getFormattedOperatorName(fout, oprcom);
12450 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12454 oprref = getFormattedOperatorName(fout, oprnegate);
12457 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12461 if (strcmp(oprcanmerge, "t") == 0)
12462 appendPQExpBufferStr(details, ",\n MERGES");
12464 if (strcmp(oprcanhash, "t") == 0)
12465 appendPQExpBufferStr(details, ",\n HASHES");
12467 oprregproc = convertRegProcReference(fout, oprrest);
12470 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12474 oprregproc = convertRegProcReference(fout, oprjoin);
12477 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12481 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12482 fmtId(oprinfo->dobj.namespace->dobj.name),
12485 appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12486 fmtId(oprinfo->dobj.namespace->dobj.name),
12487 oprinfo->dobj.name, details->data);
12489 if (dopt->binary_upgrade)
12490 binary_upgrade_extension_member(q, &oprinfo->dobj,
12491 "OPERATOR", oprid->data,
12492 oprinfo->dobj.namespace->dobj.name);
12494 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12495 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12496 oprinfo->dobj.name,
12497 oprinfo->dobj.namespace->dobj.name,
12500 false, "OPERATOR", SECTION_PRE_DATA,
12501 q->data, delq->data, NULL,
12505 /* Dump Operator Comments */
12506 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12507 dumpComment(fout, "OPERATOR", oprid->data,
12508 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12509 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12513 destroyPQExpBuffer(query);
12514 destroyPQExpBuffer(q);
12515 destroyPQExpBuffer(delq);
12516 destroyPQExpBuffer(oprid);
12517 destroyPQExpBuffer(details);
12521 * Convert a function reference obtained from pg_operator
12523 * Returns allocated string of what to print, or NULL if function references
12524 * is InvalidOid. Returned string is expected to be free'd by the caller.
12526 * The input is a REGPROCEDURE display; we have to strip the argument-types
12530 convertRegProcReference(Archive *fout, const char *proc)
12536 /* In all cases "-" means a null reference */
12537 if (strcmp(proc, "-") == 0)
12540 name = pg_strdup(proc);
12541 /* find non-double-quoted left paren */
12543 for (paren = name; *paren; paren++)
12545 if (*paren == '(' && !inquote)
12551 inquote = !inquote;
12557 * getFormattedOperatorName - retrieve the operator name for the
12558 * given operator OID (presented in string form).
12560 * Returns an allocated string, or NULL if the given OID is invalid.
12561 * Caller is responsible for free'ing result string.
12563 * What we produce has the format "OPERATOR(schema.oprname)". This is only
12564 * useful in commands where the operator's argument types can be inferred from
12565 * context. We always schema-qualify the name, though. The predecessor to
12566 * this code tried to skip the schema qualification if possible, but that led
12567 * to wrong results in corner cases, such as if an operator and its negator
12568 * are in different schemas.
12571 getFormattedOperatorName(Archive *fout, const char *oproid)
12575 /* In all cases "0" means a null reference */
12576 if (strcmp(oproid, "0") == 0)
12579 oprInfo = findOprByOid(atooid(oproid));
12580 if (oprInfo == NULL)
12582 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12587 return psprintf("OPERATOR(%s.%s)",
12588 fmtId(oprInfo->dobj.namespace->dobj.name),
12589 oprInfo->dobj.name);
12593 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12595 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12596 * argument lists of these functions are predetermined. Note that the
12597 * caller should ensure we are in the proper schema, because the results
12598 * are search path dependent!
12601 convertTSFunction(Archive *fout, Oid funcOid)
12607 snprintf(query, sizeof(query),
12608 "SELECT '%u'::pg_catalog.regproc", funcOid);
12609 res = ExecuteSqlQueryForSingleRow(fout, query);
12611 result = pg_strdup(PQgetvalue(res, 0, 0));
12620 * write out a single access method definition
12623 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12625 DumpOptions *dopt = fout->dopt;
12630 /* Skip if not to be dumped */
12631 if (!aminfo->dobj.dump || dopt->dataOnly)
12634 q = createPQExpBuffer();
12635 delq = createPQExpBuffer();
12637 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12639 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12641 switch (aminfo->amtype)
12644 appendPQExpBuffer(q, "TYPE INDEX ");
12647 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12648 aminfo->amtype, qamname);
12649 destroyPQExpBuffer(q);
12650 destroyPQExpBuffer(delq);
12655 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12657 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12660 if (dopt->binary_upgrade)
12661 binary_upgrade_extension_member(q, &aminfo->dobj,
12662 "ACCESS METHOD", qamname, NULL);
12664 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12665 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12670 false, "ACCESS METHOD", SECTION_PRE_DATA,
12671 q->data, delq->data, NULL,
12675 /* Dump Access Method Comments */
12676 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12677 dumpComment(fout, "ACCESS METHOD", qamname,
12679 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12681 destroyPQExpBuffer(q);
12682 destroyPQExpBuffer(delq);
12688 * write out a single operator class definition
12691 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12693 DumpOptions *dopt = fout->dopt;
12697 PQExpBuffer nameusing;
12704 int i_opcfamilyname;
12705 int i_opcfamilynsp;
12707 int i_amopstrategy;
12708 int i_amopreqcheck;
12711 int i_sortfamilynsp;
12714 int i_amproclefttype;
12715 int i_amprocrighttype;
12720 char *opcfamilyname;
12721 char *opcfamilynsp;
12723 char *amopstrategy;
12724 char *amopreqcheck;
12727 char *sortfamilynsp;
12730 char *amproclefttype;
12731 char *amprocrighttype;
12735 /* Skip if not to be dumped */
12736 if (!opcinfo->dobj.dump || dopt->dataOnly)
12739 query = createPQExpBuffer();
12740 q = createPQExpBuffer();
12741 delq = createPQExpBuffer();
12742 nameusing = createPQExpBuffer();
12744 /* Get additional fields from the pg_opclass row */
12745 if (fout->remoteVersion >= 80300)
12747 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12748 "opckeytype::pg_catalog.regtype, "
12749 "opcdefault, opcfamily, "
12750 "opfname AS opcfamilyname, "
12751 "nspname AS opcfamilynsp, "
12752 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12753 "FROM pg_catalog.pg_opclass c "
12754 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12755 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12756 "WHERE c.oid = '%u'::pg_catalog.oid",
12757 opcinfo->dobj.catId.oid);
12761 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12762 "opckeytype::pg_catalog.regtype, "
12763 "opcdefault, NULL AS opcfamily, "
12764 "NULL AS opcfamilyname, "
12765 "NULL AS opcfamilynsp, "
12766 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12767 "FROM pg_catalog.pg_opclass "
12768 "WHERE oid = '%u'::pg_catalog.oid",
12769 opcinfo->dobj.catId.oid);
12772 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12774 i_opcintype = PQfnumber(res, "opcintype");
12775 i_opckeytype = PQfnumber(res, "opckeytype");
12776 i_opcdefault = PQfnumber(res, "opcdefault");
12777 i_opcfamily = PQfnumber(res, "opcfamily");
12778 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12779 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12780 i_amname = PQfnumber(res, "amname");
12782 /* opcintype may still be needed after we PQclear res */
12783 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12784 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12785 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12786 /* opcfamily will still be needed after we PQclear res */
12787 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12788 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12789 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12790 /* amname will still be needed after we PQclear res */
12791 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12793 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12794 fmtQualifiedDumpable(opcinfo));
12795 appendPQExpBuffer(delq, " USING %s;\n",
12798 /* Build the fixed portion of the CREATE command */
12799 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12800 fmtQualifiedDumpable(opcinfo));
12801 if (strcmp(opcdefault, "t") == 0)
12802 appendPQExpBufferStr(q, "DEFAULT ");
12803 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12806 if (strlen(opcfamilyname) > 0)
12808 appendPQExpBufferStr(q, " FAMILY ");
12809 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12810 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12812 appendPQExpBufferStr(q, " AS\n ");
12816 if (strcmp(opckeytype, "-") != 0)
12818 appendPQExpBuffer(q, "STORAGE %s",
12826 * Now fetch and print the OPERATOR entries (pg_amop rows).
12828 * Print only those opfamily members that are tied to the opclass by
12829 * pg_depend entries.
12831 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12832 * older server's opclass in which it is used. This is to avoid
12833 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12834 * older server and then reload into that old version. This can go away
12835 * once 8.3 is so old as to not be of interest to anyone.
12837 resetPQExpBuffer(query);
12839 if (fout->remoteVersion >= 90100)
12841 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12842 "amopopr::pg_catalog.regoperator, "
12843 "opfname AS sortfamily, "
12844 "nspname AS sortfamilynsp "
12845 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12846 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12847 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12848 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12849 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12850 "AND refobjid = '%u'::pg_catalog.oid "
12851 "AND amopfamily = '%s'::pg_catalog.oid "
12852 "ORDER BY amopstrategy",
12853 opcinfo->dobj.catId.oid,
12856 else if (fout->remoteVersion >= 80400)
12858 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12859 "amopopr::pg_catalog.regoperator, "
12860 "NULL AS sortfamily, "
12861 "NULL AS sortfamilynsp "
12862 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12863 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12864 "AND refobjid = '%u'::pg_catalog.oid "
12865 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12866 "AND objid = ao.oid "
12867 "ORDER BY amopstrategy",
12868 opcinfo->dobj.catId.oid);
12870 else if (fout->remoteVersion >= 80300)
12872 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12873 "amopopr::pg_catalog.regoperator, "
12874 "NULL AS sortfamily, "
12875 "NULL AS sortfamilynsp "
12876 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12877 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12878 "AND refobjid = '%u'::pg_catalog.oid "
12879 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12880 "AND objid = ao.oid "
12881 "ORDER BY amopstrategy",
12882 opcinfo->dobj.catId.oid);
12887 * Here, we print all entries since there are no opfamilies and hence
12888 * no loose operators to worry about.
12890 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12891 "amopopr::pg_catalog.regoperator, "
12892 "NULL AS sortfamily, "
12893 "NULL AS sortfamilynsp "
12894 "FROM pg_catalog.pg_amop "
12895 "WHERE amopclaid = '%u'::pg_catalog.oid "
12896 "ORDER BY amopstrategy",
12897 opcinfo->dobj.catId.oid);
12900 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12902 ntups = PQntuples(res);
12904 i_amopstrategy = PQfnumber(res, "amopstrategy");
12905 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12906 i_amopopr = PQfnumber(res, "amopopr");
12907 i_sortfamily = PQfnumber(res, "sortfamily");
12908 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12910 for (i = 0; i < ntups; i++)
12912 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12913 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12914 amopopr = PQgetvalue(res, i, i_amopopr);
12915 sortfamily = PQgetvalue(res, i, i_sortfamily);
12916 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12919 appendPQExpBufferStr(q, " ,\n ");
12921 appendPQExpBuffer(q, "OPERATOR %s %s",
12922 amopstrategy, amopopr);
12924 if (strlen(sortfamily) > 0)
12926 appendPQExpBufferStr(q, " FOR ORDER BY ");
12927 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12928 appendPQExpBufferStr(q, fmtId(sortfamily));
12931 if (strcmp(amopreqcheck, "t") == 0)
12932 appendPQExpBufferStr(q, " RECHECK");
12940 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12942 * Print only those opfamily members that are tied to the opclass by
12943 * pg_depend entries.
12945 * We print the amproclefttype/amprocrighttype even though in most cases
12946 * the backend could deduce the right values, because of the corner case
12947 * of a btree sort support function for a cross-type comparison. That's
12948 * only allowed in 9.2 and later, but for simplicity print them in all
12949 * versions that have the columns.
12951 resetPQExpBuffer(query);
12953 if (fout->remoteVersion >= 80300)
12955 appendPQExpBuffer(query, "SELECT amprocnum, "
12956 "amproc::pg_catalog.regprocedure, "
12957 "amproclefttype::pg_catalog.regtype, "
12958 "amprocrighttype::pg_catalog.regtype "
12959 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12960 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12961 "AND refobjid = '%u'::pg_catalog.oid "
12962 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12963 "AND objid = ap.oid "
12964 "ORDER BY amprocnum",
12965 opcinfo->dobj.catId.oid);
12969 appendPQExpBuffer(query, "SELECT amprocnum, "
12970 "amproc::pg_catalog.regprocedure, "
12971 "'' AS amproclefttype, "
12972 "'' AS amprocrighttype "
12973 "FROM pg_catalog.pg_amproc "
12974 "WHERE amopclaid = '%u'::pg_catalog.oid "
12975 "ORDER BY amprocnum",
12976 opcinfo->dobj.catId.oid);
12979 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12981 ntups = PQntuples(res);
12983 i_amprocnum = PQfnumber(res, "amprocnum");
12984 i_amproc = PQfnumber(res, "amproc");
12985 i_amproclefttype = PQfnumber(res, "amproclefttype");
12986 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12988 for (i = 0; i < ntups; i++)
12990 amprocnum = PQgetvalue(res, i, i_amprocnum);
12991 amproc = PQgetvalue(res, i, i_amproc);
12992 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12993 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12996 appendPQExpBufferStr(q, " ,\n ");
12998 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
13000 if (*amproclefttype && *amprocrighttype)
13001 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13003 appendPQExpBuffer(q, " %s", amproc);
13011 * If needComma is still false it means we haven't added anything after
13012 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13013 * clause with the same datatype. This isn't sanctioned by the
13014 * documentation, but actually DefineOpClass will treat it as a no-op.
13017 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13019 appendPQExpBufferStr(q, ";\n");
13021 appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13022 appendPQExpBuffer(nameusing, " USING %s",
13025 if (dopt->binary_upgrade)
13026 binary_upgrade_extension_member(q, &opcinfo->dobj,
13027 "OPERATOR CLASS", nameusing->data,
13028 opcinfo->dobj.namespace->dobj.name);
13030 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13031 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13032 opcinfo->dobj.name,
13033 opcinfo->dobj.namespace->dobj.name,
13036 false, "OPERATOR CLASS", SECTION_PRE_DATA,
13037 q->data, delq->data, NULL,
13041 /* Dump Operator Class Comments */
13042 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13043 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13044 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13045 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13050 destroyPQExpBuffer(query);
13051 destroyPQExpBuffer(q);
13052 destroyPQExpBuffer(delq);
13053 destroyPQExpBuffer(nameusing);
13058 * write out a single operator family definition
13060 * Note: this also dumps any "loose" operator members that aren't bound to a
13061 * specific opclass within the opfamily.
13064 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13066 DumpOptions *dopt = fout->dopt;
13070 PQExpBuffer nameusing;
13073 PGresult *res_procs;
13076 int i_amopstrategy;
13077 int i_amopreqcheck;
13080 int i_sortfamilynsp;
13083 int i_amproclefttype;
13084 int i_amprocrighttype;
13086 char *amopstrategy;
13087 char *amopreqcheck;
13090 char *sortfamilynsp;
13093 char *amproclefttype;
13094 char *amprocrighttype;
13098 /* Skip if not to be dumped */
13099 if (!opfinfo->dobj.dump || dopt->dataOnly)
13102 query = createPQExpBuffer();
13103 q = createPQExpBuffer();
13104 delq = createPQExpBuffer();
13105 nameusing = createPQExpBuffer();
13108 * Fetch only those opfamily members that are tied directly to the
13109 * opfamily by pg_depend entries.
13111 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13112 * older server's opclass in which it is used. This is to avoid
13113 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13114 * older server and then reload into that old version. This can go away
13115 * once 8.3 is so old as to not be of interest to anyone.
13117 if (fout->remoteVersion >= 90100)
13119 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13120 "amopopr::pg_catalog.regoperator, "
13121 "opfname AS sortfamily, "
13122 "nspname AS sortfamilynsp "
13123 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13124 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13125 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13126 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13127 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13128 "AND refobjid = '%u'::pg_catalog.oid "
13129 "AND amopfamily = '%u'::pg_catalog.oid "
13130 "ORDER BY amopstrategy",
13131 opfinfo->dobj.catId.oid,
13132 opfinfo->dobj.catId.oid);
13134 else if (fout->remoteVersion >= 80400)
13136 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13137 "amopopr::pg_catalog.regoperator, "
13138 "NULL AS sortfamily, "
13139 "NULL AS sortfamilynsp "
13140 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13141 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13142 "AND refobjid = '%u'::pg_catalog.oid "
13143 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13144 "AND objid = ao.oid "
13145 "ORDER BY amopstrategy",
13146 opfinfo->dobj.catId.oid);
13150 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13151 "amopopr::pg_catalog.regoperator, "
13152 "NULL AS sortfamily, "
13153 "NULL AS sortfamilynsp "
13154 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13155 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13156 "AND refobjid = '%u'::pg_catalog.oid "
13157 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13158 "AND objid = ao.oid "
13159 "ORDER BY amopstrategy",
13160 opfinfo->dobj.catId.oid);
13163 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13165 resetPQExpBuffer(query);
13167 appendPQExpBuffer(query, "SELECT amprocnum, "
13168 "amproc::pg_catalog.regprocedure, "
13169 "amproclefttype::pg_catalog.regtype, "
13170 "amprocrighttype::pg_catalog.regtype "
13171 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13172 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13173 "AND refobjid = '%u'::pg_catalog.oid "
13174 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13175 "AND objid = ap.oid "
13176 "ORDER BY amprocnum",
13177 opfinfo->dobj.catId.oid);
13179 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13181 /* Get additional fields from the pg_opfamily row */
13182 resetPQExpBuffer(query);
13184 appendPQExpBuffer(query, "SELECT "
13185 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13186 "FROM pg_catalog.pg_opfamily "
13187 "WHERE oid = '%u'::pg_catalog.oid",
13188 opfinfo->dobj.catId.oid);
13190 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13192 i_amname = PQfnumber(res, "amname");
13194 /* amname will still be needed after we PQclear res */
13195 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13197 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13198 fmtQualifiedDumpable(opfinfo));
13199 appendPQExpBuffer(delq, " USING %s;\n",
13202 /* Build the fixed portion of the CREATE command */
13203 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13204 fmtQualifiedDumpable(opfinfo));
13205 appendPQExpBuffer(q, " USING %s;\n",
13210 /* Do we need an ALTER to add loose members? */
13211 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13213 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13214 fmtQualifiedDumpable(opfinfo));
13215 appendPQExpBuffer(q, " USING %s ADD\n ",
13221 * Now fetch and print the OPERATOR entries (pg_amop rows).
13223 ntups = PQntuples(res_ops);
13225 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13226 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13227 i_amopopr = PQfnumber(res_ops, "amopopr");
13228 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13229 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13231 for (i = 0; i < ntups; i++)
13233 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13234 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13235 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13236 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13237 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13240 appendPQExpBufferStr(q, " ,\n ");
13242 appendPQExpBuffer(q, "OPERATOR %s %s",
13243 amopstrategy, amopopr);
13245 if (strlen(sortfamily) > 0)
13247 appendPQExpBufferStr(q, " FOR ORDER BY ");
13248 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13249 appendPQExpBufferStr(q, fmtId(sortfamily));
13252 if (strcmp(amopreqcheck, "t") == 0)
13253 appendPQExpBufferStr(q, " RECHECK");
13259 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13261 ntups = PQntuples(res_procs);
13263 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13264 i_amproc = PQfnumber(res_procs, "amproc");
13265 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13266 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13268 for (i = 0; i < ntups; i++)
13270 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13271 amproc = PQgetvalue(res_procs, i, i_amproc);
13272 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13273 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13276 appendPQExpBufferStr(q, " ,\n ");
13278 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13279 amprocnum, amproclefttype, amprocrighttype,
13285 appendPQExpBufferStr(q, ";\n");
13288 appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13289 appendPQExpBuffer(nameusing, " USING %s",
13292 if (dopt->binary_upgrade)
13293 binary_upgrade_extension_member(q, &opfinfo->dobj,
13294 "OPERATOR FAMILY", nameusing->data,
13295 opfinfo->dobj.namespace->dobj.name);
13297 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13298 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13299 opfinfo->dobj.name,
13300 opfinfo->dobj.namespace->dobj.name,
13303 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13304 q->data, delq->data, NULL,
13308 /* Dump Operator Family Comments */
13309 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13310 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13311 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13312 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13316 PQclear(res_procs);
13317 destroyPQExpBuffer(query);
13318 destroyPQExpBuffer(q);
13319 destroyPQExpBuffer(delq);
13320 destroyPQExpBuffer(nameusing);
13325 * write out a single collation definition
13328 dumpCollation(Archive *fout, CollInfo *collinfo)
13330 DumpOptions *dopt = fout->dopt;
13336 int i_collprovider;
13339 const char *collprovider;
13340 const char *collcollate;
13341 const char *collctype;
13343 /* Skip if not to be dumped */
13344 if (!collinfo->dobj.dump || dopt->dataOnly)
13347 query = createPQExpBuffer();
13348 q = createPQExpBuffer();
13349 delq = createPQExpBuffer();
13351 qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13353 /* Get collation-specific details */
13354 if (fout->remoteVersion >= 100000)
13355 appendPQExpBuffer(query, "SELECT "
13360 "FROM pg_catalog.pg_collation c "
13361 "WHERE c.oid = '%u'::pg_catalog.oid",
13362 collinfo->dobj.catId.oid);
13364 appendPQExpBuffer(query, "SELECT "
13365 "'c' AS collprovider, "
13368 "NULL AS collversion "
13369 "FROM pg_catalog.pg_collation c "
13370 "WHERE c.oid = '%u'::pg_catalog.oid",
13371 collinfo->dobj.catId.oid);
13373 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13375 i_collprovider = PQfnumber(res, "collprovider");
13376 i_collcollate = PQfnumber(res, "collcollate");
13377 i_collctype = PQfnumber(res, "collctype");
13379 collprovider = PQgetvalue(res, 0, i_collprovider);
13380 collcollate = PQgetvalue(res, 0, i_collcollate);
13381 collctype = PQgetvalue(res, 0, i_collctype);
13383 appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13384 fmtQualifiedDumpable(collinfo));
13386 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13387 fmtQualifiedDumpable(collinfo));
13389 appendPQExpBufferStr(q, "provider = ");
13390 if (collprovider[0] == 'c')
13391 appendPQExpBufferStr(q, "libc");
13392 else if (collprovider[0] == 'i')
13393 appendPQExpBufferStr(q, "icu");
13394 else if (collprovider[0] == 'd')
13395 /* to allow dumping pg_catalog; not accepted on input */
13396 appendPQExpBufferStr(q, "default");
13398 exit_horribly(NULL,
13399 "unrecognized collation provider: %s\n",
13402 if (strcmp(collcollate, collctype) == 0)
13404 appendPQExpBufferStr(q, ", locale = ");
13405 appendStringLiteralAH(q, collcollate, fout);
13409 appendPQExpBufferStr(q, ", lc_collate = ");
13410 appendStringLiteralAH(q, collcollate, fout);
13411 appendPQExpBufferStr(q, ", lc_ctype = ");
13412 appendStringLiteralAH(q, collctype, fout);
13416 * For binary upgrade, carry over the collation version. For normal
13417 * dump/restore, omit the version, so that it is computed upon restore.
13419 if (dopt->binary_upgrade)
13423 i_collversion = PQfnumber(res, "collversion");
13424 if (!PQgetisnull(res, 0, i_collversion))
13426 appendPQExpBufferStr(q, ", version = ");
13427 appendStringLiteralAH(q,
13428 PQgetvalue(res, 0, i_collversion),
13433 appendPQExpBufferStr(q, ");\n");
13435 if (dopt->binary_upgrade)
13436 binary_upgrade_extension_member(q, &collinfo->dobj,
13437 "COLLATION", qcollname,
13438 collinfo->dobj.namespace->dobj.name);
13440 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13441 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13442 collinfo->dobj.name,
13443 collinfo->dobj.namespace->dobj.name,
13446 false, "COLLATION", SECTION_PRE_DATA,
13447 q->data, delq->data, NULL,
13451 /* Dump Collation Comments */
13452 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13453 dumpComment(fout, "COLLATION", qcollname,
13454 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13455 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13459 destroyPQExpBuffer(query);
13460 destroyPQExpBuffer(q);
13461 destroyPQExpBuffer(delq);
13467 * write out a single conversion definition
13470 dumpConversion(Archive *fout, ConvInfo *convinfo)
13472 DumpOptions *dopt = fout->dopt;
13478 int i_conforencoding;
13479 int i_contoencoding;
13482 const char *conforencoding;
13483 const char *contoencoding;
13484 const char *conproc;
13487 /* Skip if not to be dumped */
13488 if (!convinfo->dobj.dump || dopt->dataOnly)
13491 query = createPQExpBuffer();
13492 q = createPQExpBuffer();
13493 delq = createPQExpBuffer();
13495 qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13497 /* Get conversion-specific details */
13498 appendPQExpBuffer(query, "SELECT "
13499 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13500 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13501 "conproc, condefault "
13502 "FROM pg_catalog.pg_conversion c "
13503 "WHERE c.oid = '%u'::pg_catalog.oid",
13504 convinfo->dobj.catId.oid);
13506 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13508 i_conforencoding = PQfnumber(res, "conforencoding");
13509 i_contoencoding = PQfnumber(res, "contoencoding");
13510 i_conproc = PQfnumber(res, "conproc");
13511 i_condefault = PQfnumber(res, "condefault");
13513 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13514 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13515 conproc = PQgetvalue(res, 0, i_conproc);
13516 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13518 appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13519 fmtQualifiedDumpable(convinfo));
13521 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13522 (condefault) ? "DEFAULT " : "",
13523 fmtQualifiedDumpable(convinfo));
13524 appendStringLiteralAH(q, conforencoding, fout);
13525 appendPQExpBufferStr(q, " TO ");
13526 appendStringLiteralAH(q, contoencoding, fout);
13527 /* regproc output is already sufficiently quoted */
13528 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13530 if (dopt->binary_upgrade)
13531 binary_upgrade_extension_member(q, &convinfo->dobj,
13532 "CONVERSION", qconvname,
13533 convinfo->dobj.namespace->dobj.name);
13535 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13536 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13537 convinfo->dobj.name,
13538 convinfo->dobj.namespace->dobj.name,
13541 false, "CONVERSION", SECTION_PRE_DATA,
13542 q->data, delq->data, NULL,
13546 /* Dump Conversion Comments */
13547 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13548 dumpComment(fout, "CONVERSION", qconvname,
13549 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13550 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13554 destroyPQExpBuffer(query);
13555 destroyPQExpBuffer(q);
13556 destroyPQExpBuffer(delq);
13561 * format_aggregate_signature: generate aggregate name and argument list
13563 * The argument type names are qualified if needed. The aggregate name
13564 * is never qualified.
13567 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13569 PQExpBufferData buf;
13572 initPQExpBuffer(&buf);
13574 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13576 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13578 if (agginfo->aggfn.nargs == 0)
13579 appendPQExpBuffer(&buf, "(*)");
13582 appendPQExpBufferChar(&buf, '(');
13583 for (j = 0; j < agginfo->aggfn.nargs; j++)
13587 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13590 appendPQExpBuffer(&buf, "%s%s",
13591 (j > 0) ? ", " : "",
13595 appendPQExpBufferChar(&buf, ')');
13602 * write out a single aggregate definition
13605 dumpAgg(Archive *fout, AggInfo *agginfo)
13607 DumpOptions *dopt = fout->dopt;
13611 PQExpBuffer details;
13612 char *aggsig; /* identity signature */
13613 char *aggfullsig = NULL; /* full signature */
13618 int i_aggcombinefn;
13620 int i_aggdeserialfn;
13622 int i_aggminvtransfn;
13624 int i_aggfinalextra;
13625 int i_aggmfinalextra;
13626 int i_aggfinalmodify;
13627 int i_aggmfinalmodify;
13630 int i_aggtranstype;
13631 int i_aggtransspace;
13632 int i_aggmtranstype;
13633 int i_aggmtransspace;
13638 const char *aggtransfn;
13639 const char *aggfinalfn;
13640 const char *aggcombinefn;
13641 const char *aggserialfn;
13642 const char *aggdeserialfn;
13643 const char *aggmtransfn;
13644 const char *aggminvtransfn;
13645 const char *aggmfinalfn;
13646 bool aggfinalextra;
13647 bool aggmfinalextra;
13648 char aggfinalmodify;
13649 char aggmfinalmodify;
13650 const char *aggsortop;
13651 char *aggsortconvop;
13653 const char *aggtranstype;
13654 const char *aggtransspace;
13655 const char *aggmtranstype;
13656 const char *aggmtransspace;
13657 const char *agginitval;
13658 const char *aggminitval;
13660 const char *proparallel;
13661 char defaultfinalmodify;
13663 /* Skip if not to be dumped */
13664 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13667 query = createPQExpBuffer();
13668 q = createPQExpBuffer();
13669 delq = createPQExpBuffer();
13670 details = createPQExpBuffer();
13672 /* Get aggregate-specific details */
13673 if (fout->remoteVersion >= 110000)
13675 appendPQExpBuffer(query, "SELECT aggtransfn, "
13676 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13677 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13678 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13679 "aggfinalextra, aggmfinalextra, "
13680 "aggfinalmodify, aggmfinalmodify, "
13683 "aggtransspace, agginitval, "
13684 "aggmtransspace, aggminitval, "
13685 "true AS convertok, "
13686 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13687 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13689 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13690 "WHERE a.aggfnoid = p.oid "
13691 "AND p.oid = '%u'::pg_catalog.oid",
13692 agginfo->aggfn.dobj.catId.oid);
13694 else if (fout->remoteVersion >= 90600)
13696 appendPQExpBuffer(query, "SELECT aggtransfn, "
13697 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13698 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13699 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13700 "aggfinalextra, aggmfinalextra, "
13701 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13704 "aggtransspace, agginitval, "
13705 "aggmtransspace, aggminitval, "
13706 "true AS convertok, "
13707 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13708 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13710 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13711 "WHERE a.aggfnoid = p.oid "
13712 "AND p.oid = '%u'::pg_catalog.oid",
13713 agginfo->aggfn.dobj.catId.oid);
13715 else if (fout->remoteVersion >= 90400)
13717 appendPQExpBuffer(query, "SELECT aggtransfn, "
13718 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13719 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13720 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13721 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13722 "aggfinalextra, aggmfinalextra, "
13723 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13726 "aggtransspace, agginitval, "
13727 "aggmtransspace, aggminitval, "
13728 "true AS convertok, "
13729 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13730 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13731 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13732 "WHERE a.aggfnoid = p.oid "
13733 "AND p.oid = '%u'::pg_catalog.oid",
13734 agginfo->aggfn.dobj.catId.oid);
13736 else if (fout->remoteVersion >= 80400)
13738 appendPQExpBuffer(query, "SELECT aggtransfn, "
13739 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13740 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13741 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13742 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13743 "0 AS aggmtranstype, false AS aggfinalextra, "
13744 "false AS aggmfinalextra, "
13745 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13748 "0 AS aggtransspace, agginitval, "
13749 "0 AS aggmtransspace, NULL AS aggminitval, "
13750 "true AS convertok, "
13751 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13752 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13753 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13754 "WHERE a.aggfnoid = p.oid "
13755 "AND p.oid = '%u'::pg_catalog.oid",
13756 agginfo->aggfn.dobj.catId.oid);
13758 else if (fout->remoteVersion >= 80100)
13760 appendPQExpBuffer(query, "SELECT aggtransfn, "
13761 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13762 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13763 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13764 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13765 "0 AS aggmtranstype, false AS aggfinalextra, "
13766 "false AS aggmfinalextra, "
13767 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13770 "0 AS aggtransspace, agginitval, "
13771 "0 AS aggmtransspace, NULL AS aggminitval, "
13772 "true AS convertok "
13773 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13774 "WHERE a.aggfnoid = p.oid "
13775 "AND p.oid = '%u'::pg_catalog.oid",
13776 agginfo->aggfn.dobj.catId.oid);
13780 appendPQExpBuffer(query, "SELECT aggtransfn, "
13781 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13782 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13783 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13784 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13785 "0 AS aggmtranstype, false AS aggfinalextra, "
13786 "false AS aggmfinalextra, "
13787 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13790 "0 AS aggtransspace, agginitval, "
13791 "0 AS aggmtransspace, NULL AS aggminitval, "
13792 "true AS convertok "
13793 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13794 "WHERE a.aggfnoid = p.oid "
13795 "AND p.oid = '%u'::pg_catalog.oid",
13796 agginfo->aggfn.dobj.catId.oid);
13799 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13801 i_aggtransfn = PQfnumber(res, "aggtransfn");
13802 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13803 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13804 i_aggserialfn = PQfnumber(res, "aggserialfn");
13805 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13806 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13807 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13808 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13809 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13810 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13811 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13812 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13813 i_aggsortop = PQfnumber(res, "aggsortop");
13814 i_aggkind = PQfnumber(res, "aggkind");
13815 i_aggtranstype = PQfnumber(res, "aggtranstype");
13816 i_aggtransspace = PQfnumber(res, "aggtransspace");
13817 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13818 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13819 i_agginitval = PQfnumber(res, "agginitval");
13820 i_aggminitval = PQfnumber(res, "aggminitval");
13821 i_convertok = PQfnumber(res, "convertok");
13822 i_proparallel = PQfnumber(res, "proparallel");
13824 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13825 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13826 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13827 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13828 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13829 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13830 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13831 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13832 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13833 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13834 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13835 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13836 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13837 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13838 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13839 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13840 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13841 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13842 agginitval = PQgetvalue(res, 0, i_agginitval);
13843 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13844 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13846 if (fout->remoteVersion >= 80400)
13848 /* 8.4 or later; we rely on server-side code for most of the work */
13852 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13853 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13854 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13855 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13858 /* pre-8.4, do it ourselves */
13859 aggsig = format_aggregate_signature(agginfo, fout, true);
13861 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13863 if (i_proparallel != -1)
13864 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13866 proparallel = NULL;
13870 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13881 /* identify default modify flag for aggkind (must match DefineAggregate) */
13882 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13883 /* replace omitted flags for old versions */
13884 if (aggfinalmodify == '0')
13885 aggfinalmodify = defaultfinalmodify;
13886 if (aggmfinalmodify == '0')
13887 aggmfinalmodify = defaultfinalmodify;
13889 /* regproc and regtype output is already sufficiently quoted */
13890 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13891 aggtransfn, aggtranstype);
13893 if (strcmp(aggtransspace, "0") != 0)
13895 appendPQExpBuffer(details, ",\n SSPACE = %s",
13899 if (!PQgetisnull(res, 0, i_agginitval))
13901 appendPQExpBufferStr(details, ",\n INITCOND = ");
13902 appendStringLiteralAH(details, agginitval, fout);
13905 if (strcmp(aggfinalfn, "-") != 0)
13907 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13910 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13911 if (aggfinalmodify != defaultfinalmodify)
13913 switch (aggfinalmodify)
13915 case AGGMODIFY_READ_ONLY:
13916 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
13918 case AGGMODIFY_SHAREABLE:
13919 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
13921 case AGGMODIFY_READ_WRITE:
13922 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
13925 exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13926 agginfo->aggfn.dobj.name);
13932 if (strcmp(aggcombinefn, "-") != 0)
13933 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
13935 if (strcmp(aggserialfn, "-") != 0)
13936 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
13938 if (strcmp(aggdeserialfn, "-") != 0)
13939 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
13941 if (strcmp(aggmtransfn, "-") != 0)
13943 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
13949 if (strcmp(aggmtransspace, "0") != 0)
13951 appendPQExpBuffer(details, ",\n MSSPACE = %s",
13955 if (!PQgetisnull(res, 0, i_aggminitval))
13957 appendPQExpBufferStr(details, ",\n MINITCOND = ");
13958 appendStringLiteralAH(details, aggminitval, fout);
13961 if (strcmp(aggmfinalfn, "-") != 0)
13963 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
13965 if (aggmfinalextra)
13966 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
13967 if (aggmfinalmodify != defaultfinalmodify)
13969 switch (aggmfinalmodify)
13971 case AGGMODIFY_READ_ONLY:
13972 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
13974 case AGGMODIFY_SHAREABLE:
13975 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
13977 case AGGMODIFY_READ_WRITE:
13978 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
13981 exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13982 agginfo->aggfn.dobj.name);
13988 aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13991 appendPQExpBuffer(details, ",\n SORTOP = %s",
13993 free(aggsortconvop);
13996 if (aggkind == AGGKIND_HYPOTHETICAL)
13997 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
13999 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
14001 if (proparallel[0] == PROPARALLEL_SAFE)
14002 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
14003 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14004 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
14005 else if (proparallel[0] != PROPARALLEL_UNSAFE)
14006 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
14007 agginfo->aggfn.dobj.name);
14010 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14011 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14014 appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14015 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14016 aggfullsig ? aggfullsig : aggsig, details->data);
14018 if (dopt->binary_upgrade)
14019 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14020 "AGGREGATE", aggsig,
14021 agginfo->aggfn.dobj.namespace->dobj.name);
14023 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14024 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14025 agginfo->aggfn.dobj.dumpId,
14027 agginfo->aggfn.dobj.namespace->dobj.name,
14029 agginfo->aggfn.rolname,
14030 false, "AGGREGATE", SECTION_PRE_DATA,
14031 q->data, delq->data, NULL,
14035 /* Dump Aggregate Comments */
14036 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14037 dumpComment(fout, "AGGREGATE", aggsig,
14038 agginfo->aggfn.dobj.namespace->dobj.name,
14039 agginfo->aggfn.rolname,
14040 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14042 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14043 dumpSecLabel(fout, "AGGREGATE", aggsig,
14044 agginfo->aggfn.dobj.namespace->dobj.name,
14045 agginfo->aggfn.rolname,
14046 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14049 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14050 * command look like a function's GRANT; in particular this affects the
14051 * syntax for zero-argument aggregates and ordered-set aggregates.
14055 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14057 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14058 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
14059 "FUNCTION", aggsig, NULL,
14060 agginfo->aggfn.dobj.namespace->dobj.name,
14061 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14062 agginfo->aggfn.rproacl,
14063 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14072 destroyPQExpBuffer(query);
14073 destroyPQExpBuffer(q);
14074 destroyPQExpBuffer(delq);
14075 destroyPQExpBuffer(details);
14080 * write out a single text search parser
14083 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14085 DumpOptions *dopt = fout->dopt;
14090 /* Skip if not to be dumped */
14091 if (!prsinfo->dobj.dump || dopt->dataOnly)
14094 q = createPQExpBuffer();
14095 delq = createPQExpBuffer();
14097 qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14099 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14100 fmtQualifiedDumpable(prsinfo));
14102 appendPQExpBuffer(q, " START = %s,\n",
14103 convertTSFunction(fout, prsinfo->prsstart));
14104 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14105 convertTSFunction(fout, prsinfo->prstoken));
14106 appendPQExpBuffer(q, " END = %s,\n",
14107 convertTSFunction(fout, prsinfo->prsend));
14108 if (prsinfo->prsheadline != InvalidOid)
14109 appendPQExpBuffer(q, " HEADLINE = %s,\n",
14110 convertTSFunction(fout, prsinfo->prsheadline));
14111 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14112 convertTSFunction(fout, prsinfo->prslextype));
14114 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14115 fmtQualifiedDumpable(prsinfo));
14117 if (dopt->binary_upgrade)
14118 binary_upgrade_extension_member(q, &prsinfo->dobj,
14119 "TEXT SEARCH PARSER", qprsname,
14120 prsinfo->dobj.namespace->dobj.name);
14122 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14123 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14124 prsinfo->dobj.name,
14125 prsinfo->dobj.namespace->dobj.name,
14128 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14129 q->data, delq->data, NULL,
14133 /* Dump Parser Comments */
14134 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14135 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14136 prsinfo->dobj.namespace->dobj.name, "",
14137 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14139 destroyPQExpBuffer(q);
14140 destroyPQExpBuffer(delq);
14146 * write out a single text search dictionary
14149 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14151 DumpOptions *dopt = fout->dopt;
14160 /* Skip if not to be dumped */
14161 if (!dictinfo->dobj.dump || dopt->dataOnly)
14164 q = createPQExpBuffer();
14165 delq = createPQExpBuffer();
14166 query = createPQExpBuffer();
14168 qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14170 /* Fetch name and namespace of the dictionary's template */
14171 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14172 "FROM pg_ts_template p, pg_namespace n "
14173 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14174 dictinfo->dicttemplate);
14175 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14176 nspname = PQgetvalue(res, 0, 0);
14177 tmplname = PQgetvalue(res, 0, 1);
14179 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14180 fmtQualifiedDumpable(dictinfo));
14182 appendPQExpBufferStr(q, " TEMPLATE = ");
14183 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14184 appendPQExpBufferStr(q, fmtId(tmplname));
14188 /* the dictinitoption can be dumped straight into the command */
14189 if (dictinfo->dictinitoption)
14190 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14192 appendPQExpBufferStr(q, " );\n");
14194 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14195 fmtQualifiedDumpable(dictinfo));
14197 if (dopt->binary_upgrade)
14198 binary_upgrade_extension_member(q, &dictinfo->dobj,
14199 "TEXT SEARCH DICTIONARY", qdictname,
14200 dictinfo->dobj.namespace->dobj.name);
14202 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14203 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14204 dictinfo->dobj.name,
14205 dictinfo->dobj.namespace->dobj.name,
14208 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14209 q->data, delq->data, NULL,
14213 /* Dump Dictionary Comments */
14214 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14215 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14216 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14217 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14219 destroyPQExpBuffer(q);
14220 destroyPQExpBuffer(delq);
14221 destroyPQExpBuffer(query);
14227 * write out a single text search template
14230 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14232 DumpOptions *dopt = fout->dopt;
14237 /* Skip if not to be dumped */
14238 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14241 q = createPQExpBuffer();
14242 delq = createPQExpBuffer();
14244 qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14246 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14247 fmtQualifiedDumpable(tmplinfo));
14249 if (tmplinfo->tmplinit != InvalidOid)
14250 appendPQExpBuffer(q, " INIT = %s,\n",
14251 convertTSFunction(fout, tmplinfo->tmplinit));
14252 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14253 convertTSFunction(fout, tmplinfo->tmpllexize));
14255 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14256 fmtQualifiedDumpable(tmplinfo));
14258 if (dopt->binary_upgrade)
14259 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14260 "TEXT SEARCH TEMPLATE", qtmplname,
14261 tmplinfo->dobj.namespace->dobj.name);
14263 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14264 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14265 tmplinfo->dobj.name,
14266 tmplinfo->dobj.namespace->dobj.name,
14269 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14270 q->data, delq->data, NULL,
14274 /* Dump Template Comments */
14275 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14276 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14277 tmplinfo->dobj.namespace->dobj.name, "",
14278 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14280 destroyPQExpBuffer(q);
14281 destroyPQExpBuffer(delq);
14287 * write out a single text search configuration
14290 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14292 DumpOptions *dopt = fout->dopt;
14305 /* Skip if not to be dumped */
14306 if (!cfginfo->dobj.dump || dopt->dataOnly)
14309 q = createPQExpBuffer();
14310 delq = createPQExpBuffer();
14311 query = createPQExpBuffer();
14313 qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14315 /* Fetch name and namespace of the config's parser */
14316 appendPQExpBuffer(query, "SELECT nspname, prsname "
14317 "FROM pg_ts_parser p, pg_namespace n "
14318 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14319 cfginfo->cfgparser);
14320 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14321 nspname = PQgetvalue(res, 0, 0);
14322 prsname = PQgetvalue(res, 0, 1);
14324 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14325 fmtQualifiedDumpable(cfginfo));
14327 appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14328 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14332 resetPQExpBuffer(query);
14333 appendPQExpBuffer(query,
14335 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14336 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14337 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14338 "FROM pg_catalog.pg_ts_config_map AS m\n"
14339 "WHERE m.mapcfg = '%u'\n"
14340 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14341 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14343 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14344 ntups = PQntuples(res);
14346 i_tokenname = PQfnumber(res, "tokenname");
14347 i_dictname = PQfnumber(res, "dictname");
14349 for (i = 0; i < ntups; i++)
14351 char *tokenname = PQgetvalue(res, i, i_tokenname);
14352 char *dictname = PQgetvalue(res, i, i_dictname);
14355 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14357 /* starting a new token type, so start a new command */
14359 appendPQExpBufferStr(q, ";\n");
14360 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14361 fmtQualifiedDumpable(cfginfo));
14362 /* tokenname needs quoting, dictname does NOT */
14363 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14364 fmtId(tokenname), dictname);
14367 appendPQExpBuffer(q, ", %s", dictname);
14371 appendPQExpBufferStr(q, ";\n");
14375 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14376 fmtQualifiedDumpable(cfginfo));
14378 if (dopt->binary_upgrade)
14379 binary_upgrade_extension_member(q, &cfginfo->dobj,
14380 "TEXT SEARCH CONFIGURATION", qcfgname,
14381 cfginfo->dobj.namespace->dobj.name);
14383 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14384 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14385 cfginfo->dobj.name,
14386 cfginfo->dobj.namespace->dobj.name,
14389 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14390 q->data, delq->data, NULL,
14394 /* Dump Configuration Comments */
14395 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14396 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14397 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14398 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14400 destroyPQExpBuffer(q);
14401 destroyPQExpBuffer(delq);
14402 destroyPQExpBuffer(query);
14407 * dumpForeignDataWrapper
14408 * write out a single foreign-data wrapper definition
14411 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14413 DumpOptions *dopt = fout->dopt;
14418 /* Skip if not to be dumped */
14419 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14422 q = createPQExpBuffer();
14423 delq = createPQExpBuffer();
14425 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14427 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14430 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14431 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14433 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14434 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14436 if (strlen(fdwinfo->fdwoptions) > 0)
14437 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14439 appendPQExpBufferStr(q, ";\n");
14441 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14444 if (dopt->binary_upgrade)
14445 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14446 "FOREIGN DATA WRAPPER", qfdwname,
14449 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14450 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14451 fdwinfo->dobj.name,
14455 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14456 q->data, delq->data, NULL,
14460 /* Dump Foreign Data Wrapper Comments */
14461 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14462 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14463 NULL, fdwinfo->rolname,
14464 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14466 /* Handle the ACL */
14467 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14468 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14469 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14470 NULL, fdwinfo->rolname,
14471 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14472 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14476 destroyPQExpBuffer(q);
14477 destroyPQExpBuffer(delq);
14481 * dumpForeignServer
14482 * write out a foreign server definition
14485 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14487 DumpOptions *dopt = fout->dopt;
14495 /* Skip if not to be dumped */
14496 if (!srvinfo->dobj.dump || dopt->dataOnly)
14499 q = createPQExpBuffer();
14500 delq = createPQExpBuffer();
14501 query = createPQExpBuffer();
14503 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14505 /* look up the foreign-data wrapper */
14506 appendPQExpBuffer(query, "SELECT fdwname "
14507 "FROM pg_foreign_data_wrapper w "
14508 "WHERE w.oid = '%u'",
14510 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14511 fdwname = PQgetvalue(res, 0, 0);
14513 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14514 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14516 appendPQExpBufferStr(q, " TYPE ");
14517 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14519 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14521 appendPQExpBufferStr(q, " VERSION ");
14522 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14525 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14526 appendPQExpBufferStr(q, fmtId(fdwname));
14528 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14529 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14531 appendPQExpBufferStr(q, ";\n");
14533 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14536 if (dopt->binary_upgrade)
14537 binary_upgrade_extension_member(q, &srvinfo->dobj,
14538 "SERVER", qsrvname, NULL);
14540 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14541 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14542 srvinfo->dobj.name,
14546 false, "SERVER", SECTION_PRE_DATA,
14547 q->data, delq->data, NULL,
14551 /* Dump Foreign Server Comments */
14552 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14553 dumpComment(fout, "SERVER", qsrvname,
14554 NULL, srvinfo->rolname,
14555 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14557 /* Handle the ACL */
14558 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14559 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14560 "FOREIGN SERVER", qsrvname, NULL,
14561 NULL, srvinfo->rolname,
14562 srvinfo->srvacl, srvinfo->rsrvacl,
14563 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14565 /* Dump user mappings */
14566 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14567 dumpUserMappings(fout,
14568 srvinfo->dobj.name, NULL,
14570 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14574 destroyPQExpBuffer(q);
14575 destroyPQExpBuffer(delq);
14576 destroyPQExpBuffer(query);
14582 * This routine is used to dump any user mappings associated with the
14583 * server handed to this routine. Should be called after ArchiveEntry()
14587 dumpUserMappings(Archive *fout,
14588 const char *servername, const char *namespace,
14590 CatalogId catalogId, DumpId dumpId)
14602 q = createPQExpBuffer();
14603 tag = createPQExpBuffer();
14604 delq = createPQExpBuffer();
14605 query = createPQExpBuffer();
14608 * We read from the publicly accessible view pg_user_mappings, so as not
14609 * to fail if run by a non-superuser. Note that the view will show
14610 * umoptions as null if the user hasn't got privileges for the associated
14611 * server; this means that pg_dump will dump such a mapping, but with no
14612 * OPTIONS clause. A possible alternative is to skip such mappings
14613 * altogether, but it's not clear that that's an improvement.
14615 appendPQExpBuffer(query,
14617 "array_to_string(ARRAY("
14618 "SELECT quote_ident(option_name) || ' ' || "
14619 "quote_literal(option_value) "
14620 "FROM pg_options_to_table(umoptions) "
14621 "ORDER BY option_name"
14622 "), E',\n ') AS umoptions "
14623 "FROM pg_user_mappings "
14624 "WHERE srvid = '%u' "
14625 "ORDER BY usename",
14628 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14630 ntups = PQntuples(res);
14631 i_usename = PQfnumber(res, "usename");
14632 i_umoptions = PQfnumber(res, "umoptions");
14634 for (i = 0; i < ntups; i++)
14639 usename = PQgetvalue(res, i, i_usename);
14640 umoptions = PQgetvalue(res, i, i_umoptions);
14642 resetPQExpBuffer(q);
14643 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14644 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14646 if (umoptions && strlen(umoptions) > 0)
14647 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14649 appendPQExpBufferStr(q, ";\n");
14651 resetPQExpBuffer(delq);
14652 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14653 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14655 resetPQExpBuffer(tag);
14656 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14657 usename, servername);
14659 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14664 "USER MAPPING", SECTION_PRE_DATA,
14665 q->data, delq->data, NULL,
14672 destroyPQExpBuffer(query);
14673 destroyPQExpBuffer(delq);
14674 destroyPQExpBuffer(tag);
14675 destroyPQExpBuffer(q);
14679 * Write out default privileges information
14682 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14684 DumpOptions *dopt = fout->dopt;
14689 /* Skip if not to be dumped */
14690 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14693 q = createPQExpBuffer();
14694 tag = createPQExpBuffer();
14696 switch (daclinfo->defaclobjtype)
14698 case DEFACLOBJ_RELATION:
14701 case DEFACLOBJ_SEQUENCE:
14702 type = "SEQUENCES";
14704 case DEFACLOBJ_FUNCTION:
14705 type = "FUNCTIONS";
14707 case DEFACLOBJ_TYPE:
14710 case DEFACLOBJ_NAMESPACE:
14714 /* shouldn't get here */
14715 exit_horribly(NULL,
14716 "unrecognized object type in default privileges: %d\n",
14717 (int) daclinfo->defaclobjtype);
14718 type = ""; /* keep compiler quiet */
14721 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14723 /* build the actual command(s) for this tuple */
14724 if (!buildDefaultACLCommands(type,
14725 daclinfo->dobj.namespace != NULL ?
14726 daclinfo->dobj.namespace->dobj.name : NULL,
14727 daclinfo->defaclacl,
14728 daclinfo->rdefaclacl,
14729 daclinfo->initdefaclacl,
14730 daclinfo->initrdefaclacl,
14731 daclinfo->defaclrole,
14732 fout->remoteVersion,
14734 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14735 daclinfo->defaclacl);
14737 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14738 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14740 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14742 daclinfo->defaclrole,
14743 false, "DEFAULT ACL", SECTION_POST_DATA,
14748 destroyPQExpBuffer(tag);
14749 destroyPQExpBuffer(q);
14753 * Write out grant/revoke information
14755 * 'objCatId' is the catalog ID of the underlying object.
14756 * 'objDumpId' is the dump ID of the underlying object.
14757 * 'type' must be one of
14758 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14759 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14760 * 'name' is the formatted name of the object. Must be quoted etc. already.
14761 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14762 * (Currently we assume that subname is only provided for table columns.)
14763 * 'nspname' is the namespace the object is in (NULL if none).
14764 * 'owner' is the owner, NULL if there is no owner (for languages).
14765 * 'acls' contains the ACL string of the object from the appropriate system
14766 * catalog field; it will be passed to buildACLCommands for building the
14767 * appropriate GRANT commands.
14768 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14769 * object; it will be passed to buildACLCommands for building the
14770 * appropriate REVOKE commands.
14771 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14772 * privileges, to be recorded into pg_init_privs
14773 * 'initracls' In binary-upgrade mode, ACL string of the object's
14774 * revoked-from-default privileges, to be recorded into pg_init_privs
14776 * NB: initacls/initracls are needed because extensions can set privileges on
14777 * an object during the extension's script file and we record those into
14778 * pg_init_privs as that object's initial privileges.
14782 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14783 const char *type, const char *name, const char *subname,
14784 const char *nspname, const char *owner,
14785 const char *acls, const char *racls,
14786 const char *initacls, const char *initracls)
14788 DumpOptions *dopt = fout->dopt;
14791 /* Do nothing if ACL dump is not enabled */
14792 if (dopt->aclsSkip)
14795 /* --data-only skips ACLs *except* BLOB ACLs */
14796 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14799 sql = createPQExpBuffer();
14802 * Check to see if this object has had any initial ACLs included for it.
14803 * If so, we are in binary upgrade mode and these are the ACLs to turn
14804 * into GRANT and REVOKE statements to set and record the initial
14805 * privileges for an extension object. Let the backend know that these
14806 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14807 * before and after.
14809 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14811 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14812 if (!buildACLCommands(name, subname, nspname, type,
14813 initacls, initracls, owner,
14814 "", fout->remoteVersion, sql))
14815 exit_horribly(NULL,
14816 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14817 initacls, initracls, name, type);
14818 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14821 if (!buildACLCommands(name, subname, nspname, type,
14822 acls, racls, owner,
14823 "", fout->remoteVersion, sql))
14824 exit_horribly(NULL,
14825 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14826 acls, racls, name, type);
14830 PQExpBuffer tag = createPQExpBuffer();
14833 appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14835 appendPQExpBuffer(tag, "%s %s", type, name);
14837 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14838 tag->data, nspname,
14840 owner ? owner : "",
14841 false, "ACL", SECTION_NONE,
14842 sql->data, "", NULL,
14845 destroyPQExpBuffer(tag);
14848 destroyPQExpBuffer(sql);
14854 * This routine is used to dump any security labels associated with the
14855 * object handed to this routine. The routine takes the object type
14856 * and object name (ready to print, except for schema decoration), plus
14857 * the namespace and owner of the object (for labeling the ArchiveEntry),
14858 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14859 * plus the dump ID for the object (for setting a dependency).
14860 * If a matching pg_seclabel entry is found, it is dumped.
14862 * Note: although this routine takes a dumpId for dependency purposes,
14863 * that purpose is just to mark the dependency in the emitted dump file
14864 * for possible future use by pg_restore. We do NOT use it for determining
14865 * ordering of the label in the dump file, because this routine is called
14866 * after dependency sorting occurs. This routine should be called just after
14867 * calling ArchiveEntry() for the specified object.
14870 dumpSecLabel(Archive *fout, const char *type, const char *name,
14871 const char *namespace, const char *owner,
14872 CatalogId catalogId, int subid, DumpId dumpId)
14874 DumpOptions *dopt = fout->dopt;
14875 SecLabelItem *labels;
14880 /* do nothing, if --no-security-labels is supplied */
14881 if (dopt->no_security_labels)
14884 /* Security labels are schema not data ... except blob labels are data */
14885 if (strcmp(type, "LARGE OBJECT") != 0)
14887 if (dopt->dataOnly)
14892 /* We do dump blob security labels in binary-upgrade mode */
14893 if (dopt->schemaOnly && !dopt->binary_upgrade)
14897 /* Search for security labels associated with catalogId, using table */
14898 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14900 query = createPQExpBuffer();
14902 for (i = 0; i < nlabels; i++)
14905 * Ignore label entries for which the subid doesn't match.
14907 if (labels[i].objsubid != subid)
14910 appendPQExpBuffer(query,
14911 "SECURITY LABEL FOR %s ON %s ",
14912 fmtId(labels[i].provider), type);
14913 if (namespace && *namespace)
14914 appendPQExpBuffer(query, "%s.", fmtId(namespace));
14915 appendPQExpBuffer(query, "%s IS ", name);
14916 appendStringLiteralAH(query, labels[i].label, fout);
14917 appendPQExpBufferStr(query, ";\n");
14920 if (query->len > 0)
14922 PQExpBuffer tag = createPQExpBuffer();
14924 appendPQExpBuffer(tag, "%s %s", type, name);
14925 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14926 tag->data, namespace, NULL, owner,
14927 false, "SECURITY LABEL", SECTION_NONE,
14928 query->data, "", NULL,
14931 destroyPQExpBuffer(tag);
14934 destroyPQExpBuffer(query);
14938 * dumpTableSecLabel
14940 * As above, but dump security label for both the specified table (or view)
14944 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14946 DumpOptions *dopt = fout->dopt;
14947 SecLabelItem *labels;
14951 PQExpBuffer target;
14953 /* do nothing, if --no-security-labels is supplied */
14954 if (dopt->no_security_labels)
14957 /* SecLabel are SCHEMA not data */
14958 if (dopt->dataOnly)
14961 /* Search for comments associated with relation, using table */
14962 nlabels = findSecLabels(fout,
14963 tbinfo->dobj.catId.tableoid,
14964 tbinfo->dobj.catId.oid,
14967 /* If security labels exist, build SECURITY LABEL statements */
14971 query = createPQExpBuffer();
14972 target = createPQExpBuffer();
14974 for (i = 0; i < nlabels; i++)
14976 const char *colname;
14977 const char *provider = labels[i].provider;
14978 const char *label = labels[i].label;
14979 int objsubid = labels[i].objsubid;
14981 resetPQExpBuffer(target);
14984 appendPQExpBuffer(target, "%s %s", reltypename,
14985 fmtQualifiedDumpable(tbinfo));
14989 colname = getAttrName(objsubid, tbinfo);
14990 /* first fmtXXX result must be consumed before calling again */
14991 appendPQExpBuffer(target, "COLUMN %s",
14992 fmtQualifiedDumpable(tbinfo));
14993 appendPQExpBuffer(target, ".%s", fmtId(colname));
14995 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14996 fmtId(provider), target->data);
14997 appendStringLiteralAH(query, label, fout);
14998 appendPQExpBufferStr(query, ";\n");
15000 if (query->len > 0)
15002 resetPQExpBuffer(target);
15003 appendPQExpBuffer(target, "%s %s", reltypename,
15004 fmtId(tbinfo->dobj.name));
15005 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15007 tbinfo->dobj.namespace->dobj.name,
15008 NULL, tbinfo->rolname,
15009 false, "SECURITY LABEL", SECTION_NONE,
15010 query->data, "", NULL,
15011 &(tbinfo->dobj.dumpId), 1,
15014 destroyPQExpBuffer(query);
15015 destroyPQExpBuffer(target);
15021 * Find the security label(s), if any, associated with the given object.
15022 * All the objsubid values associated with the given classoid/objoid are
15023 * found with one search.
15026 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15028 /* static storage for table of security labels */
15029 static SecLabelItem *labels = NULL;
15030 static int nlabels = -1;
15032 SecLabelItem *middle = NULL;
15034 SecLabelItem *high;
15037 /* Get security labels if we didn't already */
15039 nlabels = collectSecLabels(fout, &labels);
15041 if (nlabels <= 0) /* no labels, so no match is possible */
15048 * Do binary search to find some item matching the object.
15051 high = &labels[nlabels - 1];
15052 while (low <= high)
15054 middle = low + (high - low) / 2;
15056 if (classoid < middle->classoid)
15058 else if (classoid > middle->classoid)
15060 else if (objoid < middle->objoid)
15062 else if (objoid > middle->objoid)
15065 break; /* found a match */
15068 if (low > high) /* no matches */
15075 * Now determine how many items match the object. The search loop
15076 * invariant still holds: only items between low and high inclusive could
15080 while (middle > low)
15082 if (classoid != middle[-1].classoid ||
15083 objoid != middle[-1].objoid)
15092 while (middle <= high)
15094 if (classoid != middle->classoid ||
15095 objoid != middle->objoid)
15107 * Construct a table of all security labels available for database objects.
15108 * It's much faster to pull them all at once.
15110 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15113 collectSecLabels(Archive *fout, SecLabelItem **items)
15124 SecLabelItem *labels;
15126 query = createPQExpBuffer();
15128 appendPQExpBufferStr(query,
15129 "SELECT label, provider, classoid, objoid, objsubid "
15130 "FROM pg_catalog.pg_seclabel "
15131 "ORDER BY classoid, objoid, objsubid");
15133 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15135 /* Construct lookup table containing OIDs in numeric form */
15136 i_label = PQfnumber(res, "label");
15137 i_provider = PQfnumber(res, "provider");
15138 i_classoid = PQfnumber(res, "classoid");
15139 i_objoid = PQfnumber(res, "objoid");
15140 i_objsubid = PQfnumber(res, "objsubid");
15142 ntups = PQntuples(res);
15144 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15146 for (i = 0; i < ntups; i++)
15148 labels[i].label = PQgetvalue(res, i, i_label);
15149 labels[i].provider = PQgetvalue(res, i, i_provider);
15150 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15151 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15152 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15155 /* Do NOT free the PGresult since we are keeping pointers into it */
15156 destroyPQExpBuffer(query);
15164 * write out to fout the declarations (not data) of a user-defined table
15167 dumpTable(Archive *fout, TableInfo *tbinfo)
15169 DumpOptions *dopt = fout->dopt;
15173 * noop if we are not dumping anything about this table, or if we are
15174 * doing a data-only dump
15176 if (!tbinfo->dobj.dump || dopt->dataOnly)
15179 if (tbinfo->relkind == RELKIND_SEQUENCE)
15180 dumpSequence(fout, tbinfo);
15182 dumpTableSchema(fout, tbinfo);
15184 /* Handle the ACL here */
15185 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15186 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15188 const char *objtype =
15189 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15191 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15192 objtype, namecopy, NULL,
15193 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15194 tbinfo->relacl, tbinfo->rrelacl,
15195 tbinfo->initrelacl, tbinfo->initrrelacl);
15199 * Handle column ACLs, if any. Note: we pull these with a separate query
15200 * rather than trying to fetch them during getTableAttrs, so that we won't
15201 * miss ACLs on system columns.
15203 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15205 PQExpBuffer query = createPQExpBuffer();
15209 if (fout->remoteVersion >= 90600)
15211 PQExpBuffer acl_subquery = createPQExpBuffer();
15212 PQExpBuffer racl_subquery = createPQExpBuffer();
15213 PQExpBuffer initacl_subquery = createPQExpBuffer();
15214 PQExpBuffer initracl_subquery = createPQExpBuffer();
15216 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15217 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15218 dopt->binary_upgrade);
15220 appendPQExpBuffer(query,
15221 "SELECT at.attname, "
15224 "%s AS initattacl, "
15225 "%s AS initrattacl "
15226 "FROM pg_catalog.pg_attribute at "
15227 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15228 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15229 "(at.attrelid = pip.objoid "
15230 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15231 "AND at.attnum = pip.objsubid) "
15232 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15233 "NOT at.attisdropped "
15235 "%s IS NOT NULL OR "
15236 "%s IS NOT NULL OR "
15237 "%s IS NOT NULL OR "
15239 "ORDER BY at.attnum",
15240 acl_subquery->data,
15241 racl_subquery->data,
15242 initacl_subquery->data,
15243 initracl_subquery->data,
15244 tbinfo->dobj.catId.oid,
15245 acl_subquery->data,
15246 racl_subquery->data,
15247 initacl_subquery->data,
15248 initracl_subquery->data);
15250 destroyPQExpBuffer(acl_subquery);
15251 destroyPQExpBuffer(racl_subquery);
15252 destroyPQExpBuffer(initacl_subquery);
15253 destroyPQExpBuffer(initracl_subquery);
15257 appendPQExpBuffer(query,
15258 "SELECT attname, attacl, NULL as rattacl, "
15259 "NULL AS initattacl, NULL AS initrattacl "
15260 "FROM pg_catalog.pg_attribute "
15261 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15262 "AND attacl IS NOT NULL "
15264 tbinfo->dobj.catId.oid);
15267 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15269 for (i = 0; i < PQntuples(res); i++)
15271 char *attname = PQgetvalue(res, i, 0);
15272 char *attacl = PQgetvalue(res, i, 1);
15273 char *rattacl = PQgetvalue(res, i, 2);
15274 char *initattacl = PQgetvalue(res, i, 3);
15275 char *initrattacl = PQgetvalue(res, i, 4);
15278 attnamecopy = pg_strdup(fmtId(attname));
15279 /* Column's GRANT type is always TABLE */
15280 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15281 "TABLE", namecopy, attnamecopy,
15282 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15283 attacl, rattacl, initattacl, initrattacl);
15287 destroyPQExpBuffer(query);
15296 * Create the AS clause for a view or materialized view. The semicolon is
15297 * stripped because a materialized view must add a WITH NO DATA clause.
15299 * This returns a new buffer which must be freed by the caller.
15302 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15304 PQExpBuffer query = createPQExpBuffer();
15305 PQExpBuffer result = createPQExpBuffer();
15309 /* Fetch the view definition */
15310 appendPQExpBuffer(query,
15311 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15312 tbinfo->dobj.catId.oid);
15314 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15316 if (PQntuples(res) != 1)
15318 if (PQntuples(res) < 1)
15319 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15320 tbinfo->dobj.name);
15322 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15323 tbinfo->dobj.name);
15326 len = PQgetlength(res, 0, 0);
15329 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15330 tbinfo->dobj.name);
15332 /* Strip off the trailing semicolon so that other things may follow. */
15333 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15334 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15337 destroyPQExpBuffer(query);
15343 * Create a dummy AS clause for a view. This is used when the real view
15344 * definition has to be postponed because of circular dependencies.
15345 * We must duplicate the view's external properties -- column names and types
15346 * (including collation) -- so that it works for subsequent references.
15348 * This returns a new buffer which must be freed by the caller.
15351 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15353 PQExpBuffer result = createPQExpBuffer();
15356 appendPQExpBufferStr(result, "SELECT");
15358 for (j = 0; j < tbinfo->numatts; j++)
15361 appendPQExpBufferChar(result, ',');
15362 appendPQExpBufferStr(result, "\n ");
15364 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15367 * Must add collation if not default for the type, because CREATE OR
15368 * REPLACE VIEW won't change it
15370 if (OidIsValid(tbinfo->attcollation[j]))
15374 coll = findCollationByOid(tbinfo->attcollation[j]);
15376 appendPQExpBuffer(result, " COLLATE %s",
15377 fmtQualifiedDumpable(coll));
15380 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15388 * write the declaration (not data) of one user-defined table or view
15391 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15393 DumpOptions *dopt = fout->dopt;
15394 PQExpBuffer q = createPQExpBuffer();
15395 PQExpBuffer delq = createPQExpBuffer();
15399 TableInfo **parents;
15400 int actual_atts; /* number of attrs in this CREATE statement */
15401 const char *reltypename;
15408 qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15409 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15411 if (dopt->binary_upgrade)
15412 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15413 tbinfo->dobj.catId.oid);
15415 /* Is it a table or a view? */
15416 if (tbinfo->relkind == RELKIND_VIEW)
15418 PQExpBuffer result;
15421 * Note: keep this code in sync with the is_view case in dumpRule()
15424 reltypename = "VIEW";
15426 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15428 if (dopt->binary_upgrade)
15429 binary_upgrade_set_pg_class_oids(fout, q,
15430 tbinfo->dobj.catId.oid, false);
15432 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15434 if (tbinfo->dummy_view)
15435 result = createDummyViewAsClause(fout, tbinfo);
15438 if (nonemptyReloptions(tbinfo->reloptions))
15440 appendPQExpBufferStr(q, " WITH (");
15441 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15442 appendPQExpBufferChar(q, ')');
15444 result = createViewAsClause(fout, tbinfo);
15446 appendPQExpBuffer(q, " AS\n%s", result->data);
15447 destroyPQExpBuffer(result);
15449 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15450 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15451 appendPQExpBufferStr(q, ";\n");
15455 switch (tbinfo->relkind)
15457 case RELKIND_FOREIGN_TABLE:
15459 PQExpBuffer query = createPQExpBuffer();
15464 reltypename = "FOREIGN TABLE";
15466 /* retrieve name of foreign server and generic options */
15467 appendPQExpBuffer(query,
15468 "SELECT fs.srvname, "
15469 "pg_catalog.array_to_string(ARRAY("
15470 "SELECT pg_catalog.quote_ident(option_name) || "
15471 "' ' || pg_catalog.quote_literal(option_value) "
15472 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15473 "ORDER BY option_name"
15474 "), E',\n ') AS ftoptions "
15475 "FROM pg_catalog.pg_foreign_table ft "
15476 "JOIN pg_catalog.pg_foreign_server fs "
15477 "ON (fs.oid = ft.ftserver) "
15478 "WHERE ft.ftrelid = '%u'",
15479 tbinfo->dobj.catId.oid);
15480 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15481 i_srvname = PQfnumber(res, "srvname");
15482 i_ftoptions = PQfnumber(res, "ftoptions");
15483 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15484 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15486 destroyPQExpBuffer(query);
15489 case RELKIND_MATVIEW:
15490 reltypename = "MATERIALIZED VIEW";
15495 reltypename = "TABLE";
15500 numParents = tbinfo->numParents;
15501 parents = tbinfo->parents;
15503 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15505 if (dopt->binary_upgrade)
15506 binary_upgrade_set_pg_class_oids(fout, q,
15507 tbinfo->dobj.catId.oid, false);
15509 appendPQExpBuffer(q, "CREATE %s%s %s",
15510 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15516 * Attach to type, if reloftype; except in case of a binary upgrade,
15517 * we dump the table normally and attach it to the type afterward.
15519 if (tbinfo->reloftype && !dopt->binary_upgrade)
15520 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15523 * If the table is a partition, dump it as such; except in the case of
15524 * a binary upgrade, we dump the table normally and attach it to the
15525 * parent afterward.
15527 if (tbinfo->ispartition && !dopt->binary_upgrade)
15529 TableInfo *parentRel = tbinfo->parents[0];
15532 * With partitions, unlike inheritance, there can only be one
15535 if (tbinfo->numParents != 1)
15536 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15537 tbinfo->numParents, tbinfo->dobj.name);
15539 appendPQExpBuffer(q, " PARTITION OF %s",
15540 fmtQualifiedDumpable(parentRel));
15543 if (tbinfo->relkind != RELKIND_MATVIEW)
15545 /* Dump the attributes */
15547 for (j = 0; j < tbinfo->numatts; j++)
15550 * Normally, dump if it's locally defined in this table, and
15551 * not dropped. But for binary upgrade, we'll dump all the
15552 * columns, and then fix up the dropped and nonlocal cases
15555 if (shouldPrintColumn(dopt, tbinfo, j))
15558 * Default value --- suppress if to be printed separately.
15560 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15561 !tbinfo->attrdefs[j]->separate);
15564 * Not Null constraint --- suppress if inherited, except
15565 * in binary-upgrade case where that won't work.
15567 bool has_notnull = (tbinfo->notnull[j] &&
15568 (!tbinfo->inhNotNull[j] ||
15569 dopt->binary_upgrade));
15572 * Skip column if fully defined by reloftype or the
15573 * partition parent.
15575 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15576 !has_default && !has_notnull && !dopt->binary_upgrade)
15579 /* Format properly if not first attr */
15580 if (actual_atts == 0)
15581 appendPQExpBufferStr(q, " (");
15583 appendPQExpBufferChar(q, ',');
15584 appendPQExpBufferStr(q, "\n ");
15587 /* Attribute name */
15588 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15590 if (tbinfo->attisdropped[j])
15593 * ALTER TABLE DROP COLUMN clears
15594 * pg_attribute.atttypid, so we will not have gotten a
15595 * valid type name; insert INTEGER as a stopgap. We'll
15596 * clean things up later.
15598 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15599 /* Skip all the rest, too */
15606 * In binary-upgrade mode, we always include the type. If
15607 * we aren't in binary-upgrade mode, then we skip the type
15608 * when creating a typed table ('OF type_name') or a
15609 * partition ('PARTITION OF'), since the type comes from
15610 * the parent/partitioned table.
15612 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15614 appendPQExpBuffer(q, " %s",
15615 tbinfo->atttypnames[j]);
15618 /* Add collation if not default for the type */
15619 if (OidIsValid(tbinfo->attcollation[j]))
15623 coll = findCollationByOid(tbinfo->attcollation[j]);
15625 appendPQExpBuffer(q, " COLLATE %s",
15626 fmtQualifiedDumpable(coll));
15630 appendPQExpBuffer(q, " DEFAULT %s",
15631 tbinfo->attrdefs[j]->adef_expr);
15634 appendPQExpBufferStr(q, " NOT NULL");
15639 * Add non-inherited CHECK constraints, if any.
15641 for (j = 0; j < tbinfo->ncheck; j++)
15643 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15645 if (constr->separate || !constr->conislocal)
15648 if (actual_atts == 0)
15649 appendPQExpBufferStr(q, " (\n ");
15651 appendPQExpBufferStr(q, ",\n ");
15653 appendPQExpBuffer(q, "CONSTRAINT %s ",
15654 fmtId(constr->dobj.name));
15655 appendPQExpBufferStr(q, constr->condef);
15661 appendPQExpBufferStr(q, "\n)");
15662 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15663 !dopt->binary_upgrade))
15666 * We must have a parenthesized attribute list, even though
15667 * empty, when not using the OF TYPE or PARTITION OF syntax.
15669 appendPQExpBufferStr(q, " (\n)");
15672 if (tbinfo->ispartition && !dopt->binary_upgrade)
15674 appendPQExpBufferChar(q, '\n');
15675 appendPQExpBufferStr(q, tbinfo->partbound);
15678 /* Emit the INHERITS clause, except if this is a partition. */
15679 if (numParents > 0 &&
15680 !tbinfo->ispartition &&
15681 !dopt->binary_upgrade)
15683 appendPQExpBufferStr(q, "\nINHERITS (");
15684 for (k = 0; k < numParents; k++)
15686 TableInfo *parentRel = parents[k];
15689 appendPQExpBufferStr(q, ", ");
15690 appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15692 appendPQExpBufferChar(q, ')');
15695 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15696 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15698 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15699 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15702 if (nonemptyReloptions(tbinfo->reloptions) ||
15703 nonemptyReloptions(tbinfo->toast_reloptions))
15705 bool addcomma = false;
15707 appendPQExpBufferStr(q, "\nWITH (");
15708 if (nonemptyReloptions(tbinfo->reloptions))
15711 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15713 if (nonemptyReloptions(tbinfo->toast_reloptions))
15716 appendPQExpBufferStr(q, ", ");
15717 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15720 appendPQExpBufferChar(q, ')');
15723 /* Dump generic options if any */
15724 if (ftoptions && ftoptions[0])
15725 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15728 * For materialized views, create the AS clause just like a view. At
15729 * this point, we always mark the view as not populated.
15731 if (tbinfo->relkind == RELKIND_MATVIEW)
15733 PQExpBuffer result;
15735 result = createViewAsClause(fout, tbinfo);
15736 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15738 destroyPQExpBuffer(result);
15741 appendPQExpBufferStr(q, ";\n");
15744 * in binary upgrade mode, update the catalog with any missing values
15745 * that might be present.
15747 if (dopt->binary_upgrade)
15749 for (j = 0; j < tbinfo->numatts; j++)
15751 if (tbinfo->attmissingval[j][0] != '\0')
15753 appendPQExpBufferStr(q, "\n-- set missing value.\n");
15754 appendPQExpBufferStr(q,
15755 "SELECT pg_catalog.binary_upgrade_set_missing_value(");
15756 appendStringLiteralAH(q, qualrelname, fout);
15757 appendPQExpBufferStr(q, "::pg_catalog.regclass,");
15758 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15759 appendPQExpBufferStr(q, ",");
15760 appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
15761 appendPQExpBufferStr(q, ");\n\n");
15767 * To create binary-compatible heap files, we have to ensure the same
15768 * physical column order, including dropped columns, as in the
15769 * original. Therefore, we create dropped columns above and drop them
15770 * here, also updating their attlen/attalign values so that the
15771 * dropped column can be skipped properly. (We do not bother with
15772 * restoring the original attbyval setting.) Also, inheritance
15773 * relationships are set up by doing ALTER TABLE INHERIT rather than
15774 * using an INHERITS clause --- the latter would possibly mess up the
15775 * column order. That also means we have to take care about setting
15776 * attislocal correctly, plus fix up any inherited CHECK constraints.
15777 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15779 * We process foreign and partitioned tables here, even though they
15780 * lack heap storage, because they can participate in inheritance
15781 * relationships and we want this stuff to be consistent across the
15782 * inheritance tree. We can exclude indexes, toast tables, sequences
15783 * and matviews, even though they have storage, because we don't
15784 * support altering or dropping columns in them, nor can they be part
15785 * of inheritance trees.
15787 if (dopt->binary_upgrade &&
15788 (tbinfo->relkind == RELKIND_RELATION ||
15789 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15790 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15792 for (j = 0; j < tbinfo->numatts; j++)
15794 if (tbinfo->attisdropped[j])
15796 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15797 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15798 "SET attlen = %d, "
15799 "attalign = '%c', attbyval = false\n"
15800 "WHERE attname = ",
15802 tbinfo->attalign[j]);
15803 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15804 appendPQExpBufferStr(q, "\n AND attrelid = ");
15805 appendStringLiteralAH(q, qualrelname, fout);
15806 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15808 if (tbinfo->relkind == RELKIND_RELATION ||
15809 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15810 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15813 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15815 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15816 fmtId(tbinfo->attnames[j]));
15818 else if (!tbinfo->attislocal[j])
15820 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15821 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15822 "SET attislocal = false\n"
15823 "WHERE attname = ");
15824 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15825 appendPQExpBufferStr(q, "\n AND attrelid = ");
15826 appendStringLiteralAH(q, qualrelname, fout);
15827 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15831 for (k = 0; k < tbinfo->ncheck; k++)
15833 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15835 if (constr->separate || constr->conislocal)
15838 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15839 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15841 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15842 fmtId(constr->dobj.name));
15843 appendPQExpBuffer(q, "%s;\n", constr->condef);
15844 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15845 "SET conislocal = false\n"
15846 "WHERE contype = 'c' AND conname = ");
15847 appendStringLiteralAH(q, constr->dobj.name, fout);
15848 appendPQExpBufferStr(q, "\n AND conrelid = ");
15849 appendStringLiteralAH(q, qualrelname, fout);
15850 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15853 if (numParents > 0)
15855 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15856 for (k = 0; k < numParents; k++)
15858 TableInfo *parentRel = parents[k];
15860 /* In the partitioning case, we alter the parent */
15861 if (tbinfo->ispartition)
15862 appendPQExpBuffer(q,
15863 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15864 fmtQualifiedDumpable(parentRel));
15866 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15869 /* Partition needs specifying the bounds */
15870 if (tbinfo->ispartition)
15871 appendPQExpBuffer(q, "%s %s;\n",
15873 tbinfo->partbound);
15875 appendPQExpBuffer(q, "%s;\n",
15876 fmtQualifiedDumpable(parentRel));
15880 if (tbinfo->reloftype)
15882 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15883 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15885 tbinfo->reloftype);
15890 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15891 * relminmxid of all vacuumable relations. (While vacuum.c processes
15892 * TOAST tables semi-independently, here we see them only as children
15893 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15894 * child toast table is handled below.)
15896 if (dopt->binary_upgrade &&
15897 (tbinfo->relkind == RELKIND_RELATION ||
15898 tbinfo->relkind == RELKIND_MATVIEW))
15900 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15901 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15902 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15904 tbinfo->frozenxid, tbinfo->minmxid);
15905 appendStringLiteralAH(q, qualrelname, fout);
15906 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15908 if (tbinfo->toast_oid)
15911 * The toast table will have the same OID at restore, so we
15912 * can safely target it by OID.
15914 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15915 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15916 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15917 "WHERE oid = '%u';\n",
15918 tbinfo->toast_frozenxid,
15919 tbinfo->toast_minmxid, tbinfo->toast_oid);
15924 * In binary_upgrade mode, restore matviews' populated status by
15925 * poking pg_class directly. This is pretty ugly, but we can't use
15926 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15927 * matview is not populated even though this matview is; in any case,
15928 * we want to transfer the matview's heap storage, not run REFRESH.
15930 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15931 tbinfo->relispopulated)
15933 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15934 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15935 "SET relispopulated = 't'\n"
15937 appendStringLiteralAH(q, qualrelname, fout);
15938 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15942 * Dump additional per-column properties that we can't handle in the
15943 * main CREATE TABLE command.
15945 for (j = 0; j < tbinfo->numatts; j++)
15947 /* None of this applies to dropped columns */
15948 if (tbinfo->attisdropped[j])
15952 * If we didn't dump the column definition explicitly above, and
15953 * it is NOT NULL and did not inherit that property from a parent,
15954 * we have to mark it separately.
15956 if (!shouldPrintColumn(dopt, tbinfo, j) &&
15957 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15959 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15961 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15962 fmtId(tbinfo->attnames[j]));
15966 * Dump per-column statistics information. We only issue an ALTER
15967 * TABLE statement if the attstattarget entry for this column is
15968 * non-negative (i.e. it's not the default value)
15970 if (tbinfo->attstattarget[j] >= 0)
15972 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15974 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15975 fmtId(tbinfo->attnames[j]));
15976 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15977 tbinfo->attstattarget[j]);
15981 * Dump per-column storage information. The statement is only
15982 * dumped if the storage has been changed from the type's default.
15984 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15986 switch (tbinfo->attstorage[j])
15992 storage = "EXTERNAL";
15998 storage = "EXTENDED";
16005 * Only dump the statement if it's a storage type we recognize
16007 if (storage != NULL)
16009 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16011 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16012 fmtId(tbinfo->attnames[j]));
16013 appendPQExpBuffer(q, "SET STORAGE %s;\n",
16019 * Dump per-column attributes.
16021 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
16023 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16025 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16026 fmtId(tbinfo->attnames[j]));
16027 appendPQExpBuffer(q, "SET (%s);\n",
16028 tbinfo->attoptions[j]);
16032 * Dump per-column fdw options.
16034 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16035 tbinfo->attfdwoptions[j] &&
16036 tbinfo->attfdwoptions[j][0] != '\0')
16038 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16040 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16041 fmtId(tbinfo->attnames[j]));
16042 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
16043 tbinfo->attfdwoptions[j]);
16049 * dump properties we only have ALTER TABLE syntax for
16051 if ((tbinfo->relkind == RELKIND_RELATION ||
16052 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16053 tbinfo->relkind == RELKIND_MATVIEW) &&
16054 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16056 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16058 /* nothing to do, will be set when the index is dumped */
16060 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16062 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16065 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16067 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16072 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
16073 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
16076 if (tbinfo->forcerowsec)
16077 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16080 if (dopt->binary_upgrade)
16081 binary_upgrade_extension_member(q, &tbinfo->dobj,
16082 reltypename, qrelname,
16083 tbinfo->dobj.namespace->dobj.name);
16085 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16086 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16088 tbinfo->dobj.namespace->dobj.name,
16089 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16091 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
16093 tbinfo->postponed_def ?
16094 SECTION_POST_DATA : SECTION_PRE_DATA,
16095 q->data, delq->data, NULL,
16100 /* Dump Table Comments */
16101 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16102 dumpTableComment(fout, tbinfo, reltypename);
16104 /* Dump Table Security Labels */
16105 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16106 dumpTableSecLabel(fout, tbinfo, reltypename);
16108 /* Dump comments on inlined table constraints */
16109 for (j = 0; j < tbinfo->ncheck; j++)
16111 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16113 if (constr->separate || !constr->conislocal)
16116 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16117 dumpTableConstraintComment(fout, constr);
16120 destroyPQExpBuffer(q);
16121 destroyPQExpBuffer(delq);
16127 * dumpAttrDef --- dump an attribute's default-value declaration
16130 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16132 DumpOptions *dopt = fout->dopt;
16133 TableInfo *tbinfo = adinfo->adtable;
16134 int adnum = adinfo->adnum;
16140 /* Skip if table definition not to be dumped */
16141 if (!tbinfo->dobj.dump || dopt->dataOnly)
16144 /* Skip if not "separate"; it was dumped in the table's definition */
16145 if (!adinfo->separate)
16148 q = createPQExpBuffer();
16149 delq = createPQExpBuffer();
16151 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16153 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16155 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16156 fmtId(tbinfo->attnames[adnum - 1]),
16157 adinfo->adef_expr);
16159 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16161 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16162 fmtId(tbinfo->attnames[adnum - 1]));
16164 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16166 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16167 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16169 tbinfo->dobj.namespace->dobj.name,
16172 false, "DEFAULT", SECTION_PRE_DATA,
16173 q->data, delq->data, NULL,
16178 destroyPQExpBuffer(q);
16179 destroyPQExpBuffer(delq);
16184 * getAttrName: extract the correct name for an attribute
16186 * The array tblInfo->attnames[] only provides names of user attributes;
16187 * if a system attribute number is supplied, we have to fake it.
16188 * We also do a little bit of bounds checking for safety's sake.
16190 static const char *
16191 getAttrName(int attrnum, TableInfo *tblInfo)
16193 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16194 return tblInfo->attnames[attrnum - 1];
16197 case SelfItemPointerAttributeNumber:
16199 case ObjectIdAttributeNumber:
16201 case MinTransactionIdAttributeNumber:
16203 case MinCommandIdAttributeNumber:
16205 case MaxTransactionIdAttributeNumber:
16207 case MaxCommandIdAttributeNumber:
16209 case TableOidAttributeNumber:
16212 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16213 attrnum, tblInfo->dobj.name);
16214 return NULL; /* keep compiler quiet */
16219 * write out to fout a user-defined index
16222 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16224 DumpOptions *dopt = fout->dopt;
16225 TableInfo *tbinfo = indxinfo->indextable;
16226 bool is_constraint = (indxinfo->indexconstraint != 0);
16231 if (dopt->dataOnly)
16234 q = createPQExpBuffer();
16235 delq = createPQExpBuffer();
16237 qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16240 * If there's an associated constraint, don't dump the index per se, but
16241 * do dump any comment for it. (This is safe because dependency ordering
16242 * will have ensured the constraint is emitted first.) Note that the
16243 * emitted comment has to be shown as depending on the constraint, not the
16244 * index, in such cases.
16246 if (!is_constraint)
16248 if (dopt->binary_upgrade)
16249 binary_upgrade_set_pg_class_oids(fout, q,
16250 indxinfo->dobj.catId.oid, true);
16252 /* Plain secondary index */
16253 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16256 * Append ALTER TABLE commands as needed to set properties that we
16257 * only have ALTER TABLE syntax for. Keep this in sync with the
16258 * similar code in dumpConstraint!
16261 /* If the index is clustered, we need to record that. */
16262 if (indxinfo->indisclustered)
16264 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16265 fmtQualifiedDumpable(tbinfo));
16266 /* index name is not qualified in this syntax */
16267 appendPQExpBuffer(q, " ON %s;\n",
16271 /* If the index defines identity, we need to record that. */
16272 if (indxinfo->indisreplident)
16274 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16275 fmtQualifiedDumpable(tbinfo));
16276 /* index name is not qualified in this syntax */
16277 appendPQExpBuffer(q, " INDEX %s;\n",
16281 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16282 fmtQualifiedDumpable(indxinfo));
16284 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16285 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16286 indxinfo->dobj.name,
16287 tbinfo->dobj.namespace->dobj.name,
16288 indxinfo->tablespace,
16289 tbinfo->rolname, false,
16290 "INDEX", SECTION_POST_DATA,
16291 q->data, delq->data, NULL,
16296 /* Dump Index Comments */
16297 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16298 dumpComment(fout, "INDEX", qindxname,
16299 tbinfo->dobj.namespace->dobj.name,
16301 indxinfo->dobj.catId, 0,
16302 is_constraint ? indxinfo->indexconstraint :
16303 indxinfo->dobj.dumpId);
16305 destroyPQExpBuffer(q);
16306 destroyPQExpBuffer(delq);
16312 * write out to fout a partitioned-index attachment clause
16315 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16317 if (fout->dopt->dataOnly)
16320 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16322 PQExpBuffer q = createPQExpBuffer();
16324 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16325 fmtQualifiedDumpable(attachinfo->parentIdx));
16326 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16327 fmtQualifiedDumpable(attachinfo->partitionIdx));
16329 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16330 attachinfo->dobj.name,
16333 false, "INDEX ATTACH", SECTION_POST_DATA,
16338 destroyPQExpBuffer(q);
16343 * dumpStatisticsExt
16344 * write out to fout an extended statistics object
16347 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16349 DumpOptions *dopt = fout->dopt;
16353 char *qstatsextname;
16357 /* Skip if not to be dumped */
16358 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16361 q = createPQExpBuffer();
16362 delq = createPQExpBuffer();
16363 query = createPQExpBuffer();
16365 qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16367 appendPQExpBuffer(query, "SELECT "
16368 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16369 statsextinfo->dobj.catId.oid);
16371 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16373 stxdef = PQgetvalue(res, 0, 0);
16375 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16376 appendPQExpBuffer(q, "%s;\n", stxdef);
16378 appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16379 fmtQualifiedDumpable(statsextinfo));
16381 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16382 ArchiveEntry(fout, statsextinfo->dobj.catId,
16383 statsextinfo->dobj.dumpId,
16384 statsextinfo->dobj.name,
16385 statsextinfo->dobj.namespace->dobj.name,
16387 statsextinfo->rolname, false,
16388 "STATISTICS", SECTION_POST_DATA,
16389 q->data, delq->data, NULL,
16393 /* Dump Statistics Comments */
16394 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16395 dumpComment(fout, "STATISTICS", qstatsextname,
16396 statsextinfo->dobj.namespace->dobj.name,
16397 statsextinfo->rolname,
16398 statsextinfo->dobj.catId, 0,
16399 statsextinfo->dobj.dumpId);
16402 destroyPQExpBuffer(q);
16403 destroyPQExpBuffer(delq);
16404 destroyPQExpBuffer(query);
16405 free(qstatsextname);
16410 * write out to fout a user-defined constraint
16413 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16415 DumpOptions *dopt = fout->dopt;
16416 TableInfo *tbinfo = coninfo->contable;
16421 /* Skip if not to be dumped */
16422 if (!coninfo->dobj.dump || dopt->dataOnly)
16425 q = createPQExpBuffer();
16426 delq = createPQExpBuffer();
16428 if (coninfo->contype == 'p' ||
16429 coninfo->contype == 'u' ||
16430 coninfo->contype == 'x')
16432 /* Index-related constraint */
16433 IndxInfo *indxinfo;
16436 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16438 if (indxinfo == NULL)
16439 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16440 coninfo->dobj.name);
16442 if (dopt->binary_upgrade)
16443 binary_upgrade_set_pg_class_oids(fout, q,
16444 indxinfo->dobj.catId.oid, true);
16446 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16447 fmtQualifiedDumpable(tbinfo));
16448 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16449 fmtId(coninfo->dobj.name));
16451 if (coninfo->condef)
16453 /* pg_get_constraintdef should have provided everything */
16454 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16458 appendPQExpBuffer(q, "%s (",
16459 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16460 for (k = 0; k < indxinfo->indnkeyattrs; k++)
16462 int indkey = (int) indxinfo->indkeys[k];
16463 const char *attname;
16465 if (indkey == InvalidAttrNumber)
16467 attname = getAttrName(indkey, tbinfo);
16469 appendPQExpBuffer(q, "%s%s",
16470 (k == 0) ? "" : ", ",
16474 if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
16475 appendPQExpBuffer(q, ") INCLUDE (");
16477 for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
16479 int indkey = (int) indxinfo->indkeys[k];
16480 const char *attname;
16482 if (indkey == InvalidAttrNumber)
16484 attname = getAttrName(indkey, tbinfo);
16486 appendPQExpBuffer(q, "%s%s",
16487 (k == indxinfo->indnkeyattrs) ? "" : ", ",
16491 appendPQExpBufferChar(q, ')');
16493 if (nonemptyReloptions(indxinfo->indreloptions))
16495 appendPQExpBufferStr(q, " WITH (");
16496 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16497 appendPQExpBufferChar(q, ')');
16500 if (coninfo->condeferrable)
16502 appendPQExpBufferStr(q, " DEFERRABLE");
16503 if (coninfo->condeferred)
16504 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16507 appendPQExpBufferStr(q, ";\n");
16511 * Append ALTER TABLE commands as needed to set properties that we
16512 * only have ALTER TABLE syntax for. Keep this in sync with the
16513 * similar code in dumpIndex!
16516 /* If the index is clustered, we need to record that. */
16517 if (indxinfo->indisclustered)
16519 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16520 fmtQualifiedDumpable(tbinfo));
16521 /* index name is not qualified in this syntax */
16522 appendPQExpBuffer(q, " ON %s;\n",
16523 fmtId(indxinfo->dobj.name));
16526 /* If the index defines identity, we need to record that. */
16527 if (indxinfo->indisreplident)
16529 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16530 fmtQualifiedDumpable(tbinfo));
16531 /* index name is not qualified in this syntax */
16532 appendPQExpBuffer(q, " INDEX %s;\n",
16533 fmtId(indxinfo->dobj.name));
16536 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16537 fmtQualifiedDumpable(tbinfo));
16538 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16539 fmtId(coninfo->dobj.name));
16541 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16543 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16544 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16546 tbinfo->dobj.namespace->dobj.name,
16547 indxinfo->tablespace,
16548 tbinfo->rolname, false,
16549 "CONSTRAINT", SECTION_POST_DATA,
16550 q->data, delq->data, NULL,
16554 else if (coninfo->contype == 'f')
16559 * Foreign keys on partitioned tables are always declared as
16560 * inheriting to partitions; for all other cases, emit them as
16561 * applying ONLY directly to the named table, because that's how they
16562 * work for regular inherited tables.
16564 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
16567 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16568 * current table data is not processed
16570 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
16571 only, fmtQualifiedDumpable(tbinfo));
16572 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16573 fmtId(coninfo->dobj.name),
16576 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
16577 only, fmtQualifiedDumpable(tbinfo));
16578 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16579 fmtId(coninfo->dobj.name));
16581 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16583 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16584 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16586 tbinfo->dobj.namespace->dobj.name,
16588 tbinfo->rolname, false,
16589 "FK CONSTRAINT", SECTION_POST_DATA,
16590 q->data, delq->data, NULL,
16594 else if (coninfo->contype == 'c' && tbinfo)
16596 /* CHECK constraint on a table */
16598 /* Ignore if not to be dumped separately, or if it was inherited */
16599 if (coninfo->separate && coninfo->conislocal)
16601 /* not ONLY since we want it to propagate to children */
16602 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16603 fmtQualifiedDumpable(tbinfo));
16604 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16605 fmtId(coninfo->dobj.name),
16608 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16609 fmtQualifiedDumpable(tbinfo));
16610 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16611 fmtId(coninfo->dobj.name));
16613 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16615 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16616 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16618 tbinfo->dobj.namespace->dobj.name,
16620 tbinfo->rolname, false,
16621 "CHECK CONSTRAINT", SECTION_POST_DATA,
16622 q->data, delq->data, NULL,
16627 else if (coninfo->contype == 'c' && tbinfo == NULL)
16629 /* CHECK constraint on a domain */
16630 TypeInfo *tyinfo = coninfo->condomain;
16632 /* Ignore if not to be dumped separately */
16633 if (coninfo->separate)
16635 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16636 fmtQualifiedDumpable(tyinfo));
16637 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16638 fmtId(coninfo->dobj.name),
16641 appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16642 fmtQualifiedDumpable(tyinfo));
16643 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16644 fmtId(coninfo->dobj.name));
16646 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16648 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16649 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16651 tyinfo->dobj.namespace->dobj.name,
16653 tyinfo->rolname, false,
16654 "CHECK CONSTRAINT", SECTION_POST_DATA,
16655 q->data, delq->data, NULL,
16662 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16666 /* Dump Constraint Comments --- only works for table constraints */
16667 if (tbinfo && coninfo->separate &&
16668 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16669 dumpTableConstraintComment(fout, coninfo);
16672 destroyPQExpBuffer(q);
16673 destroyPQExpBuffer(delq);
16677 * dumpTableConstraintComment --- dump a constraint's comment if any
16679 * This is split out because we need the function in two different places
16680 * depending on whether the constraint is dumped as part of CREATE TABLE
16681 * or as a separate ALTER command.
16684 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16686 TableInfo *tbinfo = coninfo->contable;
16687 PQExpBuffer conprefix = createPQExpBuffer();
16690 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16692 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16693 fmtId(coninfo->dobj.name));
16695 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16696 dumpComment(fout, conprefix->data, qtabname,
16697 tbinfo->dobj.namespace->dobj.name,
16699 coninfo->dobj.catId, 0,
16700 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16702 destroyPQExpBuffer(conprefix);
16707 * findLastBuiltinOid_V71 -
16709 * find the last built in oid
16711 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16712 * pg_database entry for the current database. (Note: current_database()
16713 * requires 7.3; pg_dump requires 8.0 now.)
16716 findLastBuiltinOid_V71(Archive *fout)
16721 res = ExecuteSqlQueryForSingleRow(fout,
16722 "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
16723 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16731 * write the declaration (not data) of one user-defined sequence
16734 dumpSequence(Archive *fout, TableInfo *tbinfo)
16736 DumpOptions *dopt = fout->dopt;
16746 int64 default_minv,
16750 PQExpBuffer query = createPQExpBuffer();
16751 PQExpBuffer delqry = createPQExpBuffer();
16754 qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16756 if (fout->remoteVersion >= 100000)
16758 appendPQExpBuffer(query,
16759 "SELECT format_type(seqtypid, NULL), "
16760 "seqstart, seqincrement, "
16762 "seqcache, seqcycle "
16763 "FROM pg_catalog.pg_sequence "
16764 "WHERE seqrelid = '%u'::oid",
16765 tbinfo->dobj.catId.oid);
16767 else if (fout->remoteVersion >= 80400)
16770 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16772 * Note: it might seem that 'bigint' potentially needs to be
16773 * schema-qualified, but actually that's a keyword.
16775 appendPQExpBuffer(query,
16776 "SELECT 'bigint' AS sequence_type, "
16777 "start_value, increment_by, max_value, min_value, "
16778 "cache_value, is_cycled FROM %s",
16779 fmtQualifiedDumpable(tbinfo));
16783 appendPQExpBuffer(query,
16784 "SELECT 'bigint' AS sequence_type, "
16785 "0 AS start_value, increment_by, max_value, min_value, "
16786 "cache_value, is_cycled FROM %s",
16787 fmtQualifiedDumpable(tbinfo));
16790 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16792 if (PQntuples(res) != 1)
16794 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16795 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16797 tbinfo->dobj.name, PQntuples(res));
16801 seqtype = PQgetvalue(res, 0, 0);
16802 startv = PQgetvalue(res, 0, 1);
16803 incby = PQgetvalue(res, 0, 2);
16804 maxv = PQgetvalue(res, 0, 3);
16805 minv = PQgetvalue(res, 0, 4);
16806 cache = PQgetvalue(res, 0, 5);
16807 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16809 /* Calculate default limits for a sequence of this type */
16810 is_ascending = (incby[0] != '-');
16811 if (strcmp(seqtype, "smallint") == 0)
16813 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16814 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16816 else if (strcmp(seqtype, "integer") == 0)
16818 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16819 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16821 else if (strcmp(seqtype, "bigint") == 0)
16823 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16824 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16828 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16829 default_minv = default_maxv = 0; /* keep compiler quiet */
16833 * 64-bit strtol() isn't very portable, so convert the limits to strings
16834 * and compare that way.
16836 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16837 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16839 /* Don't print minv/maxv if they match the respective default limit */
16840 if (strcmp(minv, bufm) == 0)
16842 if (strcmp(maxv, bufx) == 0)
16846 * Identity sequences are not to be dropped separately.
16848 if (!tbinfo->is_identity_sequence)
16850 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16851 fmtQualifiedDumpable(tbinfo));
16854 resetPQExpBuffer(query);
16856 if (dopt->binary_upgrade)
16858 binary_upgrade_set_pg_class_oids(fout, query,
16859 tbinfo->dobj.catId.oid, false);
16860 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16861 tbinfo->dobj.catId.oid);
16864 if (tbinfo->is_identity_sequence)
16866 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16868 appendPQExpBuffer(query,
16870 fmtQualifiedDumpable(owning_tab));
16871 appendPQExpBuffer(query,
16872 "ALTER COLUMN %s ADD GENERATED ",
16873 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16874 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16875 appendPQExpBuffer(query, "ALWAYS");
16876 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16877 appendPQExpBuffer(query, "BY DEFAULT");
16878 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16879 fmtQualifiedDumpable(tbinfo));
16883 appendPQExpBuffer(query,
16884 "CREATE SEQUENCE %s\n",
16885 fmtQualifiedDumpable(tbinfo));
16887 if (strcmp(seqtype, "bigint") != 0)
16888 appendPQExpBuffer(query, " AS %s\n", seqtype);
16891 if (fout->remoteVersion >= 80400)
16892 appendPQExpBuffer(query, " START WITH %s\n", startv);
16894 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
16897 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
16899 appendPQExpBufferStr(query, " NO MINVALUE\n");
16902 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
16904 appendPQExpBufferStr(query, " NO MAXVALUE\n");
16906 appendPQExpBuffer(query,
16908 cache, (cycled ? "\n CYCLE" : ""));
16910 if (tbinfo->is_identity_sequence)
16911 appendPQExpBufferStr(query, "\n);\n");
16913 appendPQExpBufferStr(query, ";\n");
16915 /* binary_upgrade: no need to clear TOAST table oid */
16917 if (dopt->binary_upgrade)
16918 binary_upgrade_extension_member(query, &tbinfo->dobj,
16919 "SEQUENCE", qseqname,
16920 tbinfo->dobj.namespace->dobj.name);
16922 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16923 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16925 tbinfo->dobj.namespace->dobj.name,
16928 false, "SEQUENCE", SECTION_PRE_DATA,
16929 query->data, delqry->data, NULL,
16934 * If the sequence is owned by a table column, emit the ALTER for it as a
16935 * separate TOC entry immediately following the sequence's own entry. It's
16936 * OK to do this rather than using full sorting logic, because the
16937 * dependency that tells us it's owned will have forced the table to be
16938 * created first. We can't just include the ALTER in the TOC entry
16939 * because it will fail if we haven't reassigned the sequence owner to
16940 * match the table's owner.
16942 * We need not schema-qualify the table reference because both sequence
16943 * and table must be in the same schema.
16945 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16947 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16949 if (owning_tab == NULL)
16950 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16951 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16953 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16955 resetPQExpBuffer(query);
16956 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16957 fmtQualifiedDumpable(tbinfo));
16958 appendPQExpBuffer(query, " OWNED BY %s",
16959 fmtQualifiedDumpable(owning_tab));
16960 appendPQExpBuffer(query, ".%s;\n",
16961 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16963 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16964 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16966 tbinfo->dobj.namespace->dobj.name,
16969 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16970 query->data, "", NULL,
16971 &(tbinfo->dobj.dumpId), 1,
16976 /* Dump Sequence Comments and Security Labels */
16977 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16978 dumpComment(fout, "SEQUENCE", qseqname,
16979 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16980 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16982 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16983 dumpSecLabel(fout, "SEQUENCE", qseqname,
16984 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16985 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16989 destroyPQExpBuffer(query);
16990 destroyPQExpBuffer(delqry);
16996 * write the data of one user-defined sequence
16999 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
17001 TableInfo *tbinfo = tdinfo->tdtable;
17005 PQExpBuffer query = createPQExpBuffer();
17007 appendPQExpBuffer(query,
17008 "SELECT last_value, is_called FROM %s",
17009 fmtQualifiedDumpable(tbinfo));
17011 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17013 if (PQntuples(res) != 1)
17015 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
17016 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
17018 tbinfo->dobj.name, PQntuples(res));
17022 last = PQgetvalue(res, 0, 0);
17023 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17025 resetPQExpBuffer(query);
17026 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17027 appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
17028 appendPQExpBuffer(query, ", %s, %s);\n",
17029 last, (called ? "true" : "false"));
17031 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17032 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17034 tbinfo->dobj.namespace->dobj.name,
17037 false, "SEQUENCE SET", SECTION_DATA,
17038 query->data, "", NULL,
17039 &(tbinfo->dobj.dumpId), 1,
17044 destroyPQExpBuffer(query);
17049 * write the declaration of one user-defined table trigger
17052 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17054 DumpOptions *dopt = fout->dopt;
17055 TableInfo *tbinfo = tginfo->tgtable;
17057 PQExpBuffer delqry;
17058 PQExpBuffer trigprefix;
17067 * we needn't check dobj.dump because TriggerInfo wouldn't have been
17068 * created in the first place for non-dumpable triggers
17070 if (dopt->dataOnly)
17073 query = createPQExpBuffer();
17074 delqry = createPQExpBuffer();
17075 trigprefix = createPQExpBuffer();
17077 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17079 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17080 fmtId(tginfo->dobj.name));
17081 appendPQExpBuffer(delqry, "ON %s;\n",
17082 fmtQualifiedDumpable(tbinfo));
17086 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17090 if (tginfo->tgisconstraint)
17092 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17093 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17097 appendPQExpBufferStr(query, "CREATE TRIGGER ");
17098 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17100 appendPQExpBufferStr(query, "\n ");
17103 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17104 appendPQExpBufferStr(query, "BEFORE");
17105 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17106 appendPQExpBufferStr(query, "AFTER");
17107 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17108 appendPQExpBufferStr(query, "INSTEAD OF");
17111 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17116 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17118 appendPQExpBufferStr(query, " INSERT");
17121 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17124 appendPQExpBufferStr(query, " OR DELETE");
17126 appendPQExpBufferStr(query, " DELETE");
17129 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17132 appendPQExpBufferStr(query, " OR UPDATE");
17134 appendPQExpBufferStr(query, " UPDATE");
17137 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17140 appendPQExpBufferStr(query, " OR TRUNCATE");
17142 appendPQExpBufferStr(query, " TRUNCATE");
17145 appendPQExpBuffer(query, " ON %s\n",
17146 fmtQualifiedDumpable(tbinfo));
17148 if (tginfo->tgisconstraint)
17150 if (OidIsValid(tginfo->tgconstrrelid))
17152 /* regclass output is already quoted */
17153 appendPQExpBuffer(query, " FROM %s\n ",
17154 tginfo->tgconstrrelname);
17156 if (!tginfo->tgdeferrable)
17157 appendPQExpBufferStr(query, "NOT ");
17158 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17159 if (tginfo->tginitdeferred)
17160 appendPQExpBufferStr(query, "DEFERRED\n");
17162 appendPQExpBufferStr(query, "IMMEDIATE\n");
17165 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17166 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
17168 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
17170 /* regproc output is already sufficiently quoted */
17171 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17174 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17177 for (findx = 0; findx < tginfo->tgnargs; findx++)
17179 /* find the embedded null that terminates this trigger argument */
17180 size_t tlen = strlen(p);
17182 if (p + tlen >= tgargs + lentgargs)
17184 /* hm, not found before end of bytea value... */
17185 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17188 tbinfo->dobj.name);
17193 appendPQExpBufferStr(query, ", ");
17194 appendStringLiteralAH(query, p, fout);
17198 appendPQExpBufferStr(query, ");\n");
17201 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17203 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17204 fmtQualifiedDumpable(tbinfo));
17205 switch (tginfo->tgenabled)
17209 appendPQExpBufferStr(query, "DISABLE");
17212 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17215 appendPQExpBufferStr(query, "ENABLE REPLICA");
17218 appendPQExpBufferStr(query, "ENABLE");
17221 appendPQExpBuffer(query, " TRIGGER %s;\n",
17222 fmtId(tginfo->dobj.name));
17225 appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17226 fmtId(tginfo->dobj.name));
17228 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17230 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17231 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17233 tbinfo->dobj.namespace->dobj.name,
17235 tbinfo->rolname, false,
17236 "TRIGGER", SECTION_POST_DATA,
17237 query->data, delqry->data, NULL,
17241 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17242 dumpComment(fout, trigprefix->data, qtabname,
17243 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17244 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17247 destroyPQExpBuffer(query);
17248 destroyPQExpBuffer(delqry);
17249 destroyPQExpBuffer(trigprefix);
17255 * write the declaration of one user-defined event trigger
17258 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17260 DumpOptions *dopt = fout->dopt;
17262 PQExpBuffer delqry;
17265 /* Skip if not to be dumped */
17266 if (!evtinfo->dobj.dump || dopt->dataOnly)
17269 query = createPQExpBuffer();
17270 delqry = createPQExpBuffer();
17272 qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17274 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17275 appendPQExpBufferStr(query, qevtname);
17276 appendPQExpBufferStr(query, " ON ");
17277 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17279 if (strcmp("", evtinfo->evttags) != 0)
17281 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17282 appendPQExpBufferStr(query, evtinfo->evttags);
17283 appendPQExpBufferChar(query, ')');
17286 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
17287 appendPQExpBufferStr(query, evtinfo->evtfname);
17288 appendPQExpBufferStr(query, "();\n");
17290 if (evtinfo->evtenabled != 'O')
17292 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17294 switch (evtinfo->evtenabled)
17297 appendPQExpBufferStr(query, "DISABLE");
17300 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17303 appendPQExpBufferStr(query, "ENABLE REPLICA");
17306 appendPQExpBufferStr(query, "ENABLE");
17309 appendPQExpBufferStr(query, ";\n");
17312 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17315 if (dopt->binary_upgrade)
17316 binary_upgrade_extension_member(query, &evtinfo->dobj,
17317 "EVENT TRIGGER", qevtname, NULL);
17319 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17320 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17321 evtinfo->dobj.name, NULL, NULL,
17322 evtinfo->evtowner, false,
17323 "EVENT TRIGGER", SECTION_POST_DATA,
17324 query->data, delqry->data, NULL,
17328 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17329 dumpComment(fout, "EVENT TRIGGER", qevtname,
17330 NULL, evtinfo->evtowner,
17331 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17333 destroyPQExpBuffer(query);
17334 destroyPQExpBuffer(delqry);
17343 dumpRule(Archive *fout, RuleInfo *rinfo)
17345 DumpOptions *dopt = fout->dopt;
17346 TableInfo *tbinfo = rinfo->ruletable;
17350 PQExpBuffer delcmd;
17351 PQExpBuffer ruleprefix;
17356 /* Skip if not to be dumped */
17357 if (!rinfo->dobj.dump || dopt->dataOnly)
17361 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17362 * we do not want to dump it as a separate object.
17364 if (!rinfo->separate)
17368 * If it's an ON SELECT rule, we want to print it as a view definition,
17369 * instead of a rule.
17371 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17373 query = createPQExpBuffer();
17374 cmd = createPQExpBuffer();
17375 delcmd = createPQExpBuffer();
17376 ruleprefix = createPQExpBuffer();
17378 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17382 PQExpBuffer result;
17385 * We need OR REPLACE here because we'll be replacing a dummy view.
17386 * Otherwise this should look largely like the regular view dump code.
17388 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17389 fmtQualifiedDumpable(tbinfo));
17390 if (nonemptyReloptions(tbinfo->reloptions))
17392 appendPQExpBufferStr(cmd, " WITH (");
17393 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17394 appendPQExpBufferChar(cmd, ')');
17396 result = createViewAsClause(fout, tbinfo);
17397 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17398 destroyPQExpBuffer(result);
17399 if (tbinfo->checkoption != NULL)
17400 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
17401 tbinfo->checkoption);
17402 appendPQExpBufferStr(cmd, ";\n");
17406 /* In the rule case, just print pg_get_ruledef's result verbatim */
17407 appendPQExpBuffer(query,
17408 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17409 rinfo->dobj.catId.oid);
17411 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17413 if (PQntuples(res) != 1)
17415 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17416 rinfo->dobj.name, tbinfo->dobj.name);
17420 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17426 * Add the command to alter the rules replication firing semantics if it
17427 * differs from the default.
17429 if (rinfo->ev_enabled != 'O')
17431 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17432 switch (rinfo->ev_enabled)
17435 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17436 fmtId(rinfo->dobj.name));
17439 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17440 fmtId(rinfo->dobj.name));
17443 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17444 fmtId(rinfo->dobj.name));
17452 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17453 * REPLACE VIEW to replace the rule with something with minimal
17456 PQExpBuffer result;
17458 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17459 fmtQualifiedDumpable(tbinfo));
17460 result = createDummyViewAsClause(fout, tbinfo);
17461 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17462 destroyPQExpBuffer(result);
17466 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17467 fmtId(rinfo->dobj.name));
17468 appendPQExpBuffer(delcmd, "ON %s;\n",
17469 fmtQualifiedDumpable(tbinfo));
17472 appendPQExpBuffer(ruleprefix, "RULE %s ON",
17473 fmtId(rinfo->dobj.name));
17475 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17477 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17478 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17480 tbinfo->dobj.namespace->dobj.name,
17482 tbinfo->rolname, false,
17483 "RULE", SECTION_POST_DATA,
17484 cmd->data, delcmd->data, NULL,
17488 /* Dump rule comments */
17489 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17490 dumpComment(fout, ruleprefix->data, qtabname,
17491 tbinfo->dobj.namespace->dobj.name,
17493 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17496 destroyPQExpBuffer(query);
17497 destroyPQExpBuffer(cmd);
17498 destroyPQExpBuffer(delcmd);
17499 destroyPQExpBuffer(ruleprefix);
17504 * getExtensionMembership --- obtain extension membership data
17506 * We need to identify objects that are extension members as soon as they're
17507 * loaded, so that we can correctly determine whether they need to be dumped.
17508 * Generally speaking, extension member objects will get marked as *not* to
17509 * be dumped, as they will be recreated by the single CREATE EXTENSION
17510 * command. However, in binary upgrade mode we still need to dump the members
17514 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17525 ExtensionMemberId *extmembers;
17526 ExtensionInfo *ext;
17528 /* Nothing to do if no extensions */
17529 if (numExtensions == 0)
17532 query = createPQExpBuffer();
17534 /* refclassid constraint is redundant but may speed the search */
17535 appendPQExpBufferStr(query, "SELECT "
17536 "classid, objid, refobjid "
17538 "WHERE refclassid = 'pg_extension'::regclass "
17539 "AND deptype = 'e' "
17542 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17544 ntups = PQntuples(res);
17546 i_classid = PQfnumber(res, "classid");
17547 i_objid = PQfnumber(res, "objid");
17548 i_refobjid = PQfnumber(res, "refobjid");
17550 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17554 * Accumulate data into extmembers[].
17556 * Since we ordered the SELECT by referenced ID, we can expect that
17557 * multiple entries for the same extension will appear together; this
17558 * saves on searches.
17562 for (i = 0; i < ntups; i++)
17567 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17568 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17569 extId = atooid(PQgetvalue(res, i, i_refobjid));
17572 ext->dobj.catId.oid != extId)
17573 ext = findExtensionByOid(extId);
17577 /* shouldn't happen */
17578 fprintf(stderr, "could not find referenced extension %u\n", extId);
17582 extmembers[nextmembers].catId = objId;
17583 extmembers[nextmembers].ext = ext;
17589 /* Remember the data for use later */
17590 setExtensionMembership(extmembers, nextmembers);
17592 destroyPQExpBuffer(query);
17596 * processExtensionTables --- deal with extension configuration tables
17598 * There are two parts to this process:
17600 * 1. Identify and create dump records for extension configuration tables.
17602 * Extensions can mark tables as "configuration", which means that the user
17603 * is able and expected to modify those tables after the extension has been
17604 * loaded. For these tables, we dump out only the data- the structure is
17605 * expected to be handled at CREATE EXTENSION time, including any indexes or
17606 * foreign keys, which brings us to-
17608 * 2. Record FK dependencies between configuration tables.
17610 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17611 * the data is loaded, we have to work out what the best order for reloading
17612 * the data is, to avoid FK violations when the tables are restored. This is
17613 * not perfect- we can't handle circular dependencies and if any exist they
17614 * will cause an invalid dump to be produced (though at least all of the data
17615 * is included for a user to manually restore). This is currently documented
17616 * but perhaps we can provide a better solution in the future.
17619 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17622 DumpOptions *dopt = fout->dopt;
17630 /* Nothing to do if no extensions */
17631 if (numExtensions == 0)
17635 * Identify extension configuration tables and create TableDataInfo
17636 * objects for them, ensuring their data will be dumped even though the
17637 * tables themselves won't be.
17639 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17640 * user data in a configuration table is treated like schema data. This
17641 * seems appropriate since system data in a config table would get
17642 * reloaded by CREATE EXTENSION.
17644 for (i = 0; i < numExtensions; i++)
17646 ExtensionInfo *curext = &(extinfo[i]);
17647 char *extconfig = curext->extconfig;
17648 char *extcondition = curext->extcondition;
17649 char **extconfigarray = NULL;
17650 char **extconditionarray = NULL;
17652 int nconditionitems;
17654 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17655 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17656 nconfigitems == nconditionitems)
17660 for (j = 0; j < nconfigitems; j++)
17662 TableInfo *configtbl;
17663 Oid configtbloid = atooid(extconfigarray[j]);
17665 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17667 configtbl = findTableByOid(configtbloid);
17668 if (configtbl == NULL)
17672 * Tables of not-to-be-dumped extensions shouldn't be dumped
17673 * unless the table or its schema is explicitly included
17675 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17677 /* check table explicitly requested */
17678 if (table_include_oids.head != NULL &&
17679 simple_oid_list_member(&table_include_oids,
17683 /* check table's schema explicitly requested */
17684 if (configtbl->dobj.namespace->dobj.dump &
17685 DUMP_COMPONENT_DATA)
17689 /* check table excluded by an exclusion switch */
17690 if (table_exclude_oids.head != NULL &&
17691 simple_oid_list_member(&table_exclude_oids,
17695 /* check schema excluded by an exclusion switch */
17696 if (simple_oid_list_member(&schema_exclude_oids,
17697 configtbl->dobj.namespace->dobj.catId.oid))
17703 * Note: config tables are dumped without OIDs regardless
17704 * of the --oids setting. This is because row filtering
17705 * conditions aren't compatible with dumping OIDs.
17707 makeTableDataInfo(dopt, configtbl, false);
17708 if (configtbl->dataObj != NULL)
17710 if (strlen(extconditionarray[j]) > 0)
17711 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17716 if (extconfigarray)
17717 free(extconfigarray);
17718 if (extconditionarray)
17719 free(extconditionarray);
17723 * Now that all the TableInfoData objects have been created for all the
17724 * extensions, check their FK dependencies and register them to try and
17725 * dump the data out in an order that they can be restored in.
17727 * Note that this is not a problem for user tables as their FKs are
17728 * recreated after the data has been loaded.
17731 query = createPQExpBuffer();
17733 printfPQExpBuffer(query,
17734 "SELECT conrelid, confrelid "
17735 "FROM pg_constraint "
17736 "JOIN pg_depend ON (objid = confrelid) "
17737 "WHERE contype = 'f' "
17738 "AND refclassid = 'pg_extension'::regclass "
17739 "AND classid = 'pg_class'::regclass;");
17741 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17742 ntups = PQntuples(res);
17744 i_conrelid = PQfnumber(res, "conrelid");
17745 i_confrelid = PQfnumber(res, "confrelid");
17747 /* Now get the dependencies and register them */
17748 for (i = 0; i < ntups; i++)
17752 TableInfo *reftable,
17755 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17756 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17757 contable = findTableByOid(conrelid);
17758 reftable = findTableByOid(confrelid);
17760 if (reftable == NULL ||
17761 reftable->dataObj == NULL ||
17762 contable == NULL ||
17763 contable->dataObj == NULL)
17767 * Make referencing TABLE_DATA object depend on the referenced table's
17768 * TABLE_DATA object.
17770 addObjectDependency(&contable->dataObj->dobj,
17771 reftable->dataObj->dobj.dumpId);
17774 destroyPQExpBuffer(query);
17778 * getDependencies --- obtain available dependency data
17781 getDependencies(Archive *fout)
17792 DumpableObject *dobj,
17796 write_msg(NULL, "reading dependency data\n");
17798 query = createPQExpBuffer();
17801 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17802 * already processed by getExtensionMembership.
17804 appendPQExpBufferStr(query, "SELECT "
17805 "classid, objid, refclassid, refobjid, deptype "
17807 "WHERE deptype != 'p' AND deptype != 'e' "
17810 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17812 ntups = PQntuples(res);
17814 i_classid = PQfnumber(res, "classid");
17815 i_objid = PQfnumber(res, "objid");
17816 i_refclassid = PQfnumber(res, "refclassid");
17817 i_refobjid = PQfnumber(res, "refobjid");
17818 i_deptype = PQfnumber(res, "deptype");
17821 * Since we ordered the SELECT by referencing ID, we can expect that
17822 * multiple entries for the same object will appear together; this saves
17827 for (i = 0; i < ntups; i++)
17830 CatalogId refobjId;
17833 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17834 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17835 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17836 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17837 deptype = *(PQgetvalue(res, i, i_deptype));
17839 if (dobj == NULL ||
17840 dobj->catId.tableoid != objId.tableoid ||
17841 dobj->catId.oid != objId.oid)
17842 dobj = findObjectByCatalogId(objId);
17845 * Failure to find objects mentioned in pg_depend is not unexpected,
17846 * since for example we don't collect info about TOAST tables.
17851 fprintf(stderr, "no referencing object %u %u\n",
17852 objId.tableoid, objId.oid);
17857 refdobj = findObjectByCatalogId(refobjId);
17859 if (refdobj == NULL)
17862 fprintf(stderr, "no referenced object %u %u\n",
17863 refobjId.tableoid, refobjId.oid);
17869 * Ordinarily, table rowtypes have implicit dependencies on their
17870 * tables. However, for a composite type the implicit dependency goes
17871 * the other way in pg_depend; which is the right thing for DROP but
17872 * it doesn't produce the dependency ordering we need. So in that one
17873 * case, we reverse the direction of the dependency.
17875 if (deptype == 'i' &&
17876 dobj->objType == DO_TABLE &&
17877 refdobj->objType == DO_TYPE)
17878 addObjectDependency(refdobj, dobj->dumpId);
17881 addObjectDependency(dobj, refdobj->dumpId);
17886 destroyPQExpBuffer(query);
17891 * createBoundaryObjects - create dummy DumpableObjects to represent
17892 * dump section boundaries.
17894 static DumpableObject *
17895 createBoundaryObjects(void)
17897 DumpableObject *dobjs;
17899 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17901 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17902 dobjs[0].catId = nilCatalogId;
17903 AssignDumpId(dobjs + 0);
17904 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17906 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17907 dobjs[1].catId = nilCatalogId;
17908 AssignDumpId(dobjs + 1);
17909 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17915 * addBoundaryDependencies - add dependencies as needed to enforce the dump
17916 * section boundaries.
17919 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17920 DumpableObject *boundaryObjs)
17922 DumpableObject *preDataBound = boundaryObjs + 0;
17923 DumpableObject *postDataBound = boundaryObjs + 1;
17926 for (i = 0; i < numObjs; i++)
17928 DumpableObject *dobj = dobjs[i];
17931 * The classification of object types here must match the SECTION_xxx
17932 * values assigned during subsequent ArchiveEntry calls!
17934 switch (dobj->objType)
17939 case DO_SHELL_TYPE:
17943 case DO_ACCESS_METHOD:
17947 case DO_CONVERSION:
17952 case DO_DUMMY_TYPE:
17955 case DO_TSTEMPLATE:
17958 case DO_FOREIGN_SERVER:
17961 /* Pre-data objects: must come before the pre-data boundary */
17962 addObjectDependency(preDataBound, dobj->dumpId);
17964 case DO_TABLE_DATA:
17965 case DO_SEQUENCE_SET:
17967 /* Data objects: must come between the boundaries */
17968 addObjectDependency(dobj, preDataBound->dumpId);
17969 addObjectDependency(postDataBound, dobj->dumpId);
17972 case DO_INDEX_ATTACH:
17974 case DO_REFRESH_MATVIEW:
17976 case DO_EVENT_TRIGGER:
17977 case DO_DEFAULT_ACL:
17979 case DO_PUBLICATION:
17980 case DO_PUBLICATION_REL:
17981 case DO_SUBSCRIPTION:
17982 /* Post-data objects: must come after the post-data boundary */
17983 addObjectDependency(dobj, postDataBound->dumpId);
17986 /* Rules are post-data, but only if dumped separately */
17987 if (((RuleInfo *) dobj)->separate)
17988 addObjectDependency(dobj, postDataBound->dumpId);
17990 case DO_CONSTRAINT:
17991 case DO_FK_CONSTRAINT:
17992 /* Constraints are post-data, but only if dumped separately */
17993 if (((ConstraintInfo *) dobj)->separate)
17994 addObjectDependency(dobj, postDataBound->dumpId);
17996 case DO_PRE_DATA_BOUNDARY:
17997 /* nothing to do */
17999 case DO_POST_DATA_BOUNDARY:
18000 /* must come after the pre-data boundary */
18001 addObjectDependency(dobj, preDataBound->dumpId);
18009 * BuildArchiveDependencies - create dependency data for archive TOC entries
18011 * The raw dependency data obtained by getDependencies() is not terribly
18012 * useful in an archive dump, because in many cases there are dependency
18013 * chains linking through objects that don't appear explicitly in the dump.
18014 * For example, a view will depend on its _RETURN rule while the _RETURN rule
18015 * will depend on other objects --- but the rule will not appear as a separate
18016 * object in the dump. We need to adjust the view's dependencies to include
18017 * whatever the rule depends on that is included in the dump.
18019 * Just to make things more complicated, there are also "special" dependencies
18020 * such as the dependency of a TABLE DATA item on its TABLE, which we must
18021 * not rearrange because pg_restore knows that TABLE DATA only depends on
18022 * its table. In these cases we must leave the dependencies strictly as-is
18023 * even if they refer to not-to-be-dumped objects.
18025 * To handle this, the convention is that "special" dependencies are created
18026 * during ArchiveEntry calls, and an archive TOC item that has any such
18027 * entries will not be touched here. Otherwise, we recursively search the
18028 * DumpableObject data structures to build the correct dependencies for each
18029 * archive TOC item.
18032 BuildArchiveDependencies(Archive *fout)
18034 ArchiveHandle *AH = (ArchiveHandle *) fout;
18037 /* Scan all TOC entries in the archive */
18038 for (te = AH->toc->next; te != AH->toc; te = te->next)
18040 DumpableObject *dobj;
18041 DumpId *dependencies;
18045 /* No need to process entries that will not be dumped */
18048 /* Ignore entries that already have "special" dependencies */
18051 /* Otherwise, look up the item's original DumpableObject, if any */
18052 dobj = findObjectByDumpId(te->dumpId);
18055 /* No work if it has no dependencies */
18056 if (dobj->nDeps <= 0)
18058 /* Set up work array */
18060 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18062 /* Recursively find all dumpable dependencies */
18063 findDumpableDependencies(AH, dobj,
18064 &dependencies, &nDeps, &allocDeps);
18065 /* And save 'em ... */
18068 dependencies = (DumpId *) pg_realloc(dependencies,
18069 nDeps * sizeof(DumpId));
18070 te->dependencies = dependencies;
18074 free(dependencies);
18078 /* Recursive search subroutine for BuildArchiveDependencies */
18080 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18081 DumpId **dependencies, int *nDeps, int *allocDeps)
18086 * Ignore section boundary objects: if we search through them, we'll
18087 * report lots of bogus dependencies.
18089 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18090 dobj->objType == DO_POST_DATA_BOUNDARY)
18093 for (i = 0; i < dobj->nDeps; i++)
18095 DumpId depid = dobj->dependencies[i];
18097 if (TocIDRequired(AH, depid) != 0)
18099 /* Object will be dumped, so just reference it as a dependency */
18100 if (*nDeps >= *allocDeps)
18103 *dependencies = (DumpId *) pg_realloc(*dependencies,
18104 *allocDeps * sizeof(DumpId));
18106 (*dependencies)[*nDeps] = depid;
18112 * Object will not be dumped, so recursively consider its deps. We
18113 * rely on the assumption that sortDumpableObjects already broke
18114 * any dependency loops, else we might recurse infinitely.
18116 DumpableObject *otherdobj = findObjectByDumpId(depid);
18119 findDumpableDependencies(AH, otherdobj,
18120 dependencies, nDeps, allocDeps);
18127 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18130 * This does not guarantee to schema-qualify the output, so it should not
18131 * be used to create the target object name for CREATE or ALTER commands.
18133 * TODO: there might be some value in caching the results.
18136 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18144 if ((opts & zeroAsOpaque) != 0)
18145 return pg_strdup(g_opaque_type);
18146 else if ((opts & zeroAsAny) != 0)
18147 return pg_strdup("'any'");
18148 else if ((opts & zeroAsStar) != 0)
18149 return pg_strdup("*");
18150 else if ((opts & zeroAsNone) != 0)
18151 return pg_strdup("NONE");
18154 query = createPQExpBuffer();
18155 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18158 res = ExecuteSqlQueryForSingleRow(fout, query->data);
18160 /* result of format_type is already quoted */
18161 result = pg_strdup(PQgetvalue(res, 0, 0));
18164 destroyPQExpBuffer(query);
18170 * Return a column list clause for the given relation.
18172 * Special case: if there are no undropped columns in the relation, return
18173 * "", not an invalid "()" column list.
18175 static const char *
18176 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18178 int numatts = ti->numatts;
18179 char **attnames = ti->attnames;
18180 bool *attisdropped = ti->attisdropped;
18184 appendPQExpBufferChar(buffer, '(');
18186 for (i = 0; i < numatts; i++)
18188 if (attisdropped[i])
18191 appendPQExpBufferStr(buffer, ", ");
18192 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18197 return ""; /* no undropped columns */
18199 appendPQExpBufferChar(buffer, ')');
18200 return buffer->data;
18204 * Check if a reloptions array is nonempty.
18207 nonemptyReloptions(const char *reloptions)
18209 /* Don't want to print it if it's just "{}" */
18210 return (reloptions != NULL && strlen(reloptions) > 2);
18214 * Format a reloptions array and append it to the given buffer.
18216 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18219 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18220 const char *prefix, Archive *fout)
18224 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18225 fout->std_strings);
18227 write_msg(NULL, "WARNING: could not parse reloptions array\n");