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"
57 #include "storage/block.h"
59 #include "dumputils.h"
61 #include "pg_backup_db.h"
62 #include "pg_backup_utils.h"
64 #include "fe_utils/connect.h"
65 #include "fe_utils/string_utils.h"
70 const char *descr; /* comment for an object */
71 Oid classoid; /* object class (catalog OID) */
72 Oid objoid; /* object OID */
73 int objsubid; /* subobject (table column #) */
78 const char *provider; /* label provider of this security label */
79 const char *label; /* security label for an object */
80 Oid classoid; /* object class (catalog OID) */
81 Oid objoid; /* object OID */
82 int objsubid; /* subobject (table column #) */
85 typedef enum OidOptions
94 bool g_verbose; /* User wants verbose narration of our
96 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
98 /* subquery used to convert user ID (eg, datdba) to user name */
99 static const char *username_subquery;
102 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
103 * FirstNormalObjectId - 1.
105 static Oid g_last_builtin_oid; /* value of the last builtin oid */
107 /* The specified names/patterns should to match at least one entity */
108 static int strict_names = 0;
111 * Object inclusion/exclusion lists
113 * The string lists record the patterns given by command-line switches,
114 * which we then convert to lists of OIDs of matching objects.
116 static SimpleStringList schema_include_patterns = {NULL, NULL};
117 static SimpleOidList schema_include_oids = {NULL, NULL};
118 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
119 static SimpleOidList schema_exclude_oids = {NULL, NULL};
121 static SimpleStringList table_include_patterns = {NULL, NULL};
122 static SimpleOidList table_include_oids = {NULL, NULL};
123 static SimpleStringList table_exclude_patterns = {NULL, NULL};
124 static SimpleOidList table_exclude_oids = {NULL, NULL};
125 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
126 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
129 char g_opaque_type[10]; /* name for the opaque type */
131 /* placeholders for the delimiters for comments */
132 char g_comment_start[10];
133 char g_comment_end[10];
135 static const CatalogId nilCatalogId = {0, 0};
138 * Macro for producing quoted, schema-qualified name of a dumpable object.
140 #define fmtQualifiedDumpable(obj) \
141 fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
144 static void help(const char *progname);
145 static void setup_connection(Archive *AH,
146 const char *dumpencoding, const char *dumpsnapshot,
148 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
149 static void expand_schema_name_patterns(Archive *fout,
150 SimpleStringList *patterns,
153 static void expand_table_name_patterns(Archive *fout,
154 SimpleStringList *patterns,
157 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
158 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
159 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
160 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
161 static void dumpComment(Archive *fout, const char *type, const char *name,
162 const char *namespace, const char *owner,
163 CatalogId catalogId, int subid, DumpId dumpId);
164 static int findComments(Archive *fout, Oid classoid, Oid objoid,
165 CommentItem **items);
166 static int collectComments(Archive *fout, CommentItem **items);
167 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
168 const char *namespace, const char *owner,
169 CatalogId catalogId, int subid, DumpId dumpId);
170 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
171 SecLabelItem **items);
172 static int collectSecLabels(Archive *fout, SecLabelItem **items);
173 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
174 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
175 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
176 static void dumpType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
182 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
183 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
184 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
185 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
186 static void dumpFunc(Archive *fout, FuncInfo *finfo);
187 static void dumpCast(Archive *fout, CastInfo *cast);
188 static void dumpTransform(Archive *fout, TransformInfo *transform);
189 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
190 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
191 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
192 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
193 static void dumpCollation(Archive *fout, CollInfo *collinfo);
194 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
195 static void dumpRule(Archive *fout, RuleInfo *rinfo);
196 static void dumpAgg(Archive *fout, AggInfo *agginfo);
197 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
198 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
199 static void dumpTable(Archive *fout, TableInfo *tbinfo);
200 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
201 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
202 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
203 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
204 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
205 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
206 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
207 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
208 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
209 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
210 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
211 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
212 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
213 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
214 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
215 static void dumpUserMappings(Archive *fout,
216 const char *servername, const char *namespace,
217 const char *owner, CatalogId catalogId, DumpId dumpId);
218 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
220 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
221 const char *type, const char *name, const char *subname,
222 const char *nspname, const char *owner,
223 const char *acls, const char *racls,
224 const char *initacls, const char *initracls);
226 static void getDependencies(Archive *fout);
227 static void BuildArchiveDependencies(Archive *fout);
228 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
229 DumpId **dependencies, int *nDeps, int *allocDeps);
231 static DumpableObject *createBoundaryObjects(void);
232 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
233 DumpableObject *boundaryObjs);
235 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
236 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind);
237 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo);
238 static void buildMatViewRefreshDependencies(Archive *fout);
239 static void getTableDataFKConstraints(void);
240 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
242 static char *format_function_arguments_old(Archive *fout,
243 FuncInfo *finfo, int nallargs,
247 static char *format_function_signature(Archive *fout,
248 FuncInfo *finfo, bool honor_quotes);
249 static char *convertRegProcReference(Archive *fout,
251 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
252 static char *convertTSFunction(Archive *fout, Oid funcOid);
253 static Oid findLastBuiltinOid_V71(Archive *fout);
254 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
255 static void getBlobs(Archive *fout);
256 static void dumpBlob(Archive *fout, BlobInfo *binfo);
257 static int dumpBlobs(Archive *fout, void *arg);
258 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
259 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
260 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
261 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
262 static void dumpDatabase(Archive *AH);
263 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
264 const char *dbname, Oid dboid);
265 static void dumpEncoding(Archive *AH);
266 static void dumpStdStrings(Archive *AH);
267 static void dumpSearchPath(Archive *AH);
268 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
269 PQExpBuffer upgrade_buffer,
271 bool force_array_type);
272 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
273 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
274 static void binary_upgrade_set_pg_class_oids(Archive *fout,
275 PQExpBuffer upgrade_buffer,
276 Oid pg_class_oid, bool is_index);
277 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
278 DumpableObject *dobj,
281 const char *objnamespace);
282 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
283 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
284 static bool nonemptyReloptions(const char *reloptions);
285 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
286 const char *prefix, Archive *fout);
287 static char *get_synchronized_snapshot(Archive *fout);
288 static void setupDumpWorker(Archive *AHX);
289 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
293 main(int argc, char **argv)
296 const char *filename = NULL;
297 const char *format = "p";
300 DumpableObject **dobjs;
302 DumpableObject *boundaryObjs;
305 RestoreOptions *ropt;
306 Archive *fout; /* the script file */
307 const char *dumpencoding = NULL;
308 const char *dumpsnapshot = NULL;
309 char *use_role = NULL;
311 trivalue prompt_password = TRI_DEFAULT;
312 int compressLevel = -1;
314 ArchiveFormat archiveFormat = archUnknown;
315 ArchiveMode archiveMode;
317 static DumpOptions dopt;
319 static struct option long_options[] = {
320 {"data-only", no_argument, NULL, 'a'},
321 {"blobs", no_argument, NULL, 'b'},
322 {"no-blobs", no_argument, NULL, 'B'},
323 {"clean", no_argument, NULL, 'c'},
324 {"create", no_argument, NULL, 'C'},
325 {"dbname", required_argument, NULL, 'd'},
326 {"file", required_argument, NULL, 'f'},
327 {"format", required_argument, NULL, 'F'},
328 {"host", required_argument, NULL, 'h'},
329 {"jobs", 1, NULL, 'j'},
330 {"no-reconnect", no_argument, NULL, 'R'},
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': /* Don't reconnect to match owner */
475 dopt.outputNoOwner = 1;
478 case 'p': /* server port */
479 dopt.pgport = pg_strdup(optarg);
483 /* no-op, still accepted for backwards compatibility */
486 case 's': /* dump schema only */
487 dopt.schemaOnly = true;
490 case 'S': /* Username for superuser in plain text output */
491 dopt.outputSuperuser = pg_strdup(optarg);
494 case 't': /* include table(s) */
495 simple_string_list_append(&table_include_patterns, optarg);
496 dopt.include_everything = false;
499 case 'T': /* exclude table(s) */
500 simple_string_list_append(&table_exclude_patterns, optarg);
504 dopt.username = pg_strdup(optarg);
507 case 'v': /* verbose */
512 prompt_password = TRI_NO;
516 prompt_password = TRI_YES;
519 case 'x': /* skip ACL dump */
520 dopt.aclsSkip = true;
523 case 'Z': /* Compression Level */
524 compressLevel = atoi(optarg);
525 if (compressLevel < 0 || compressLevel > 9)
527 write_msg(NULL, "compression level must be in range 0..9\n");
533 /* This covers the long options. */
536 case 2: /* lock-wait-timeout */
537 dopt.lockWaitTimeout = pg_strdup(optarg);
540 case 3: /* SET ROLE */
541 use_role = pg_strdup(optarg);
544 case 4: /* exclude table(s) data */
545 simple_string_list_append(&tabledata_exclude_patterns, optarg);
548 case 5: /* section */
549 set_dump_section(optarg, &dopt.dumpSections);
552 case 6: /* snapshot */
553 dumpsnapshot = pg_strdup(optarg);
556 case 7: /* no-sync */
561 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
567 * Non-option argument specifies database name as long as it wasn't
568 * already specified with -d / --dbname
570 if (optind < argc && dopt.dbname == NULL)
571 dopt.dbname = argv[optind++];
573 /* Complain if any arguments remain */
576 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
577 progname, argv[optind]);
578 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
583 /* --column-inserts implies --inserts */
584 if (dopt.column_inserts)
585 dopt.dump_inserts = 1;
588 * Binary upgrade mode implies dumping sequence data even in schema-only
589 * mode. This is not exposed as a separate option, but kept separate
590 * internally for clarity.
592 if (dopt.binary_upgrade)
593 dopt.sequence_data = 1;
595 if (dopt.dataOnly && dopt.schemaOnly)
597 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
601 if (dopt.dataOnly && dopt.outputClean)
603 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
607 if (dopt.if_exists && !dopt.outputClean)
608 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
610 if (dopt.do_nothing && !(dopt.dump_inserts || dopt.column_inserts))
611 exit_horribly(NULL, "option --on-conflict-do-nothing requires option --inserts or --column-inserts\n");
613 /* Identify archive format to emit */
614 archiveFormat = parseArchiveFormat(format, &archiveMode);
616 /* archiveFormat specific setup */
617 if (archiveFormat == archNull)
620 /* Custom and directory formats are compressed by default, others not */
621 if (compressLevel == -1)
624 if (archiveFormat == archCustom || archiveFormat == archDirectory)
625 compressLevel = Z_DEFAULT_COMPRESSION;
632 if (compressLevel != 0)
633 write_msg(NULL, "WARNING: requested compression not available in this "
634 "installation -- archive will be uncompressed\n");
639 * If emitting an archive format, we always want to emit a DATABASE item,
640 * in case --create is specified at pg_restore time.
643 dopt.outputCreateDB = 1;
646 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
647 * parallel jobs because that's the maximum limit for the
648 * WaitForMultipleObjects() call.
652 || numWorkers > MAXIMUM_WAIT_OBJECTS
655 exit_horribly(NULL, "invalid number of parallel jobs\n");
657 /* Parallel backup only in the directory archive format so far */
658 if (archiveFormat != archDirectory && numWorkers > 1)
659 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
661 /* Open the output file */
662 fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
663 archiveMode, setupDumpWorker);
665 /* Make dump options accessible right away */
666 SetArchiveOptions(fout, &dopt, NULL);
668 /* Register the cleanup hook */
669 on_exit_close_archive(fout);
671 /* Let the archiver know how noisy to be */
672 fout->verbose = g_verbose;
675 * We allow the server to be back to 8.0, and up to any minor release of
676 * our own major version. (See also version check in pg_dumpall.c.)
678 fout->minRemoteVersion = 80000;
679 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
681 fout->numWorkers = numWorkers;
684 * Open the database using the Archiver, so it knows about it. Errors mean
687 ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
688 setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
691 * Disable security label support if server version < v9.1.x (prevents
692 * access to nonexistent pg_seclabel catalog)
694 if (fout->remoteVersion < 90100)
695 dopt.no_security_labels = 1;
698 * On hot standbys, never try to dump unlogged table data, since it will
699 * just throw an error.
702 dopt.no_unlogged_table_data = true;
704 /* Select the appropriate subquery to convert user IDs to names */
705 if (fout->remoteVersion >= 80100)
706 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
708 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
710 /* check the version for the synchronized snapshots feature */
711 if (numWorkers > 1 && fout->remoteVersion < 90200
712 && !dopt.no_synchronized_snapshots)
714 "Synchronized snapshots are not supported by this server version.\n"
715 "Run with --no-synchronized-snapshots instead if you do not need\n"
716 "synchronized snapshots.\n");
718 /* check the version when a snapshot is explicitly specified by user */
719 if (dumpsnapshot && fout->remoteVersion < 90200)
721 "Exported snapshots are not supported by this server version.\n");
724 * Find the last built-in OID, if needed (prior to 8.1)
726 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
728 if (fout->remoteVersion < 80100)
729 g_last_builtin_oid = findLastBuiltinOid_V71(fout);
731 g_last_builtin_oid = FirstNormalObjectId - 1;
734 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
736 /* Expand schema selection patterns into OID lists */
737 if (schema_include_patterns.head != NULL)
739 expand_schema_name_patterns(fout, &schema_include_patterns,
740 &schema_include_oids,
742 if (schema_include_oids.head == NULL)
743 exit_horribly(NULL, "no matching schemas were found\n");
745 expand_schema_name_patterns(fout, &schema_exclude_patterns,
746 &schema_exclude_oids,
748 /* non-matching exclusion patterns aren't an error */
750 /* Expand table selection patterns into OID lists */
751 if (table_include_patterns.head != NULL)
753 expand_table_name_patterns(fout, &table_include_patterns,
756 if (table_include_oids.head == NULL)
757 exit_horribly(NULL, "no matching tables were found\n");
759 expand_table_name_patterns(fout, &table_exclude_patterns,
763 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
764 &tabledata_exclude_oids,
767 /* non-matching exclusion patterns aren't an error */
770 * Dumping blobs is the default for dumps where an inclusion switch is not
771 * used (an "include everything" dump). -B can be used to exclude blobs
772 * from those dumps. -b can be used to include blobs even when an
773 * inclusion switch is used.
775 * -s means "schema only" and blobs are data, not schema, so we never
776 * include blobs when -s is used.
778 if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
779 dopt.outputBlobs = true;
782 * Now scan the database and create DumpableObject structs for all the
783 * objects we intend to dump.
785 tblinfo = getSchemaData(fout, &numTables);
787 if (fout->remoteVersion < 80400)
788 guessConstraintInheritance(tblinfo, numTables);
790 if (!dopt.schemaOnly)
792 getTableData(&dopt, tblinfo, numTables, 0);
793 buildMatViewRefreshDependencies(fout);
795 getTableDataFKConstraints();
798 if (dopt.schemaOnly && dopt.sequence_data)
799 getTableData(&dopt, tblinfo, numTables, RELKIND_SEQUENCE);
802 * In binary-upgrade mode, we do not have to worry about the actual blob
803 * data or the associated metadata that resides in the pg_largeobject and
804 * pg_largeobject_metadata tables, respectively.
806 * However, we do need to collect blob information as there may be
807 * comments or other information on blobs that we do need to dump out.
809 if (dopt.outputBlobs || dopt.binary_upgrade)
813 * Collect dependency data to assist in ordering the objects.
815 getDependencies(fout);
817 /* Lastly, create dummy objects to represent the section boundaries */
818 boundaryObjs = createBoundaryObjects();
820 /* Get pointers to all the known DumpableObjects */
821 getDumpableObjects(&dobjs, &numObjs);
824 * Add dummy dependencies to enforce the dump section ordering.
826 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
829 * Sort the objects into a safe dump order (no forward references).
831 * We rely on dependency information to help us determine a safe order, so
832 * the initial sort is mostly for cosmetic purposes: we sort by name to
833 * ensure that logically identical schemas will dump identically.
835 sortDumpableObjectsByTypeName(dobjs, numObjs);
837 sortDumpableObjects(dobjs, numObjs,
838 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
841 * Create archive TOC entries for all the objects to be dumped, in a safe
845 /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
847 dumpStdStrings(fout);
848 dumpSearchPath(fout);
850 /* The database items are always next, unless we don't want them at all */
851 if (dopt.outputCreateDB)
854 /* Now the rearrangeable objects. */
855 for (i = 0; i < numObjs; i++)
856 dumpDumpableObject(fout, dobjs[i]);
859 * Set up options info to ensure we dump what we want.
861 ropt = NewRestoreOptions();
862 ropt->filename = filename;
864 /* if you change this list, see dumpOptionsFromRestoreOptions */
865 ropt->dropSchema = dopt.outputClean;
866 ropt->dataOnly = dopt.dataOnly;
867 ropt->schemaOnly = dopt.schemaOnly;
868 ropt->if_exists = dopt.if_exists;
869 ropt->column_inserts = dopt.column_inserts;
870 ropt->dumpSections = dopt.dumpSections;
871 ropt->aclsSkip = dopt.aclsSkip;
872 ropt->superuser = dopt.outputSuperuser;
873 ropt->createDB = dopt.outputCreateDB;
874 ropt->noOwner = dopt.outputNoOwner;
875 ropt->noTablespace = dopt.outputNoTablespaces;
876 ropt->disable_triggers = dopt.disable_triggers;
877 ropt->use_setsessauth = dopt.use_setsessauth;
878 ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
879 ropt->dump_inserts = dopt.dump_inserts;
880 ropt->no_comments = dopt.no_comments;
881 ropt->no_publications = dopt.no_publications;
882 ropt->no_security_labels = dopt.no_security_labels;
883 ropt->no_subscriptions = dopt.no_subscriptions;
884 ropt->lockWaitTimeout = dopt.lockWaitTimeout;
885 ropt->include_everything = dopt.include_everything;
886 ropt->enable_row_security = dopt.enable_row_security;
887 ropt->sequence_data = dopt.sequence_data;
888 ropt->binary_upgrade = dopt.binary_upgrade;
890 if (compressLevel == -1)
891 ropt->compression = 0;
893 ropt->compression = compressLevel;
895 ropt->suppressDumpWarnings = true; /* We've already shown them */
897 SetArchiveOptions(fout, &dopt, ropt);
899 /* Mark which entries should be output */
900 ProcessArchiveRestoreOptions(fout);
903 * The archive's TOC entries are now marked as to which ones will actually
904 * be output, so we can set up their dependency lists properly. This isn't
905 * necessary for plain-text output, though.
908 BuildArchiveDependencies(fout);
911 * And finally we can do the actual output.
913 * Note: for non-plain-text output formats, the output file is written
914 * inside CloseArchive(). This is, um, bizarre; but not worth changing
918 RestoreArchive(fout);
927 help(const char *progname)
929 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
930 printf(_("Usage:\n"));
931 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
933 printf(_("\nGeneral options:\n"));
934 printf(_(" -f, --file=FILENAME output file or directory name\n"));
935 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
936 " plain text (default))\n"));
937 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
938 printf(_(" -v, --verbose verbose mode\n"));
939 printf(_(" -V, --version output version information, then exit\n"));
940 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
941 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
942 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
943 printf(_(" -?, --help show this help, then exit\n"));
945 printf(_("\nOptions controlling the output content:\n"));
946 printf(_(" -a, --data-only dump only the data, not the schema\n"));
947 printf(_(" -b, --blobs include large objects in dump\n"));
948 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
949 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
950 printf(_(" -C, --create include commands to create database in dump\n"));
951 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
952 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
953 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
954 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
955 " plain-text format\n"));
956 printf(_(" -s, --schema-only dump only the schema, no data\n"));
957 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
958 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
959 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
960 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
961 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
962 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
963 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
964 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
965 printf(_(" --enable-row-security enable row security (dump only content user has\n"
967 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
968 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
969 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
970 printf(_(" --load-via-partition-root load partitions via the root table\n"));
971 printf(_(" --no-comments do not dump comments\n"));
972 printf(_(" --no-publications do not dump publications\n"));
973 printf(_(" --no-security-labels do not dump security label assignments\n"));
974 printf(_(" --no-subscriptions do not dump subscriptions\n"));
975 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
976 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
977 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
978 printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
979 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
980 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
981 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
982 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
983 printf(_(" --strict-names require table and/or schema include patterns to\n"
984 " match at least one entity each\n"));
985 printf(_(" --use-set-session-authorization\n"
986 " use SET SESSION AUTHORIZATION commands instead of\n"
987 " ALTER OWNER commands to set ownership\n"));
989 printf(_("\nConnection options:\n"));
990 printf(_(" -d, --dbname=DBNAME database to dump\n"));
991 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
992 printf(_(" -p, --port=PORT database server port number\n"));
993 printf(_(" -U, --username=NAME connect as specified database user\n"));
994 printf(_(" -w, --no-password never prompt for password\n"));
995 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
996 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
998 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
999 "variable value is used.\n\n"));
1000 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1004 setup_connection(Archive *AH, const char *dumpencoding,
1005 const char *dumpsnapshot, char *use_role)
1007 DumpOptions *dopt = AH->dopt;
1008 PGconn *conn = GetConnection(AH);
1009 const char *std_strings;
1011 PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1014 * Set the client encoding if requested.
1018 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1019 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1024 * Get the active encoding and the standard_conforming_strings setting, so
1025 * we know how to escape strings.
1027 AH->encoding = PQclientEncoding(conn);
1029 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1030 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1033 * Set the role if requested. In a parallel dump worker, we'll be passed
1034 * use_role == NULL, but AH->use_role is already set (if user specified it
1035 * originally) and we should use that.
1037 if (!use_role && AH->use_role)
1038 use_role = AH->use_role;
1040 /* Set the role if requested */
1041 if (use_role && AH->remoteVersion >= 80100)
1043 PQExpBuffer query = createPQExpBuffer();
1045 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1046 ExecuteSqlStatement(AH, query->data);
1047 destroyPQExpBuffer(query);
1049 /* save it for possible later use by parallel workers */
1051 AH->use_role = pg_strdup(use_role);
1054 /* Set the datestyle to ISO to ensure the dump's portability */
1055 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1057 /* Likewise, avoid using sql_standard intervalstyle */
1058 if (AH->remoteVersion >= 80400)
1059 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1062 * Set extra_float_digits so that we can dump float data exactly (given
1063 * correctly implemented float I/O code, anyway)
1065 if (AH->remoteVersion >= 90000)
1066 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1068 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1071 * If synchronized scanning is supported, disable it, to prevent
1072 * unpredictable changes in row ordering across a dump and reload.
1074 if (AH->remoteVersion >= 80300)
1075 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1078 * Disable timeouts if supported.
1080 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1081 if (AH->remoteVersion >= 90300)
1082 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1083 if (AH->remoteVersion >= 90600)
1084 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1087 * Quote all identifiers, if requested.
1089 if (quote_all_identifiers && AH->remoteVersion >= 90100)
1090 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1093 * Adjust row-security mode, if supported.
1095 if (AH->remoteVersion >= 90500)
1097 if (dopt->enable_row_security)
1098 ExecuteSqlStatement(AH, "SET row_security = on");
1100 ExecuteSqlStatement(AH, "SET row_security = off");
1104 * Start transaction-snapshot mode transaction to dump consistent data.
1106 ExecuteSqlStatement(AH, "BEGIN");
1107 if (AH->remoteVersion >= 90100)
1110 * To support the combination of serializable_deferrable with the jobs
1111 * option we use REPEATABLE READ for the worker connections that are
1112 * passed a snapshot. As long as the snapshot is acquired in a
1113 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1114 * REPEATABLE READ transaction provides the appropriate integrity
1115 * guarantees. This is a kluge, but safe for back-patching.
1117 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1118 ExecuteSqlStatement(AH,
1119 "SET TRANSACTION ISOLATION LEVEL "
1120 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1122 ExecuteSqlStatement(AH,
1123 "SET TRANSACTION ISOLATION LEVEL "
1124 "REPEATABLE READ, READ ONLY");
1128 ExecuteSqlStatement(AH,
1129 "SET TRANSACTION ISOLATION LEVEL "
1130 "SERIALIZABLE, READ ONLY");
1134 * If user specified a snapshot to use, select that. In a parallel dump
1135 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1136 * is already set (if the server can handle it) and we should use that.
1139 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1141 if (AH->sync_snapshot_id)
1143 PQExpBuffer query = createPQExpBuffer();
1145 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1146 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1147 ExecuteSqlStatement(AH, query->data);
1148 destroyPQExpBuffer(query);
1150 else if (AH->numWorkers > 1 &&
1151 AH->remoteVersion >= 90200 &&
1152 !dopt->no_synchronized_snapshots)
1154 if (AH->isStandby && AH->remoteVersion < 100000)
1156 "Synchronized snapshots on standby servers are not supported by this server version.\n"
1157 "Run with --no-synchronized-snapshots instead if you do not need\n"
1158 "synchronized snapshots.\n");
1161 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1165 /* Set up connection for a parallel worker process */
1167 setupDumpWorker(Archive *AH)
1170 * We want to re-select all the same values the master connection is
1171 * using. We'll have inherited directly-usable values in
1172 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1173 * inherited encoding value back to a string to pass to setup_connection.
1175 setup_connection(AH,
1176 pg_encoding_to_char(AH->encoding),
1182 get_synchronized_snapshot(Archive *fout)
1184 char *query = "SELECT pg_catalog.pg_export_snapshot()";
1188 res = ExecuteSqlQueryForSingleRow(fout, query);
1189 result = pg_strdup(PQgetvalue(res, 0, 0));
1195 static ArchiveFormat
1196 parseArchiveFormat(const char *format, ArchiveMode *mode)
1198 ArchiveFormat archiveFormat;
1200 *mode = archModeWrite;
1202 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1204 /* This is used by pg_dumpall, and is not documented */
1205 archiveFormat = archNull;
1206 *mode = archModeAppend;
1208 else if (pg_strcasecmp(format, "c") == 0)
1209 archiveFormat = archCustom;
1210 else if (pg_strcasecmp(format, "custom") == 0)
1211 archiveFormat = archCustom;
1212 else if (pg_strcasecmp(format, "d") == 0)
1213 archiveFormat = archDirectory;
1214 else if (pg_strcasecmp(format, "directory") == 0)
1215 archiveFormat = archDirectory;
1216 else if (pg_strcasecmp(format, "p") == 0)
1217 archiveFormat = archNull;
1218 else if (pg_strcasecmp(format, "plain") == 0)
1219 archiveFormat = archNull;
1220 else if (pg_strcasecmp(format, "t") == 0)
1221 archiveFormat = archTar;
1222 else if (pg_strcasecmp(format, "tar") == 0)
1223 archiveFormat = archTar;
1225 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1226 return archiveFormat;
1230 * Find the OIDs of all schemas matching the given list of patterns,
1231 * and append them to the given OID list.
1234 expand_schema_name_patterns(Archive *fout,
1235 SimpleStringList *patterns,
1236 SimpleOidList *oids,
1241 SimpleStringListCell *cell;
1244 if (patterns->head == NULL)
1245 return; /* nothing to do */
1247 query = createPQExpBuffer();
1250 * The loop below runs multiple SELECTs might sometimes result in
1251 * duplicate entries in the OID list, but we don't care.
1254 for (cell = patterns->head; cell; cell = cell->next)
1256 appendPQExpBuffer(query,
1257 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1258 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1259 false, NULL, "n.nspname", NULL, NULL);
1261 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1262 if (strict_names && PQntuples(res) == 0)
1263 exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1265 for (i = 0; i < PQntuples(res); i++)
1267 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1271 resetPQExpBuffer(query);
1274 destroyPQExpBuffer(query);
1278 * Find the OIDs of all tables matching the given list of patterns,
1279 * and append them to the given OID list.
1282 expand_table_name_patterns(Archive *fout,
1283 SimpleStringList *patterns, SimpleOidList *oids,
1288 SimpleStringListCell *cell;
1291 if (patterns->head == NULL)
1292 return; /* nothing to do */
1294 query = createPQExpBuffer();
1297 * this might sometimes result in duplicate entries in the OID list, but
1301 for (cell = patterns->head; cell; cell = cell->next)
1304 * Query must remain ABSOLUTELY devoid of unqualified names. This
1305 * would be unnecessary given a pg_table_is_visible() variant taking a
1306 * search_path argument.
1308 appendPQExpBuffer(query,
1310 "\nFROM pg_catalog.pg_class c"
1311 "\n LEFT JOIN pg_catalog.pg_namespace n"
1312 "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1313 "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1314 "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1315 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1316 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1317 RELKIND_PARTITIONED_TABLE);
1318 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1319 false, "n.nspname", "c.relname", NULL,
1320 "pg_catalog.pg_table_is_visible(c.oid)");
1322 ExecuteSqlStatement(fout, "RESET search_path");
1323 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1324 PQclear(ExecuteSqlQueryForSingleRow(fout,
1325 ALWAYS_SECURE_SEARCH_PATH_SQL));
1326 if (strict_names && PQntuples(res) == 0)
1327 exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1329 for (i = 0; i < PQntuples(res); i++)
1331 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1335 resetPQExpBuffer(query);
1338 destroyPQExpBuffer(query);
1342 * checkExtensionMembership
1343 * Determine whether object is an extension member, and if so,
1344 * record an appropriate dependency and set the object's dump flag.
1346 * It's important to call this for each object that could be an extension
1347 * member. Generally, we integrate this with determining the object's
1348 * to-be-dumped-ness, since extension membership overrides other rules for that.
1350 * Returns true if object is an extension member, else false.
1353 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1355 ExtensionInfo *ext = findOwningExtension(dobj->catId);
1360 dobj->ext_member = true;
1362 /* Record dependency so that getDependencies needn't deal with that */
1363 addObjectDependency(dobj, ext->dobj.dumpId);
1366 * In 9.6 and above, mark the member object to have any non-initial ACL,
1367 * policies, and security labels dumped.
1369 * Note that any initial ACLs (see pg_init_privs) will be removed when we
1370 * extract the information about the object. We don't provide support for
1371 * initial policies and security labels and it seems unlikely for those to
1372 * ever exist, but we may have to revisit this later.
1374 * Prior to 9.6, we do not include any extension member components.
1376 * In binary upgrades, we still dump all components of the members
1377 * individually, since the idea is to exactly reproduce the database
1378 * contents rather than replace the extension contents with something
1381 if (fout->dopt->binary_upgrade)
1382 dobj->dump = ext->dobj.dump;
1385 if (fout->remoteVersion < 90600)
1386 dobj->dump = DUMP_COMPONENT_NONE;
1388 dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1389 DUMP_COMPONENT_SECLABEL |
1390 DUMP_COMPONENT_POLICY);
1397 * selectDumpableNamespace: policy-setting subroutine
1398 * Mark a namespace as to be dumped or not
1401 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1404 * If specific tables are being dumped, do not dump any complete
1405 * namespaces. If specific namespaces are being dumped, dump just those
1406 * namespaces. Otherwise, dump all non-system namespaces.
1408 if (table_include_oids.head != NULL)
1409 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1410 else if (schema_include_oids.head != NULL)
1411 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1412 simple_oid_list_member(&schema_include_oids,
1413 nsinfo->dobj.catId.oid) ?
1414 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1415 else if (fout->remoteVersion >= 90600 &&
1416 strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1419 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1420 * they are interesting (and not the original ACLs which were set at
1421 * initdb time, see pg_init_privs).
1423 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1425 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1426 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1428 /* Other system schemas don't get dumped */
1429 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1431 else if (strcmp(nsinfo->dobj.name, "public") == 0)
1434 * The public schema is a strange beast that sits in a sort of
1435 * no-mans-land between being a system object and a user object. We
1436 * don't want to dump creation or comment commands for it, because
1437 * that complicates matters for non-superuser use of pg_dump. But we
1438 * should dump any ACL changes that have occurred for it, and of
1439 * course we should dump contained objects.
1441 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1442 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1445 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1448 * In any case, a namespace can be excluded by an exclusion switch
1450 if (nsinfo->dobj.dump_contains &&
1451 simple_oid_list_member(&schema_exclude_oids,
1452 nsinfo->dobj.catId.oid))
1453 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1456 * If the schema belongs to an extension, allow extension membership to
1457 * override the dump decision for the schema itself. However, this does
1458 * not change dump_contains, so this won't change what we do with objects
1459 * within the schema. (If they belong to the extension, they'll get
1460 * suppressed by it, otherwise not.)
1462 (void) checkExtensionMembership(&nsinfo->dobj, fout);
1466 * selectDumpableTable: policy-setting subroutine
1467 * Mark a table as to be dumped or not
1470 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1472 if (checkExtensionMembership(&tbinfo->dobj, fout))
1473 return; /* extension membership overrides all else */
1476 * If specific tables are being dumped, dump just those tables; else, dump
1477 * according to the parent namespace's dump flag.
1479 if (table_include_oids.head != NULL)
1480 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1481 tbinfo->dobj.catId.oid) ?
1482 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1484 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1487 * In any case, a table can be excluded by an exclusion switch
1489 if (tbinfo->dobj.dump &&
1490 simple_oid_list_member(&table_exclude_oids,
1491 tbinfo->dobj.catId.oid))
1492 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1496 * selectDumpableType: policy-setting subroutine
1497 * Mark a type as to be dumped or not
1499 * If it's a table's rowtype or an autogenerated array type, we also apply a
1500 * special type code to facilitate sorting into the desired order. (We don't
1501 * want to consider those to be ordinary types because that would bring tables
1502 * up into the datatype part of the dump order.) We still set the object's
1503 * dump flag; that's not going to cause the dummy type to be dumped, but we
1504 * need it so that casts involving such types will be dumped correctly -- see
1505 * dumpCast. This means the flag should be set the same as for the underlying
1506 * object (the table or base type).
1509 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1511 /* skip complex types, except for standalone composite types */
1512 if (OidIsValid(tyinfo->typrelid) &&
1513 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1515 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1517 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1518 if (tytable != NULL)
1519 tyinfo->dobj.dump = tytable->dobj.dump;
1521 tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1525 /* skip auto-generated array types */
1526 if (tyinfo->isArray)
1528 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1531 * Fall through to set the dump flag; we assume that the subsequent
1532 * rules will do the same thing as they would for the array's base
1533 * type. (We cannot reliably look up the base type here, since
1534 * getTypes may not have processed it yet.)
1538 if (checkExtensionMembership(&tyinfo->dobj, fout))
1539 return; /* extension membership overrides all else */
1541 /* Dump based on if the contents of the namespace are being dumped */
1542 tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1546 * selectDumpableDefaultACL: policy-setting subroutine
1547 * Mark a default ACL as to be dumped or not
1549 * For per-schema default ACLs, dump if the schema is to be dumped.
1550 * Otherwise dump if we are dumping "everything". Note that dataOnly
1551 * and aclsSkip are checked separately.
1554 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1556 /* Default ACLs can't be extension members */
1558 if (dinfo->dobj.namespace)
1559 /* default ACLs are considered part of the namespace */
1560 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1562 dinfo->dobj.dump = dopt->include_everything ?
1563 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1567 * selectDumpableCast: policy-setting subroutine
1568 * Mark a cast as to be dumped or not
1570 * Casts do not belong to any particular namespace (since they haven't got
1571 * names), nor do they have identifiable owners. To distinguish user-defined
1572 * casts from built-in ones, we must resort to checking whether the cast's
1573 * OID is in the range reserved for initdb.
1576 selectDumpableCast(CastInfo *cast, Archive *fout)
1578 if (checkExtensionMembership(&cast->dobj, fout))
1579 return; /* extension membership overrides all else */
1582 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1583 * support ACLs currently.
1585 if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1586 cast->dobj.dump = DUMP_COMPONENT_NONE;
1588 cast->dobj.dump = fout->dopt->include_everything ?
1589 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1593 * selectDumpableProcLang: policy-setting subroutine
1594 * Mark a procedural language as to be dumped or not
1596 * Procedural languages do not belong to any particular namespace. To
1597 * identify built-in languages, we must resort to checking whether the
1598 * language's OID is in the range reserved for initdb.
1601 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1603 if (checkExtensionMembership(&plang->dobj, fout))
1604 return; /* extension membership overrides all else */
1607 * Only include procedural languages when we are dumping everything.
1609 * For from-initdb procedural languages, only include ACLs, as we do for
1610 * the pg_catalog namespace. We need this because procedural languages do
1611 * not live in any namespace.
1613 if (!fout->dopt->include_everything)
1614 plang->dobj.dump = DUMP_COMPONENT_NONE;
1617 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1618 plang->dobj.dump = fout->remoteVersion < 90600 ?
1619 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1621 plang->dobj.dump = DUMP_COMPONENT_ALL;
1626 * selectDumpableAccessMethod: policy-setting subroutine
1627 * Mark an access method as to be dumped or not
1629 * Access methods do not belong to any particular namespace. To identify
1630 * built-in access methods, we must resort to checking whether the
1631 * method's OID is in the range reserved for initdb.
1634 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1636 if (checkExtensionMembership(&method->dobj, fout))
1637 return; /* extension membership overrides all else */
1640 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1641 * they do not support ACLs currently.
1643 if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1644 method->dobj.dump = DUMP_COMPONENT_NONE;
1646 method->dobj.dump = fout->dopt->include_everything ?
1647 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1651 * selectDumpableExtension: policy-setting subroutine
1652 * Mark an extension as to be dumped or not
1654 * Built-in extensions should be skipped except for checking ACLs, since we
1655 * assume those will already be installed in the target database. We identify
1656 * such extensions by their having OIDs in the range reserved for initdb.
1657 * We dump all user-added extensions by default, or none of them if
1658 * include_everything is false (i.e., a --schema or --table switch was given).
1661 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1664 * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1665 * change permissions on their member objects, if they wish to, and have
1666 * those changes preserved.
1668 if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1669 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1671 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1672 dopt->include_everything ? DUMP_COMPONENT_ALL :
1673 DUMP_COMPONENT_NONE;
1677 * selectDumpablePublicationTable: policy-setting subroutine
1678 * Mark a publication table as to be dumped or not
1680 * Publication tables have schemas, but those are ignored in decision making,
1681 * because publications are only dumped when we are dumping everything.
1684 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1686 if (checkExtensionMembership(dobj, fout))
1687 return; /* extension membership overrides all else */
1689 dobj->dump = fout->dopt->include_everything ?
1690 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1694 * selectDumpableObject: policy-setting subroutine
1695 * Mark a generic dumpable object as to be dumped or not
1697 * Use this only for object types without a special-case routine above.
1700 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1702 if (checkExtensionMembership(dobj, fout))
1703 return; /* extension membership overrides all else */
1706 * Default policy is to dump if parent namespace is dumpable, or for
1707 * non-namespace-associated items, dump if we're dumping "everything".
1709 if (dobj->namespace)
1710 dobj->dump = dobj->namespace->dobj.dump_contains;
1712 dobj->dump = fout->dopt->include_everything ?
1713 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1717 * Dump a table's contents for loading using the COPY command
1718 * - this routine is called by the Archiver when it wants the table
1723 dumpTableData_copy(Archive *fout, void *dcontext)
1725 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1726 TableInfo *tbinfo = tdinfo->tdtable;
1727 const char *classname = tbinfo->dobj.name;
1728 PQExpBuffer q = createPQExpBuffer();
1731 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1732 * which uses it already.
1734 PQExpBuffer clistBuf = createPQExpBuffer();
1735 PGconn *conn = GetConnection(fout);
1739 const char *column_list;
1742 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1743 tbinfo->dobj.namespace->dobj.name, classname);
1746 * Specify the column list explicitly so that we have no possibility of
1747 * retrieving data in the wrong column order. (The default column
1748 * ordering of COPY will not be what we want in certain corner cases
1749 * involving ADD COLUMN and inheritance.)
1751 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1753 if (tdinfo->filtercond)
1755 /* Note: this syntax is only supported in 8.2 and up */
1756 appendPQExpBufferStr(q, "COPY (SELECT ");
1757 /* klugery to get rid of parens in column list */
1758 if (strlen(column_list) > 2)
1760 appendPQExpBufferStr(q, column_list + 1);
1761 q->data[q->len - 1] = ' ';
1764 appendPQExpBufferStr(q, "* ");
1765 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1766 fmtQualifiedDumpable(tbinfo),
1767 tdinfo->filtercond);
1771 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1772 fmtQualifiedDumpable(tbinfo),
1775 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1777 destroyPQExpBuffer(clistBuf);
1781 ret = PQgetCopyData(conn, ©buf, 0);
1784 break; /* done or error */
1788 WriteData(fout, copybuf, ret);
1795 * There was considerable discussion in late July, 2000 regarding
1796 * slowing down pg_dump when backing up large tables. Users with both
1797 * slow & fast (multi-processor) machines experienced performance
1798 * degradation when doing a backup.
1800 * Initial attempts based on sleeping for a number of ms for each ms
1801 * of work were deemed too complex, then a simple 'sleep in each loop'
1802 * implementation was suggested. The latter failed because the loop
1803 * was too tight. Finally, the following was implemented:
1805 * If throttle is non-zero, then
1806 * See how long since the last sleep.
1807 * Work out how long to sleep (based on ratio).
1808 * If sleep is more than 100ms, then
1814 * where the throttle value was the number of ms to sleep per ms of
1815 * work. The calculation was done in each loop.
1817 * Most of the hard work is done in the backend, and this solution
1818 * still did not work particularly well: on slow machines, the ratio
1819 * was 50:1, and on medium paced machines, 1:1, and on fast
1820 * multi-processor machines, it had little or no effect, for reasons
1821 * that were unclear.
1823 * Further discussion ensued, and the proposal was dropped.
1825 * For those people who want this feature, it can be implemented using
1826 * gettimeofday in each loop, calculating the time since last sleep,
1827 * multiplying that by the sleep ratio, then if the result is more
1828 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1829 * function to sleep for a subsecond period ie.
1831 * select(0, NULL, NULL, NULL, &tvi);
1833 * This will return after the interval specified in the structure tvi.
1834 * Finally, call gettimeofday again to save the 'last sleep time'.
1838 archprintf(fout, "\\.\n\n\n");
1842 /* copy data transfer failed */
1843 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1844 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1845 write_msg(NULL, "The command was: %s\n", q->data);
1849 /* Check command status and return to normal libpq state */
1850 res = PQgetResult(conn);
1851 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1853 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1854 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1855 write_msg(NULL, "The command was: %s\n", q->data);
1860 /* Do this to ensure we've pumped libpq back to idle state */
1861 if (PQgetResult(conn) != NULL)
1862 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1865 destroyPQExpBuffer(q);
1870 * Dump table data using INSERT commands.
1872 * Caution: when we restore from an archive file direct to database, the
1873 * INSERT commands emitted by this function have to be parsed by
1874 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1875 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1878 dumpTableData_insert(Archive *fout, void *dcontext)
1880 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1881 TableInfo *tbinfo = tdinfo->tdtable;
1882 DumpOptions *dopt = fout->dopt;
1883 PQExpBuffer q = createPQExpBuffer();
1884 PQExpBuffer insertStmt = NULL;
1890 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1891 "SELECT * FROM ONLY %s",
1892 fmtQualifiedDumpable(tbinfo));
1893 if (tdinfo->filtercond)
1894 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1896 ExecuteSqlStatement(fout, q->data);
1900 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1902 nfields = PQnfields(res);
1903 for (tuple = 0; tuple < PQntuples(res); tuple++)
1906 * First time through, we build as much of the INSERT statement as
1907 * possible in "insertStmt", which we can then just print for each
1908 * line. If the table happens to have zero columns then this will
1909 * be a complete statement, otherwise it will end in "VALUES(" and
1910 * be ready to have the row's column values appended.
1912 if (insertStmt == NULL)
1914 TableInfo *targettab;
1916 insertStmt = createPQExpBuffer();
1919 * When load-via-partition-root is set, get the root table
1920 * name for the partition table, so that we can reload data
1921 * through the root table.
1923 if (dopt->load_via_partition_root && tbinfo->ispartition)
1924 targettab = getRootTableInfo(tbinfo);
1928 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1929 fmtQualifiedDumpable(targettab));
1931 /* corner case for zero-column table */
1934 appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1938 /* append the list of column names if required */
1939 if (dopt->column_inserts)
1941 appendPQExpBufferChar(insertStmt, '(');
1942 for (field = 0; field < nfields; field++)
1945 appendPQExpBufferStr(insertStmt, ", ");
1946 appendPQExpBufferStr(insertStmt,
1947 fmtId(PQfname(res, field)));
1949 appendPQExpBufferStr(insertStmt, ") ");
1952 if (tbinfo->needs_override)
1953 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1955 appendPQExpBufferStr(insertStmt, "VALUES (");
1959 archputs(insertStmt->data, fout);
1961 /* if it is zero-column table then we're done */
1965 for (field = 0; field < nfields; field++)
1968 archputs(", ", fout);
1969 if (PQgetisnull(res, tuple, field))
1971 archputs("NULL", fout);
1975 /* XXX This code is partially duplicated in ruleutils.c */
1976 switch (PQftype(res, field))
1987 * These types are printed without quotes unless
1988 * they contain values that aren't accepted by the
1989 * scanner unquoted (e.g., 'NaN'). Note that
1990 * strtod() and friends might accept NaN, so we
1991 * can't use that to test.
1993 * In reality we only need to defend against
1994 * infinity and NaN, so we need not get too crazy
1995 * about pattern matching here.
1997 const char *s = PQgetvalue(res, tuple, field);
1999 if (strspn(s, "0123456789 +-eE.") == strlen(s))
2002 archprintf(fout, "'%s'", s);
2008 archprintf(fout, "B'%s'",
2009 PQgetvalue(res, tuple, field));
2013 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2014 archputs("true", fout);
2016 archputs("false", fout);
2020 /* All other types are printed as string literals. */
2021 resetPQExpBuffer(q);
2022 appendStringLiteralAH(q,
2023 PQgetvalue(res, tuple, field),
2025 archputs(q->data, fout);
2030 if (!dopt->do_nothing)
2031 archputs(");\n", fout);
2033 archputs(") ON CONFLICT DO NOTHING;\n", fout);
2036 if (PQntuples(res) <= 0)
2044 archputs("\n\n", fout);
2046 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2048 destroyPQExpBuffer(q);
2049 if (insertStmt != NULL)
2050 destroyPQExpBuffer(insertStmt);
2057 * get the root TableInfo for the given partition table.
2060 getRootTableInfo(TableInfo *tbinfo)
2062 TableInfo *parentTbinfo;
2064 Assert(tbinfo->ispartition);
2065 Assert(tbinfo->numParents == 1);
2067 parentTbinfo = tbinfo->parents[0];
2068 while (parentTbinfo->ispartition)
2070 Assert(parentTbinfo->numParents == 1);
2071 parentTbinfo = parentTbinfo->parents[0];
2074 return parentTbinfo;
2079 * dump the contents of a single table
2081 * Actually, this just makes an ArchiveEntry for the table contents.
2084 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2086 DumpOptions *dopt = fout->dopt;
2087 TableInfo *tbinfo = tdinfo->tdtable;
2088 PQExpBuffer copyBuf = createPQExpBuffer();
2089 PQExpBuffer clistBuf = createPQExpBuffer();
2090 DataDumperPtr dumpFn;
2092 const char *copyFrom;
2094 if (!dopt->dump_inserts)
2096 /* Dump/restore using COPY */
2097 dumpFn = dumpTableData_copy;
2100 * When load-via-partition-root is set, get the root table name for
2101 * the partition table, so that we can reload data through the root
2104 if (dopt->load_via_partition_root && tbinfo->ispartition)
2106 TableInfo *parentTbinfo;
2108 parentTbinfo = getRootTableInfo(tbinfo);
2109 copyFrom = fmtQualifiedDumpable(parentTbinfo);
2112 copyFrom = fmtQualifiedDumpable(tbinfo);
2114 /* must use 2 steps here 'cause fmtId is nonreentrant */
2115 appendPQExpBuffer(copyBuf, "COPY %s ",
2117 appendPQExpBuffer(copyBuf, "%s FROM stdin;\n",
2118 fmtCopyColumnList(tbinfo, clistBuf));
2119 copyStmt = copyBuf->data;
2123 /* Restore using INSERT */
2124 dumpFn = dumpTableData_insert;
2129 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2130 * dependency on its table as "special" and pass it to ArchiveEntry now.
2131 * See comments for BuildArchiveDependencies.
2133 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2137 te = ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2138 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2139 NULL, tbinfo->rolname,
2140 "TABLE DATA", SECTION_DATA,
2142 &(tbinfo->dobj.dumpId), 1,
2146 * Set the TocEntry's dataLength in case we are doing a parallel dump
2147 * and want to order dump jobs by table size. We choose to measure
2148 * dataLength in table pages during dump, so no scaling is needed.
2149 * However, relpages is declared as "integer" in pg_class, and hence
2150 * also in TableInfo, but it's really BlockNumber a/k/a unsigned int.
2151 * Cast so that we get the right interpretation of table sizes
2152 * exceeding INT_MAX pages.
2154 te->dataLength = (BlockNumber) tbinfo->relpages;
2157 destroyPQExpBuffer(copyBuf);
2158 destroyPQExpBuffer(clistBuf);
2162 * refreshMatViewData -
2163 * load or refresh the contents of a single materialized view
2165 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2169 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2171 TableInfo *tbinfo = tdinfo->tdtable;
2174 /* If the materialized view is not flagged as populated, skip this. */
2175 if (!tbinfo->relispopulated)
2178 q = createPQExpBuffer();
2180 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2181 fmtQualifiedDumpable(tbinfo));
2183 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2185 tdinfo->dobj.catId, /* catalog ID */
2186 tdinfo->dobj.dumpId, /* dump ID */
2187 tbinfo->dobj.name, /* Name */
2188 tbinfo->dobj.namespace->dobj.name, /* Namespace */
2189 NULL, /* Tablespace */
2190 tbinfo->rolname, /* Owner */
2191 "MATERIALIZED VIEW DATA", /* Desc */
2192 SECTION_POST_DATA, /* Section */
2193 q->data, /* Create */
2196 tdinfo->dobj.dependencies, /* Deps */
2197 tdinfo->dobj.nDeps, /* # Deps */
2199 NULL); /* Dumper Arg */
2201 destroyPQExpBuffer(q);
2206 * set up dumpable objects representing the contents of tables
2209 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind)
2213 for (i = 0; i < numTables; i++)
2215 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2216 (!relkind || tblinfo[i].relkind == relkind))
2217 makeTableDataInfo(dopt, &(tblinfo[i]));
2222 * Make a dumpable object for the data of this specific table
2224 * Note: we make a TableDataInfo if and only if we are going to dump the
2225 * table data; the "dump" flag in such objects isn't used.
2228 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo)
2230 TableDataInfo *tdinfo;
2233 * Nothing to do if we already decided to dump the table. This will
2234 * happen for "config" tables.
2236 if (tbinfo->dataObj != NULL)
2239 /* Skip VIEWs (no data to dump) */
2240 if (tbinfo->relkind == RELKIND_VIEW)
2242 /* Skip FOREIGN TABLEs (no data to dump) */
2243 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2245 /* Skip partitioned tables (data in partitions) */
2246 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2249 /* Don't dump data in unlogged tables, if so requested */
2250 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2251 dopt->no_unlogged_table_data)
2254 /* Check that the data is not explicitly excluded */
2255 if (simple_oid_list_member(&tabledata_exclude_oids,
2256 tbinfo->dobj.catId.oid))
2259 /* OK, let's dump it */
2260 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2262 if (tbinfo->relkind == RELKIND_MATVIEW)
2263 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2264 else if (tbinfo->relkind == RELKIND_SEQUENCE)
2265 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2267 tdinfo->dobj.objType = DO_TABLE_DATA;
2270 * Note: use tableoid 0 so that this object won't be mistaken for
2271 * something that pg_depend entries apply to.
2273 tdinfo->dobj.catId.tableoid = 0;
2274 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2275 AssignDumpId(&tdinfo->dobj);
2276 tdinfo->dobj.name = tbinfo->dobj.name;
2277 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2278 tdinfo->tdtable = tbinfo;
2279 tdinfo->filtercond = NULL; /* might get set later */
2280 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2282 tbinfo->dataObj = tdinfo;
2286 * The refresh for a materialized view must be dependent on the refresh for
2287 * any materialized view that this one is dependent on.
2289 * This must be called after all the objects are created, but before they are
2293 buildMatViewRefreshDependencies(Archive *fout)
2303 /* No Mat Views before 9.3. */
2304 if (fout->remoteVersion < 90300)
2307 query = createPQExpBuffer();
2309 appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2311 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2312 "FROM pg_depend d1 "
2313 "JOIN pg_class c1 ON c1.oid = d1.objid "
2314 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2315 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2316 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2317 "AND d2.objid = r1.oid "
2318 "AND d2.refobjid <> d1.objid "
2319 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2320 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2321 CppAsString2(RELKIND_VIEW) ") "
2322 "WHERE d1.classid = 'pg_class'::regclass "
2324 "SELECT w.objid, d3.refobjid, c3.relkind "
2326 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2327 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2328 "AND d3.objid = r3.oid "
2329 "AND d3.refobjid <> w.refobjid "
2330 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2331 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2332 CppAsString2(RELKIND_VIEW) ") "
2334 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2336 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2338 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2340 ntups = PQntuples(res);
2342 i_classid = PQfnumber(res, "classid");
2343 i_objid = PQfnumber(res, "objid");
2344 i_refobjid = PQfnumber(res, "refobjid");
2346 for (i = 0; i < ntups; i++)
2350 DumpableObject *dobj;
2351 DumpableObject *refdobj;
2353 TableInfo *reftbinfo;
2355 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2356 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2357 refobjId.tableoid = objId.tableoid;
2358 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2360 dobj = findObjectByCatalogId(objId);
2364 Assert(dobj->objType == DO_TABLE);
2365 tbinfo = (TableInfo *) dobj;
2366 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2367 dobj = (DumpableObject *) tbinfo->dataObj;
2370 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2372 refdobj = findObjectByCatalogId(refobjId);
2373 if (refdobj == NULL)
2376 Assert(refdobj->objType == DO_TABLE);
2377 reftbinfo = (TableInfo *) refdobj;
2378 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2379 refdobj = (DumpableObject *) reftbinfo->dataObj;
2380 if (refdobj == NULL)
2382 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2384 addObjectDependency(dobj, refdobj->dumpId);
2386 if (!reftbinfo->relispopulated)
2387 tbinfo->relispopulated = false;
2392 destroyPQExpBuffer(query);
2396 * getTableDataFKConstraints -
2397 * add dump-order dependencies reflecting foreign key constraints
2399 * This code is executed only in a data-only dump --- in schema+data dumps
2400 * we handle foreign key issues by not creating the FK constraints until
2401 * after the data is loaded. In a data-only dump, however, we want to
2402 * order the table data objects in such a way that a table's referenced
2403 * tables are restored first. (In the presence of circular references or
2404 * self-references this may be impossible; we'll detect and complain about
2405 * that during the dependency sorting step.)
2408 getTableDataFKConstraints(void)
2410 DumpableObject **dobjs;
2414 /* Search through all the dumpable objects for FK constraints */
2415 getDumpableObjects(&dobjs, &numObjs);
2416 for (i = 0; i < numObjs; i++)
2418 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2420 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2423 /* Not interesting unless both tables are to be dumped */
2424 if (cinfo->contable == NULL ||
2425 cinfo->contable->dataObj == NULL)
2427 ftable = findTableByOid(cinfo->confrelid);
2428 if (ftable == NULL ||
2429 ftable->dataObj == NULL)
2433 * Okay, make referencing table's TABLE_DATA object depend on the
2434 * referenced table's TABLE_DATA object.
2436 addObjectDependency(&cinfo->contable->dataObj->dobj,
2437 ftable->dataObj->dobj.dumpId);
2445 * guessConstraintInheritance:
2446 * In pre-8.4 databases, we can't tell for certain which constraints
2447 * are inherited. We assume a CHECK constraint is inherited if its name
2448 * matches the name of any constraint in the parent. Originally this code
2449 * tried to compare the expression texts, but that can fail for various
2450 * reasons --- for example, if the parent and child tables are in different
2451 * schemas, reverse-listing of function calls may produce different text
2452 * (schema-qualified or not) depending on search path.
2454 * In 8.4 and up we can rely on the conislocal field to decide which
2455 * constraints must be dumped; much safer.
2457 * This function assumes all conislocal flags were initialized to true.
2458 * It clears the flag on anything that seems to be inherited.
2461 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2467 for (i = 0; i < numTables; i++)
2469 TableInfo *tbinfo = &(tblinfo[i]);
2471 TableInfo **parents;
2474 /* Sequences and views never have parents */
2475 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2476 tbinfo->relkind == RELKIND_VIEW)
2479 /* Don't bother computing anything for non-target tables, either */
2480 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2483 numParents = tbinfo->numParents;
2484 parents = tbinfo->parents;
2486 if (numParents == 0)
2487 continue; /* nothing to see here, move along */
2489 /* scan for inherited CHECK constraints */
2490 for (j = 0; j < tbinfo->ncheck; j++)
2492 ConstraintInfo *constr;
2494 constr = &(tbinfo->checkexprs[j]);
2496 for (k = 0; k < numParents; k++)
2500 parent = parents[k];
2501 for (l = 0; l < parent->ncheck; l++)
2503 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2505 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2507 constr->conislocal = false;
2511 if (!constr->conislocal)
2521 * dump the database definition
2524 dumpDatabase(Archive *fout)
2526 DumpOptions *dopt = fout->dopt;
2527 PQExpBuffer dbQry = createPQExpBuffer();
2528 PQExpBuffer delQry = createPQExpBuffer();
2529 PQExpBuffer creaQry = createPQExpBuffer();
2530 PQExpBuffer labelq = createPQExpBuffer();
2531 PGconn *conn = GetConnection(fout);
2549 const char *datname,
2564 write_msg(NULL, "saving database definition\n");
2566 /* Fetch the database-level properties for this database */
2567 if (fout->remoteVersion >= 90600)
2569 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2570 "(%s datdba) AS dba, "
2571 "pg_encoding_to_char(encoding) AS encoding, "
2572 "datcollate, datctype, datfrozenxid, datminmxid, "
2573 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2574 " SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2575 " EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2577 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2578 " SELECT unnest(acldefault('d',datdba)) AS acl "
2579 " EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2581 "datistemplate, datconnlimit, "
2582 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2583 "shobj_description(oid, 'pg_database') AS description "
2586 "WHERE datname = current_database()",
2589 else if (fout->remoteVersion >= 90300)
2591 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2592 "(%s datdba) AS dba, "
2593 "pg_encoding_to_char(encoding) AS encoding, "
2594 "datcollate, datctype, datfrozenxid, datminmxid, "
2595 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2596 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2597 "shobj_description(oid, 'pg_database') AS description "
2600 "WHERE datname = current_database()",
2603 else if (fout->remoteVersion >= 80400)
2605 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2606 "(%s datdba) AS dba, "
2607 "pg_encoding_to_char(encoding) AS encoding, "
2608 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2609 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2610 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2611 "shobj_description(oid, 'pg_database') AS description "
2614 "WHERE datname = current_database()",
2617 else if (fout->remoteVersion >= 80200)
2619 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2620 "(%s datdba) AS dba, "
2621 "pg_encoding_to_char(encoding) AS encoding, "
2622 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2623 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2624 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2625 "shobj_description(oid, 'pg_database') AS description "
2628 "WHERE datname = current_database()",
2633 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2634 "(%s datdba) AS dba, "
2635 "pg_encoding_to_char(encoding) AS encoding, "
2636 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2637 "datacl, '' as rdatacl, datistemplate, "
2638 "-1 as datconnlimit, "
2639 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2641 "WHERE datname = current_database()",
2645 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2647 i_tableoid = PQfnumber(res, "tableoid");
2648 i_oid = PQfnumber(res, "oid");
2649 i_datname = PQfnumber(res, "datname");
2650 i_dba = PQfnumber(res, "dba");
2651 i_encoding = PQfnumber(res, "encoding");
2652 i_collate = PQfnumber(res, "datcollate");
2653 i_ctype = PQfnumber(res, "datctype");
2654 i_frozenxid = PQfnumber(res, "datfrozenxid");
2655 i_minmxid = PQfnumber(res, "datminmxid");
2656 i_datacl = PQfnumber(res, "datacl");
2657 i_rdatacl = PQfnumber(res, "rdatacl");
2658 i_datistemplate = PQfnumber(res, "datistemplate");
2659 i_datconnlimit = PQfnumber(res, "datconnlimit");
2660 i_tablespace = PQfnumber(res, "tablespace");
2662 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2663 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2664 datname = PQgetvalue(res, 0, i_datname);
2665 dba = PQgetvalue(res, 0, i_dba);
2666 encoding = PQgetvalue(res, 0, i_encoding);
2667 collate = PQgetvalue(res, 0, i_collate);
2668 ctype = PQgetvalue(res, 0, i_ctype);
2669 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2670 minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2671 datacl = PQgetvalue(res, 0, i_datacl);
2672 rdatacl = PQgetvalue(res, 0, i_rdatacl);
2673 datistemplate = PQgetvalue(res, 0, i_datistemplate);
2674 datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2675 tablespace = PQgetvalue(res, 0, i_tablespace);
2677 qdatname = pg_strdup(fmtId(datname));
2680 * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2681 * and tablespace since those can't be altered later. Other DB properties
2682 * are left to the DATABASE PROPERTIES entry, so that they can be applied
2683 * after reconnecting to the target DB.
2685 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2687 if (strlen(encoding) > 0)
2689 appendPQExpBufferStr(creaQry, " ENCODING = ");
2690 appendStringLiteralAH(creaQry, encoding, fout);
2692 if (strlen(collate) > 0)
2694 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2695 appendStringLiteralAH(creaQry, collate, fout);
2697 if (strlen(ctype) > 0)
2699 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2700 appendStringLiteralAH(creaQry, ctype, fout);
2704 * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2705 * thing; the decision whether to specify a tablespace should be left till
2706 * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2707 * label the DATABASE entry with the tablespace and let the normal
2708 * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2709 * attention to default_tablespace, so that won't work.
2711 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2712 !dopt->outputNoTablespaces)
2713 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2715 appendPQExpBufferStr(creaQry, ";\n");
2717 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2720 dbDumpId = createDumpId();
2723 dbCatId, /* catalog ID */
2724 dbDumpId, /* dump ID */
2726 NULL, /* Namespace */
2727 NULL, /* Tablespace */
2729 "DATABASE", /* Desc */
2730 SECTION_PRE_DATA, /* Section */
2731 creaQry->data, /* Create */
2732 delQry->data, /* Del */
2737 NULL); /* Dumper Arg */
2739 /* Compute correct tag for archive entry */
2740 appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2742 /* Dump DB comment if any */
2743 if (fout->remoteVersion >= 80200)
2746 * 8.2 and up keep comments on shared objects in a shared table, so we
2747 * cannot use the dumpComment() code used for other database objects.
2748 * Be careful that the ArchiveEntry parameters match that function.
2750 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2752 if (comment && *comment && !dopt->no_comments)
2754 resetPQExpBuffer(dbQry);
2757 * Generates warning when loaded into a differently-named
2760 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2761 appendStringLiteralAH(dbQry, comment, fout);
2762 appendPQExpBufferStr(dbQry, ";\n");
2764 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2765 labelq->data, NULL, NULL, dba,
2766 "COMMENT", SECTION_NONE,
2767 dbQry->data, "", NULL,
2774 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2775 dbCatId, 0, dbDumpId);
2778 /* Dump DB security label, if enabled */
2779 if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2782 PQExpBuffer seclabelQry;
2784 seclabelQry = createPQExpBuffer();
2786 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2787 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2788 resetPQExpBuffer(seclabelQry);
2789 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2790 if (seclabelQry->len > 0)
2791 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2792 labelq->data, NULL, NULL, dba,
2793 "SECURITY LABEL", SECTION_NONE,
2794 seclabelQry->data, "", NULL,
2797 destroyPQExpBuffer(seclabelQry);
2802 * Dump ACL if any. Note that we do not support initial privileges
2803 * (pg_init_privs) on databases.
2805 dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2806 qdatname, NULL, NULL,
2807 dba, datacl, rdatacl, "", "");
2810 * Now construct a DATABASE PROPERTIES archive entry to restore any
2811 * non-default database-level properties. (The reason this must be
2812 * separate is that we cannot put any additional commands into the TOC
2813 * entry that has CREATE DATABASE. pg_restore would execute such a group
2814 * in an implicit transaction block, and the backend won't allow CREATE
2815 * DATABASE in that context.)
2817 resetPQExpBuffer(creaQry);
2818 resetPQExpBuffer(delQry);
2820 if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2821 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2822 qdatname, datconnlimit);
2824 if (strcmp(datistemplate, "t") == 0)
2826 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2830 * The backend won't accept DROP DATABASE on a template database. We
2831 * can deal with that by removing the template marking before the DROP
2832 * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
2833 * since no such command is currently supported, fake it with a direct
2834 * UPDATE on pg_database.
2836 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2837 "SET datistemplate = false WHERE datname = ");
2838 appendStringLiteralAH(delQry, datname, fout);
2839 appendPQExpBufferStr(delQry, ";\n");
2842 /* Add database-specific SET options */
2843 dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2846 * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2847 * entry, too, for lack of a better place.
2849 if (dopt->binary_upgrade)
2851 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2852 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2853 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2855 frozenxid, minmxid);
2856 appendStringLiteralAH(creaQry, datname, fout);
2857 appendPQExpBufferStr(creaQry, ";\n");
2860 if (creaQry->len > 0)
2861 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2862 datname, NULL, NULL, dba,
2863 "DATABASE PROPERTIES", SECTION_PRE_DATA,
2864 creaQry->data, delQry->data, NULL,
2869 * pg_largeobject comes from the old system intact, so set its
2870 * relfrozenxids and relminmxids.
2872 if (dopt->binary_upgrade)
2875 PQExpBuffer loFrozenQry = createPQExpBuffer();
2876 PQExpBuffer loOutQry = createPQExpBuffer();
2883 if (fout->remoteVersion >= 90300)
2884 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2885 "FROM pg_catalog.pg_class\n"
2886 "WHERE oid = %u;\n",
2887 LargeObjectRelationId);
2889 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2890 "FROM pg_catalog.pg_class\n"
2891 "WHERE oid = %u;\n",
2892 LargeObjectRelationId);
2894 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2896 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2897 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2899 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2900 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2901 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2902 "WHERE oid = %u;\n",
2903 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2904 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2905 LargeObjectRelationId);
2906 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2907 "pg_largeobject", NULL, NULL, "",
2908 "pg_largeobject", SECTION_PRE_DATA,
2909 loOutQry->data, "", NULL,
2915 destroyPQExpBuffer(loFrozenQry);
2916 destroyPQExpBuffer(loOutQry);
2922 destroyPQExpBuffer(dbQry);
2923 destroyPQExpBuffer(delQry);
2924 destroyPQExpBuffer(creaQry);
2925 destroyPQExpBuffer(labelq);
2929 * Collect any database-specific or role-and-database-specific SET options
2930 * for this database, and append them to outbuf.
2933 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
2934 const char *dbname, Oid dboid)
2936 PGconn *conn = GetConnection(AH);
2937 PQExpBuffer buf = createPQExpBuffer();
2942 * First collect database-specific options. Pre-8.4 server versions lack
2943 * unnest(), so we do this the hard way by querying once per subscript.
2947 if (AH->remoteVersion >= 90000)
2948 printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
2949 "WHERE setrole = 0 AND setdatabase = '%u'::oid",
2952 printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
2954 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
2956 if (PQntuples(res) == 1 &&
2957 !PQgetisnull(res, 0, 0))
2959 makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
2960 "DATABASE", dbname, NULL, NULL,
2972 /* Now look for role-and-database-specific options */
2973 if (AH->remoteVersion >= 90000)
2975 /* Here we can assume we have unnest() */
2976 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
2977 "FROM pg_db_role_setting s, pg_roles r "
2978 "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
2981 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
2983 if (PQntuples(res) > 0)
2987 for (i = 0; i < PQntuples(res); i++)
2988 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
2989 "ROLE", PQgetvalue(res, i, 0),
2997 destroyPQExpBuffer(buf);
3001 * dumpEncoding: put the correct encoding into the archive
3004 dumpEncoding(Archive *AH)
3006 const char *encname = pg_encoding_to_char(AH->encoding);
3007 PQExpBuffer qry = createPQExpBuffer();
3010 write_msg(NULL, "saving encoding = %s\n", encname);
3012 appendPQExpBufferStr(qry, "SET client_encoding = ");
3013 appendStringLiteralAH(qry, encname, AH);
3014 appendPQExpBufferStr(qry, ";\n");
3016 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3017 "ENCODING", NULL, NULL, "",
3018 "ENCODING", SECTION_PRE_DATA,
3019 qry->data, "", NULL,
3023 destroyPQExpBuffer(qry);
3028 * dumpStdStrings: put the correct escape string behavior into the archive
3031 dumpStdStrings(Archive *AH)
3033 const char *stdstrings = AH->std_strings ? "on" : "off";
3034 PQExpBuffer qry = createPQExpBuffer();
3037 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3040 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3043 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3044 "STDSTRINGS", NULL, NULL, "",
3045 "STDSTRINGS", SECTION_PRE_DATA,
3046 qry->data, "", NULL,
3050 destroyPQExpBuffer(qry);
3054 * dumpSearchPath: record the active search_path in the archive
3057 dumpSearchPath(Archive *AH)
3059 PQExpBuffer qry = createPQExpBuffer();
3060 PQExpBuffer path = createPQExpBuffer();
3062 char **schemanames = NULL;
3063 int nschemanames = 0;
3067 * We use the result of current_schemas(), not the search_path GUC,
3068 * because that might contain wildcards such as "$user", which won't
3069 * necessarily have the same value during restore. Also, this way avoids
3070 * listing schemas that may appear in search_path but not actually exist,
3071 * which seems like a prudent exclusion.
3073 res = ExecuteSqlQueryForSingleRow(AH,
3074 "SELECT pg_catalog.current_schemas(false)");
3076 if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3077 exit_horribly(NULL, "could not parse result of current_schemas()\n");
3080 * We use set_config(), not a simple "SET search_path" command, because
3081 * the latter has less-clean behavior if the search path is empty. While
3082 * that's likely to get fixed at some point, it seems like a good idea to
3083 * be as backwards-compatible as possible in what we put into archives.
3085 for (i = 0; i < nschemanames; i++)
3088 appendPQExpBufferStr(path, ", ");
3089 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3092 appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3093 appendStringLiteralAH(qry, path->data, AH);
3094 appendPQExpBufferStr(qry, ", false);\n");
3097 write_msg(NULL, "saving search_path = %s\n", path->data);
3099 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3100 "SEARCHPATH", NULL, NULL, "",
3101 "SEARCHPATH", SECTION_PRE_DATA,
3102 qry->data, "", NULL,
3106 /* Also save it in AH->searchpath, in case we're doing plain text dump */
3107 AH->searchpath = pg_strdup(qry->data);
3112 destroyPQExpBuffer(qry);
3113 destroyPQExpBuffer(path);
3119 * Collect schema-level data about large objects
3122 getBlobs(Archive *fout)
3124 DumpOptions *dopt = fout->dopt;
3125 PQExpBuffer blobQry = createPQExpBuffer();
3127 DumpableObject *bdata;
3138 /* Verbose message */
3140 write_msg(NULL, "reading large objects\n");
3142 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3143 if (fout->remoteVersion >= 90600)
3145 PQExpBuffer acl_subquery = createPQExpBuffer();
3146 PQExpBuffer racl_subquery = createPQExpBuffer();
3147 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3148 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3150 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3151 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3152 dopt->binary_upgrade);
3154 appendPQExpBuffer(blobQry,
3155 "SELECT l.oid, (%s l.lomowner) AS rolname, "
3158 "%s AS initlomacl, "
3159 "%s AS initrlomacl "
3160 "FROM pg_largeobject_metadata l "
3161 "LEFT JOIN pg_init_privs pip ON "
3162 "(l.oid = pip.objoid "
3163 "AND pip.classoid = 'pg_largeobject'::regclass "
3164 "AND pip.objsubid = 0) ",
3167 racl_subquery->data,
3168 init_acl_subquery->data,
3169 init_racl_subquery->data);
3171 destroyPQExpBuffer(acl_subquery);
3172 destroyPQExpBuffer(racl_subquery);
3173 destroyPQExpBuffer(init_acl_subquery);
3174 destroyPQExpBuffer(init_racl_subquery);
3176 else if (fout->remoteVersion >= 90000)
3177 appendPQExpBuffer(blobQry,
3178 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3179 "NULL AS rlomacl, NULL AS initlomacl, "
3180 "NULL AS initrlomacl "
3181 " FROM pg_largeobject_metadata",
3184 appendPQExpBufferStr(blobQry,
3185 "SELECT DISTINCT loid AS oid, "
3186 "NULL::name AS rolname, NULL::oid AS lomacl, "
3187 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3188 "NULL::oid AS initrlomacl "
3189 " FROM pg_largeobject");
3191 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3193 i_oid = PQfnumber(res, "oid");
3194 i_lomowner = PQfnumber(res, "rolname");
3195 i_lomacl = PQfnumber(res, "lomacl");
3196 i_rlomacl = PQfnumber(res, "rlomacl");
3197 i_initlomacl = PQfnumber(res, "initlomacl");
3198 i_initrlomacl = PQfnumber(res, "initrlomacl");
3200 ntups = PQntuples(res);
3203 * Each large object has its own BLOB archive entry.
3205 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3207 for (i = 0; i < ntups; i++)
3209 binfo[i].dobj.objType = DO_BLOB;
3210 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3211 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3212 AssignDumpId(&binfo[i].dobj);
3214 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3215 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3216 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3217 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3218 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3219 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3221 if (PQgetisnull(res, i, i_lomacl) &&
3222 PQgetisnull(res, i, i_rlomacl) &&
3223 PQgetisnull(res, i, i_initlomacl) &&
3224 PQgetisnull(res, i, i_initrlomacl))
3225 binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3228 * In binary-upgrade mode for blobs, we do *not* dump out the blob
3229 * data, as it will be copied by pg_upgrade, which simply copies the
3230 * pg_largeobject table. We *do* however dump out anything but the
3231 * data, as pg_upgrade copies just pg_largeobject, but not
3232 * pg_largeobject_metadata, after the dump is restored.
3234 if (dopt->binary_upgrade)
3235 binfo[i].dobj.dump &= ~DUMP_COMPONENT_DATA;
3239 * If we have any large objects, a "BLOBS" archive entry is needed. This
3240 * is just a placeholder for sorting; it carries no data now.
3244 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3245 bdata->objType = DO_BLOB_DATA;
3246 bdata->catId = nilCatalogId;
3247 AssignDumpId(bdata);
3248 bdata->name = pg_strdup("BLOBS");
3252 destroyPQExpBuffer(blobQry);
3258 * dump the definition (metadata) of the given large object
3261 dumpBlob(Archive *fout, BlobInfo *binfo)
3263 PQExpBuffer cquery = createPQExpBuffer();
3264 PQExpBuffer dquery = createPQExpBuffer();
3266 appendPQExpBuffer(cquery,
3267 "SELECT pg_catalog.lo_create('%s');\n",
3270 appendPQExpBuffer(dquery,
3271 "SELECT pg_catalog.lo_unlink('%s');\n",
3274 if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3275 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3279 "BLOB", SECTION_PRE_DATA,
3280 cquery->data, dquery->data, NULL,
3284 /* Dump comment if any */
3285 if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3286 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3287 NULL, binfo->rolname,
3288 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3290 /* Dump security label if any */
3291 if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3292 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3293 NULL, binfo->rolname,
3294 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3296 /* Dump ACL if any */
3297 if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3298 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3299 binfo->dobj.name, NULL,
3300 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3301 binfo->initblobacl, binfo->initrblobacl);
3303 destroyPQExpBuffer(cquery);
3304 destroyPQExpBuffer(dquery);
3309 * dump the data contents of all large objects
3312 dumpBlobs(Archive *fout, void *arg)
3314 const char *blobQry;
3315 const char *blobFetchQry;
3316 PGconn *conn = GetConnection(fout);
3318 char buf[LOBBUFSIZE];
3324 write_msg(NULL, "saving large objects\n");
3327 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3328 * the already-in-memory dumpable objects instead...
3330 if (fout->remoteVersion >= 90000)
3332 "DECLARE bloboid CURSOR FOR "
3333 "SELECT oid FROM pg_largeobject_metadata ORDER BY 1";
3336 "DECLARE bloboid CURSOR FOR "
3337 "SELECT DISTINCT loid FROM pg_largeobject ORDER BY 1";
3339 ExecuteSqlStatement(fout, blobQry);
3341 /* Command to fetch from cursor */
3342 blobFetchQry = "FETCH 1000 IN bloboid";
3347 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3349 /* Process the tuples, if any */
3350 ntups = PQntuples(res);
3351 for (i = 0; i < ntups; i++)
3356 blobOid = atooid(PQgetvalue(res, i, 0));
3358 loFd = lo_open(conn, blobOid, INV_READ);
3360 exit_horribly(NULL, "could not open large object %u: %s",
3361 blobOid, PQerrorMessage(conn));
3363 StartBlob(fout, blobOid);
3365 /* Now read it in chunks, sending data to archive */
3368 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3370 exit_horribly(NULL, "error reading large object %u: %s",
3371 blobOid, PQerrorMessage(conn));
3373 WriteData(fout, buf, cnt);
3376 lo_close(conn, loFd);
3378 EndBlob(fout, blobOid);
3382 } while (ntups > 0);
3389 * get information about policies on a dumpable table.
3392 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3396 PolicyInfo *polinfo;
3401 int i_polpermissive;
3409 if (fout->remoteVersion < 90500)
3412 query = createPQExpBuffer();
3414 for (i = 0; i < numTables; i++)
3416 TableInfo *tbinfo = &tblinfo[i];
3418 /* Ignore row security on tables not to be dumped */
3419 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3423 write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3424 tbinfo->dobj.namespace->dobj.name,
3428 * Get row security enabled information for the table. We represent
3429 * RLS being enabled on a table by creating a PolicyInfo object with
3435 * Note: use tableoid 0 so that this object won't be mistaken for
3436 * something that pg_depend entries apply to.
3438 polinfo = pg_malloc(sizeof(PolicyInfo));
3439 polinfo->dobj.objType = DO_POLICY;
3440 polinfo->dobj.catId.tableoid = 0;
3441 polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3442 AssignDumpId(&polinfo->dobj);
3443 polinfo->dobj.namespace = tbinfo->dobj.namespace;
3444 polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3445 polinfo->poltable = tbinfo;
3446 polinfo->polname = NULL;
3447 polinfo->polcmd = '\0';
3448 polinfo->polpermissive = 0;
3449 polinfo->polroles = NULL;
3450 polinfo->polqual = NULL;
3451 polinfo->polwithcheck = NULL;
3455 write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3456 tbinfo->dobj.namespace->dobj.name,
3459 resetPQExpBuffer(query);
3461 /* Get the policies for the table. */
3462 if (fout->remoteVersion >= 100000)
3463 appendPQExpBuffer(query,
3464 "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3465 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3466 " 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, "
3467 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3468 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3469 "FROM pg_catalog.pg_policy pol "
3470 "WHERE polrelid = '%u'",
3471 tbinfo->dobj.catId.oid);
3473 appendPQExpBuffer(query,
3474 "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3475 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3476 " 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, "
3477 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3478 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3479 "FROM pg_catalog.pg_policy pol "
3480 "WHERE polrelid = '%u'",
3481 tbinfo->dobj.catId.oid);
3482 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3484 ntups = PQntuples(res);
3489 * No explicit policies to handle (only the default-deny policy,
3490 * which is handled as part of the table definition). Clean up
3497 i_oid = PQfnumber(res, "oid");
3498 i_tableoid = PQfnumber(res, "tableoid");
3499 i_polname = PQfnumber(res, "polname");
3500 i_polcmd = PQfnumber(res, "polcmd");
3501 i_polpermissive = PQfnumber(res, "polpermissive");
3502 i_polroles = PQfnumber(res, "polroles");
3503 i_polqual = PQfnumber(res, "polqual");
3504 i_polwithcheck = PQfnumber(res, "polwithcheck");
3506 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3508 for (j = 0; j < ntups; j++)
3510 polinfo[j].dobj.objType = DO_POLICY;
3511 polinfo[j].dobj.catId.tableoid =
3512 atooid(PQgetvalue(res, j, i_tableoid));
3513 polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3514 AssignDumpId(&polinfo[j].dobj);
3515 polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3516 polinfo[j].poltable = tbinfo;
3517 polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3518 polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3520 polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3521 polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3523 if (PQgetisnull(res, j, i_polroles))
3524 polinfo[j].polroles = NULL;
3526 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3528 if (PQgetisnull(res, j, i_polqual))
3529 polinfo[j].polqual = NULL;
3531 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3533 if (PQgetisnull(res, j, i_polwithcheck))
3534 polinfo[j].polwithcheck = NULL;
3536 polinfo[j].polwithcheck
3537 = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3541 destroyPQExpBuffer(query);
3546 * dump the definition of the given policy
3549 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3551 DumpOptions *dopt = fout->dopt;
3552 TableInfo *tbinfo = polinfo->poltable;
3562 * If polname is NULL, then this record is just indicating that ROW LEVEL
3563 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3564 * ROW LEVEL SECURITY.
3566 if (polinfo->polname == NULL)
3568 query = createPQExpBuffer();
3570 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3571 fmtQualifiedDumpable(tbinfo));
3574 * We must emit the ROW SECURITY object's dependency on its table
3575 * explicitly, because it will not match anything in pg_depend (unlike
3576 * the case for other PolicyInfo objects).
3578 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3579 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3581 polinfo->dobj.namespace->dobj.name,
3584 "ROW SECURITY", SECTION_POST_DATA,
3585 query->data, "", NULL,
3586 &(tbinfo->dobj.dumpId), 1,
3589 destroyPQExpBuffer(query);
3593 if (polinfo->polcmd == '*')
3595 else if (polinfo->polcmd == 'r')
3596 cmd = " FOR SELECT";
3597 else if (polinfo->polcmd == 'a')
3598 cmd = " FOR INSERT";
3599 else if (polinfo->polcmd == 'w')
3600 cmd = " FOR UPDATE";
3601 else if (polinfo->polcmd == 'd')
3602 cmd = " FOR DELETE";
3605 write_msg(NULL, "unexpected policy command type: %c\n",
3610 query = createPQExpBuffer();
3611 delqry = createPQExpBuffer();
3613 appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3615 appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3616 !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3618 if (polinfo->polroles != NULL)
3619 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3621 if (polinfo->polqual != NULL)
3622 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3624 if (polinfo->polwithcheck != NULL)
3625 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3627 appendPQExpBuffer(query, ";\n");
3629 appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3630 appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3632 tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3634 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3635 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3637 polinfo->dobj.namespace->dobj.name,
3640 "POLICY", SECTION_POST_DATA,
3641 query->data, delqry->data, NULL,
3646 destroyPQExpBuffer(query);
3647 destroyPQExpBuffer(delqry);
3652 * get information about publications
3655 getPublications(Archive *fout)
3657 DumpOptions *dopt = fout->dopt;
3660 PublicationInfo *pubinfo;
3673 if (dopt->no_publications || fout->remoteVersion < 100000)
3676 query = createPQExpBuffer();
3678 resetPQExpBuffer(query);
3680 /* Get the publications. */
3681 if (fout->remoteVersion >= 110000)
3682 appendPQExpBuffer(query,
3683 "SELECT p.tableoid, p.oid, p.pubname, "
3684 "(%s p.pubowner) AS rolname, "
3685 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3686 "FROM pg_publication p",
3689 appendPQExpBuffer(query,
3690 "SELECT p.tableoid, p.oid, p.pubname, "
3691 "(%s p.pubowner) AS rolname, "
3692 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3693 "FROM pg_publication p",
3696 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3698 ntups = PQntuples(res);
3700 i_tableoid = PQfnumber(res, "tableoid");
3701 i_oid = PQfnumber(res, "oid");
3702 i_pubname = PQfnumber(res, "pubname");
3703 i_rolname = PQfnumber(res, "rolname");
3704 i_puballtables = PQfnumber(res, "puballtables");
3705 i_pubinsert = PQfnumber(res, "pubinsert");
3706 i_pubupdate = PQfnumber(res, "pubupdate");
3707 i_pubdelete = PQfnumber(res, "pubdelete");
3708 i_pubtruncate = PQfnumber(res, "pubtruncate");
3710 pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3712 for (i = 0; i < ntups; i++)
3714 pubinfo[i].dobj.objType = DO_PUBLICATION;
3715 pubinfo[i].dobj.catId.tableoid =
3716 atooid(PQgetvalue(res, i, i_tableoid));
3717 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3718 AssignDumpId(&pubinfo[i].dobj);
3719 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3720 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3721 pubinfo[i].puballtables =
3722 (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3723 pubinfo[i].pubinsert =
3724 (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3725 pubinfo[i].pubupdate =
3726 (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3727 pubinfo[i].pubdelete =
3728 (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3729 pubinfo[i].pubtruncate =
3730 (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
3732 if (strlen(pubinfo[i].rolname) == 0)
3733 write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3734 pubinfo[i].dobj.name);
3736 /* Decide whether we want to dump it */
3737 selectDumpableObject(&(pubinfo[i].dobj), fout);
3741 destroyPQExpBuffer(query);
3746 * dump the definition of the given publication
3749 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3756 if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3759 delq = createPQExpBuffer();
3760 query = createPQExpBuffer();
3762 qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3764 appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3767 appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3770 if (pubinfo->puballtables)
3771 appendPQExpBufferStr(query, " FOR ALL TABLES");
3773 appendPQExpBufferStr(query, " WITH (publish = '");
3774 if (pubinfo->pubinsert)
3776 appendPQExpBufferStr(query, "insert");
3780 if (pubinfo->pubupdate)
3783 appendPQExpBufferStr(query, ", ");
3785 appendPQExpBufferStr(query, "update");
3789 if (pubinfo->pubdelete)
3792 appendPQExpBufferStr(query, ", ");
3794 appendPQExpBufferStr(query, "delete");
3798 if (pubinfo->pubtruncate)
3801 appendPQExpBufferStr(query, ", ");
3803 appendPQExpBufferStr(query, "truncate");
3807 appendPQExpBufferStr(query, "');\n");
3809 ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3814 "PUBLICATION", SECTION_POST_DATA,
3815 query->data, delq->data, NULL,
3819 if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3820 dumpComment(fout, "PUBLICATION", qpubname,
3821 NULL, pubinfo->rolname,
3822 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3824 if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3825 dumpSecLabel(fout, "PUBLICATION", qpubname,
3826 NULL, pubinfo->rolname,
3827 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3829 destroyPQExpBuffer(delq);
3830 destroyPQExpBuffer(query);
3835 * getPublicationTables
3836 * get information about publication membership for dumpable tables.
3839 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3843 PublicationRelInfo *pubrinfo;
3844 DumpOptions *dopt = fout->dopt;
3852 if (dopt->no_publications || fout->remoteVersion < 100000)
3855 query = createPQExpBuffer();
3857 for (i = 0; i < numTables; i++)
3859 TableInfo *tbinfo = &tblinfo[i];
3861 /* Only plain tables can be aded to publications. */
3862 if (tbinfo->relkind != RELKIND_RELATION)
3866 * Ignore publication membership of tables whose definitions are not
3869 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3873 write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3874 tbinfo->dobj.namespace->dobj.name,
3877 resetPQExpBuffer(query);
3879 /* Get the publication membership for the table. */
3880 appendPQExpBuffer(query,
3881 "SELECT pr.tableoid, pr.oid, p.pubname "
3882 "FROM pg_publication_rel pr, pg_publication p "
3883 "WHERE pr.prrelid = '%u'"
3884 " AND p.oid = pr.prpubid",
3885 tbinfo->dobj.catId.oid);
3886 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3888 ntups = PQntuples(res);
3893 * Table is not member of any publications. Clean up and return.
3899 i_tableoid = PQfnumber(res, "tableoid");
3900 i_oid = PQfnumber(res, "oid");
3901 i_pubname = PQfnumber(res, "pubname");
3903 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3905 for (j = 0; j < ntups; j++)
3907 pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3908 pubrinfo[j].dobj.catId.tableoid =
3909 atooid(PQgetvalue(res, j, i_tableoid));
3910 pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3911 AssignDumpId(&pubrinfo[j].dobj);
3912 pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3913 pubrinfo[j].dobj.name = tbinfo->dobj.name;
3914 pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3915 pubrinfo[j].pubtable = tbinfo;
3917 /* Decide whether we want to dump it */
3918 selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3922 destroyPQExpBuffer(query);
3926 * dumpPublicationTable
3927 * dump the definition of the given publication table mapping
3930 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3932 TableInfo *tbinfo = pubrinfo->pubtable;
3936 if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3939 tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3941 query = createPQExpBuffer();
3943 appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3944 fmtId(pubrinfo->pubname));
3945 appendPQExpBuffer(query, " %s;\n",
3946 fmtQualifiedDumpable(tbinfo));
3949 * There is no point in creating drop query as drop query as the drop is
3950 * done by table drop.
3952 ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3954 tbinfo->dobj.namespace->dobj.name,
3957 "PUBLICATION TABLE", SECTION_POST_DATA,
3958 query->data, "", NULL,
3963 destroyPQExpBuffer(query);
3967 * Is the currently connected user a superuser?
3970 is_superuser(Archive *fout)
3972 ArchiveHandle *AH = (ArchiveHandle *) fout;
3975 val = PQparameterStatus(AH->connection, "is_superuser");
3977 if (val && strcmp(val, "on") == 0)
3985 * get information about subscriptions
3988 getSubscriptions(Archive *fout)
3990 DumpOptions *dopt = fout->dopt;
3993 SubscriptionInfo *subinfo;
4000 int i_subsynccommit;
4001 int i_subpublications;
4005 if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4008 if (!is_superuser(fout))
4012 res = ExecuteSqlQuery(fout,
4013 "SELECT count(*) FROM pg_subscription "
4014 "WHERE subdbid = (SELECT oid FROM pg_database"
4015 " WHERE datname = current_database())",
4017 n = atoi(PQgetvalue(res, 0, 0));
4019 write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4024 query = createPQExpBuffer();
4026 resetPQExpBuffer(query);
4028 /* Get the subscriptions in current database. */
4029 appendPQExpBuffer(query,
4030 "SELECT s.tableoid, s.oid, s.subname,"
4031 "(%s s.subowner) AS rolname, "
4032 " s.subconninfo, s.subslotname, s.subsynccommit, "
4033 " s.subpublications "
4034 "FROM pg_subscription s "
4035 "WHERE s.subdbid = (SELECT oid FROM pg_database"
4036 " WHERE datname = current_database())",
4038 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4040 ntups = PQntuples(res);
4042 i_tableoid = PQfnumber(res, "tableoid");
4043 i_oid = PQfnumber(res, "oid");
4044 i_subname = PQfnumber(res, "subname");
4045 i_rolname = PQfnumber(res, "rolname");
4046 i_subconninfo = PQfnumber(res, "subconninfo");
4047 i_subslotname = PQfnumber(res, "subslotname");
4048 i_subsynccommit = PQfnumber(res, "subsynccommit");
4049 i_subpublications = PQfnumber(res, "subpublications");
4051 subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4053 for (i = 0; i < ntups; i++)
4055 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4056 subinfo[i].dobj.catId.tableoid =
4057 atooid(PQgetvalue(res, i, i_tableoid));
4058 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4059 AssignDumpId(&subinfo[i].dobj);
4060 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4061 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4062 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4063 if (PQgetisnull(res, i, i_subslotname))
4064 subinfo[i].subslotname = NULL;
4066 subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4067 subinfo[i].subsynccommit =
4068 pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4069 subinfo[i].subpublications =
4070 pg_strdup(PQgetvalue(res, i, i_subpublications));
4072 if (strlen(subinfo[i].rolname) == 0)
4073 write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4074 subinfo[i].dobj.name);
4076 /* Decide whether we want to dump it */
4077 selectDumpableObject(&(subinfo[i].dobj), fout);
4081 destroyPQExpBuffer(query);
4086 * dump the definition of the given subscription
4089 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4093 PQExpBuffer publications;
4095 char **pubnames = NULL;
4099 if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4102 delq = createPQExpBuffer();
4103 query = createPQExpBuffer();
4105 qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4107 appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4110 appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4112 appendStringLiteralAH(query, subinfo->subconninfo, fout);
4114 /* Build list of quoted publications and append them to query. */
4115 if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4118 "WARNING: could not parse subpublications array\n");
4125 publications = createPQExpBuffer();
4126 for (i = 0; i < npubnames; i++)
4129 appendPQExpBufferStr(publications, ", ");
4131 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4134 appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4135 if (subinfo->subslotname)
4136 appendStringLiteralAH(query, subinfo->subslotname, fout);
4138 appendPQExpBufferStr(query, "NONE");
4140 if (strcmp(subinfo->subsynccommit, "off") != 0)
4141 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4143 appendPQExpBufferStr(query, ");\n");
4145 ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4150 "SUBSCRIPTION", SECTION_POST_DATA,
4151 query->data, delq->data, NULL,
4155 if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4156 dumpComment(fout, "SUBSCRIPTION", qsubname,
4157 NULL, subinfo->rolname,
4158 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4160 if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4161 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4162 NULL, subinfo->rolname,
4163 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4165 destroyPQExpBuffer(publications);
4169 destroyPQExpBuffer(delq);
4170 destroyPQExpBuffer(query);
4175 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4176 PQExpBuffer upgrade_buffer,
4178 bool force_array_type)
4180 PQExpBuffer upgrade_query = createPQExpBuffer();
4182 Oid pg_type_array_oid;
4184 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4185 appendPQExpBuffer(upgrade_buffer,
4186 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4189 /* we only support old >= 8.3 for binary upgrades */
4190 appendPQExpBuffer(upgrade_query,
4192 "FROM pg_catalog.pg_type "
4193 "WHERE oid = '%u'::pg_catalog.oid;",
4196 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4198 pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4202 if (!OidIsValid(pg_type_array_oid) && force_array_type)
4205 * If the old version didn't assign an array type, but the new version
4206 * does, we must select an unused type OID to assign. This currently
4207 * only happens for domains, when upgrading pre-v11 to v11 and up.
4209 * Note: local state here is kind of ugly, but we must have some,
4210 * since we mustn't choose the same unused OID more than once.
4212 static Oid next_possible_free_oid = FirstNormalObjectId;
4217 ++next_possible_free_oid;
4218 printfPQExpBuffer(upgrade_query,
4219 "SELECT EXISTS(SELECT 1 "
4220 "FROM pg_catalog.pg_type "
4221 "WHERE oid = '%u'::pg_catalog.oid);",
4222 next_possible_free_oid);
4223 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4224 is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4228 pg_type_array_oid = next_possible_free_oid;
4231 if (OidIsValid(pg_type_array_oid))
4233 appendPQExpBufferStr(upgrade_buffer,
4234 "\n-- For binary upgrade, must preserve pg_type array oid\n");
4235 appendPQExpBuffer(upgrade_buffer,
4236 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4240 destroyPQExpBuffer(upgrade_query);
4244 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4245 PQExpBuffer upgrade_buffer,
4248 PQExpBuffer upgrade_query = createPQExpBuffer();
4249 PGresult *upgrade_res;
4251 bool toast_set = false;
4253 /* we only support old >= 8.3 for binary upgrades */
4254 appendPQExpBuffer(upgrade_query,
4255 "SELECT c.reltype AS crel, t.reltype AS trel "
4256 "FROM pg_catalog.pg_class c "
4257 "LEFT JOIN pg_catalog.pg_class t ON "
4258 " (c.reltoastrelid = t.oid) "
4259 "WHERE c.oid = '%u'::pg_catalog.oid;",
4262 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4264 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4266 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4267 pg_type_oid, false);
4269 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4271 /* Toast tables do not have pg_type array rows */
4272 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4273 PQfnumber(upgrade_res, "trel")));
4275 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4276 appendPQExpBuffer(upgrade_buffer,
4277 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4283 PQclear(upgrade_res);
4284 destroyPQExpBuffer(upgrade_query);
4290 binary_upgrade_set_pg_class_oids(Archive *fout,
4291 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4294 PQExpBuffer upgrade_query = createPQExpBuffer();
4295 PGresult *upgrade_res;
4296 Oid pg_class_reltoastrelid;
4297 Oid pg_index_indexrelid;
4299 appendPQExpBuffer(upgrade_query,
4300 "SELECT c.reltoastrelid, i.indexrelid "
4301 "FROM pg_catalog.pg_class c LEFT JOIN "
4302 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4303 "WHERE c.oid = '%u'::pg_catalog.oid;",
4306 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4308 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4309 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4311 appendPQExpBufferStr(upgrade_buffer,
4312 "\n-- For binary upgrade, must preserve pg_class oids\n");
4316 appendPQExpBuffer(upgrade_buffer,
4317 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4319 /* only tables have toast tables, not indexes */
4320 if (OidIsValid(pg_class_reltoastrelid))
4323 * One complexity is that the table definition might not require
4324 * the creation of a TOAST table, and the TOAST table might have
4325 * been created long after table creation, when the table was
4326 * loaded with wide data. By setting the TOAST oid we force
4327 * creation of the TOAST heap and TOAST index by the backend so we
4328 * can cleanly copy the files during binary upgrade.
4331 appendPQExpBuffer(upgrade_buffer,
4332 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4333 pg_class_reltoastrelid);
4335 /* every toast table has an index */
4336 appendPQExpBuffer(upgrade_buffer,
4337 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4338 pg_index_indexrelid);
4342 appendPQExpBuffer(upgrade_buffer,
4343 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4346 appendPQExpBufferChar(upgrade_buffer, '\n');
4348 PQclear(upgrade_res);
4349 destroyPQExpBuffer(upgrade_query);
4353 * If the DumpableObject is a member of an extension, add a suitable
4354 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4356 * For somewhat historical reasons, objname should already be quoted,
4357 * but not objnamespace (if any).
4360 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4361 DumpableObject *dobj,
4362 const char *objtype,
4363 const char *objname,
4364 const char *objnamespace)
4366 DumpableObject *extobj = NULL;
4369 if (!dobj->ext_member)
4373 * Find the parent extension. We could avoid this search if we wanted to
4374 * add a link field to DumpableObject, but the space costs of that would
4375 * be considerable. We assume that member objects could only have a
4376 * direct dependency on their own extension, not any others.
4378 for (i = 0; i < dobj->nDeps; i++)
4380 extobj = findObjectByDumpId(dobj->dependencies[i]);
4381 if (extobj && extobj->objType == DO_EXTENSION)
4386 exit_horribly(NULL, "could not find parent extension for %s %s\n",
4389 appendPQExpBufferStr(upgrade_buffer,
4390 "\n-- For binary upgrade, handle extension membership the hard way\n");
4391 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4392 fmtId(extobj->name),
4394 if (objnamespace && *objnamespace)
4395 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4396 appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4401 * read all namespaces in the system catalogs and return them in the
4402 * NamespaceInfo* structure
4404 * numNamespaces is set to the number of namespaces read in
4407 getNamespaces(Archive *fout, int *numNamespaces)
4409 DumpOptions *dopt = fout->dopt;
4414 NamespaceInfo *nsinfo;
4424 query = createPQExpBuffer();
4427 * we fetch all namespaces including system ones, so that every object we
4428 * read in can be linked to a containing namespace.
4430 if (fout->remoteVersion >= 90600)
4432 PQExpBuffer acl_subquery = createPQExpBuffer();
4433 PQExpBuffer racl_subquery = createPQExpBuffer();
4434 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4435 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4437 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4438 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4439 dopt->binary_upgrade);
4441 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4442 "(%s nspowner) AS rolname, "
4445 "%s as initnspacl, "
4446 "%s as initrnspacl "
4447 "FROM pg_namespace n "
4448 "LEFT JOIN pg_init_privs pip "
4449 "ON (n.oid = pip.objoid "
4450 "AND pip.classoid = 'pg_namespace'::regclass "
4451 "AND pip.objsubid = 0",
4454 racl_subquery->data,
4455 init_acl_subquery->data,
4456 init_racl_subquery->data);
4458 appendPQExpBuffer(query, ") ");
4460 destroyPQExpBuffer(acl_subquery);
4461 destroyPQExpBuffer(racl_subquery);
4462 destroyPQExpBuffer(init_acl_subquery);
4463 destroyPQExpBuffer(init_racl_subquery);
4466 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4467 "(%s nspowner) AS rolname, "
4468 "nspacl, NULL as rnspacl, "
4469 "NULL AS initnspacl, NULL as initrnspacl "
4470 "FROM pg_namespace",
4473 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4475 ntups = PQntuples(res);
4477 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4479 i_tableoid = PQfnumber(res, "tableoid");
4480 i_oid = PQfnumber(res, "oid");
4481 i_nspname = PQfnumber(res, "nspname");
4482 i_rolname = PQfnumber(res, "rolname");
4483 i_nspacl = PQfnumber(res, "nspacl");
4484 i_rnspacl = PQfnumber(res, "rnspacl");
4485 i_initnspacl = PQfnumber(res, "initnspacl");
4486 i_initrnspacl = PQfnumber(res, "initrnspacl");
4488 for (i = 0; i < ntups; i++)
4490 nsinfo[i].dobj.objType = DO_NAMESPACE;
4491 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4492 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4493 AssignDumpId(&nsinfo[i].dobj);
4494 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4495 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4496 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4497 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4498 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4499 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4501 /* Decide whether to dump this namespace */
4502 selectDumpableNamespace(&nsinfo[i], fout);
4505 * Do not try to dump ACL if the ACL is empty or the default.
4507 * This is useful because, for some schemas/objects, the only
4508 * component we are going to try and dump is the ACL and if we can
4509 * remove that then 'dump' goes to zero/false and we don't consider
4510 * this object for dumping at all later on.
4512 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4513 PQgetisnull(res, i, i_initnspacl) &&
4514 PQgetisnull(res, i, i_initrnspacl))
4515 nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4517 if (strlen(nsinfo[i].rolname) == 0)
4518 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4519 nsinfo[i].dobj.name);
4523 destroyPQExpBuffer(query);
4525 *numNamespaces = ntups;
4532 * given a namespace OID, look up the info read by getNamespaces
4534 static NamespaceInfo *
4535 findNamespace(Archive *fout, Oid nsoid)
4537 NamespaceInfo *nsinfo;
4539 nsinfo = findNamespaceByOid(nsoid);
4541 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4547 * read all extensions in the system catalogs and return them in the
4548 * ExtensionInfo* structure
4550 * numExtensions is set to the number of extensions read in
4553 getExtensions(Archive *fout, int *numExtensions)
4555 DumpOptions *dopt = fout->dopt;
4560 ExtensionInfo *extinfo;
4565 int i_extrelocatable;
4571 * Before 9.1, there are no extensions.
4573 if (fout->remoteVersion < 90100)
4579 query = createPQExpBuffer();
4581 appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4582 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4583 "FROM pg_extension x "
4584 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4586 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4588 ntups = PQntuples(res);
4590 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4592 i_tableoid = PQfnumber(res, "tableoid");
4593 i_oid = PQfnumber(res, "oid");
4594 i_extname = PQfnumber(res, "extname");
4595 i_nspname = PQfnumber(res, "nspname");
4596 i_extrelocatable = PQfnumber(res, "extrelocatable");
4597 i_extversion = PQfnumber(res, "extversion");
4598 i_extconfig = PQfnumber(res, "extconfig");
4599 i_extcondition = PQfnumber(res, "extcondition");
4601 for (i = 0; i < ntups; i++)
4603 extinfo[i].dobj.objType = DO_EXTENSION;
4604 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4605 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4606 AssignDumpId(&extinfo[i].dobj);
4607 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4608 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4609 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4610 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4611 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4612 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4614 /* Decide whether we want to dump it */
4615 selectDumpableExtension(&(extinfo[i]), dopt);
4619 destroyPQExpBuffer(query);
4621 *numExtensions = ntups;
4628 * read all types in the system catalogs and return them in the
4629 * TypeInfo* structure
4631 * numTypes is set to the number of types read in
4633 * NB: this must run after getFuncs() because we assume we can do
4637 getTypes(Archive *fout, int *numTypes)
4639 DumpOptions *dopt = fout->dopt;
4643 PQExpBuffer query = createPQExpBuffer();
4645 ShellTypeInfo *stinfo;
4663 * we include even the built-in types because those may be used as array
4664 * elements by user-defined types
4666 * we filter out the built-in types when we dump out the types
4668 * same approach for undefined (shell) types and array types
4670 * Note: as of 8.3 we can reliably detect whether a type is an
4671 * auto-generated array type by checking the element type's typarray.
4672 * (Before that the test is capable of generating false positives.) We
4673 * still check for name beginning with '_', though, so as to avoid the
4674 * cost of the subselect probe for all standard types. This would have to
4675 * be revisited if the backend ever allows renaming of array types.
4678 if (fout->remoteVersion >= 90600)
4680 PQExpBuffer acl_subquery = createPQExpBuffer();
4681 PQExpBuffer racl_subquery = createPQExpBuffer();
4682 PQExpBuffer initacl_subquery = createPQExpBuffer();
4683 PQExpBuffer initracl_subquery = createPQExpBuffer();
4685 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4686 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4687 dopt->binary_upgrade);
4689 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4693 "%s AS inittypacl, "
4694 "%s AS initrtypacl, "
4695 "(%s t.typowner) AS rolname, "
4696 "t.typelem, t.typrelid, "
4697 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4698 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4699 "t.typtype, t.typisdefined, "
4700 "t.typname[0] = '_' AND t.typelem != 0 AND "
4701 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4703 "LEFT JOIN pg_init_privs pip ON "
4704 "(t.oid = pip.objoid "
4705 "AND pip.classoid = 'pg_type'::regclass "
4706 "AND pip.objsubid = 0) ",
4708 racl_subquery->data,
4709 initacl_subquery->data,
4710 initracl_subquery->data,
4713 destroyPQExpBuffer(acl_subquery);
4714 destroyPQExpBuffer(racl_subquery);
4715 destroyPQExpBuffer(initacl_subquery);
4716 destroyPQExpBuffer(initracl_subquery);
4718 else if (fout->remoteVersion >= 90200)
4720 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4721 "typnamespace, typacl, NULL as rtypacl, "
4722 "NULL AS inittypacl, NULL AS initrtypacl, "
4723 "(%s typowner) AS rolname, "
4724 "typelem, typrelid, "
4725 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4726 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4727 "typtype, typisdefined, "
4728 "typname[0] = '_' AND typelem != 0 AND "
4729 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4733 else if (fout->remoteVersion >= 80300)
4735 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4736 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4737 "NULL AS inittypacl, NULL AS initrtypacl, "
4738 "(%s typowner) AS rolname, "
4739 "typelem, typrelid, "
4740 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4741 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4742 "typtype, typisdefined, "
4743 "typname[0] = '_' AND typelem != 0 AND "
4744 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4750 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4751 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4752 "NULL AS inittypacl, NULL AS initrtypacl, "
4753 "(%s typowner) AS rolname, "
4754 "typelem, typrelid, "
4755 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4756 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4757 "typtype, typisdefined, "
4758 "typname[0] = '_' AND typelem != 0 AS isarray "
4763 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4765 ntups = PQntuples(res);
4767 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4769 i_tableoid = PQfnumber(res, "tableoid");
4770 i_oid = PQfnumber(res, "oid");
4771 i_typname = PQfnumber(res, "typname");
4772 i_typnamespace = PQfnumber(res, "typnamespace");
4773 i_typacl = PQfnumber(res, "typacl");
4774 i_rtypacl = PQfnumber(res, "rtypacl");
4775 i_inittypacl = PQfnumber(res, "inittypacl");
4776 i_initrtypacl = PQfnumber(res, "initrtypacl");
4777 i_rolname = PQfnumber(res, "rolname");
4778 i_typelem = PQfnumber(res, "typelem");
4779 i_typrelid = PQfnumber(res, "typrelid");
4780 i_typrelkind = PQfnumber(res, "typrelkind");
4781 i_typtype = PQfnumber(res, "typtype");
4782 i_typisdefined = PQfnumber(res, "typisdefined");
4783 i_isarray = PQfnumber(res, "isarray");
4785 for (i = 0; i < ntups; i++)
4787 tyinfo[i].dobj.objType = DO_TYPE;
4788 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4789 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4790 AssignDumpId(&tyinfo[i].dobj);
4791 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4792 tyinfo[i].dobj.namespace =
4794 atooid(PQgetvalue(res, i, i_typnamespace)));
4795 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4796 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4797 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4798 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4799 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4800 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4801 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4802 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4803 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4804 tyinfo[i].shellType = NULL;
4806 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4807 tyinfo[i].isDefined = true;
4809 tyinfo[i].isDefined = false;
4811 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4812 tyinfo[i].isArray = true;
4814 tyinfo[i].isArray = false;
4816 /* Decide whether we want to dump it */
4817 selectDumpableType(&tyinfo[i], fout);
4819 /* Do not try to dump ACL if no ACL exists. */
4820 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4821 PQgetisnull(res, i, i_inittypacl) &&
4822 PQgetisnull(res, i, i_initrtypacl))
4823 tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4826 * If it's a domain, fetch info about its constraints, if any
4828 tyinfo[i].nDomChecks = 0;
4829 tyinfo[i].domChecks = NULL;
4830 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4831 tyinfo[i].typtype == TYPTYPE_DOMAIN)
4832 getDomainConstraints(fout, &(tyinfo[i]));
4835 * If it's a base type, make a DumpableObject representing a shell
4836 * definition of the type. We will need to dump that ahead of the I/O
4837 * functions for the type. Similarly, range types need a shell
4838 * definition in case they have a canonicalize function.
4840 * Note: the shell type doesn't have a catId. You might think it
4841 * should copy the base type's catId, but then it might capture the
4842 * pg_depend entries for the type, which we don't want.
4844 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4845 (tyinfo[i].typtype == TYPTYPE_BASE ||
4846 tyinfo[i].typtype == TYPTYPE_RANGE))
4848 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4849 stinfo->dobj.objType = DO_SHELL_TYPE;
4850 stinfo->dobj.catId = nilCatalogId;
4851 AssignDumpId(&stinfo->dobj);
4852 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4853 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4854 stinfo->baseType = &(tyinfo[i]);
4855 tyinfo[i].shellType = stinfo;
4858 * Initially mark the shell type as not to be dumped. We'll only
4859 * dump it if the I/O or canonicalize functions need to be dumped;
4860 * this is taken care of while sorting dependencies.
4862 stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4865 if (strlen(tyinfo[i].rolname) == 0)
4866 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4867 tyinfo[i].dobj.name);
4874 destroyPQExpBuffer(query);
4881 * read all operators in the system catalogs and return them in the
4882 * OprInfo* structure
4884 * numOprs is set to the number of operators read in
4887 getOperators(Archive *fout, int *numOprs)
4892 PQExpBuffer query = createPQExpBuffer();
4903 * find all operators, including builtin operators; we filter out
4904 * system-defined operators at dump-out time.
4907 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4909 "(%s oprowner) AS rolname, "
4911 "oprcode::oid AS oprcode "
4915 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4917 ntups = PQntuples(res);
4920 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4922 i_tableoid = PQfnumber(res, "tableoid");
4923 i_oid = PQfnumber(res, "oid");
4924 i_oprname = PQfnumber(res, "oprname");
4925 i_oprnamespace = PQfnumber(res, "oprnamespace");
4926 i_rolname = PQfnumber(res, "rolname");
4927 i_oprkind = PQfnumber(res, "oprkind");
4928 i_oprcode = PQfnumber(res, "oprcode");
4930 for (i = 0; i < ntups; i++)
4932 oprinfo[i].dobj.objType = DO_OPERATOR;
4933 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4934 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4935 AssignDumpId(&oprinfo[i].dobj);
4936 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4937 oprinfo[i].dobj.namespace =
4939 atooid(PQgetvalue(res, i, i_oprnamespace)));
4940 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4941 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4942 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4944 /* Decide whether we want to dump it */
4945 selectDumpableObject(&(oprinfo[i].dobj), fout);
4947 /* Operators do not currently have ACLs. */
4948 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4950 if (strlen(oprinfo[i].rolname) == 0)
4951 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4952 oprinfo[i].dobj.name);
4957 destroyPQExpBuffer(query);
4964 * read all collations in the system catalogs and return them in the
4965 * CollInfo* structure
4967 * numCollations is set to the number of collations read in
4970 getCollations(Archive *fout, int *numCollations)
4980 int i_collnamespace;
4983 /* Collations didn't exist pre-9.1 */
4984 if (fout->remoteVersion < 90100)
4990 query = createPQExpBuffer();
4993 * find all collations, including builtin collations; we filter out
4994 * system-defined collations at dump-out time.
4997 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
4999 "(%s collowner) AS rolname "
5000 "FROM pg_collation",
5003 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5005 ntups = PQntuples(res);
5006 *numCollations = ntups;
5008 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5010 i_tableoid = PQfnumber(res, "tableoid");
5011 i_oid = PQfnumber(res, "oid");
5012 i_collname = PQfnumber(res, "collname");
5013 i_collnamespace = PQfnumber(res, "collnamespace");
5014 i_rolname = PQfnumber(res, "rolname");
5016 for (i = 0; i < ntups; i++)
5018 collinfo[i].dobj.objType = DO_COLLATION;
5019 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5020 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5021 AssignDumpId(&collinfo[i].dobj);
5022 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5023 collinfo[i].dobj.namespace =
5025 atooid(PQgetvalue(res, i, i_collnamespace)));
5026 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5028 /* Decide whether we want to dump it */
5029 selectDumpableObject(&(collinfo[i].dobj), fout);
5031 /* Collations do not currently have ACLs. */
5032 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5037 destroyPQExpBuffer(query);
5044 * read all conversions in the system catalogs and return them in the
5045 * ConvInfo* structure
5047 * numConversions is set to the number of conversions read in
5050 getConversions(Archive *fout, int *numConversions)
5063 query = createPQExpBuffer();
5066 * find all conversions, including builtin conversions; we filter out
5067 * system-defined conversions at dump-out time.
5070 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5072 "(%s conowner) AS rolname "
5073 "FROM pg_conversion",
5076 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5078 ntups = PQntuples(res);
5079 *numConversions = ntups;
5081 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5083 i_tableoid = PQfnumber(res, "tableoid");
5084 i_oid = PQfnumber(res, "oid");
5085 i_conname = PQfnumber(res, "conname");
5086 i_connamespace = PQfnumber(res, "connamespace");
5087 i_rolname = PQfnumber(res, "rolname");
5089 for (i = 0; i < ntups; i++)
5091 convinfo[i].dobj.objType = DO_CONVERSION;
5092 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5093 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5094 AssignDumpId(&convinfo[i].dobj);
5095 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5096 convinfo[i].dobj.namespace =
5098 atooid(PQgetvalue(res, i, i_connamespace)));
5099 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5101 /* Decide whether we want to dump it */
5102 selectDumpableObject(&(convinfo[i].dobj), fout);
5104 /* Conversions do not currently have ACLs. */
5105 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5110 destroyPQExpBuffer(query);
5117 * read all user-defined access methods in the system catalogs and return
5118 * them in the AccessMethodInfo* structure
5120 * numAccessMethods is set to the number of access methods read in
5123 getAccessMethods(Archive *fout, int *numAccessMethods)
5129 AccessMethodInfo *aminfo;
5136 /* Before 9.6, there are no user-defined access methods */
5137 if (fout->remoteVersion < 90600)
5139 *numAccessMethods = 0;
5143 query = createPQExpBuffer();
5145 /* Select all access methods from pg_am table */
5146 appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5147 "amhandler::pg_catalog.regproc AS amhandler "
5150 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5152 ntups = PQntuples(res);
5153 *numAccessMethods = ntups;
5155 aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5157 i_tableoid = PQfnumber(res, "tableoid");
5158 i_oid = PQfnumber(res, "oid");
5159 i_amname = PQfnumber(res, "amname");
5160 i_amhandler = PQfnumber(res, "amhandler");
5161 i_amtype = PQfnumber(res, "amtype");
5163 for (i = 0; i < ntups; i++)
5165 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5166 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5167 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5168 AssignDumpId(&aminfo[i].dobj);
5169 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5170 aminfo[i].dobj.namespace = NULL;
5171 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5172 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5174 /* Decide whether we want to dump it */
5175 selectDumpableAccessMethod(&(aminfo[i]), fout);
5177 /* Access methods do not currently have ACLs. */
5178 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5183 destroyPQExpBuffer(query);
5191 * read all opclasses in the system catalogs and return them in the
5192 * OpclassInfo* structure
5194 * numOpclasses is set to the number of opclasses read in
5197 getOpclasses(Archive *fout, int *numOpclasses)
5202 PQExpBuffer query = createPQExpBuffer();
5203 OpclassInfo *opcinfo;
5211 * find all opclasses, including builtin opclasses; we filter out
5212 * system-defined opclasses at dump-out time.
5215 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5217 "(%s opcowner) AS rolname "
5221 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5223 ntups = PQntuples(res);
5224 *numOpclasses = ntups;
5226 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5228 i_tableoid = PQfnumber(res, "tableoid");
5229 i_oid = PQfnumber(res, "oid");
5230 i_opcname = PQfnumber(res, "opcname");
5231 i_opcnamespace = PQfnumber(res, "opcnamespace");
5232 i_rolname = PQfnumber(res, "rolname");
5234 for (i = 0; i < ntups; i++)
5236 opcinfo[i].dobj.objType = DO_OPCLASS;
5237 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5238 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5239 AssignDumpId(&opcinfo[i].dobj);
5240 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5241 opcinfo[i].dobj.namespace =
5243 atooid(PQgetvalue(res, i, i_opcnamespace)));
5244 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5246 /* Decide whether we want to dump it */
5247 selectDumpableObject(&(opcinfo[i].dobj), fout);
5249 /* Op Classes do not currently have ACLs. */
5250 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5252 if (strlen(opcinfo[i].rolname) == 0)
5253 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5254 opcinfo[i].dobj.name);
5259 destroyPQExpBuffer(query);
5266 * read all opfamilies in the system catalogs and return them in the
5267 * OpfamilyInfo* structure
5269 * numOpfamilies is set to the number of opfamilies read in
5272 getOpfamilies(Archive *fout, int *numOpfamilies)
5278 OpfamilyInfo *opfinfo;
5285 /* Before 8.3, there is no separate concept of opfamilies */
5286 if (fout->remoteVersion < 80300)
5292 query = createPQExpBuffer();
5295 * find all opfamilies, including builtin opfamilies; we filter out
5296 * system-defined opfamilies at dump-out time.
5299 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5301 "(%s opfowner) AS rolname "
5305 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5307 ntups = PQntuples(res);
5308 *numOpfamilies = ntups;
5310 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5312 i_tableoid = PQfnumber(res, "tableoid");
5313 i_oid = PQfnumber(res, "oid");
5314 i_opfname = PQfnumber(res, "opfname");
5315 i_opfnamespace = PQfnumber(res, "opfnamespace");
5316 i_rolname = PQfnumber(res, "rolname");
5318 for (i = 0; i < ntups; i++)
5320 opfinfo[i].dobj.objType = DO_OPFAMILY;
5321 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5322 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5323 AssignDumpId(&opfinfo[i].dobj);
5324 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5325 opfinfo[i].dobj.namespace =
5327 atooid(PQgetvalue(res, i, i_opfnamespace)));
5328 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5330 /* Decide whether we want to dump it */
5331 selectDumpableObject(&(opfinfo[i].dobj), fout);
5333 /* Extensions do not currently have ACLs. */
5334 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5336 if (strlen(opfinfo[i].rolname) == 0)
5337 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5338 opfinfo[i].dobj.name);
5343 destroyPQExpBuffer(query);
5350 * read all the user-defined aggregates in the system catalogs and
5351 * return them in the AggInfo* structure
5353 * numAggs is set to the number of aggregates read in
5356 getAggregates(Archive *fout, int *numAggs)
5358 DumpOptions *dopt = fout->dopt;
5362 PQExpBuffer query = createPQExpBuffer();
5377 * Find all interesting aggregates. See comment in getFuncs() for the
5378 * rationale behind the filtering logic.
5380 if (fout->remoteVersion >= 90600)
5382 PQExpBuffer acl_subquery = createPQExpBuffer();
5383 PQExpBuffer racl_subquery = createPQExpBuffer();
5384 PQExpBuffer initacl_subquery = createPQExpBuffer();
5385 PQExpBuffer initracl_subquery = createPQExpBuffer();
5386 const char *agg_check;
5388 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5389 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5390 dopt->binary_upgrade);
5392 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5395 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5396 "p.proname AS aggname, "
5397 "p.pronamespace AS aggnamespace, "
5398 "p.pronargs, p.proargtypes, "
5399 "(%s p.proowner) AS rolname, "
5402 "%s AS initaggacl, "
5403 "%s AS initraggacl "
5405 "LEFT JOIN pg_init_privs pip ON "
5406 "(p.oid = pip.objoid "
5407 "AND pip.classoid = 'pg_proc'::regclass "
5408 "AND pip.objsubid = 0) "
5410 "p.pronamespace != "
5411 "(SELECT oid FROM pg_namespace "
5412 "WHERE nspname = 'pg_catalog') OR "
5413 "p.proacl IS DISTINCT FROM pip.initprivs",
5416 racl_subquery->data,
5417 initacl_subquery->data,
5418 initracl_subquery->data,
5420 if (dopt->binary_upgrade)
5421 appendPQExpBufferStr(query,
5422 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5423 "classid = 'pg_proc'::regclass AND "
5424 "objid = p.oid AND "
5425 "refclassid = 'pg_extension'::regclass AND "
5427 appendPQExpBufferChar(query, ')');
5429 destroyPQExpBuffer(acl_subquery);
5430 destroyPQExpBuffer(racl_subquery);
5431 destroyPQExpBuffer(initacl_subquery);
5432 destroyPQExpBuffer(initracl_subquery);
5434 else if (fout->remoteVersion >= 80200)
5436 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5437 "pronamespace AS aggnamespace, "
5438 "pronargs, proargtypes, "
5439 "(%s proowner) AS rolname, "
5440 "proacl AS aggacl, "
5442 "NULL AS initaggacl, NULL AS initraggacl "
5444 "WHERE proisagg AND ("
5446 "(SELECT oid FROM pg_namespace "
5447 "WHERE nspname = 'pg_catalog')",
5449 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5450 appendPQExpBufferStr(query,
5451 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5452 "classid = 'pg_proc'::regclass AND "
5453 "objid = p.oid AND "
5454 "refclassid = 'pg_extension'::regclass AND "
5456 appendPQExpBufferChar(query, ')');
5460 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5461 "pronamespace AS aggnamespace, "
5462 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5464 "(%s proowner) AS rolname, "
5465 "proacl AS aggacl, "
5467 "NULL AS initaggacl, NULL AS initraggacl "
5470 "AND pronamespace != "
5471 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5475 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5477 ntups = PQntuples(res);
5480 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5482 i_tableoid = PQfnumber(res, "tableoid");
5483 i_oid = PQfnumber(res, "oid");
5484 i_aggname = PQfnumber(res, "aggname");
5485 i_aggnamespace = PQfnumber(res, "aggnamespace");
5486 i_pronargs = PQfnumber(res, "pronargs");
5487 i_proargtypes = PQfnumber(res, "proargtypes");
5488 i_rolname = PQfnumber(res, "rolname");
5489 i_aggacl = PQfnumber(res, "aggacl");
5490 i_raggacl = PQfnumber(res, "raggacl");
5491 i_initaggacl = PQfnumber(res, "initaggacl");
5492 i_initraggacl = PQfnumber(res, "initraggacl");
5494 for (i = 0; i < ntups; i++)
5496 agginfo[i].aggfn.dobj.objType = DO_AGG;
5497 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5498 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5499 AssignDumpId(&agginfo[i].aggfn.dobj);
5500 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5501 agginfo[i].aggfn.dobj.namespace =
5503 atooid(PQgetvalue(res, i, i_aggnamespace)));
5504 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5505 if (strlen(agginfo[i].aggfn.rolname) == 0)
5506 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5507 agginfo[i].aggfn.dobj.name);
5508 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5509 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
5510 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5511 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5512 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5513 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5514 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5515 if (agginfo[i].aggfn.nargs == 0)
5516 agginfo[i].aggfn.argtypes = NULL;
5519 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5520 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5521 agginfo[i].aggfn.argtypes,
5522 agginfo[i].aggfn.nargs);
5525 /* Decide whether we want to dump it */
5526 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5528 /* Do not try to dump ACL if no ACL exists. */
5529 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5530 PQgetisnull(res, i, i_initaggacl) &&
5531 PQgetisnull(res, i, i_initraggacl))
5532 agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5537 destroyPQExpBuffer(query);
5544 * read all the user-defined functions in the system catalogs and
5545 * return them in the FuncInfo* structure
5547 * numFuncs is set to the number of functions read in
5550 getFuncs(Archive *fout, int *numFuncs)
5552 DumpOptions *dopt = fout->dopt;
5556 PQExpBuffer query = createPQExpBuffer();
5573 * Find all interesting functions. This is a bit complicated:
5575 * 1. Always exclude aggregates; those are handled elsewhere.
5577 * 2. Always exclude functions that are internally dependent on something
5578 * else, since presumably those will be created as a result of creating
5579 * the something else. This currently acts only to suppress constructor
5580 * functions for range types (so we only need it in 9.2 and up). Note
5581 * this is OK only because the constructors don't have any dependencies
5582 * the range type doesn't have; otherwise we might not get creation
5585 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5586 * they're members of extensions and we are in binary-upgrade mode then
5587 * include them, since we want to dump extension members individually in
5588 * that mode. Also, if they are used by casts or transforms then we need
5589 * to gather the information about them, though they won't be dumped if
5590 * they are built-in. Also, in 9.6 and up, include functions in
5591 * pg_catalog if they have an ACL different from what's shown in
5594 if (fout->remoteVersion >= 90600)
5596 PQExpBuffer acl_subquery = createPQExpBuffer();
5597 PQExpBuffer racl_subquery = createPQExpBuffer();
5598 PQExpBuffer initacl_subquery = createPQExpBuffer();
5599 PQExpBuffer initracl_subquery = createPQExpBuffer();
5600 const char *not_agg_check;
5602 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5603 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5604 dopt->binary_upgrade);
5606 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5607 : "NOT p.proisagg");
5609 appendPQExpBuffer(query,
5610 "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5611 "p.pronargs, p.proargtypes, p.prorettype, "
5614 "%s AS initproacl, "
5615 "%s AS initrproacl, "
5617 "(%s p.proowner) AS rolname "
5619 "LEFT JOIN pg_init_privs pip ON "
5620 "(p.oid = pip.objoid "
5621 "AND pip.classoid = 'pg_proc'::regclass "
5622 "AND pip.objsubid = 0) "
5624 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5625 "WHERE classid = 'pg_proc'::regclass AND "
5626 "objid = p.oid AND deptype = 'i')"
5628 "\n pronamespace != "
5629 "(SELECT oid FROM pg_namespace "
5630 "WHERE nspname = 'pg_catalog')"
5631 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5632 "\n WHERE pg_cast.oid > %u "
5633 "\n AND p.oid = pg_cast.castfunc)"
5634 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5635 "\n WHERE pg_transform.oid > %u AND "
5636 "\n (p.oid = pg_transform.trffromsql"
5637 "\n OR p.oid = pg_transform.trftosql))",
5639 racl_subquery->data,
5640 initacl_subquery->data,
5641 initracl_subquery->data,
5645 g_last_builtin_oid);
5646 if (dopt->binary_upgrade)
5647 appendPQExpBufferStr(query,
5648 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5649 "classid = 'pg_proc'::regclass AND "
5650 "objid = p.oid AND "
5651 "refclassid = 'pg_extension'::regclass AND "
5653 appendPQExpBufferStr(query,
5654 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5655 appendPQExpBufferChar(query, ')');
5657 destroyPQExpBuffer(acl_subquery);
5658 destroyPQExpBuffer(racl_subquery);
5659 destroyPQExpBuffer(initacl_subquery);
5660 destroyPQExpBuffer(initracl_subquery);
5664 appendPQExpBuffer(query,
5665 "SELECT tableoid, oid, proname, prolang, "
5666 "pronargs, proargtypes, prorettype, proacl, "
5668 "NULL as initproacl, NULL AS initrproacl, "
5670 "(%s proowner) AS rolname "
5672 "WHERE NOT proisagg",
5674 if (fout->remoteVersion >= 90200)
5675 appendPQExpBufferStr(query,
5676 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5677 "WHERE classid = 'pg_proc'::regclass AND "
5678 "objid = p.oid AND deptype = 'i')");
5679 appendPQExpBuffer(query,
5681 "\n pronamespace != "
5682 "(SELECT oid FROM pg_namespace "
5683 "WHERE nspname = 'pg_catalog')"
5684 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5685 "\n WHERE pg_cast.oid > '%u'::oid"
5686 "\n AND p.oid = pg_cast.castfunc)",
5687 g_last_builtin_oid);
5689 if (fout->remoteVersion >= 90500)
5690 appendPQExpBuffer(query,
5691 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5692 "\n WHERE pg_transform.oid > '%u'::oid"
5693 "\n AND (p.oid = pg_transform.trffromsql"
5694 "\n OR p.oid = pg_transform.trftosql))",
5695 g_last_builtin_oid);
5697 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5698 appendPQExpBufferStr(query,
5699 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5700 "classid = 'pg_proc'::regclass AND "
5701 "objid = p.oid AND "
5702 "refclassid = 'pg_extension'::regclass AND "
5704 appendPQExpBufferChar(query, ')');
5707 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5709 ntups = PQntuples(res);
5713 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5715 i_tableoid = PQfnumber(res, "tableoid");
5716 i_oid = PQfnumber(res, "oid");
5717 i_proname = PQfnumber(res, "proname");
5718 i_pronamespace = PQfnumber(res, "pronamespace");
5719 i_rolname = PQfnumber(res, "rolname");
5720 i_prolang = PQfnumber(res, "prolang");
5721 i_pronargs = PQfnumber(res, "pronargs");
5722 i_proargtypes = PQfnumber(res, "proargtypes");
5723 i_prorettype = PQfnumber(res, "prorettype");
5724 i_proacl = PQfnumber(res, "proacl");
5725 i_rproacl = PQfnumber(res, "rproacl");
5726 i_initproacl = PQfnumber(res, "initproacl");
5727 i_initrproacl = PQfnumber(res, "initrproacl");
5729 for (i = 0; i < ntups; i++)
5731 finfo[i].dobj.objType = DO_FUNC;
5732 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5733 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5734 AssignDumpId(&finfo[i].dobj);
5735 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5736 finfo[i].dobj.namespace =
5738 atooid(PQgetvalue(res, i, i_pronamespace)));
5739 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5740 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5741 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5742 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5743 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5744 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5745 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5746 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5747 if (finfo[i].nargs == 0)
5748 finfo[i].argtypes = NULL;
5751 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5752 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5753 finfo[i].argtypes, finfo[i].nargs);
5756 /* Decide whether we want to dump it */
5757 selectDumpableObject(&(finfo[i].dobj), fout);
5759 /* Do not try to dump ACL if no ACL exists. */
5760 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5761 PQgetisnull(res, i, i_initproacl) &&
5762 PQgetisnull(res, i, i_initrproacl))
5763 finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5765 if (strlen(finfo[i].rolname) == 0)
5767 "WARNING: owner of function \"%s\" appears to be invalid\n",
5768 finfo[i].dobj.name);
5773 destroyPQExpBuffer(query);
5780 * read all the tables (no indexes)
5781 * in the system catalogs return them in the TableInfo* structure
5783 * numTables is set to the number of tables read in
5786 getTables(Archive *fout, int *numTables)
5788 DumpOptions *dopt = fout->dopt;
5792 PQExpBuffer query = createPQExpBuffer();
5805 int i_relhastriggers;
5809 int i_relforcerowsec;
5814 int i_toastfrozenxid;
5816 int i_relpersistence;
5817 int i_relispopulated;
5821 int i_reltablespace;
5824 int i_toastreloptions;
5827 int i_is_identity_sequence;
5834 * Find all the tables and table-like objects.
5836 * We include system catalogs, so that we can work if a user table is
5837 * defined to inherit from a system catalog (pretty weird, but...)
5839 * We ignore relations that are not ordinary tables, sequences, views,
5840 * materialized views, composite types, or foreign tables.
5842 * Composite-type table entries won't be dumped as such, but we have to
5843 * make a DumpableObject for them so that we can track dependencies of the
5844 * composite type (pg_depend entries for columns of the composite type
5845 * link to the pg_class entry not the pg_type entry).
5847 * Note: in this phase we should collect only a minimal amount of
5848 * information about each table, basically just enough to decide if it is
5849 * interesting. We must fetch all tables in this phase because otherwise
5850 * we cannot correctly identify inherited columns, owned sequences, etc.
5853 if (fout->remoteVersion >= 90600)
5855 char *partkeydef = "NULL";
5856 char *ispartition = "false";
5857 char *partbound = "NULL";
5858 char *relhasoids = "c.relhasoids";
5860 PQExpBuffer acl_subquery = createPQExpBuffer();
5861 PQExpBuffer racl_subquery = createPQExpBuffer();
5862 PQExpBuffer initacl_subquery = createPQExpBuffer();
5863 PQExpBuffer initracl_subquery = createPQExpBuffer();
5865 PQExpBuffer attacl_subquery = createPQExpBuffer();
5866 PQExpBuffer attracl_subquery = createPQExpBuffer();
5867 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5868 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5871 * Collect the information about any partitioned tables, which were
5875 if (fout->remoteVersion >= 100000)
5877 partkeydef = "pg_get_partkeydef(c.oid)";
5878 ispartition = "c.relispartition";
5879 partbound = "pg_get_expr(c.relpartbound, c.oid)";
5882 /* In PG12 upwards WITH OIDS does not exist anymore. */
5883 if (fout->remoteVersion >= 120000)
5884 relhasoids = "'f'::bool";
5887 * Left join to pick up dependency info linking sequences to their
5888 * owning column, if any (note this dependency is AUTO as of 8.2)
5890 * Left join to detect if any privileges are still as-set-at-init, in
5891 * which case we won't dump out ACL commands for those.
5894 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5895 initracl_subquery, "c.relacl", "c.relowner",
5896 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5897 " THEN 's' ELSE 'r' END::\"char\"",
5898 dopt->binary_upgrade);
5900 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5901 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5902 dopt->binary_upgrade);
5904 appendPQExpBuffer(query,
5905 "SELECT c.tableoid, c.oid, c.relname, "
5906 "%s AS relacl, %s as rrelacl, "
5907 "%s AS initrelacl, %s as initrrelacl, "
5908 "c.relkind, c.relnamespace, "
5909 "(%s c.relowner) AS rolname, "
5910 "c.relchecks, c.relhastriggers, "
5911 "c.relhasindex, c.relhasrules, %s AS relhasoids, "
5912 "c.relrowsecurity, c.relforcerowsecurity, "
5913 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5914 "tc.relfrozenxid AS tfrozenxid, "
5915 "tc.relminmxid AS tminmxid, "
5916 "c.relpersistence, c.relispopulated, "
5917 "c.relreplident, c.relpages, "
5918 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5919 "d.refobjid AS owning_tab, "
5920 "d.refobjsubid AS owning_col, "
5921 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5922 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5923 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5924 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5925 "tc.reloptions AS toast_reloptions, "
5926 "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, "
5927 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5928 "(c.oid = pip.objoid "
5929 "AND pip.classoid = 'pg_class'::regclass "
5930 "AND pip.objsubid = at.attnum)"
5931 "WHERE at.attrelid = c.oid AND ("
5933 "OR %s IS NOT NULL "
5934 "OR %s IS NOT NULL "
5938 "%s AS partkeydef, "
5939 "%s AS ispartition, "
5942 "LEFT JOIN pg_depend d ON "
5943 "(c.relkind = '%c' AND "
5944 "d.classid = c.tableoid AND d.objid = c.oid AND "
5945 "d.objsubid = 0 AND "
5946 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5947 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5948 "LEFT JOIN pg_init_privs pip ON "
5949 "(c.oid = pip.objoid "
5950 "AND pip.classoid = 'pg_class'::regclass "
5951 "AND pip.objsubid = 0) "
5952 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5955 racl_subquery->data,
5956 initacl_subquery->data,
5957 initracl_subquery->data,
5961 attacl_subquery->data,
5962 attracl_subquery->data,
5963 attinitacl_subquery->data,
5964 attinitracl_subquery->data,
5969 RELKIND_RELATION, RELKIND_SEQUENCE,
5970 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5971 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5972 RELKIND_PARTITIONED_TABLE);
5974 destroyPQExpBuffer(acl_subquery);
5975 destroyPQExpBuffer(racl_subquery);
5976 destroyPQExpBuffer(initacl_subquery);
5977 destroyPQExpBuffer(initracl_subquery);
5979 destroyPQExpBuffer(attacl_subquery);
5980 destroyPQExpBuffer(attracl_subquery);
5981 destroyPQExpBuffer(attinitacl_subquery);
5982 destroyPQExpBuffer(attinitracl_subquery);
5984 else if (fout->remoteVersion >= 90500)
5987 * Left join to pick up dependency info linking sequences to their
5988 * owning column, if any (note this dependency is AUTO as of 8.2)
5990 appendPQExpBuffer(query,
5991 "SELECT c.tableoid, c.oid, c.relname, "
5992 "c.relacl, NULL as rrelacl, "
5993 "NULL AS initrelacl, NULL AS initrrelacl, "
5996 "(%s c.relowner) AS rolname, "
5997 "c.relchecks, c.relhastriggers, "
5998 "c.relhasindex, c.relhasrules, c.relhasoids, "
5999 "c.relrowsecurity, c.relforcerowsecurity, "
6000 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6001 "tc.relfrozenxid AS tfrozenxid, "
6002 "tc.relminmxid AS tminmxid, "
6003 "c.relpersistence, c.relispopulated, "
6004 "c.relreplident, c.relpages, "
6005 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6006 "d.refobjid AS owning_tab, "
6007 "d.refobjsubid AS owning_col, "
6008 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6009 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6010 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6011 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6012 "tc.reloptions AS toast_reloptions, "
6013 "NULL AS changed_acl, "
6014 "NULL AS partkeydef, "
6015 "false AS ispartition, "
6016 "NULL AS partbound "
6018 "LEFT JOIN pg_depend d ON "
6019 "(c.relkind = '%c' AND "
6020 "d.classid = c.tableoid AND d.objid = c.oid AND "
6021 "d.objsubid = 0 AND "
6022 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6023 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6024 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6028 RELKIND_RELATION, RELKIND_SEQUENCE,
6029 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6030 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6032 else if (fout->remoteVersion >= 90400)
6035 * Left join to pick up dependency info linking sequences to their
6036 * owning column, if any (note this dependency is AUTO as of 8.2)
6038 appendPQExpBuffer(query,
6039 "SELECT c.tableoid, c.oid, c.relname, "
6040 "c.relacl, NULL as rrelacl, "
6041 "NULL AS initrelacl, NULL AS initrrelacl, "
6044 "(%s c.relowner) AS rolname, "
6045 "c.relchecks, c.relhastriggers, "
6046 "c.relhasindex, c.relhasrules, c.relhasoids, "
6047 "'f'::bool AS relrowsecurity, "
6048 "'f'::bool AS relforcerowsecurity, "
6049 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6050 "tc.relfrozenxid AS tfrozenxid, "
6051 "tc.relminmxid AS tminmxid, "
6052 "c.relpersistence, c.relispopulated, "
6053 "c.relreplident, c.relpages, "
6054 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6055 "d.refobjid AS owning_tab, "
6056 "d.refobjsubid AS owning_col, "
6057 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6058 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6059 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6060 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6061 "tc.reloptions AS toast_reloptions, "
6062 "NULL AS changed_acl, "
6063 "NULL AS partkeydef, "
6064 "false AS ispartition, "
6065 "NULL AS partbound "
6067 "LEFT JOIN pg_depend d ON "
6068 "(c.relkind = '%c' AND "
6069 "d.classid = c.tableoid AND d.objid = c.oid AND "
6070 "d.objsubid = 0 AND "
6071 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6072 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6073 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6077 RELKIND_RELATION, RELKIND_SEQUENCE,
6078 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6079 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6081 else if (fout->remoteVersion >= 90300)
6084 * Left join to pick up dependency info linking sequences to their
6085 * owning column, if any (note this dependency is AUTO as of 8.2)
6087 appendPQExpBuffer(query,
6088 "SELECT c.tableoid, c.oid, c.relname, "
6089 "c.relacl, NULL as rrelacl, "
6090 "NULL AS initrelacl, NULL AS initrrelacl, "
6093 "(%s c.relowner) AS rolname, "
6094 "c.relchecks, c.relhastriggers, "
6095 "c.relhasindex, c.relhasrules, c.relhasoids, "
6096 "'f'::bool AS relrowsecurity, "
6097 "'f'::bool AS relforcerowsecurity, "
6098 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6099 "tc.relfrozenxid AS tfrozenxid, "
6100 "tc.relminmxid AS tminmxid, "
6101 "c.relpersistence, c.relispopulated, "
6102 "'d' AS relreplident, c.relpages, "
6103 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6104 "d.refobjid AS owning_tab, "
6105 "d.refobjsubid AS owning_col, "
6106 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6107 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6108 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6109 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6110 "tc.reloptions AS toast_reloptions, "
6111 "NULL AS changed_acl, "
6112 "NULL AS partkeydef, "
6113 "false AS ispartition, "
6114 "NULL AS partbound "
6116 "LEFT JOIN pg_depend d ON "
6117 "(c.relkind = '%c' AND "
6118 "d.classid = c.tableoid AND d.objid = c.oid AND "
6119 "d.objsubid = 0 AND "
6120 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6121 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6122 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6126 RELKIND_RELATION, RELKIND_SEQUENCE,
6127 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6128 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6130 else if (fout->remoteVersion >= 90100)
6133 * Left join to pick up dependency info linking sequences to their
6134 * owning column, if any (note this dependency is AUTO as of 8.2)
6136 appendPQExpBuffer(query,
6137 "SELECT c.tableoid, c.oid, c.relname, "
6138 "c.relacl, NULL as rrelacl, "
6139 "NULL AS initrelacl, NULL AS initrrelacl, "
6142 "(%s c.relowner) AS rolname, "
6143 "c.relchecks, c.relhastriggers, "
6144 "c.relhasindex, c.relhasrules, c.relhasoids, "
6145 "'f'::bool AS relrowsecurity, "
6146 "'f'::bool AS relforcerowsecurity, "
6147 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6148 "tc.relfrozenxid AS tfrozenxid, "
6150 "c.relpersistence, 't' as relispopulated, "
6151 "'d' AS relreplident, c.relpages, "
6152 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6153 "d.refobjid AS owning_tab, "
6154 "d.refobjsubid AS owning_col, "
6155 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6156 "c.reloptions AS reloptions, "
6157 "tc.reloptions AS toast_reloptions, "
6158 "NULL AS changed_acl, "
6159 "NULL AS partkeydef, "
6160 "false AS ispartition, "
6161 "NULL AS partbound "
6163 "LEFT JOIN pg_depend d ON "
6164 "(c.relkind = '%c' AND "
6165 "d.classid = c.tableoid AND d.objid = c.oid AND "
6166 "d.objsubid = 0 AND "
6167 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6168 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6169 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6173 RELKIND_RELATION, RELKIND_SEQUENCE,
6174 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6175 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6177 else if (fout->remoteVersion >= 90000)
6180 * Left join to pick up dependency info linking sequences to their
6181 * owning column, if any (note this dependency is AUTO as of 8.2)
6183 appendPQExpBuffer(query,
6184 "SELECT c.tableoid, c.oid, c.relname, "
6185 "c.relacl, NULL as rrelacl, "
6186 "NULL AS initrelacl, NULL AS initrrelacl, "
6189 "(%s c.relowner) AS rolname, "
6190 "c.relchecks, c.relhastriggers, "
6191 "c.relhasindex, c.relhasrules, c.relhasoids, "
6192 "'f'::bool AS relrowsecurity, "
6193 "'f'::bool AS relforcerowsecurity, "
6194 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6195 "tc.relfrozenxid AS tfrozenxid, "
6197 "'p' AS relpersistence, 't' as relispopulated, "
6198 "'d' AS relreplident, c.relpages, "
6199 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6200 "d.refobjid AS owning_tab, "
6201 "d.refobjsubid AS owning_col, "
6202 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6203 "c.reloptions AS reloptions, "
6204 "tc.reloptions AS toast_reloptions, "
6205 "NULL AS changed_acl, "
6206 "NULL AS partkeydef, "
6207 "false AS ispartition, "
6208 "NULL AS partbound "
6210 "LEFT JOIN pg_depend d ON "
6211 "(c.relkind = '%c' AND "
6212 "d.classid = c.tableoid AND d.objid = c.oid AND "
6213 "d.objsubid = 0 AND "
6214 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6215 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6216 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6220 RELKIND_RELATION, RELKIND_SEQUENCE,
6221 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6223 else if (fout->remoteVersion >= 80400)
6226 * Left join to pick up dependency info linking sequences to their
6227 * owning column, if any (note this dependency is AUTO as of 8.2)
6229 appendPQExpBuffer(query,
6230 "SELECT c.tableoid, c.oid, c.relname, "
6231 "c.relacl, NULL as rrelacl, "
6232 "NULL AS initrelacl, NULL AS initrrelacl, "
6235 "(%s c.relowner) AS rolname, "
6236 "c.relchecks, c.relhastriggers, "
6237 "c.relhasindex, c.relhasrules, c.relhasoids, "
6238 "'f'::bool AS relrowsecurity, "
6239 "'f'::bool AS relforcerowsecurity, "
6240 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6241 "tc.relfrozenxid AS tfrozenxid, "
6243 "'p' AS relpersistence, 't' as relispopulated, "
6244 "'d' AS relreplident, c.relpages, "
6245 "NULL AS reloftype, "
6246 "d.refobjid AS owning_tab, "
6247 "d.refobjsubid AS owning_col, "
6248 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6249 "c.reloptions AS reloptions, "
6250 "tc.reloptions AS toast_reloptions, "
6251 "NULL AS changed_acl, "
6252 "NULL AS partkeydef, "
6253 "false AS ispartition, "
6254 "NULL AS partbound "
6256 "LEFT JOIN pg_depend d ON "
6257 "(c.relkind = '%c' AND "
6258 "d.classid = c.tableoid AND d.objid = c.oid AND "
6259 "d.objsubid = 0 AND "
6260 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6261 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6262 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6266 RELKIND_RELATION, RELKIND_SEQUENCE,
6267 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6269 else if (fout->remoteVersion >= 80200)
6272 * Left join to pick up dependency info linking sequences to their
6273 * owning column, if any (note this dependency is AUTO as of 8.2)
6275 appendPQExpBuffer(query,
6276 "SELECT c.tableoid, c.oid, c.relname, "
6277 "c.relacl, NULL as rrelacl, "
6278 "NULL AS initrelacl, NULL AS initrrelacl, "
6281 "(%s c.relowner) AS rolname, "
6282 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6283 "c.relhasindex, c.relhasrules, c.relhasoids, "
6284 "'f'::bool AS relrowsecurity, "
6285 "'f'::bool AS relforcerowsecurity, "
6286 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6287 "tc.relfrozenxid AS tfrozenxid, "
6289 "'p' AS relpersistence, 't' as relispopulated, "
6290 "'d' AS relreplident, c.relpages, "
6291 "NULL AS reloftype, "
6292 "d.refobjid AS owning_tab, "
6293 "d.refobjsubid AS owning_col, "
6294 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6295 "c.reloptions AS reloptions, "
6296 "NULL AS toast_reloptions, "
6297 "NULL AS changed_acl, "
6298 "NULL AS partkeydef, "
6299 "false AS ispartition, "
6300 "NULL AS partbound "
6302 "LEFT JOIN pg_depend d ON "
6303 "(c.relkind = '%c' AND "
6304 "d.classid = c.tableoid AND d.objid = c.oid AND "
6305 "d.objsubid = 0 AND "
6306 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6307 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6308 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6312 RELKIND_RELATION, RELKIND_SEQUENCE,
6313 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6318 * Left join to pick up dependency info linking sequences to their
6319 * owning column, if any
6321 appendPQExpBuffer(query,
6322 "SELECT c.tableoid, c.oid, relname, "
6323 "relacl, NULL as rrelacl, "
6324 "NULL AS initrelacl, NULL AS initrrelacl, "
6325 "relkind, relnamespace, "
6326 "(%s relowner) AS rolname, "
6327 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6328 "relhasindex, relhasrules, relhasoids, "
6329 "'f'::bool AS relrowsecurity, "
6330 "'f'::bool AS relforcerowsecurity, "
6331 "0 AS relfrozenxid, 0 AS relminmxid,"
6333 "0 AS tfrozenxid, 0 AS tminmxid,"
6334 "'p' AS relpersistence, 't' as relispopulated, "
6335 "'d' AS relreplident, relpages, "
6336 "NULL AS reloftype, "
6337 "d.refobjid AS owning_tab, "
6338 "d.refobjsubid AS owning_col, "
6339 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6340 "NULL AS reloptions, "
6341 "NULL AS toast_reloptions, "
6342 "NULL AS changed_acl, "
6343 "NULL AS partkeydef, "
6344 "false AS ispartition, "
6345 "NULL AS partbound "
6347 "LEFT JOIN pg_depend d ON "
6348 "(c.relkind = '%c' AND "
6349 "d.classid = c.tableoid AND d.objid = c.oid AND "
6350 "d.objsubid = 0 AND "
6351 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6352 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6356 RELKIND_RELATION, RELKIND_SEQUENCE,
6357 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6360 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6362 ntups = PQntuples(res);
6367 * Extract data from result and lock dumpable tables. We do the locking
6368 * before anything else, to minimize the window wherein a table could
6369 * disappear under us.
6371 * Note that we have to save info about all tables here, even when dumping
6372 * only one, because we don't yet know which tables might be inheritance
6373 * ancestors of the target table.
6375 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6377 i_reltableoid = PQfnumber(res, "tableoid");
6378 i_reloid = PQfnumber(res, "oid");
6379 i_relname = PQfnumber(res, "relname");
6380 i_relnamespace = PQfnumber(res, "relnamespace");
6381 i_relacl = PQfnumber(res, "relacl");
6382 i_rrelacl = PQfnumber(res, "rrelacl");
6383 i_initrelacl = PQfnumber(res, "initrelacl");
6384 i_initrrelacl = PQfnumber(res, "initrrelacl");
6385 i_relkind = PQfnumber(res, "relkind");
6386 i_rolname = PQfnumber(res, "rolname");
6387 i_relchecks = PQfnumber(res, "relchecks");
6388 i_relhastriggers = PQfnumber(res, "relhastriggers");
6389 i_relhasindex = PQfnumber(res, "relhasindex");
6390 i_relhasrules = PQfnumber(res, "relhasrules");
6391 i_relrowsec = PQfnumber(res, "relrowsecurity");
6392 i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6393 i_relhasoids = PQfnumber(res, "relhasoids");
6394 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6395 i_relminmxid = PQfnumber(res, "relminmxid");
6396 i_toastoid = PQfnumber(res, "toid");
6397 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6398 i_toastminmxid = PQfnumber(res, "tminmxid");
6399 i_relpersistence = PQfnumber(res, "relpersistence");
6400 i_relispopulated = PQfnumber(res, "relispopulated");
6401 i_relreplident = PQfnumber(res, "relreplident");
6402 i_relpages = PQfnumber(res, "relpages");
6403 i_owning_tab = PQfnumber(res, "owning_tab");
6404 i_owning_col = PQfnumber(res, "owning_col");
6405 i_reltablespace = PQfnumber(res, "reltablespace");
6406 i_reloptions = PQfnumber(res, "reloptions");
6407 i_checkoption = PQfnumber(res, "checkoption");
6408 i_toastreloptions = PQfnumber(res, "toast_reloptions");
6409 i_reloftype = PQfnumber(res, "reloftype");
6410 i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6411 i_changed_acl = PQfnumber(res, "changed_acl");
6412 i_partkeydef = PQfnumber(res, "partkeydef");
6413 i_ispartition = PQfnumber(res, "ispartition");
6414 i_partbound = PQfnumber(res, "partbound");
6416 if (dopt->lockWaitTimeout)
6419 * Arrange to fail instead of waiting forever for a table lock.
6421 * NB: this coding assumes that the only queries issued within the
6422 * following loop are LOCK TABLEs; else the timeout may be undesirably
6423 * applied to other things too.
6425 resetPQExpBuffer(query);
6426 appendPQExpBufferStr(query, "SET statement_timeout = ");
6427 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6428 ExecuteSqlStatement(fout, query->data);
6431 for (i = 0; i < ntups; i++)
6433 tblinfo[i].dobj.objType = DO_TABLE;
6434 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6435 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6436 AssignDumpId(&tblinfo[i].dobj);
6437 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6438 tblinfo[i].dobj.namespace =
6440 atooid(PQgetvalue(res, i, i_relnamespace)));
6441 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6442 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6443 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6444 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6445 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6446 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6447 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6448 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6449 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6450 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6451 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6452 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6453 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6454 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6455 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6456 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6457 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6458 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6459 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6460 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6461 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6462 if (PQgetisnull(res, i, i_reloftype))
6463 tblinfo[i].reloftype = NULL;
6465 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6466 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6467 if (PQgetisnull(res, i, i_owning_tab))
6469 tblinfo[i].owning_tab = InvalidOid;
6470 tblinfo[i].owning_col = 0;
6474 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6475 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6477 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6478 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6479 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6480 tblinfo[i].checkoption = NULL;
6482 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6483 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6485 /* other fields were zeroed above */
6488 * Decide whether we want to dump this table.
6490 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6491 tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6493 selectDumpableTable(&tblinfo[i], fout);
6496 * If the table-level and all column-level ACLs for this table are
6497 * unchanged, then we don't need to worry about including the ACLs for
6498 * this table. If any column-level ACLs have been changed, the
6499 * 'changed_acl' column from the query will indicate that.
6501 * This can result in a significant performance improvement in cases
6502 * where we are only looking to dump out the ACL (eg: pg_catalog).
6504 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6505 PQgetisnull(res, i, i_initrelacl) &&
6506 PQgetisnull(res, i, i_initrrelacl) &&
6507 strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6508 tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6510 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6511 tblinfo[i].dummy_view = false; /* might get set during sort */
6512 tblinfo[i].postponed_def = false; /* might get set during sort */
6514 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6515 strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6517 /* Partition key string or NULL */
6518 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6519 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6520 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6523 * Read-lock target tables to make sure they aren't DROPPED or altered
6524 * in schema before we get around to dumping them.
6526 * Note that we don't explicitly lock parents of the target tables; we
6527 * assume our lock on the child is enough to prevent schema
6528 * alterations to parent tables.
6530 * NOTE: it'd be kinda nice to lock other relations too, not only
6531 * plain or partitioned tables, but the backend doesn't presently
6534 * We only need to lock the table for certain components; see
6537 if (tblinfo[i].dobj.dump &&
6538 (tblinfo[i].relkind == RELKIND_RELATION ||
6539 tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6540 (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6542 resetPQExpBuffer(query);
6543 appendPQExpBuffer(query,
6544 "LOCK TABLE %s IN ACCESS SHARE MODE",
6545 fmtQualifiedDumpable(&tblinfo[i]));
6546 ExecuteSqlStatement(fout, query->data);
6549 /* Emit notice if join for owner failed */
6550 if (strlen(tblinfo[i].rolname) == 0)
6551 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6552 tblinfo[i].dobj.name);
6555 if (dopt->lockWaitTimeout)
6557 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6562 destroyPQExpBuffer(query);
6569 * identify owned sequences and mark them as dumpable if owning table is
6571 * We used to do this in getTables(), but it's better to do it after the
6572 * index used by findTableByOid() has been set up.
6575 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6580 * Force sequences that are "owned" by table columns to be dumped whenever
6581 * their owning table is being dumped.
6583 for (i = 0; i < numTables; i++)
6585 TableInfo *seqinfo = &tblinfo[i];
6586 TableInfo *owning_tab;
6588 if (!OidIsValid(seqinfo->owning_tab))
6589 continue; /* not an owned sequence */
6591 owning_tab = findTableByOid(seqinfo->owning_tab);
6592 if (owning_tab == NULL)
6593 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6594 seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6597 * Only dump identity sequences if we're going to dump the table that
6600 if (owning_tab->dobj.dump == DUMP_COMPONENT_NONE &&
6601 seqinfo->is_identity_sequence)
6603 seqinfo->dobj.dump = DUMP_COMPONENT_NONE;
6608 * Otherwise we need to dump the components that are being dumped for
6609 * the table and any components which the sequence is explicitly
6612 * We can't simply use the set of components which are being dumped
6613 * for the table as the table might be in an extension (and only the
6614 * non-extension components, eg: ACLs if changed, security labels, and
6615 * policies, are being dumped) while the sequence is not (and
6616 * therefore the definition and other components should also be
6619 * If the sequence is part of the extension then it should be properly
6620 * marked by checkExtensionMembership() and this will be a no-op as
6621 * the table will be equivalently marked.
6623 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6625 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6626 seqinfo->interesting = true;
6632 * read all the inheritance information
6633 * from the system catalogs return them in the InhInfo* structure
6635 * numInherits is set to the number of pairs read in
6638 getInherits(Archive *fout, int *numInherits)
6643 PQExpBuffer query = createPQExpBuffer();
6650 * Find all the inheritance information, excluding implicit inheritance
6651 * via partitioning. We handle that case using getPartitions(), because
6652 * we want more information about partitions than just the parent-child
6655 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6657 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6659 ntups = PQntuples(res);
6661 *numInherits = ntups;
6663 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6665 i_inhrelid = PQfnumber(res, "inhrelid");
6666 i_inhparent = PQfnumber(res, "inhparent");
6668 for (i = 0; i < ntups; i++)
6670 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6671 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6676 destroyPQExpBuffer(query);
6683 * get information about every index on a dumpable table
6685 * Note: index data is not returned directly to the caller, but it
6686 * does get entered into the DumpableObject tables.
6689 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6693 PQExpBuffer query = createPQExpBuffer();
6696 ConstraintInfo *constrinfo;
6718 for (i = 0; i < numTables; i++)
6720 TableInfo *tbinfo = &tblinfo[i];
6722 if (!tbinfo->hasindex)
6726 * Ignore indexes of tables whose definitions are not to be dumped.
6728 * We also need indexes on partitioned tables which have partitions to
6729 * be dumped, in order to dump the indexes on the partitions.
6731 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6732 !tbinfo->interesting)
6736 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6737 tbinfo->dobj.namespace->dobj.name,
6741 * The point of the messy-looking outer join is to find a constraint
6742 * that is related by an internal dependency link to the index. If we
6743 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6744 * assume an index won't have more than one internal dependency.
6746 * As of 9.0 we don't need to look at pg_depend but can check for a
6747 * match to pg_constraint.conindid. The check on conrelid is
6748 * redundant but useful because that column is indexed while conindid
6751 resetPQExpBuffer(query);
6752 if (fout->remoteVersion >= 110000)
6754 appendPQExpBuffer(query,
6755 "SELECT t.tableoid, t.oid, "
6756 "t.relname AS indexname, "
6757 "inh.inhparent AS parentidx, "
6758 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6759 "i.indnkeyatts AS indnkeyatts, "
6760 "i.indnatts AS indnatts, "
6761 "i.indkey, i.indisclustered, "
6762 "i.indisreplident, "
6763 "c.contype, c.conname, "
6764 "c.condeferrable, c.condeferred, "
6765 "c.tableoid AS contableoid, "
6767 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6768 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6769 "t.reloptions AS indreloptions "
6770 "FROM pg_catalog.pg_index i "
6771 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6772 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6773 "LEFT JOIN pg_catalog.pg_constraint c "
6774 "ON (i.indrelid = c.conrelid AND "
6775 "i.indexrelid = c.conindid AND "
6776 "c.contype IN ('p','u','x')) "
6777 "LEFT JOIN pg_catalog.pg_inherits inh "
6778 "ON (inh.inhrelid = indexrelid) "
6779 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6780 "AND (i.indisvalid OR t2.relkind = 'p') "
6782 "ORDER BY indexname",
6783 tbinfo->dobj.catId.oid);
6785 else if (fout->remoteVersion >= 90400)
6788 * the test on indisready is necessary in 9.2, and harmless in
6789 * earlier/later versions
6791 appendPQExpBuffer(query,
6792 "SELECT t.tableoid, t.oid, "
6793 "t.relname AS indexname, "
6795 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6796 "i.indnatts AS indnkeyatts, "
6797 "i.indnatts AS indnatts, "
6798 "i.indkey, i.indisclustered, "
6799 "i.indisreplident, "
6800 "c.contype, c.conname, "
6801 "c.condeferrable, c.condeferred, "
6802 "c.tableoid AS contableoid, "
6804 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6805 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6806 "t.reloptions AS indreloptions "
6807 "FROM pg_catalog.pg_index i "
6808 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6809 "LEFT JOIN pg_catalog.pg_constraint c "
6810 "ON (i.indrelid = c.conrelid AND "
6811 "i.indexrelid = c.conindid AND "
6812 "c.contype IN ('p','u','x')) "
6813 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6814 "AND i.indisvalid AND i.indisready "
6815 "ORDER BY indexname",
6816 tbinfo->dobj.catId.oid);
6818 else if (fout->remoteVersion >= 90000)
6821 * the test on indisready is necessary in 9.2, and harmless in
6822 * earlier/later versions
6824 appendPQExpBuffer(query,
6825 "SELECT t.tableoid, t.oid, "
6826 "t.relname AS indexname, "
6828 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6829 "i.indnatts AS indnkeyatts, "
6830 "i.indnatts AS indnatts, "
6831 "i.indkey, i.indisclustered, "
6832 "false AS indisreplident, "
6833 "c.contype, c.conname, "
6834 "c.condeferrable, c.condeferred, "
6835 "c.tableoid AS contableoid, "
6837 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6838 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6839 "t.reloptions AS indreloptions "
6840 "FROM pg_catalog.pg_index i "
6841 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6842 "LEFT JOIN pg_catalog.pg_constraint c "
6843 "ON (i.indrelid = c.conrelid AND "
6844 "i.indexrelid = c.conindid AND "
6845 "c.contype IN ('p','u','x')) "
6846 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6847 "AND i.indisvalid AND i.indisready "
6848 "ORDER BY indexname",
6849 tbinfo->dobj.catId.oid);
6851 else if (fout->remoteVersion >= 80200)
6853 appendPQExpBuffer(query,
6854 "SELECT t.tableoid, t.oid, "
6855 "t.relname AS indexname, "
6857 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6858 "i.indnatts AS indnkeyatts, "
6859 "i.indnatts AS indnatts, "
6860 "i.indkey, i.indisclustered, "
6861 "false AS indisreplident, "
6862 "c.contype, c.conname, "
6863 "c.condeferrable, c.condeferred, "
6864 "c.tableoid AS contableoid, "
6867 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6868 "t.reloptions AS indreloptions "
6869 "FROM pg_catalog.pg_index i "
6870 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6871 "LEFT JOIN pg_catalog.pg_depend d "
6872 "ON (d.classid = t.tableoid "
6873 "AND d.objid = t.oid "
6874 "AND d.deptype = 'i') "
6875 "LEFT JOIN pg_catalog.pg_constraint c "
6876 "ON (d.refclassid = c.tableoid "
6877 "AND d.refobjid = c.oid) "
6878 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6880 "ORDER BY indexname",
6881 tbinfo->dobj.catId.oid);
6885 appendPQExpBuffer(query,
6886 "SELECT t.tableoid, t.oid, "
6887 "t.relname AS indexname, "
6889 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6890 "t.relnatts AS indnkeyatts, "
6891 "t.relnatts AS indnatts, "
6892 "i.indkey, i.indisclustered, "
6893 "false AS indisreplident, "
6894 "c.contype, c.conname, "
6895 "c.condeferrable, c.condeferred, "
6896 "c.tableoid AS contableoid, "
6899 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6900 "null AS indreloptions "
6901 "FROM pg_catalog.pg_index i "
6902 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6903 "LEFT JOIN pg_catalog.pg_depend d "
6904 "ON (d.classid = t.tableoid "
6905 "AND d.objid = t.oid "
6906 "AND d.deptype = 'i') "
6907 "LEFT JOIN pg_catalog.pg_constraint c "
6908 "ON (d.refclassid = c.tableoid "
6909 "AND d.refobjid = c.oid) "
6910 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6911 "ORDER BY indexname",
6912 tbinfo->dobj.catId.oid);
6915 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6917 ntups = PQntuples(res);
6919 i_tableoid = PQfnumber(res, "tableoid");
6920 i_oid = PQfnumber(res, "oid");
6921 i_indexname = PQfnumber(res, "indexname");
6922 i_parentidx = PQfnumber(res, "parentidx");
6923 i_indexdef = PQfnumber(res, "indexdef");
6924 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
6925 i_indnatts = PQfnumber(res, "indnatts");
6926 i_indkey = PQfnumber(res, "indkey");
6927 i_indisclustered = PQfnumber(res, "indisclustered");
6928 i_indisreplident = PQfnumber(res, "indisreplident");
6929 i_contype = PQfnumber(res, "contype");
6930 i_conname = PQfnumber(res, "conname");
6931 i_condeferrable = PQfnumber(res, "condeferrable");
6932 i_condeferred = PQfnumber(res, "condeferred");
6933 i_contableoid = PQfnumber(res, "contableoid");
6934 i_conoid = PQfnumber(res, "conoid");
6935 i_condef = PQfnumber(res, "condef");
6936 i_tablespace = PQfnumber(res, "tablespace");
6937 i_indreloptions = PQfnumber(res, "indreloptions");
6939 tbinfo->indexes = indxinfo =
6940 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6941 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6942 tbinfo->numIndexes = ntups;
6944 for (j = 0; j < ntups; j++)
6948 indxinfo[j].dobj.objType = DO_INDEX;
6949 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6950 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6951 AssignDumpId(&indxinfo[j].dobj);
6952 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6953 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6954 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6955 indxinfo[j].indextable = tbinfo;
6956 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6957 indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
6958 indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
6959 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6960 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6961 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
6962 parseOidArray(PQgetvalue(res, j, i_indkey),
6963 indxinfo[j].indkeys, indxinfo[j].indnattrs);
6964 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6965 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6966 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6967 contype = *(PQgetvalue(res, j, i_contype));
6969 if (contype == 'p' || contype == 'u' || contype == 'x')
6972 * If we found a constraint matching the index, create an
6975 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6976 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6977 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6978 AssignDumpId(&constrinfo[j].dobj);
6979 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
6980 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6981 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6982 constrinfo[j].contable = tbinfo;
6983 constrinfo[j].condomain = NULL;
6984 constrinfo[j].contype = contype;
6986 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6988 constrinfo[j].condef = NULL;
6989 constrinfo[j].confrelid = InvalidOid;
6990 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
6991 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
6992 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
6993 constrinfo[j].conislocal = true;
6994 constrinfo[j].separate = true;
6996 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7000 /* Plain secondary index */
7001 indxinfo[j].indexconstraint = 0;
7008 destroyPQExpBuffer(query);
7012 * getExtendedStatistics
7013 * get information about extended-statistics objects.
7015 * Note: extended statistics data is not returned directly to the caller, but
7016 * it does get entered into the DumpableObject tables.
7019 getExtendedStatistics(Archive *fout)
7023 StatsExtInfo *statsextinfo;
7032 /* Extended statistics were new in v10 */
7033 if (fout->remoteVersion < 100000)
7036 query = createPQExpBuffer();
7038 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7039 "stxnamespace, (%s stxowner) AS rolname "
7040 "FROM pg_catalog.pg_statistic_ext",
7043 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7045 ntups = PQntuples(res);
7047 i_tableoid = PQfnumber(res, "tableoid");
7048 i_oid = PQfnumber(res, "oid");
7049 i_stxname = PQfnumber(res, "stxname");
7050 i_stxnamespace = PQfnumber(res, "stxnamespace");
7051 i_rolname = PQfnumber(res, "rolname");
7053 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7055 for (i = 0; i < ntups; i++)
7057 statsextinfo[i].dobj.objType = DO_STATSEXT;
7058 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7059 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7060 AssignDumpId(&statsextinfo[i].dobj);
7061 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7062 statsextinfo[i].dobj.namespace =
7064 atooid(PQgetvalue(res, i, i_stxnamespace)));
7065 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7067 /* Decide whether we want to dump it */
7068 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7070 /* Stats objects do not currently have ACLs. */
7071 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7075 destroyPQExpBuffer(query);
7081 * Get info about constraints on dumpable tables.
7083 * Currently handles foreign keys only.
7084 * Unique and primary key constraints are handled with indexes,
7085 * while check constraints are processed in getTableAttrs().
7088 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7092 ConstraintInfo *constrinfo;
7102 query = createPQExpBuffer();
7104 for (i = 0; i < numTables; i++)
7106 TableInfo *tbinfo = &tblinfo[i];
7109 * For partitioned tables, foreign keys have no triggers so they must
7110 * be included anyway in case some foreign keys are defined.
7112 if ((!tbinfo->hastriggers &&
7113 tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7114 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7118 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7119 tbinfo->dobj.namespace->dobj.name,
7122 resetPQExpBuffer(query);
7123 if (fout->remoteVersion >= 110000)
7124 appendPQExpBuffer(query,
7125 "SELECT tableoid, oid, conname, confrelid, "
7126 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7127 "FROM pg_catalog.pg_constraint "
7128 "WHERE conrelid = '%u'::pg_catalog.oid "
7129 "AND conparentid = 0 "
7130 "AND contype = 'f'",
7131 tbinfo->dobj.catId.oid);
7133 appendPQExpBuffer(query,
7134 "SELECT tableoid, oid, conname, confrelid, "
7135 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7136 "FROM pg_catalog.pg_constraint "
7137 "WHERE conrelid = '%u'::pg_catalog.oid "
7138 "AND contype = 'f'",
7139 tbinfo->dobj.catId.oid);
7140 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7142 ntups = PQntuples(res);
7144 i_contableoid = PQfnumber(res, "tableoid");
7145 i_conoid = PQfnumber(res, "oid");
7146 i_conname = PQfnumber(res, "conname");
7147 i_confrelid = PQfnumber(res, "confrelid");
7148 i_condef = PQfnumber(res, "condef");
7150 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7152 for (j = 0; j < ntups; j++)
7154 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7155 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7156 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7157 AssignDumpId(&constrinfo[j].dobj);
7158 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7159 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7160 constrinfo[j].contable = tbinfo;
7161 constrinfo[j].condomain = NULL;
7162 constrinfo[j].contype = 'f';
7163 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7164 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7165 constrinfo[j].conindex = 0;
7166 constrinfo[j].condeferrable = false;
7167 constrinfo[j].condeferred = false;
7168 constrinfo[j].conislocal = true;
7169 constrinfo[j].separate = true;
7175 destroyPQExpBuffer(query);
7179 * getDomainConstraints
7181 * Get info about constraints on a domain.
7184 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7187 ConstraintInfo *constrinfo;
7196 query = createPQExpBuffer();
7198 if (fout->remoteVersion >= 90100)
7199 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7200 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7202 "FROM pg_catalog.pg_constraint "
7203 "WHERE contypid = '%u'::pg_catalog.oid "
7205 tyinfo->dobj.catId.oid);
7208 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7209 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7210 "true as convalidated "
7211 "FROM pg_catalog.pg_constraint "
7212 "WHERE contypid = '%u'::pg_catalog.oid "
7214 tyinfo->dobj.catId.oid);
7216 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7218 ntups = PQntuples(res);
7220 i_tableoid = PQfnumber(res, "tableoid");
7221 i_oid = PQfnumber(res, "oid");
7222 i_conname = PQfnumber(res, "conname");
7223 i_consrc = PQfnumber(res, "consrc");
7225 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7227 tyinfo->nDomChecks = ntups;
7228 tyinfo->domChecks = constrinfo;
7230 for (i = 0; i < ntups; i++)
7232 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7234 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7235 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7236 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7237 AssignDumpId(&constrinfo[i].dobj);
7238 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7239 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7240 constrinfo[i].contable = NULL;
7241 constrinfo[i].condomain = tyinfo;
7242 constrinfo[i].contype = 'c';
7243 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7244 constrinfo[i].confrelid = InvalidOid;
7245 constrinfo[i].conindex = 0;
7246 constrinfo[i].condeferrable = false;
7247 constrinfo[i].condeferred = false;
7248 constrinfo[i].conislocal = true;
7250 constrinfo[i].separate = !validated;
7253 * Make the domain depend on the constraint, ensuring it won't be
7254 * output till any constraint dependencies are OK. If the constraint
7255 * has not been validated, it's going to be dumped after the domain
7256 * anyway, so this doesn't matter.
7259 addObjectDependency(&tyinfo->dobj,
7260 constrinfo[i].dobj.dumpId);
7265 destroyPQExpBuffer(query);
7270 * get basic information about every rule in the system
7272 * numRules is set to the number of rules read in
7275 getRules(Archive *fout, int *numRules)
7280 PQExpBuffer query = createPQExpBuffer();
7290 if (fout->remoteVersion >= 80300)
7292 appendPQExpBufferStr(query, "SELECT "
7293 "tableoid, oid, rulename, "
7294 "ev_class AS ruletable, ev_type, is_instead, "
7301 appendPQExpBufferStr(query, "SELECT "
7302 "tableoid, oid, rulename, "
7303 "ev_class AS ruletable, ev_type, is_instead, "
7304 "'O'::char AS ev_enabled "
7309 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7311 ntups = PQntuples(res);
7315 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7317 i_tableoid = PQfnumber(res, "tableoid");
7318 i_oid = PQfnumber(res, "oid");
7319 i_rulename = PQfnumber(res, "rulename");
7320 i_ruletable = PQfnumber(res, "ruletable");
7321 i_ev_type = PQfnumber(res, "ev_type");
7322 i_is_instead = PQfnumber(res, "is_instead");
7323 i_ev_enabled = PQfnumber(res, "ev_enabled");
7325 for (i = 0; i < ntups; i++)
7329 ruleinfo[i].dobj.objType = DO_RULE;
7330 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7331 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7332 AssignDumpId(&ruleinfo[i].dobj);
7333 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7334 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7335 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7336 if (ruleinfo[i].ruletable == NULL)
7337 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7338 ruletableoid, ruleinfo[i].dobj.catId.oid);
7339 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7340 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7341 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7342 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7343 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7344 if (ruleinfo[i].ruletable)
7347 * If the table is a view or materialized view, force its ON
7348 * SELECT rule to be sorted before the view itself --- this
7349 * ensures that any dependencies for the rule affect the table's
7350 * positioning. Other rules are forced to appear after their
7353 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7354 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7355 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7357 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7358 ruleinfo[i].dobj.dumpId);
7359 /* We'll merge the rule into CREATE VIEW, if possible */
7360 ruleinfo[i].separate = false;
7364 addObjectDependency(&ruleinfo[i].dobj,
7365 ruleinfo[i].ruletable->dobj.dumpId);
7366 ruleinfo[i].separate = true;
7370 ruleinfo[i].separate = true;
7375 destroyPQExpBuffer(query);
7382 * get information about every trigger on a dumpable table
7384 * Note: trigger data is not returned directly to the caller, but it
7385 * does get entered into the DumpableObject tables.
7388 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7392 PQExpBuffer query = createPQExpBuffer();
7394 TriggerInfo *tginfo;
7412 for (i = 0; i < numTables; i++)
7414 TableInfo *tbinfo = &tblinfo[i];
7416 if (!tbinfo->hastriggers ||
7417 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7421 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7422 tbinfo->dobj.namespace->dobj.name,
7425 resetPQExpBuffer(query);
7426 if (fout->remoteVersion >= 90000)
7429 * NB: think not to use pretty=true in pg_get_triggerdef. It
7430 * could result in non-forward-compatible dumps of WHEN clauses
7431 * due to under-parenthesization.
7433 appendPQExpBuffer(query,
7435 "tgfoid::pg_catalog.regproc AS tgfname, "
7436 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7437 "tgenabled, tableoid, oid "
7438 "FROM pg_catalog.pg_trigger t "
7439 "WHERE tgrelid = '%u'::pg_catalog.oid "
7440 "AND NOT tgisinternal",
7441 tbinfo->dobj.catId.oid);
7443 else if (fout->remoteVersion >= 80300)
7446 * We ignore triggers that are tied to a foreign-key constraint
7448 appendPQExpBuffer(query,
7450 "tgfoid::pg_catalog.regproc AS tgfname, "
7451 "tgtype, tgnargs, tgargs, tgenabled, "
7452 "tgisconstraint, tgconstrname, tgdeferrable, "
7453 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7454 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7455 "FROM pg_catalog.pg_trigger t "
7456 "WHERE tgrelid = '%u'::pg_catalog.oid "
7457 "AND tgconstraint = 0",
7458 tbinfo->dobj.catId.oid);
7463 * We ignore triggers that are tied to a foreign-key constraint,
7464 * but in these versions we have to grovel through pg_constraint
7467 appendPQExpBuffer(query,
7469 "tgfoid::pg_catalog.regproc AS tgfname, "
7470 "tgtype, tgnargs, tgargs, tgenabled, "
7471 "tgisconstraint, tgconstrname, tgdeferrable, "
7472 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7473 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7474 "FROM pg_catalog.pg_trigger t "
7475 "WHERE tgrelid = '%u'::pg_catalog.oid "
7476 "AND (NOT tgisconstraint "
7478 " (SELECT 1 FROM pg_catalog.pg_depend d "
7479 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7480 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7481 tbinfo->dobj.catId.oid);
7484 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7486 ntups = PQntuples(res);
7488 i_tableoid = PQfnumber(res, "tableoid");
7489 i_oid = PQfnumber(res, "oid");
7490 i_tgname = PQfnumber(res, "tgname");
7491 i_tgfname = PQfnumber(res, "tgfname");
7492 i_tgtype = PQfnumber(res, "tgtype");
7493 i_tgnargs = PQfnumber(res, "tgnargs");
7494 i_tgargs = PQfnumber(res, "tgargs");
7495 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7496 i_tgconstrname = PQfnumber(res, "tgconstrname");
7497 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7498 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7499 i_tgenabled = PQfnumber(res, "tgenabled");
7500 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7501 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7502 i_tgdef = PQfnumber(res, "tgdef");
7504 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7506 tbinfo->numTriggers = ntups;
7507 tbinfo->triggers = tginfo;
7509 for (j = 0; j < ntups; j++)
7511 tginfo[j].dobj.objType = DO_TRIGGER;
7512 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7513 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7514 AssignDumpId(&tginfo[j].dobj);
7515 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7516 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7517 tginfo[j].tgtable = tbinfo;
7518 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7521 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7523 /* remaining fields are not valid if we have tgdef */
7524 tginfo[j].tgfname = NULL;
7525 tginfo[j].tgtype = 0;
7526 tginfo[j].tgnargs = 0;
7527 tginfo[j].tgargs = NULL;
7528 tginfo[j].tgisconstraint = false;
7529 tginfo[j].tgdeferrable = false;
7530 tginfo[j].tginitdeferred = false;
7531 tginfo[j].tgconstrname = NULL;
7532 tginfo[j].tgconstrrelid = InvalidOid;
7533 tginfo[j].tgconstrrelname = NULL;
7537 tginfo[j].tgdef = NULL;
7539 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7540 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7541 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7542 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7543 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7544 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7545 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7547 if (tginfo[j].tgisconstraint)
7549 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7550 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7551 if (OidIsValid(tginfo[j].tgconstrrelid))
7553 if (PQgetisnull(res, j, i_tgconstrrelname))
7554 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7555 tginfo[j].dobj.name,
7557 tginfo[j].tgconstrrelid);
7558 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7561 tginfo[j].tgconstrrelname = NULL;
7565 tginfo[j].tgconstrname = NULL;
7566 tginfo[j].tgconstrrelid = InvalidOid;
7567 tginfo[j].tgconstrrelname = NULL;
7575 destroyPQExpBuffer(query);
7580 * get information about event triggers
7583 getEventTriggers(Archive *fout, int *numEventTriggers)
7588 EventTriggerInfo *evtinfo;
7599 /* Before 9.3, there are no event triggers */
7600 if (fout->remoteVersion < 90300)
7602 *numEventTriggers = 0;
7606 query = createPQExpBuffer();
7608 appendPQExpBuffer(query,
7609 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7610 "evtevent, (%s evtowner) AS evtowner, "
7611 "array_to_string(array("
7612 "select quote_literal(x) "
7613 " from unnest(evttags) as t(x)), ', ') as evttags, "
7614 "e.evtfoid::regproc as evtfname "
7615 "FROM pg_event_trigger e "
7619 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7621 ntups = PQntuples(res);
7623 *numEventTriggers = ntups;
7625 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7627 i_tableoid = PQfnumber(res, "tableoid");
7628 i_oid = PQfnumber(res, "oid");
7629 i_evtname = PQfnumber(res, "evtname");
7630 i_evtevent = PQfnumber(res, "evtevent");
7631 i_evtowner = PQfnumber(res, "evtowner");
7632 i_evttags = PQfnumber(res, "evttags");
7633 i_evtfname = PQfnumber(res, "evtfname");
7634 i_evtenabled = PQfnumber(res, "evtenabled");
7636 for (i = 0; i < ntups; i++)
7638 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7639 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7640 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7641 AssignDumpId(&evtinfo[i].dobj);
7642 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7643 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7644 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7645 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7646 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7647 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7648 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7650 /* Decide whether we want to dump it */
7651 selectDumpableObject(&(evtinfo[i].dobj), fout);
7653 /* Event Triggers do not currently have ACLs. */
7654 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7659 destroyPQExpBuffer(query);
7666 * get basic information about every procedural language in the system
7668 * numProcLangs is set to the number of langs read in
7670 * NB: this must run after getFuncs() because we assume we can do
7674 getProcLangs(Archive *fout, int *numProcLangs)
7676 DumpOptions *dopt = fout->dopt;
7680 PQExpBuffer query = createPQExpBuffer();
7681 ProcLangInfo *planginfo;
7686 int i_lanplcallfoid;
7695 if (fout->remoteVersion >= 90600)
7697 PQExpBuffer acl_subquery = createPQExpBuffer();
7698 PQExpBuffer racl_subquery = createPQExpBuffer();
7699 PQExpBuffer initacl_subquery = createPQExpBuffer();
7700 PQExpBuffer initracl_subquery = createPQExpBuffer();
7702 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7703 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7704 dopt->binary_upgrade);
7706 /* pg_language has a laninline column */
7707 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7708 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7709 "l.laninline, l.lanvalidator, "
7712 "%s AS initlanacl, "
7713 "%s AS initrlanacl, "
7714 "(%s l.lanowner) AS lanowner "
7715 "FROM pg_language l "
7716 "LEFT JOIN pg_init_privs pip ON "
7717 "(l.oid = pip.objoid "
7718 "AND pip.classoid = 'pg_language'::regclass "
7719 "AND pip.objsubid = 0) "
7723 racl_subquery->data,
7724 initacl_subquery->data,
7725 initracl_subquery->data,
7728 destroyPQExpBuffer(acl_subquery);
7729 destroyPQExpBuffer(racl_subquery);
7730 destroyPQExpBuffer(initacl_subquery);
7731 destroyPQExpBuffer(initracl_subquery);
7733 else if (fout->remoteVersion >= 90000)
7735 /* pg_language has a laninline column */
7736 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7737 "lanname, lanpltrusted, lanplcallfoid, "
7738 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7739 "NULL AS initlanacl, NULL AS initrlanacl, "
7740 "(%s lanowner) AS lanowner "
7746 else if (fout->remoteVersion >= 80300)
7748 /* pg_language has a lanowner column */
7749 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7750 "lanname, lanpltrusted, lanplcallfoid, "
7751 "0 AS laninline, lanvalidator, lanacl, "
7753 "NULL AS initlanacl, NULL AS initrlanacl, "
7754 "(%s lanowner) AS lanowner "
7760 else if (fout->remoteVersion >= 80100)
7762 /* Languages are owned by the bootstrap superuser, OID 10 */
7763 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7764 "lanname, lanpltrusted, lanplcallfoid, "
7765 "0 AS laninline, lanvalidator, lanacl, "
7767 "NULL AS initlanacl, NULL AS initrlanacl, "
7768 "(%s '10') AS lanowner "
7776 /* Languages are owned by the bootstrap superuser, sysid 1 */
7777 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7778 "lanname, lanpltrusted, lanplcallfoid, "
7779 "0 AS laninline, lanvalidator, lanacl, "
7781 "NULL AS initlanacl, NULL AS initrlanacl, "
7782 "(%s '1') AS lanowner "
7789 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7791 ntups = PQntuples(res);
7793 *numProcLangs = ntups;
7795 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7797 i_tableoid = PQfnumber(res, "tableoid");
7798 i_oid = PQfnumber(res, "oid");
7799 i_lanname = PQfnumber(res, "lanname");
7800 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7801 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7802 i_laninline = PQfnumber(res, "laninline");
7803 i_lanvalidator = PQfnumber(res, "lanvalidator");
7804 i_lanacl = PQfnumber(res, "lanacl");
7805 i_rlanacl = PQfnumber(res, "rlanacl");
7806 i_initlanacl = PQfnumber(res, "initlanacl");
7807 i_initrlanacl = PQfnumber(res, "initrlanacl");
7808 i_lanowner = PQfnumber(res, "lanowner");
7810 for (i = 0; i < ntups; i++)
7812 planginfo[i].dobj.objType = DO_PROCLANG;
7813 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7814 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7815 AssignDumpId(&planginfo[i].dobj);
7817 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7818 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7819 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7820 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7821 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7822 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7823 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7824 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7825 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7826 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7828 /* Decide whether we want to dump it */
7829 selectDumpableProcLang(&(planginfo[i]), fout);
7831 /* Do not try to dump ACL if no ACL exists. */
7832 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7833 PQgetisnull(res, i, i_initlanacl) &&
7834 PQgetisnull(res, i, i_initrlanacl))
7835 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7840 destroyPQExpBuffer(query);
7847 * get basic information about every cast in the system
7849 * numCasts is set to the number of casts read in
7852 getCasts(Archive *fout, int *numCasts)
7857 PQExpBuffer query = createPQExpBuffer();
7867 if (fout->remoteVersion >= 80400)
7869 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7870 "castsource, casttarget, castfunc, castcontext, "
7872 "FROM pg_cast ORDER BY 3,4");
7876 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7877 "castsource, casttarget, castfunc, castcontext, "
7878 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7879 "FROM pg_cast ORDER BY 3,4");
7882 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7884 ntups = PQntuples(res);
7888 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7890 i_tableoid = PQfnumber(res, "tableoid");
7891 i_oid = PQfnumber(res, "oid");
7892 i_castsource = PQfnumber(res, "castsource");
7893 i_casttarget = PQfnumber(res, "casttarget");
7894 i_castfunc = PQfnumber(res, "castfunc");
7895 i_castcontext = PQfnumber(res, "castcontext");
7896 i_castmethod = PQfnumber(res, "castmethod");
7898 for (i = 0; i < ntups; i++)
7900 PQExpBufferData namebuf;
7901 TypeInfo *sTypeInfo;
7902 TypeInfo *tTypeInfo;
7904 castinfo[i].dobj.objType = DO_CAST;
7905 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7906 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7907 AssignDumpId(&castinfo[i].dobj);
7908 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7909 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7910 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7911 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7912 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7915 * Try to name cast as concatenation of typnames. This is only used
7916 * for purposes of sorting. If we fail to find either type, the name
7917 * will be an empty string.
7919 initPQExpBuffer(&namebuf);
7920 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7921 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7922 if (sTypeInfo && tTypeInfo)
7923 appendPQExpBuffer(&namebuf, "%s %s",
7924 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7925 castinfo[i].dobj.name = namebuf.data;
7927 /* Decide whether we want to dump it */
7928 selectDumpableCast(&(castinfo[i]), fout);
7930 /* Casts do not currently have ACLs. */
7931 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7936 destroyPQExpBuffer(query);
7942 get_language_name(Archive *fout, Oid langid)
7948 query = createPQExpBuffer();
7949 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7950 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7951 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7952 destroyPQExpBuffer(query);
7960 * get basic information about every transform in the system
7962 * numTransforms is set to the number of transforms read in
7965 getTransforms(Archive *fout, int *numTransforms)
7971 TransformInfo *transforminfo;
7979 /* Transforms didn't exist pre-9.5 */
7980 if (fout->remoteVersion < 90500)
7986 query = createPQExpBuffer();
7988 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7989 "trftype, trflang, trffromsql::oid, trftosql::oid "
7990 "FROM pg_transform "
7993 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7995 ntups = PQntuples(res);
7997 *numTransforms = ntups;
7999 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8001 i_tableoid = PQfnumber(res, "tableoid");
8002 i_oid = PQfnumber(res, "oid");
8003 i_trftype = PQfnumber(res, "trftype");
8004 i_trflang = PQfnumber(res, "trflang");
8005 i_trffromsql = PQfnumber(res, "trffromsql");
8006 i_trftosql = PQfnumber(res, "trftosql");
8008 for (i = 0; i < ntups; i++)
8010 PQExpBufferData namebuf;
8014 transforminfo[i].dobj.objType = DO_TRANSFORM;
8015 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8016 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8017 AssignDumpId(&transforminfo[i].dobj);
8018 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8019 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8020 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8021 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8024 * Try to name transform as concatenation of type and language name.
8025 * This is only used for purposes of sorting. If we fail to find
8026 * either, the name will be an empty string.
8028 initPQExpBuffer(&namebuf);
8029 typeInfo = findTypeByOid(transforminfo[i].trftype);
8030 lanname = get_language_name(fout, transforminfo[i].trflang);
8031 if (typeInfo && lanname)
8032 appendPQExpBuffer(&namebuf, "%s %s",
8033 typeInfo->dobj.name, lanname);
8034 transforminfo[i].dobj.name = namebuf.data;
8037 /* Decide whether we want to dump it */
8038 selectDumpableObject(&(transforminfo[i].dobj), fout);
8043 destroyPQExpBuffer(query);
8045 return transforminfo;
8050 * for each interesting table, read info about its attributes
8051 * (names, types, default values, CHECK constraints, etc)
8053 * This is implemented in a very inefficient way right now, looping
8054 * through the tblinfo and doing a join per table to find the attrs and their
8055 * types. However, because we want type names and so forth to be named
8056 * relative to the schema of each table, we couldn't do it in just one
8057 * query. (Maybe one query per schema?)
8062 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8064 DumpOptions *dopt = fout->dopt;
8067 PQExpBuffer q = createPQExpBuffer();
8072 int i_attstattarget;
8084 int i_attfdwoptions;
8085 int i_attmissingval;
8090 for (i = 0; i < numTables; i++)
8092 TableInfo *tbinfo = &tblinfo[i];
8094 /* Don't bother to collect info for sequences */
8095 if (tbinfo->relkind == RELKIND_SEQUENCE)
8098 /* Don't bother with uninteresting tables, either */
8099 if (!tbinfo->interesting)
8102 /* find all the user attributes and their types */
8105 * we must read the attribute names in attribute number order! because
8106 * we will use the attnum to index into the attnames array later.
8109 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8110 tbinfo->dobj.namespace->dobj.name,
8113 resetPQExpBuffer(q);
8115 appendPQExpBuffer(q,
8120 "a.attstattarget,\n"
8129 "pg_catalog.format_type(t.oid, a.atttypmod) AS atttypname,\n");
8131 if (fout->remoteVersion >= 110000)
8132 appendPQExpBuffer(q,
8133 "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8134 "THEN a.attmissingval ELSE null END AS attmissingval,\n");
8136 appendPQExpBuffer(q,
8137 "NULL AS attmissingval,\n");
8139 if (fout->remoteVersion >= 100000)
8140 appendPQExpBuffer(q,
8141 "a.attidentity,\n");
8143 appendPQExpBuffer(q,
8144 "'' AS attidentity,\n");
8146 if (fout->remoteVersion >= 90200)
8147 appendPQExpBuffer(q,
8148 "pg_catalog.array_to_string(ARRAY("
8149 "SELECT pg_catalog.quote_ident(option_name) || "
8150 "' ' || pg_catalog.quote_literal(option_value) "
8151 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8152 "ORDER BY option_name"
8153 "), E',\n ') AS attfdwoptions,\n");
8155 appendPQExpBuffer(q,
8156 "'' AS attfdwoptions,\n");
8158 if (fout->remoteVersion >= 90100)
8161 * Since we only want to dump COLLATE clauses for attributes whose
8162 * collation is different from their type's default, we use a CASE
8163 * here to suppress uninteresting attcollations cheaply.
8165 appendPQExpBuffer(q,
8166 "CASE WHEN a.attcollation <> t.typcollation "
8167 "THEN a.attcollation ELSE 0 END AS attcollation,\n");
8170 appendPQExpBuffer(q,
8171 "0 AS attcollation,\n");
8173 if (fout->remoteVersion >= 90000)
8174 appendPQExpBuffer(q,
8175 "array_to_string(a.attoptions, ', ') AS attoptions\n");
8177 appendPQExpBuffer(q,
8178 "'' AS attoptions\n");
8180 /* need left join here to not fail on dropped columns ... */
8181 appendPQExpBuffer(q,
8182 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8183 "ON a.atttypid = t.oid\n"
8184 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8185 "AND a.attnum > 0::pg_catalog.int2\n"
8186 "ORDER BY a.attnum",
8187 tbinfo->dobj.catId.oid);
8189 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8191 ntups = PQntuples(res);
8193 i_attnum = PQfnumber(res, "attnum");
8194 i_attname = PQfnumber(res, "attname");
8195 i_atttypname = PQfnumber(res, "atttypname");
8196 i_atttypmod = PQfnumber(res, "atttypmod");
8197 i_attstattarget = PQfnumber(res, "attstattarget");
8198 i_attstorage = PQfnumber(res, "attstorage");
8199 i_typstorage = PQfnumber(res, "typstorage");
8200 i_attnotnull = PQfnumber(res, "attnotnull");
8201 i_atthasdef = PQfnumber(res, "atthasdef");
8202 i_attidentity = PQfnumber(res, "attidentity");
8203 i_attisdropped = PQfnumber(res, "attisdropped");
8204 i_attlen = PQfnumber(res, "attlen");
8205 i_attalign = PQfnumber(res, "attalign");
8206 i_attislocal = PQfnumber(res, "attislocal");
8207 i_attoptions = PQfnumber(res, "attoptions");
8208 i_attcollation = PQfnumber(res, "attcollation");
8209 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8210 i_attmissingval = PQfnumber(res, "attmissingval");
8212 tbinfo->numatts = ntups;
8213 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8214 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8215 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8216 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8217 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8218 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8219 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8220 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8221 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8222 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8223 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8224 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8225 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8226 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8227 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8228 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8229 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8230 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8231 hasdefaults = false;
8233 for (j = 0; j < ntups; j++)
8235 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8237 "invalid column numbering in table \"%s\"\n",
8239 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8240 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8241 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8242 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8243 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8244 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8245 tbinfo->attidentity[j] = *(PQgetvalue(res, j, i_attidentity));
8246 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8247 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8248 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8249 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8250 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8251 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8252 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8253 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8254 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8255 tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8256 tbinfo->attrdefs[j] = NULL; /* fix below */
8257 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8259 /* these flags will be set in flagInhAttrs() */
8260 tbinfo->inhNotNull[j] = false;
8266 * Get info about column defaults
8270 AttrDefInfo *attrdefs;
8274 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8275 tbinfo->dobj.namespace->dobj.name,
8278 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8279 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8280 "FROM pg_catalog.pg_attrdef "
8281 "WHERE adrelid = '%u'::pg_catalog.oid",
8282 tbinfo->dobj.catId.oid);
8284 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8286 numDefaults = PQntuples(res);
8287 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8289 for (j = 0; j < numDefaults; j++)
8293 adnum = atoi(PQgetvalue(res, j, 2));
8295 if (adnum <= 0 || adnum > ntups)
8297 "invalid adnum value %d for table \"%s\"\n",
8298 adnum, tbinfo->dobj.name);
8301 * dropped columns shouldn't have defaults, but just in case,
8304 if (tbinfo->attisdropped[adnum - 1])
8307 attrdefs[j].dobj.objType = DO_ATTRDEF;
8308 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8309 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8310 AssignDumpId(&attrdefs[j].dobj);
8311 attrdefs[j].adtable = tbinfo;
8312 attrdefs[j].adnum = adnum;
8313 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8315 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8316 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8318 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8321 * Defaults on a VIEW must always be dumped as separate ALTER
8322 * TABLE commands. Defaults on regular tables are dumped as
8323 * part of the CREATE TABLE if possible, which it won't be if
8324 * the column is not going to be emitted explicitly.
8326 if (tbinfo->relkind == RELKIND_VIEW)
8328 attrdefs[j].separate = true;
8330 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8332 /* column will be suppressed, print default separately */
8333 attrdefs[j].separate = true;
8337 attrdefs[j].separate = false;
8340 * Mark the default as needing to appear before the table,
8341 * so that any dependencies it has must be emitted before
8342 * the CREATE TABLE. If this is not possible, we'll
8343 * change to "separate" mode while sorting dependencies.
8345 addObjectDependency(&tbinfo->dobj,
8346 attrdefs[j].dobj.dumpId);
8349 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8355 * Get info about table CHECK constraints
8357 if (tbinfo->ncheck > 0)
8359 ConstraintInfo *constrs;
8363 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8364 tbinfo->dobj.namespace->dobj.name,
8367 resetPQExpBuffer(q);
8368 if (fout->remoteVersion >= 90200)
8371 * convalidated is new in 9.2 (actually, it is there in 9.1,
8372 * but it wasn't ever false for check constraints until 9.2).
8374 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8375 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8376 "conislocal, convalidated "
8377 "FROM pg_catalog.pg_constraint "
8378 "WHERE conrelid = '%u'::pg_catalog.oid "
8379 " AND contype = 'c' "
8381 tbinfo->dobj.catId.oid);
8383 else if (fout->remoteVersion >= 80400)
8385 /* conislocal is new in 8.4 */
8386 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8387 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8388 "conislocal, true AS convalidated "
8389 "FROM pg_catalog.pg_constraint "
8390 "WHERE conrelid = '%u'::pg_catalog.oid "
8391 " AND contype = 'c' "
8393 tbinfo->dobj.catId.oid);
8397 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8398 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8399 "true AS conislocal, true AS convalidated "
8400 "FROM pg_catalog.pg_constraint "
8401 "WHERE conrelid = '%u'::pg_catalog.oid "
8402 " AND contype = 'c' "
8404 tbinfo->dobj.catId.oid);
8407 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8409 numConstrs = PQntuples(res);
8410 if (numConstrs != tbinfo->ncheck)
8412 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8413 "expected %d check constraints on table \"%s\" but found %d\n",
8415 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8416 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8420 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8421 tbinfo->checkexprs = constrs;
8423 for (j = 0; j < numConstrs; j++)
8425 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8427 constrs[j].dobj.objType = DO_CONSTRAINT;
8428 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8429 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8430 AssignDumpId(&constrs[j].dobj);
8431 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8432 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8433 constrs[j].contable = tbinfo;
8434 constrs[j].condomain = NULL;
8435 constrs[j].contype = 'c';
8436 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8437 constrs[j].confrelid = InvalidOid;
8438 constrs[j].conindex = 0;
8439 constrs[j].condeferrable = false;
8440 constrs[j].condeferred = false;
8441 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8444 * An unvalidated constraint needs to be dumped separately, so
8445 * that potentially-violating existing data is loaded before
8448 constrs[j].separate = !validated;
8450 constrs[j].dobj.dump = tbinfo->dobj.dump;
8453 * Mark the constraint as needing to appear before the table
8454 * --- this is so that any other dependencies of the
8455 * constraint will be emitted before we try to create the
8456 * table. If the constraint is to be dumped separately, it
8457 * will be dumped after data is loaded anyway, so don't do it.
8458 * (There's an automatic dependency in the opposite direction
8459 * anyway, so don't need to add one manually here.)
8461 if (!constrs[j].separate)
8462 addObjectDependency(&tbinfo->dobj,
8463 constrs[j].dobj.dumpId);
8466 * If the constraint is inherited, this will be detected later
8467 * (in pre-8.4 databases). We also detect later if the
8468 * constraint must be split out from the table definition.
8475 destroyPQExpBuffer(q);
8479 * Test whether a column should be printed as part of table's CREATE TABLE.
8480 * Column number is zero-based.
8482 * Normally this is always true, but it's false for dropped columns, as well
8483 * as those that were inherited without any local definition. (If we print
8484 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8485 * However, in binary_upgrade mode, we must print all such columns anyway and
8486 * fix the attislocal/attisdropped state later, so as to keep control of the
8487 * physical column order.
8489 * This function exists because there are scattered nonobvious places that
8490 * must be kept in sync with this decision.
8493 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8495 if (dopt->binary_upgrade)
8497 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8503 * read all text search parsers in the system catalogs and return them
8504 * in the TSParserInfo* structure
8506 * numTSParsers is set to the number of parsers read in
8509 getTSParsers(Archive *fout, int *numTSParsers)
8515 TSParserInfo *prsinfo;
8526 /* Before 8.3, there is no built-in text search support */
8527 if (fout->remoteVersion < 80300)
8533 query = createPQExpBuffer();
8536 * find all text search objects, including builtin ones; we filter out
8537 * system-defined objects at dump-out time.
8540 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8541 "prsstart::oid, prstoken::oid, "
8542 "prsend::oid, prsheadline::oid, prslextype::oid "
8543 "FROM pg_ts_parser");
8545 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8547 ntups = PQntuples(res);
8548 *numTSParsers = ntups;
8550 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8552 i_tableoid = PQfnumber(res, "tableoid");
8553 i_oid = PQfnumber(res, "oid");
8554 i_prsname = PQfnumber(res, "prsname");
8555 i_prsnamespace = PQfnumber(res, "prsnamespace");
8556 i_prsstart = PQfnumber(res, "prsstart");
8557 i_prstoken = PQfnumber(res, "prstoken");
8558 i_prsend = PQfnumber(res, "prsend");
8559 i_prsheadline = PQfnumber(res, "prsheadline");
8560 i_prslextype = PQfnumber(res, "prslextype");
8562 for (i = 0; i < ntups; i++)
8564 prsinfo[i].dobj.objType = DO_TSPARSER;
8565 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8566 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8567 AssignDumpId(&prsinfo[i].dobj);
8568 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8569 prsinfo[i].dobj.namespace =
8571 atooid(PQgetvalue(res, i, i_prsnamespace)));
8572 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8573 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8574 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8575 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8576 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8578 /* Decide whether we want to dump it */
8579 selectDumpableObject(&(prsinfo[i].dobj), fout);
8581 /* Text Search Parsers do not currently have ACLs. */
8582 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8587 destroyPQExpBuffer(query);
8593 * getTSDictionaries:
8594 * read all text search dictionaries in the system catalogs and return them
8595 * in the TSDictInfo* structure
8597 * numTSDicts is set to the number of dictionaries read in
8600 getTSDictionaries(Archive *fout, int *numTSDicts)
8606 TSDictInfo *dictinfo;
8610 int i_dictnamespace;
8613 int i_dictinitoption;
8615 /* Before 8.3, there is no built-in text search support */
8616 if (fout->remoteVersion < 80300)
8622 query = createPQExpBuffer();
8624 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8625 "dictnamespace, (%s dictowner) AS rolname, "
8626 "dicttemplate, dictinitoption "
8630 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8632 ntups = PQntuples(res);
8633 *numTSDicts = ntups;
8635 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8637 i_tableoid = PQfnumber(res, "tableoid");
8638 i_oid = PQfnumber(res, "oid");
8639 i_dictname = PQfnumber(res, "dictname");
8640 i_dictnamespace = PQfnumber(res, "dictnamespace");
8641 i_rolname = PQfnumber(res, "rolname");
8642 i_dictinitoption = PQfnumber(res, "dictinitoption");
8643 i_dicttemplate = PQfnumber(res, "dicttemplate");
8645 for (i = 0; i < ntups; i++)
8647 dictinfo[i].dobj.objType = DO_TSDICT;
8648 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8649 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8650 AssignDumpId(&dictinfo[i].dobj);
8651 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8652 dictinfo[i].dobj.namespace =
8654 atooid(PQgetvalue(res, i, i_dictnamespace)));
8655 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8656 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8657 if (PQgetisnull(res, i, i_dictinitoption))
8658 dictinfo[i].dictinitoption = NULL;
8660 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8662 /* Decide whether we want to dump it */
8663 selectDumpableObject(&(dictinfo[i].dobj), fout);
8665 /* Text Search Dictionaries do not currently have ACLs. */
8666 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8671 destroyPQExpBuffer(query);
8678 * read all text search templates in the system catalogs and return them
8679 * in the TSTemplateInfo* structure
8681 * numTSTemplates is set to the number of templates read in
8684 getTSTemplates(Archive *fout, int *numTSTemplates)
8690 TSTemplateInfo *tmplinfo;
8694 int i_tmplnamespace;
8698 /* Before 8.3, there is no built-in text search support */
8699 if (fout->remoteVersion < 80300)
8701 *numTSTemplates = 0;
8705 query = createPQExpBuffer();
8707 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8708 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8709 "FROM pg_ts_template");
8711 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8713 ntups = PQntuples(res);
8714 *numTSTemplates = ntups;
8716 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8718 i_tableoid = PQfnumber(res, "tableoid");
8719 i_oid = PQfnumber(res, "oid");
8720 i_tmplname = PQfnumber(res, "tmplname");
8721 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8722 i_tmplinit = PQfnumber(res, "tmplinit");
8723 i_tmpllexize = PQfnumber(res, "tmpllexize");
8725 for (i = 0; i < ntups; i++)
8727 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8728 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8729 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8730 AssignDumpId(&tmplinfo[i].dobj);
8731 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8732 tmplinfo[i].dobj.namespace =
8734 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8735 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8736 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8738 /* Decide whether we want to dump it */
8739 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8741 /* Text Search Templates do not currently have ACLs. */
8742 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8747 destroyPQExpBuffer(query);
8753 * getTSConfigurations:
8754 * read all text search configurations in the system catalogs and return
8755 * them in the TSConfigInfo* structure
8757 * numTSConfigs is set to the number of configurations read in
8760 getTSConfigurations(Archive *fout, int *numTSConfigs)
8766 TSConfigInfo *cfginfo;
8774 /* Before 8.3, there is no built-in text search support */
8775 if (fout->remoteVersion < 80300)
8781 query = createPQExpBuffer();
8783 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8784 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8785 "FROM pg_ts_config",
8788 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8790 ntups = PQntuples(res);
8791 *numTSConfigs = ntups;
8793 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8795 i_tableoid = PQfnumber(res, "tableoid");
8796 i_oid = PQfnumber(res, "oid");
8797 i_cfgname = PQfnumber(res, "cfgname");
8798 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8799 i_rolname = PQfnumber(res, "rolname");
8800 i_cfgparser = PQfnumber(res, "cfgparser");
8802 for (i = 0; i < ntups; i++)
8804 cfginfo[i].dobj.objType = DO_TSCONFIG;
8805 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8806 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8807 AssignDumpId(&cfginfo[i].dobj);
8808 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8809 cfginfo[i].dobj.namespace =
8811 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8812 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8813 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8815 /* Decide whether we want to dump it */
8816 selectDumpableObject(&(cfginfo[i].dobj), fout);
8818 /* Text Search Configurations do not currently have ACLs. */
8819 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8824 destroyPQExpBuffer(query);
8830 * getForeignDataWrappers:
8831 * read all foreign-data wrappers in the system catalogs and return
8832 * them in the FdwInfo* structure
8834 * numForeignDataWrappers is set to the number of fdws read in
8837 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8839 DumpOptions *dopt = fout->dopt;
8857 /* Before 8.4, there are no foreign-data wrappers */
8858 if (fout->remoteVersion < 80400)
8860 *numForeignDataWrappers = 0;
8864 query = createPQExpBuffer();
8866 if (fout->remoteVersion >= 90600)
8868 PQExpBuffer acl_subquery = createPQExpBuffer();
8869 PQExpBuffer racl_subquery = createPQExpBuffer();
8870 PQExpBuffer initacl_subquery = createPQExpBuffer();
8871 PQExpBuffer initracl_subquery = createPQExpBuffer();
8873 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8874 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8875 dopt->binary_upgrade);
8877 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8878 "(%s f.fdwowner) AS rolname, "
8879 "f.fdwhandler::pg_catalog.regproc, "
8880 "f.fdwvalidator::pg_catalog.regproc, "
8883 "%s AS initfdwacl, "
8884 "%s AS initrfdwacl, "
8885 "array_to_string(ARRAY("
8886 "SELECT quote_ident(option_name) || ' ' || "
8887 "quote_literal(option_value) "
8888 "FROM pg_options_to_table(f.fdwoptions) "
8889 "ORDER BY option_name"
8890 "), E',\n ') AS fdwoptions "
8891 "FROM pg_foreign_data_wrapper f "
8892 "LEFT JOIN pg_init_privs pip ON "
8893 "(f.oid = pip.objoid "
8894 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8895 "AND pip.objsubid = 0) ",
8898 racl_subquery->data,
8899 initacl_subquery->data,
8900 initracl_subquery->data);
8902 destroyPQExpBuffer(acl_subquery);
8903 destroyPQExpBuffer(racl_subquery);
8904 destroyPQExpBuffer(initacl_subquery);
8905 destroyPQExpBuffer(initracl_subquery);
8907 else if (fout->remoteVersion >= 90100)
8909 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8910 "(%s fdwowner) AS rolname, "
8911 "fdwhandler::pg_catalog.regproc, "
8912 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8914 "NULL as initfdwacl, NULL AS initrfdwacl, "
8915 "array_to_string(ARRAY("
8916 "SELECT quote_ident(option_name) || ' ' || "
8917 "quote_literal(option_value) "
8918 "FROM pg_options_to_table(fdwoptions) "
8919 "ORDER BY option_name"
8920 "), E',\n ') AS fdwoptions "
8921 "FROM pg_foreign_data_wrapper",
8926 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8927 "(%s fdwowner) AS rolname, "
8928 "'-' AS fdwhandler, "
8929 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8931 "NULL as initfdwacl, NULL AS initrfdwacl, "
8932 "array_to_string(ARRAY("
8933 "SELECT quote_ident(option_name) || ' ' || "
8934 "quote_literal(option_value) "
8935 "FROM pg_options_to_table(fdwoptions) "
8936 "ORDER BY option_name"
8937 "), E',\n ') AS fdwoptions "
8938 "FROM pg_foreign_data_wrapper",
8942 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8944 ntups = PQntuples(res);
8945 *numForeignDataWrappers = ntups;
8947 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
8949 i_tableoid = PQfnumber(res, "tableoid");
8950 i_oid = PQfnumber(res, "oid");
8951 i_fdwname = PQfnumber(res, "fdwname");
8952 i_rolname = PQfnumber(res, "rolname");
8953 i_fdwhandler = PQfnumber(res, "fdwhandler");
8954 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
8955 i_fdwacl = PQfnumber(res, "fdwacl");
8956 i_rfdwacl = PQfnumber(res, "rfdwacl");
8957 i_initfdwacl = PQfnumber(res, "initfdwacl");
8958 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
8959 i_fdwoptions = PQfnumber(res, "fdwoptions");
8961 for (i = 0; i < ntups; i++)
8963 fdwinfo[i].dobj.objType = DO_FDW;
8964 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8965 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8966 AssignDumpId(&fdwinfo[i].dobj);
8967 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
8968 fdwinfo[i].dobj.namespace = NULL;
8969 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8970 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
8971 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
8972 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
8973 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
8974 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
8975 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
8976 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
8978 /* Decide whether we want to dump it */
8979 selectDumpableObject(&(fdwinfo[i].dobj), fout);
8981 /* Do not try to dump ACL if no ACL exists. */
8982 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
8983 PQgetisnull(res, i, i_initfdwacl) &&
8984 PQgetisnull(res, i, i_initrfdwacl))
8985 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8990 destroyPQExpBuffer(query);
8996 * getForeignServers:
8997 * read all foreign servers in the system catalogs and return
8998 * them in the ForeignServerInfo * structure
9000 * numForeignServers is set to the number of servers read in
9003 getForeignServers(Archive *fout, int *numForeignServers)
9005 DumpOptions *dopt = fout->dopt;
9010 ForeignServerInfo *srvinfo;
9024 /* Before 8.4, there are no foreign servers */
9025 if (fout->remoteVersion < 80400)
9027 *numForeignServers = 0;
9031 query = createPQExpBuffer();
9033 if (fout->remoteVersion >= 90600)
9035 PQExpBuffer acl_subquery = createPQExpBuffer();
9036 PQExpBuffer racl_subquery = createPQExpBuffer();
9037 PQExpBuffer initacl_subquery = createPQExpBuffer();
9038 PQExpBuffer initracl_subquery = createPQExpBuffer();
9040 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9041 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9042 dopt->binary_upgrade);
9044 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9045 "(%s f.srvowner) AS rolname, "
9046 "f.srvfdw, f.srvtype, f.srvversion, "
9049 "%s AS initsrvacl, "
9050 "%s AS initrsrvacl, "
9051 "array_to_string(ARRAY("
9052 "SELECT quote_ident(option_name) || ' ' || "
9053 "quote_literal(option_value) "
9054 "FROM pg_options_to_table(f.srvoptions) "
9055 "ORDER BY option_name"
9056 "), E',\n ') AS srvoptions "
9057 "FROM pg_foreign_server f "
9058 "LEFT JOIN pg_init_privs pip "
9059 "ON (f.oid = pip.objoid "
9060 "AND pip.classoid = 'pg_foreign_server'::regclass "
9061 "AND pip.objsubid = 0) ",
9064 racl_subquery->data,
9065 initacl_subquery->data,
9066 initracl_subquery->data);
9068 destroyPQExpBuffer(acl_subquery);
9069 destroyPQExpBuffer(racl_subquery);
9070 destroyPQExpBuffer(initacl_subquery);
9071 destroyPQExpBuffer(initracl_subquery);
9075 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9076 "(%s srvowner) AS rolname, "
9077 "srvfdw, srvtype, srvversion, srvacl, "
9079 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9080 "array_to_string(ARRAY("
9081 "SELECT quote_ident(option_name) || ' ' || "
9082 "quote_literal(option_value) "
9083 "FROM pg_options_to_table(srvoptions) "
9084 "ORDER BY option_name"
9085 "), E',\n ') AS srvoptions "
9086 "FROM pg_foreign_server",
9090 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9092 ntups = PQntuples(res);
9093 *numForeignServers = ntups;
9095 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9097 i_tableoid = PQfnumber(res, "tableoid");
9098 i_oid = PQfnumber(res, "oid");
9099 i_srvname = PQfnumber(res, "srvname");
9100 i_rolname = PQfnumber(res, "rolname");
9101 i_srvfdw = PQfnumber(res, "srvfdw");
9102 i_srvtype = PQfnumber(res, "srvtype");
9103 i_srvversion = PQfnumber(res, "srvversion");
9104 i_srvacl = PQfnumber(res, "srvacl");
9105 i_rsrvacl = PQfnumber(res, "rsrvacl");
9106 i_initsrvacl = PQfnumber(res, "initsrvacl");
9107 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9108 i_srvoptions = PQfnumber(res, "srvoptions");
9110 for (i = 0; i < ntups; i++)
9112 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9113 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9114 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9115 AssignDumpId(&srvinfo[i].dobj);
9116 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9117 srvinfo[i].dobj.namespace = NULL;
9118 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9119 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9120 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9121 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9122 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9123 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9124 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9125 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9126 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9128 /* Decide whether we want to dump it */
9129 selectDumpableObject(&(srvinfo[i].dobj), fout);
9131 /* Do not try to dump ACL if no ACL exists. */
9132 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9133 PQgetisnull(res, i, i_initsrvacl) &&
9134 PQgetisnull(res, i, i_initrsrvacl))
9135 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9140 destroyPQExpBuffer(query);
9147 * read all default ACL information in the system catalogs and return
9148 * them in the DefaultACLInfo structure
9150 * numDefaultACLs is set to the number of ACLs read in
9153 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9155 DumpOptions *dopt = fout->dopt;
9156 DefaultACLInfo *daclinfo;
9162 int i_defaclnamespace;
9163 int i_defaclobjtype;
9166 int i_initdefaclacl;
9167 int i_initrdefaclacl;
9171 if (fout->remoteVersion < 90000)
9173 *numDefaultACLs = 0;
9177 query = createPQExpBuffer();
9179 if (fout->remoteVersion >= 90600)
9181 PQExpBuffer acl_subquery = createPQExpBuffer();
9182 PQExpBuffer racl_subquery = createPQExpBuffer();
9183 PQExpBuffer initacl_subquery = createPQExpBuffer();
9184 PQExpBuffer initracl_subquery = createPQExpBuffer();
9186 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9187 initracl_subquery, "defaclacl", "defaclrole",
9188 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9189 dopt->binary_upgrade);
9191 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9192 "(%s d.defaclrole) AS defaclrole, "
9193 "d.defaclnamespace, "
9196 "%s AS rdefaclacl, "
9197 "%s AS initdefaclacl, "
9198 "%s AS initrdefaclacl "
9199 "FROM pg_default_acl d "
9200 "LEFT JOIN pg_init_privs pip ON "
9201 "(d.oid = pip.objoid "
9202 "AND pip.classoid = 'pg_default_acl'::regclass "
9203 "AND pip.objsubid = 0) ",
9206 racl_subquery->data,
9207 initacl_subquery->data,
9208 initracl_subquery->data);
9212 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9213 "(%s defaclrole) AS defaclrole, "
9217 "NULL AS rdefaclacl, "
9218 "NULL AS initdefaclacl, "
9219 "NULL AS initrdefaclacl "
9220 "FROM pg_default_acl",
9224 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9226 ntups = PQntuples(res);
9227 *numDefaultACLs = ntups;
9229 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9231 i_oid = PQfnumber(res, "oid");
9232 i_tableoid = PQfnumber(res, "tableoid");
9233 i_defaclrole = PQfnumber(res, "defaclrole");
9234 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9235 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9236 i_defaclacl = PQfnumber(res, "defaclacl");
9237 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9238 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9239 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9241 for (i = 0; i < ntups; i++)
9243 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9245 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9246 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9247 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9248 AssignDumpId(&daclinfo[i].dobj);
9249 /* cheesy ... is it worth coming up with a better object name? */
9250 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9252 if (nspid != InvalidOid)
9253 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9255 daclinfo[i].dobj.namespace = NULL;
9257 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9258 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9259 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9260 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9261 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9262 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9264 /* Decide whether we want to dump it */
9265 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9270 destroyPQExpBuffer(query);
9278 * This routine is used to dump any comments associated with the
9279 * object handed to this routine. The routine takes the object type
9280 * and object name (ready to print, except for schema decoration), plus
9281 * the namespace and owner of the object (for labeling the ArchiveEntry),
9282 * plus catalog ID and subid which are the lookup key for pg_description,
9283 * plus the dump ID for the object (for setting a dependency).
9284 * If a matching pg_description entry is found, it is dumped.
9286 * Note: in some cases, such as comments for triggers and rules, the "type"
9287 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9288 * but it doesn't seem worth complicating the API for all callers to make
9291 * Note: although this routine takes a dumpId for dependency purposes,
9292 * that purpose is just to mark the dependency in the emitted dump file
9293 * for possible future use by pg_restore. We do NOT use it for determining
9294 * ordering of the comment in the dump file, because this routine is called
9295 * after dependency sorting occurs. This routine should be called just after
9296 * calling ArchiveEntry() for the specified object.
9299 dumpComment(Archive *fout, const char *type, const char *name,
9300 const char *namespace, const char *owner,
9301 CatalogId catalogId, int subid, DumpId dumpId)
9303 DumpOptions *dopt = fout->dopt;
9304 CommentItem *comments;
9307 /* do nothing, if --no-comments is supplied */
9308 if (dopt->no_comments)
9311 /* Comments are schema not data ... except blob comments are data */
9312 if (strcmp(type, "LARGE OBJECT") != 0)
9319 /* We do dump blob comments in binary-upgrade mode */
9320 if (dopt->schemaOnly && !dopt->binary_upgrade)
9324 /* Search for comments associated with catalogId, using table */
9325 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9328 /* Is there one matching the subid? */
9329 while (ncomments > 0)
9331 if (comments->objsubid == subid)
9337 /* If a comment exists, build COMMENT ON statement */
9340 PQExpBuffer query = createPQExpBuffer();
9341 PQExpBuffer tag = createPQExpBuffer();
9343 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9344 if (namespace && *namespace)
9345 appendPQExpBuffer(query, "%s.", fmtId(namespace));
9346 appendPQExpBuffer(query, "%s IS ", name);
9347 appendStringLiteralAH(query, comments->descr, fout);
9348 appendPQExpBufferStr(query, ";\n");
9350 appendPQExpBuffer(tag, "%s %s", type, name);
9353 * We mark comments as SECTION_NONE because they really belong in the
9354 * same section as their parent, whether that is pre-data or
9357 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9358 tag->data, namespace, NULL, owner,
9359 "COMMENT", SECTION_NONE,
9360 query->data, "", NULL,
9364 destroyPQExpBuffer(query);
9365 destroyPQExpBuffer(tag);
9370 * dumpTableComment --
9372 * As above, but dump comments for both the specified table (or view)
9376 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9377 const char *reltypename)
9379 DumpOptions *dopt = fout->dopt;
9380 CommentItem *comments;
9385 /* do nothing, if --no-comments is supplied */
9386 if (dopt->no_comments)
9389 /* Comments are SCHEMA not data */
9393 /* Search for comments associated with relation, using table */
9394 ncomments = findComments(fout,
9395 tbinfo->dobj.catId.tableoid,
9396 tbinfo->dobj.catId.oid,
9399 /* If comments exist, build COMMENT ON statements */
9403 query = createPQExpBuffer();
9404 tag = createPQExpBuffer();
9406 while (ncomments > 0)
9408 const char *descr = comments->descr;
9409 int objsubid = comments->objsubid;
9413 resetPQExpBuffer(tag);
9414 appendPQExpBuffer(tag, "%s %s", reltypename,
9415 fmtId(tbinfo->dobj.name));
9417 resetPQExpBuffer(query);
9418 appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9419 fmtQualifiedDumpable(tbinfo));
9420 appendStringLiteralAH(query, descr, fout);
9421 appendPQExpBufferStr(query, ";\n");
9423 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9425 tbinfo->dobj.namespace->dobj.name,
9426 NULL, tbinfo->rolname,
9427 "COMMENT", SECTION_NONE,
9428 query->data, "", NULL,
9429 &(tbinfo->dobj.dumpId), 1,
9432 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9434 resetPQExpBuffer(tag);
9435 appendPQExpBuffer(tag, "COLUMN %s.",
9436 fmtId(tbinfo->dobj.name));
9437 appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9439 resetPQExpBuffer(query);
9440 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9441 fmtQualifiedDumpable(tbinfo));
9442 appendPQExpBuffer(query, "%s IS ",
9443 fmtId(tbinfo->attnames[objsubid - 1]));
9444 appendStringLiteralAH(query, descr, fout);
9445 appendPQExpBufferStr(query, ";\n");
9447 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9449 tbinfo->dobj.namespace->dobj.name,
9450 NULL, tbinfo->rolname,
9451 "COMMENT", SECTION_NONE,
9452 query->data, "", NULL,
9453 &(tbinfo->dobj.dumpId), 1,
9461 destroyPQExpBuffer(query);
9462 destroyPQExpBuffer(tag);
9468 * Find the comment(s), if any, associated with the given object. All the
9469 * objsubid values associated with the given classoid/objoid are found with
9473 findComments(Archive *fout, Oid classoid, Oid objoid,
9474 CommentItem **items)
9476 /* static storage for table of comments */
9477 static CommentItem *comments = NULL;
9478 static int ncomments = -1;
9480 CommentItem *middle = NULL;
9485 /* Get comments if we didn't already */
9487 ncomments = collectComments(fout, &comments);
9490 * Do binary search to find some item matching the object.
9493 high = &comments[ncomments - 1];
9496 middle = low + (high - low) / 2;
9498 if (classoid < middle->classoid)
9500 else if (classoid > middle->classoid)
9502 else if (objoid < middle->objoid)
9504 else if (objoid > middle->objoid)
9507 break; /* found a match */
9510 if (low > high) /* no matches */
9517 * Now determine how many items match the object. The search loop
9518 * invariant still holds: only items between low and high inclusive could
9522 while (middle > low)
9524 if (classoid != middle[-1].classoid ||
9525 objoid != middle[-1].objoid)
9534 while (middle <= high)
9536 if (classoid != middle->classoid ||
9537 objoid != middle->objoid)
9547 * collectComments --
9549 * Construct a table of all comments available for database objects.
9550 * We used to do per-object queries for the comments, but it's much faster
9551 * to pull them all over at once, and on most databases the memory cost
9554 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9557 collectComments(Archive *fout, CommentItem **items)
9567 CommentItem *comments;
9569 query = createPQExpBuffer();
9571 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9572 "FROM pg_catalog.pg_description "
9573 "ORDER BY classoid, objoid, objsubid");
9575 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9577 /* Construct lookup table containing OIDs in numeric form */
9579 i_description = PQfnumber(res, "description");
9580 i_classoid = PQfnumber(res, "classoid");
9581 i_objoid = PQfnumber(res, "objoid");
9582 i_objsubid = PQfnumber(res, "objsubid");
9584 ntups = PQntuples(res);
9586 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9588 for (i = 0; i < ntups; i++)
9590 comments[i].descr = PQgetvalue(res, i, i_description);
9591 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9592 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9593 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9596 /* Do NOT free the PGresult since we are keeping pointers into it */
9597 destroyPQExpBuffer(query);
9604 * dumpDumpableObject
9606 * This routine and its subsidiaries are responsible for creating
9607 * ArchiveEntries (TOC objects) for each object to be dumped.
9610 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9612 switch (dobj->objType)
9615 dumpNamespace(fout, (NamespaceInfo *) dobj);
9618 dumpExtension(fout, (ExtensionInfo *) dobj);
9621 dumpType(fout, (TypeInfo *) dobj);
9624 dumpShellType(fout, (ShellTypeInfo *) dobj);
9627 dumpFunc(fout, (FuncInfo *) dobj);
9630 dumpAgg(fout, (AggInfo *) dobj);
9633 dumpOpr(fout, (OprInfo *) dobj);
9635 case DO_ACCESS_METHOD:
9636 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9639 dumpOpclass(fout, (OpclassInfo *) dobj);
9642 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9645 dumpCollation(fout, (CollInfo *) dobj);
9648 dumpConversion(fout, (ConvInfo *) dobj);
9651 dumpTable(fout, (TableInfo *) dobj);
9654 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9657 dumpIndex(fout, (IndxInfo *) dobj);
9659 case DO_INDEX_ATTACH:
9660 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9663 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9665 case DO_REFRESH_MATVIEW:
9666 refreshMatViewData(fout, (TableDataInfo *) dobj);
9669 dumpRule(fout, (RuleInfo *) dobj);
9672 dumpTrigger(fout, (TriggerInfo *) dobj);
9674 case DO_EVENT_TRIGGER:
9675 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9678 dumpConstraint(fout, (ConstraintInfo *) dobj);
9680 case DO_FK_CONSTRAINT:
9681 dumpConstraint(fout, (ConstraintInfo *) dobj);
9684 dumpProcLang(fout, (ProcLangInfo *) dobj);
9687 dumpCast(fout, (CastInfo *) dobj);
9690 dumpTransform(fout, (TransformInfo *) dobj);
9692 case DO_SEQUENCE_SET:
9693 dumpSequenceData(fout, (TableDataInfo *) dobj);
9696 dumpTableData(fout, (TableDataInfo *) dobj);
9699 /* table rowtypes and array types are never dumped separately */
9702 dumpTSParser(fout, (TSParserInfo *) dobj);
9705 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9708 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9711 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9714 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9716 case DO_FOREIGN_SERVER:
9717 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9719 case DO_DEFAULT_ACL:
9720 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9723 dumpBlob(fout, (BlobInfo *) dobj);
9726 if (dobj->dump & DUMP_COMPONENT_DATA)
9730 te = ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9731 dobj->name, NULL, NULL, "",
9732 "BLOBS", SECTION_DATA,
9738 * Set the TocEntry's dataLength in case we are doing a
9739 * parallel dump and want to order dump jobs by table size.
9740 * (We need some size estimate for every TocEntry with a
9741 * DataDumper function.) We don't currently have any cheap
9742 * way to estimate the size of blobs, but it doesn't matter;
9743 * let's just set the size to a large value so parallel dumps
9744 * will launch this job first. If there's lots of blobs, we
9745 * win, and if there aren't, we don't lose much. (If you want
9746 * to improve on this, really what you should be thinking
9747 * about is allowing blob dumping to be parallelized, not just
9748 * getting a smarter estimate for the single TOC entry.)
9750 te->dataLength = MaxBlockNumber;
9754 dumpPolicy(fout, (PolicyInfo *) dobj);
9756 case DO_PUBLICATION:
9757 dumpPublication(fout, (PublicationInfo *) dobj);
9759 case DO_PUBLICATION_REL:
9760 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9762 case DO_SUBSCRIPTION:
9763 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9765 case DO_PRE_DATA_BOUNDARY:
9766 case DO_POST_DATA_BOUNDARY:
9767 /* never dumped, nothing to do */
9774 * writes out to fout the queries to recreate a user-defined namespace
9777 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9779 DumpOptions *dopt = fout->dopt;
9784 /* Skip if not to be dumped */
9785 if (!nspinfo->dobj.dump || dopt->dataOnly)
9788 q = createPQExpBuffer();
9789 delq = createPQExpBuffer();
9791 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9793 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9795 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9797 if (dopt->binary_upgrade)
9798 binary_upgrade_extension_member(q, &nspinfo->dobj,
9799 "SCHEMA", qnspname, NULL);
9801 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9802 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9806 "SCHEMA", SECTION_PRE_DATA,
9807 q->data, delq->data, NULL,
9811 /* Dump Schema Comments and Security Labels */
9812 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9813 dumpComment(fout, "SCHEMA", qnspname,
9814 NULL, nspinfo->rolname,
9815 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9817 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9818 dumpSecLabel(fout, "SCHEMA", qnspname,
9819 NULL, nspinfo->rolname,
9820 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9822 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9823 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9824 qnspname, NULL, NULL,
9825 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9826 nspinfo->initnspacl, nspinfo->initrnspacl);
9830 destroyPQExpBuffer(q);
9831 destroyPQExpBuffer(delq);
9836 * writes out to fout the queries to recreate an extension
9839 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9841 DumpOptions *dopt = fout->dopt;
9846 /* Skip if not to be dumped */
9847 if (!extinfo->dobj.dump || dopt->dataOnly)
9850 q = createPQExpBuffer();
9851 delq = createPQExpBuffer();
9853 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9855 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9857 if (!dopt->binary_upgrade)
9860 * In a regular dump, we simply create the extension, intentionally
9861 * not specifying a version, so that the destination installation's
9862 * default version is used.
9864 * Use of IF NOT EXISTS here is unlike our behavior for other object
9865 * types; but there are various scenarios in which it's convenient to
9866 * manually create the desired extension before restoring, so we
9867 * prefer to allow it to exist already.
9869 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9870 qextname, fmtId(extinfo->namespace));
9875 * In binary-upgrade mode, it's critical to reproduce the state of the
9876 * database exactly, so our procedure is to create an empty extension,
9877 * restore all the contained objects normally, and add them to the
9878 * extension one by one. This function performs just the first of
9879 * those steps. binary_upgrade_extension_member() takes care of
9880 * adding member objects as they're created.
9885 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9888 * We unconditionally create the extension, so we must drop it if it
9889 * exists. This could happen if the user deleted 'plpgsql' and then
9890 * readded it, causing its oid to be greater than g_last_builtin_oid.
9892 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9894 appendPQExpBufferStr(q,
9895 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9896 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9897 appendPQExpBufferStr(q, ", ");
9898 appendStringLiteralAH(q, extinfo->namespace, fout);
9899 appendPQExpBufferStr(q, ", ");
9900 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9901 appendStringLiteralAH(q, extinfo->extversion, fout);
9902 appendPQExpBufferStr(q, ", ");
9905 * Note that we're pushing extconfig (an OID array) back into
9906 * pg_extension exactly as-is. This is OK because pg_class OIDs are
9907 * preserved in binary upgrade.
9909 if (strlen(extinfo->extconfig) > 2)
9910 appendStringLiteralAH(q, extinfo->extconfig, fout);
9912 appendPQExpBufferStr(q, "NULL");
9913 appendPQExpBufferStr(q, ", ");
9914 if (strlen(extinfo->extcondition) > 2)
9915 appendStringLiteralAH(q, extinfo->extcondition, fout);
9917 appendPQExpBufferStr(q, "NULL");
9918 appendPQExpBufferStr(q, ", ");
9919 appendPQExpBufferStr(q, "ARRAY[");
9921 for (i = 0; i < extinfo->dobj.nDeps; i++)
9923 DumpableObject *extobj;
9925 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9926 if (extobj && extobj->objType == DO_EXTENSION)
9929 appendPQExpBufferChar(q, ',');
9930 appendStringLiteralAH(q, extobj->name, fout);
9933 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
9934 appendPQExpBufferStr(q, ");\n");
9937 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9938 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
9942 "EXTENSION", SECTION_PRE_DATA,
9943 q->data, delq->data, NULL,
9947 /* Dump Extension Comments and Security Labels */
9948 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9949 dumpComment(fout, "EXTENSION", qextname,
9951 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9953 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9954 dumpSecLabel(fout, "EXTENSION", qextname,
9956 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9960 destroyPQExpBuffer(q);
9961 destroyPQExpBuffer(delq);
9966 * writes out to fout the queries to recreate a user-defined type
9969 dumpType(Archive *fout, TypeInfo *tyinfo)
9971 DumpOptions *dopt = fout->dopt;
9973 /* Skip if not to be dumped */
9974 if (!tyinfo->dobj.dump || dopt->dataOnly)
9977 /* Dump out in proper style */
9978 if (tyinfo->typtype == TYPTYPE_BASE)
9979 dumpBaseType(fout, tyinfo);
9980 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
9981 dumpDomain(fout, tyinfo);
9982 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
9983 dumpCompositeType(fout, tyinfo);
9984 else if (tyinfo->typtype == TYPTYPE_ENUM)
9985 dumpEnumType(fout, tyinfo);
9986 else if (tyinfo->typtype == TYPTYPE_RANGE)
9987 dumpRangeType(fout, tyinfo);
9988 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
9989 dumpUndefinedType(fout, tyinfo);
9991 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
9997 * writes out to fout the queries to recreate a user-defined enum type
10000 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10002 DumpOptions *dopt = fout->dopt;
10003 PQExpBuffer q = createPQExpBuffer();
10004 PQExpBuffer delq = createPQExpBuffer();
10005 PQExpBuffer query = createPQExpBuffer();
10014 if (fout->remoteVersion >= 90100)
10015 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10016 "FROM pg_catalog.pg_enum "
10017 "WHERE enumtypid = '%u'"
10018 "ORDER BY enumsortorder",
10019 tyinfo->dobj.catId.oid);
10021 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10022 "FROM pg_catalog.pg_enum "
10023 "WHERE enumtypid = '%u'"
10025 tyinfo->dobj.catId.oid);
10027 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10029 num = PQntuples(res);
10031 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10032 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10035 * CASCADE shouldn't be required here as for normal types since the I/O
10036 * functions are generic and do not get dropped.
10038 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10040 if (dopt->binary_upgrade)
10041 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10042 tyinfo->dobj.catId.oid,
10045 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10048 if (!dopt->binary_upgrade)
10050 /* Labels with server-assigned oids */
10051 for (i = 0; i < num; i++)
10053 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10055 appendPQExpBufferChar(q, ',');
10056 appendPQExpBufferStr(q, "\n ");
10057 appendStringLiteralAH(q, label, fout);
10061 appendPQExpBufferStr(q, "\n);\n");
10063 if (dopt->binary_upgrade)
10065 /* Labels with dump-assigned (preserved) oids */
10066 for (i = 0; i < num; i++)
10068 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10069 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10072 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10073 appendPQExpBuffer(q,
10074 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10076 appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10077 appendStringLiteralAH(q, label, fout);
10078 appendPQExpBufferStr(q, ";\n\n");
10082 if (dopt->binary_upgrade)
10083 binary_upgrade_extension_member(q, &tyinfo->dobj,
10085 tyinfo->dobj.namespace->dobj.name);
10087 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10088 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10090 tyinfo->dobj.namespace->dobj.name,
10093 "TYPE", SECTION_PRE_DATA,
10094 q->data, delq->data, NULL,
10098 /* Dump Type Comments and Security Labels */
10099 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10100 dumpComment(fout, "TYPE", qtypname,
10101 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10102 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10104 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10105 dumpSecLabel(fout, "TYPE", qtypname,
10106 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10107 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10109 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10110 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10112 tyinfo->dobj.namespace->dobj.name,
10113 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10114 tyinfo->inittypacl, tyinfo->initrtypacl);
10117 destroyPQExpBuffer(q);
10118 destroyPQExpBuffer(delq);
10119 destroyPQExpBuffer(query);
10126 * writes out to fout the queries to recreate a user-defined range type
10129 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10131 DumpOptions *dopt = fout->dopt;
10132 PQExpBuffer q = createPQExpBuffer();
10133 PQExpBuffer delq = createPQExpBuffer();
10134 PQExpBuffer query = createPQExpBuffer();
10141 appendPQExpBuffer(query,
10142 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10143 "opc.opcname AS opcname, "
10144 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10145 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10147 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10148 " ELSE rngcollation END AS collation, "
10149 "rngcanonical, rngsubdiff "
10150 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10151 " pg_catalog.pg_opclass opc "
10152 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10154 tyinfo->dobj.catId.oid);
10156 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10158 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10159 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10162 * CASCADE shouldn't be required here as for normal types since the I/O
10163 * functions are generic and do not get dropped.
10165 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10167 if (dopt->binary_upgrade)
10168 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10169 tyinfo->dobj.catId.oid,
10172 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10175 appendPQExpBuffer(q, "\n subtype = %s",
10176 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10178 /* print subtype_opclass only if not default for subtype */
10179 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10181 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10182 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10184 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10186 appendPQExpBufferStr(q, fmtId(opcname));
10189 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10190 if (OidIsValid(collationOid))
10192 CollInfo *coll = findCollationByOid(collationOid);
10195 appendPQExpBuffer(q, ",\n collation = %s",
10196 fmtQualifiedDumpable(coll));
10199 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10200 if (strcmp(procname, "-") != 0)
10201 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10203 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10204 if (strcmp(procname, "-") != 0)
10205 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10207 appendPQExpBufferStr(q, "\n);\n");
10209 if (dopt->binary_upgrade)
10210 binary_upgrade_extension_member(q, &tyinfo->dobj,
10212 tyinfo->dobj.namespace->dobj.name);
10214 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10215 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10217 tyinfo->dobj.namespace->dobj.name,
10220 "TYPE", SECTION_PRE_DATA,
10221 q->data, delq->data, NULL,
10225 /* Dump Type Comments and Security Labels */
10226 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10227 dumpComment(fout, "TYPE", qtypname,
10228 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10229 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10231 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10232 dumpSecLabel(fout, "TYPE", qtypname,
10233 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10234 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10236 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10237 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10239 tyinfo->dobj.namespace->dobj.name,
10240 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10241 tyinfo->inittypacl, tyinfo->initrtypacl);
10244 destroyPQExpBuffer(q);
10245 destroyPQExpBuffer(delq);
10246 destroyPQExpBuffer(query);
10252 * dumpUndefinedType
10253 * writes out to fout the queries to recreate a !typisdefined type
10255 * This is a shell type, but we use different terminology to distinguish
10256 * this case from where we have to emit a shell type definition to break
10257 * circular dependencies. An undefined type shouldn't ever have anything
10261 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10263 DumpOptions *dopt = fout->dopt;
10264 PQExpBuffer q = createPQExpBuffer();
10265 PQExpBuffer delq = createPQExpBuffer();
10269 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10270 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10272 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10274 if (dopt->binary_upgrade)
10275 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10276 tyinfo->dobj.catId.oid,
10279 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10282 if (dopt->binary_upgrade)
10283 binary_upgrade_extension_member(q, &tyinfo->dobj,
10285 tyinfo->dobj.namespace->dobj.name);
10287 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10288 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10290 tyinfo->dobj.namespace->dobj.name,
10293 "TYPE", SECTION_PRE_DATA,
10294 q->data, delq->data, NULL,
10298 /* Dump Type Comments and Security Labels */
10299 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10300 dumpComment(fout, "TYPE", qtypname,
10301 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10302 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10304 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10305 dumpSecLabel(fout, "TYPE", qtypname,
10306 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10307 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10309 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10310 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10312 tyinfo->dobj.namespace->dobj.name,
10313 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10314 tyinfo->inittypacl, tyinfo->initrtypacl);
10316 destroyPQExpBuffer(q);
10317 destroyPQExpBuffer(delq);
10324 * writes out to fout the queries to recreate a user-defined base type
10327 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10329 DumpOptions *dopt = fout->dopt;
10330 PQExpBuffer q = createPQExpBuffer();
10331 PQExpBuffer delq = createPQExpBuffer();
10332 PQExpBuffer query = createPQExpBuffer();
10350 char *typispreferred;
10355 char *typcollatable;
10357 bool typdefault_is_literal = false;
10359 /* Fetch type-specific details */
10360 if (fout->remoteVersion >= 90100)
10362 appendPQExpBuffer(query, "SELECT typlen, "
10363 "typinput, typoutput, typreceive, typsend, "
10364 "typmodin, typmodout, typanalyze, "
10365 "typreceive::pg_catalog.oid AS typreceiveoid, "
10366 "typsend::pg_catalog.oid AS typsendoid, "
10367 "typmodin::pg_catalog.oid AS typmodinoid, "
10368 "typmodout::pg_catalog.oid AS typmodoutoid, "
10369 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10370 "typcategory, typispreferred, "
10371 "typdelim, typbyval, typalign, typstorage, "
10372 "(typcollation <> 0) AS typcollatable, "
10373 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10374 "FROM pg_catalog.pg_type "
10375 "WHERE oid = '%u'::pg_catalog.oid",
10376 tyinfo->dobj.catId.oid);
10378 else if (fout->remoteVersion >= 80400)
10380 appendPQExpBuffer(query, "SELECT typlen, "
10381 "typinput, typoutput, typreceive, typsend, "
10382 "typmodin, typmodout, typanalyze, "
10383 "typreceive::pg_catalog.oid AS typreceiveoid, "
10384 "typsend::pg_catalog.oid AS typsendoid, "
10385 "typmodin::pg_catalog.oid AS typmodinoid, "
10386 "typmodout::pg_catalog.oid AS typmodoutoid, "
10387 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10388 "typcategory, typispreferred, "
10389 "typdelim, typbyval, typalign, typstorage, "
10390 "false AS typcollatable, "
10391 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10392 "FROM pg_catalog.pg_type "
10393 "WHERE oid = '%u'::pg_catalog.oid",
10394 tyinfo->dobj.catId.oid);
10396 else if (fout->remoteVersion >= 80300)
10398 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10399 appendPQExpBuffer(query, "SELECT typlen, "
10400 "typinput, typoutput, typreceive, typsend, "
10401 "typmodin, typmodout, typanalyze, "
10402 "typreceive::pg_catalog.oid AS typreceiveoid, "
10403 "typsend::pg_catalog.oid AS typsendoid, "
10404 "typmodin::pg_catalog.oid AS typmodinoid, "
10405 "typmodout::pg_catalog.oid AS typmodoutoid, "
10406 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10407 "'U' AS typcategory, false AS typispreferred, "
10408 "typdelim, typbyval, typalign, typstorage, "
10409 "false AS typcollatable, "
10410 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10411 "FROM pg_catalog.pg_type "
10412 "WHERE oid = '%u'::pg_catalog.oid",
10413 tyinfo->dobj.catId.oid);
10417 appendPQExpBuffer(query, "SELECT typlen, "
10418 "typinput, typoutput, typreceive, typsend, "
10419 "'-' AS typmodin, '-' AS typmodout, "
10421 "typreceive::pg_catalog.oid AS typreceiveoid, "
10422 "typsend::pg_catalog.oid AS typsendoid, "
10423 "0 AS typmodinoid, 0 AS typmodoutoid, "
10424 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10425 "'U' AS typcategory, false AS typispreferred, "
10426 "typdelim, typbyval, typalign, typstorage, "
10427 "false AS typcollatable, "
10428 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10429 "FROM pg_catalog.pg_type "
10430 "WHERE oid = '%u'::pg_catalog.oid",
10431 tyinfo->dobj.catId.oid);
10434 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10436 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10437 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10438 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10439 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10440 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10441 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10442 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10443 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10444 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10445 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10446 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10447 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10448 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10449 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10450 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10451 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10452 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10453 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10454 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10455 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10456 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10457 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10458 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10460 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10461 typdefault_is_literal = true; /* it needs quotes */
10466 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10467 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10470 * The reason we include CASCADE is that the circular dependency between
10471 * the type and its I/O functions makes it impossible to drop the type any
10474 appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10477 * We might already have a shell type, but setting pg_type_oid is
10478 * harmless, and in any case we'd better set the array type OID.
10480 if (dopt->binary_upgrade)
10481 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10482 tyinfo->dobj.catId.oid,
10485 appendPQExpBuffer(q,
10486 "CREATE TYPE %s (\n"
10487 " INTERNALLENGTH = %s",
10489 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10491 /* regproc result is sufficiently quoted already */
10492 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10493 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10494 if (OidIsValid(typreceiveoid))
10495 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10496 if (OidIsValid(typsendoid))
10497 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10498 if (OidIsValid(typmodinoid))
10499 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10500 if (OidIsValid(typmodoutoid))
10501 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10502 if (OidIsValid(typanalyzeoid))
10503 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10505 if (strcmp(typcollatable, "t") == 0)
10506 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10508 if (typdefault != NULL)
10510 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10511 if (typdefault_is_literal)
10512 appendStringLiteralAH(q, typdefault, fout);
10514 appendPQExpBufferStr(q, typdefault);
10517 if (OidIsValid(tyinfo->typelem))
10521 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10522 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10526 if (strcmp(typcategory, "U") != 0)
10528 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10529 appendStringLiteralAH(q, typcategory, fout);
10532 if (strcmp(typispreferred, "t") == 0)
10533 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10535 if (typdelim && strcmp(typdelim, ",") != 0)
10537 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10538 appendStringLiteralAH(q, typdelim, fout);
10541 if (strcmp(typalign, "c") == 0)
10542 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10543 else if (strcmp(typalign, "s") == 0)
10544 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10545 else if (strcmp(typalign, "i") == 0)
10546 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10547 else if (strcmp(typalign, "d") == 0)
10548 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10550 if (strcmp(typstorage, "p") == 0)
10551 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10552 else if (strcmp(typstorage, "e") == 0)
10553 appendPQExpBufferStr(q, ",\n STORAGE = external");
10554 else if (strcmp(typstorage, "x") == 0)
10555 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10556 else if (strcmp(typstorage, "m") == 0)
10557 appendPQExpBufferStr(q, ",\n STORAGE = main");
10559 if (strcmp(typbyval, "t") == 0)
10560 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10562 appendPQExpBufferStr(q, "\n);\n");
10564 if (dopt->binary_upgrade)
10565 binary_upgrade_extension_member(q, &tyinfo->dobj,
10567 tyinfo->dobj.namespace->dobj.name);
10569 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10570 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10572 tyinfo->dobj.namespace->dobj.name,
10575 "TYPE", SECTION_PRE_DATA,
10576 q->data, delq->data, NULL,
10580 /* Dump Type Comments and Security Labels */
10581 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10582 dumpComment(fout, "TYPE", qtypname,
10583 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10584 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10586 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10587 dumpSecLabel(fout, "TYPE", qtypname,
10588 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10589 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10591 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10592 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10594 tyinfo->dobj.namespace->dobj.name,
10595 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10596 tyinfo->inittypacl, tyinfo->initrtypacl);
10599 destroyPQExpBuffer(q);
10600 destroyPQExpBuffer(delq);
10601 destroyPQExpBuffer(query);
10608 * writes out to fout the queries to recreate a user-defined domain
10611 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10613 DumpOptions *dopt = fout->dopt;
10614 PQExpBuffer q = createPQExpBuffer();
10615 PQExpBuffer delq = createPQExpBuffer();
10616 PQExpBuffer query = createPQExpBuffer();
10625 bool typdefault_is_literal = false;
10627 /* Fetch domain specific details */
10628 if (fout->remoteVersion >= 90100)
10630 /* typcollation is new in 9.1 */
10631 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10632 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10633 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10635 "CASE WHEN t.typcollation <> u.typcollation "
10636 "THEN t.typcollation ELSE 0 END AS typcollation "
10637 "FROM pg_catalog.pg_type t "
10638 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10639 "WHERE t.oid = '%u'::pg_catalog.oid",
10640 tyinfo->dobj.catId.oid);
10644 appendPQExpBuffer(query, "SELECT typnotnull, "
10645 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10646 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10647 "typdefault, 0 AS typcollation "
10648 "FROM pg_catalog.pg_type "
10649 "WHERE oid = '%u'::pg_catalog.oid",
10650 tyinfo->dobj.catId.oid);
10653 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10655 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10656 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10657 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10658 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10659 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10661 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10662 typdefault_is_literal = true; /* it needs quotes */
10666 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10668 if (dopt->binary_upgrade)
10669 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10670 tyinfo->dobj.catId.oid,
10671 true); /* force array type */
10673 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10674 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10676 appendPQExpBuffer(q,
10677 "CREATE DOMAIN %s AS %s",
10681 /* Print collation only if different from base type's collation */
10682 if (OidIsValid(typcollation))
10686 coll = findCollationByOid(typcollation);
10688 appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10691 if (typnotnull[0] == 't')
10692 appendPQExpBufferStr(q, " NOT NULL");
10694 if (typdefault != NULL)
10696 appendPQExpBufferStr(q, " DEFAULT ");
10697 if (typdefault_is_literal)
10698 appendStringLiteralAH(q, typdefault, fout);
10700 appendPQExpBufferStr(q, typdefault);
10706 * Add any CHECK constraints for the domain
10708 for (i = 0; i < tyinfo->nDomChecks; i++)
10710 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10712 if (!domcheck->separate)
10713 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10714 fmtId(domcheck->dobj.name), domcheck->condef);
10717 appendPQExpBufferStr(q, ";\n");
10719 appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10721 if (dopt->binary_upgrade)
10722 binary_upgrade_extension_member(q, &tyinfo->dobj,
10723 "DOMAIN", qtypname,
10724 tyinfo->dobj.namespace->dobj.name);
10726 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10727 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10729 tyinfo->dobj.namespace->dobj.name,
10732 "DOMAIN", SECTION_PRE_DATA,
10733 q->data, delq->data, NULL,
10737 /* Dump Domain Comments and Security Labels */
10738 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10739 dumpComment(fout, "DOMAIN", qtypname,
10740 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10741 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10743 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10744 dumpSecLabel(fout, "DOMAIN", qtypname,
10745 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10746 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10748 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10749 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10751 tyinfo->dobj.namespace->dobj.name,
10752 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10753 tyinfo->inittypacl, tyinfo->initrtypacl);
10755 /* Dump any per-constraint comments */
10756 for (i = 0; i < tyinfo->nDomChecks; i++)
10758 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10759 PQExpBuffer conprefix = createPQExpBuffer();
10761 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10762 fmtId(domcheck->dobj.name));
10764 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10765 dumpComment(fout, conprefix->data, qtypname,
10766 tyinfo->dobj.namespace->dobj.name,
10768 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10770 destroyPQExpBuffer(conprefix);
10773 destroyPQExpBuffer(q);
10774 destroyPQExpBuffer(delq);
10775 destroyPQExpBuffer(query);
10781 * dumpCompositeType
10782 * writes out to fout the queries to recreate a user-defined stand-alone
10786 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10788 DumpOptions *dopt = fout->dopt;
10789 PQExpBuffer q = createPQExpBuffer();
10790 PQExpBuffer dropped = createPQExpBuffer();
10791 PQExpBuffer delq = createPQExpBuffer();
10792 PQExpBuffer query = createPQExpBuffer();
10801 int i_attisdropped;
10802 int i_attcollation;
10806 /* Fetch type specific details */
10807 if (fout->remoteVersion >= 90100)
10810 * attcollation is new in 9.1. Since we only want to dump COLLATE
10811 * clauses for attributes whose collation is different from their
10812 * type's default, we use a CASE here to suppress uninteresting
10813 * attcollations cheaply. atttypid will be 0 for dropped columns;
10814 * collation does not matter for those.
10816 appendPQExpBuffer(query, "SELECT a.attname, "
10817 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10818 "a.attlen, a.attalign, a.attisdropped, "
10819 "CASE WHEN a.attcollation <> at.typcollation "
10820 "THEN a.attcollation ELSE 0 END AS attcollation "
10821 "FROM pg_catalog.pg_type ct "
10822 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10823 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10824 "WHERE ct.oid = '%u'::pg_catalog.oid "
10825 "ORDER BY a.attnum ",
10826 tyinfo->dobj.catId.oid);
10831 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10832 * should always be false.
10834 appendPQExpBuffer(query, "SELECT a.attname, "
10835 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10836 "a.attlen, a.attalign, a.attisdropped, "
10837 "0 AS attcollation "
10838 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10839 "WHERE ct.oid = '%u'::pg_catalog.oid "
10840 "AND a.attrelid = ct.typrelid "
10841 "ORDER BY a.attnum ",
10842 tyinfo->dobj.catId.oid);
10845 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10847 ntups = PQntuples(res);
10849 i_attname = PQfnumber(res, "attname");
10850 i_atttypdefn = PQfnumber(res, "atttypdefn");
10851 i_attlen = PQfnumber(res, "attlen");
10852 i_attalign = PQfnumber(res, "attalign");
10853 i_attisdropped = PQfnumber(res, "attisdropped");
10854 i_attcollation = PQfnumber(res, "attcollation");
10856 if (dopt->binary_upgrade)
10858 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10859 tyinfo->dobj.catId.oid,
10861 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10864 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10865 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10867 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10871 for (i = 0; i < ntups; i++)
10880 attname = PQgetvalue(res, i, i_attname);
10881 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10882 attlen = PQgetvalue(res, i, i_attlen);
10883 attalign = PQgetvalue(res, i, i_attalign);
10884 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10885 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10887 if (attisdropped && !dopt->binary_upgrade)
10890 /* Format properly if not first attr */
10891 if (actual_atts++ > 0)
10892 appendPQExpBufferChar(q, ',');
10893 appendPQExpBufferStr(q, "\n\t");
10897 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10899 /* Add collation if not default for the column type */
10900 if (OidIsValid(attcollation))
10904 coll = findCollationByOid(attcollation);
10906 appendPQExpBuffer(q, " COLLATE %s",
10907 fmtQualifiedDumpable(coll));
10913 * This is a dropped attribute and we're in binary_upgrade mode.
10914 * Insert a placeholder for it in the CREATE TYPE command, and set
10915 * length and alignment with direct UPDATE to the catalogs
10916 * afterwards. See similar code in dumpTableSchema().
10918 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
10920 /* stash separately for insertion after the CREATE TYPE */
10921 appendPQExpBufferStr(dropped,
10922 "\n-- For binary upgrade, recreate dropped column.\n");
10923 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
10924 "SET attlen = %s, "
10925 "attalign = '%s', attbyval = false\n"
10926 "WHERE attname = ", attlen, attalign);
10927 appendStringLiteralAH(dropped, attname, fout);
10928 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
10929 appendStringLiteralAH(dropped, qualtypname, fout);
10930 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
10932 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
10934 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
10938 appendPQExpBufferStr(q, "\n);\n");
10939 appendPQExpBufferStr(q, dropped->data);
10941 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10943 if (dopt->binary_upgrade)
10944 binary_upgrade_extension_member(q, &tyinfo->dobj,
10946 tyinfo->dobj.namespace->dobj.name);
10948 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10949 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10951 tyinfo->dobj.namespace->dobj.name,
10954 "TYPE", SECTION_PRE_DATA,
10955 q->data, delq->data, NULL,
10960 /* Dump Type Comments and Security Labels */
10961 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10962 dumpComment(fout, "TYPE", qtypname,
10963 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10964 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10966 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10967 dumpSecLabel(fout, "TYPE", qtypname,
10968 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10969 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10971 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10972 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10974 tyinfo->dobj.namespace->dobj.name,
10975 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10976 tyinfo->inittypacl, tyinfo->initrtypacl);
10979 destroyPQExpBuffer(q);
10980 destroyPQExpBuffer(dropped);
10981 destroyPQExpBuffer(delq);
10982 destroyPQExpBuffer(query);
10986 /* Dump any per-column comments */
10987 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10988 dumpCompositeTypeColComments(fout, tyinfo);
10992 * dumpCompositeTypeColComments
10993 * writes out to fout the queries to recreate comments on the columns of
10994 * a user-defined stand-alone composite type
10997 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
10999 CommentItem *comments;
11003 PQExpBuffer target;
11010 /* do nothing, if --no-comments is supplied */
11011 if (fout->dopt->no_comments)
11014 query = createPQExpBuffer();
11016 appendPQExpBuffer(query,
11017 "SELECT c.tableoid, a.attname, a.attnum "
11018 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11019 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11020 " AND NOT a.attisdropped "
11021 "ORDER BY a.attnum ",
11024 /* Fetch column attnames */
11025 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11027 ntups = PQntuples(res);
11031 destroyPQExpBuffer(query);
11035 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11037 /* Search for comments associated with type's pg_class OID */
11038 ncomments = findComments(fout,
11043 /* If no comments exist, we're done */
11044 if (ncomments <= 0)
11047 destroyPQExpBuffer(query);
11051 /* Build COMMENT ON statements */
11052 target = createPQExpBuffer();
11054 i_attnum = PQfnumber(res, "attnum");
11055 i_attname = PQfnumber(res, "attname");
11056 while (ncomments > 0)
11058 const char *attname;
11061 for (i = 0; i < ntups; i++)
11063 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11065 attname = PQgetvalue(res, i, i_attname);
11069 if (attname) /* just in case we don't find it */
11071 const char *descr = comments->descr;
11073 resetPQExpBuffer(target);
11074 appendPQExpBuffer(target, "COLUMN %s.",
11075 fmtId(tyinfo->dobj.name));
11076 appendPQExpBufferStr(target, fmtId(attname));
11078 resetPQExpBuffer(query);
11079 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11080 fmtQualifiedDumpable(tyinfo));
11081 appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11082 appendStringLiteralAH(query, descr, fout);
11083 appendPQExpBufferStr(query, ";\n");
11085 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11087 tyinfo->dobj.namespace->dobj.name,
11088 NULL, tyinfo->rolname,
11089 "COMMENT", SECTION_NONE,
11090 query->data, "", NULL,
11091 &(tyinfo->dobj.dumpId), 1,
11100 destroyPQExpBuffer(query);
11101 destroyPQExpBuffer(target);
11106 * writes out to fout the queries to create a shell type
11108 * We dump a shell definition in advance of the I/O functions for the type.
11111 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11113 DumpOptions *dopt = fout->dopt;
11116 /* Skip if not to be dumped */
11117 if (!stinfo->dobj.dump || dopt->dataOnly)
11120 q = createPQExpBuffer();
11123 * Note the lack of a DROP command for the shell type; any required DROP
11124 * is driven off the base type entry, instead. This interacts with
11125 * _printTocEntry()'s use of the presence of a DROP command to decide
11126 * whether an entry needs an ALTER OWNER command. We don't want to alter
11127 * the shell type's owner immediately on creation; that should happen only
11128 * after it's filled in, otherwise the backend complains.
11131 if (dopt->binary_upgrade)
11132 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11133 stinfo->baseType->dobj.catId.oid,
11136 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11137 fmtQualifiedDumpable(stinfo));
11139 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11140 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11142 stinfo->dobj.namespace->dobj.name,
11144 stinfo->baseType->rolname,
11145 "SHELL TYPE", SECTION_PRE_DATA,
11150 destroyPQExpBuffer(q);
11155 * writes out to fout the queries to recreate a user-defined
11156 * procedural language
11159 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11161 DumpOptions *dopt = fout->dopt;
11162 PQExpBuffer defqry;
11163 PQExpBuffer delqry;
11166 FuncInfo *funcInfo;
11167 FuncInfo *inlineInfo = NULL;
11168 FuncInfo *validatorInfo = NULL;
11170 /* Skip if not to be dumped */
11171 if (!plang->dobj.dump || dopt->dataOnly)
11175 * Try to find the support function(s). It is not an error if we don't
11176 * find them --- if the functions are in the pg_catalog schema, as is
11177 * standard in 8.1 and up, then we won't have loaded them. (In this case
11178 * we will emit a parameterless CREATE LANGUAGE command, which will
11179 * require PL template knowledge in the backend to reload.)
11182 funcInfo = findFuncByOid(plang->lanplcallfoid);
11183 if (funcInfo != NULL && !funcInfo->dobj.dump)
11184 funcInfo = NULL; /* treat not-dumped same as not-found */
11186 if (OidIsValid(plang->laninline))
11188 inlineInfo = findFuncByOid(plang->laninline);
11189 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11193 if (OidIsValid(plang->lanvalidator))
11195 validatorInfo = findFuncByOid(plang->lanvalidator);
11196 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11197 validatorInfo = NULL;
11201 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11202 * with parameters. Otherwise, we'll write a parameterless command, which
11203 * will rely on data from pg_pltemplate.
11205 useParams = (funcInfo != NULL &&
11206 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11207 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11209 defqry = createPQExpBuffer();
11210 delqry = createPQExpBuffer();
11212 qlanname = pg_strdup(fmtId(plang->dobj.name));
11214 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11219 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11220 plang->lanpltrusted ? "TRUSTED " : "",
11222 appendPQExpBuffer(defqry, " HANDLER %s",
11223 fmtQualifiedDumpable(funcInfo));
11224 if (OidIsValid(plang->laninline))
11225 appendPQExpBuffer(defqry, " INLINE %s",
11226 fmtQualifiedDumpable(inlineInfo));
11227 if (OidIsValid(plang->lanvalidator))
11228 appendPQExpBuffer(defqry, " VALIDATOR %s",
11229 fmtQualifiedDumpable(validatorInfo));
11234 * If not dumping parameters, then use CREATE OR REPLACE so that the
11235 * command will not fail if the language is preinstalled in the target
11236 * database. We restrict the use of REPLACE to this case so as to
11237 * eliminate the risk of replacing a language with incompatible
11238 * parameter settings: this command will only succeed at all if there
11239 * is a pg_pltemplate entry, and if there is one, the existing entry
11240 * must match it too.
11242 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11245 appendPQExpBufferStr(defqry, ";\n");
11247 if (dopt->binary_upgrade)
11248 binary_upgrade_extension_member(defqry, &plang->dobj,
11249 "LANGUAGE", qlanname, NULL);
11251 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11252 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11254 NULL, NULL, plang->lanowner,
11255 "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11256 defqry->data, delqry->data, NULL,
11260 /* Dump Proc Lang Comments and Security Labels */
11261 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11262 dumpComment(fout, "LANGUAGE", qlanname,
11263 NULL, plang->lanowner,
11264 plang->dobj.catId, 0, plang->dobj.dumpId);
11266 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11267 dumpSecLabel(fout, "LANGUAGE", qlanname,
11268 NULL, plang->lanowner,
11269 plang->dobj.catId, 0, plang->dobj.dumpId);
11271 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11272 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11273 qlanname, NULL, NULL,
11274 plang->lanowner, plang->lanacl, plang->rlanacl,
11275 plang->initlanacl, plang->initrlanacl);
11279 destroyPQExpBuffer(defqry);
11280 destroyPQExpBuffer(delqry);
11284 * format_function_arguments: generate function name and argument list
11286 * This is used when we can rely on pg_get_function_arguments to format
11287 * the argument list. Note, however, that pg_get_function_arguments
11288 * does not special-case zero-argument aggregates.
11291 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11293 PQExpBufferData fn;
11295 initPQExpBuffer(&fn);
11296 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11297 if (is_agg && finfo->nargs == 0)
11298 appendPQExpBufferStr(&fn, "(*)");
11300 appendPQExpBuffer(&fn, "(%s)", funcargs);
11305 * format_function_arguments_old: generate function name and argument list
11307 * The argument type names are qualified if needed. The function name
11308 * is never qualified.
11310 * This is used only with pre-8.4 servers, so we aren't expecting to see
11311 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11313 * Any or all of allargtypes, argmodes, argnames may be NULL.
11316 format_function_arguments_old(Archive *fout,
11317 FuncInfo *finfo, int nallargs,
11318 char **allargtypes,
11322 PQExpBufferData fn;
11325 initPQExpBuffer(&fn);
11326 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11327 for (j = 0; j < nallargs; j++)
11331 const char *argmode;
11332 const char *argname;
11334 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11335 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11339 switch (argmodes[j][0])
11341 case PROARGMODE_IN:
11344 case PROARGMODE_OUT:
11347 case PROARGMODE_INOUT:
11348 argmode = "INOUT ";
11351 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11359 argname = argnames ? argnames[j] : (char *) NULL;
11360 if (argname && argname[0] == '\0')
11363 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11364 (j > 0) ? ", " : "",
11366 argname ? fmtId(argname) : "",
11367 argname ? " " : "",
11371 appendPQExpBufferChar(&fn, ')');
11376 * format_function_signature: generate function name and argument list
11378 * This is like format_function_arguments_old except that only a minimal
11379 * list of input argument types is generated; this is sufficient to
11380 * reference the function, but not to define it.
11382 * If honor_quotes is false then the function name is never quoted.
11383 * This is appropriate for use in TOC tags, but not in SQL commands.
11386 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11388 PQExpBufferData fn;
11391 initPQExpBuffer(&fn);
11393 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11395 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11396 for (j = 0; j < finfo->nargs; j++)
11401 appendPQExpBufferStr(&fn, ", ");
11403 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11405 appendPQExpBufferStr(&fn, typname);
11408 appendPQExpBufferChar(&fn, ')');
11415 * dump out one function
11418 dumpFunc(Archive *fout, FuncInfo *finfo)
11420 DumpOptions *dopt = fout->dopt;
11423 PQExpBuffer delqry;
11424 PQExpBuffer asPart;
11426 char *funcsig; /* identity signature */
11427 char *funcfullsig = NULL; /* full signature */
11435 char *proallargtypes;
11443 char *proleakproof;
11451 char **allargtypes = NULL;
11452 char **argmodes = NULL;
11453 char **argnames = NULL;
11454 char **configitems = NULL;
11455 int nconfigitems = 0;
11456 const char *keyword;
11459 /* Skip if not to be dumped */
11460 if (!finfo->dobj.dump || dopt->dataOnly)
11463 query = createPQExpBuffer();
11464 q = createPQExpBuffer();
11465 delqry = createPQExpBuffer();
11466 asPart = createPQExpBuffer();
11468 /* Fetch function-specific details */
11469 if (fout->remoteVersion >= 110000)
11472 * prokind was added in 11
11474 appendPQExpBuffer(query,
11475 "SELECT proretset, prosrc, probin, "
11476 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11477 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11478 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11479 "array_to_string(protrftypes, ' ') AS protrftypes, "
11480 "prokind, provolatile, proisstrict, prosecdef, "
11481 "proleakproof, proconfig, procost, prorows, "
11483 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11484 "FROM pg_catalog.pg_proc "
11485 "WHERE oid = '%u'::pg_catalog.oid",
11486 finfo->dobj.catId.oid);
11488 else if (fout->remoteVersion >= 90600)
11491 * proparallel was added in 9.6
11493 appendPQExpBuffer(query,
11494 "SELECT proretset, prosrc, probin, "
11495 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11496 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11497 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11498 "array_to_string(protrftypes, ' ') AS protrftypes, "
11499 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11500 "provolatile, proisstrict, prosecdef, "
11501 "proleakproof, proconfig, procost, prorows, "
11503 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11504 "FROM pg_catalog.pg_proc "
11505 "WHERE oid = '%u'::pg_catalog.oid",
11506 finfo->dobj.catId.oid);
11508 else if (fout->remoteVersion >= 90500)
11511 * protrftypes was added in 9.5
11513 appendPQExpBuffer(query,
11514 "SELECT proretset, prosrc, probin, "
11515 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11516 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11517 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11518 "array_to_string(protrftypes, ' ') AS protrftypes, "
11519 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11520 "provolatile, proisstrict, prosecdef, "
11521 "proleakproof, proconfig, procost, prorows, "
11522 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11523 "FROM pg_catalog.pg_proc "
11524 "WHERE oid = '%u'::pg_catalog.oid",
11525 finfo->dobj.catId.oid);
11527 else if (fout->remoteVersion >= 90200)
11530 * proleakproof was added in 9.2
11532 appendPQExpBuffer(query,
11533 "SELECT proretset, prosrc, probin, "
11534 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11535 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11536 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11537 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11538 "provolatile, proisstrict, prosecdef, "
11539 "proleakproof, proconfig, procost, prorows, "
11540 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11541 "FROM pg_catalog.pg_proc "
11542 "WHERE oid = '%u'::pg_catalog.oid",
11543 finfo->dobj.catId.oid);
11545 else if (fout->remoteVersion >= 80400)
11548 * In 8.4 and up we rely on pg_get_function_arguments and
11549 * pg_get_function_result instead of examining proallargtypes etc.
11551 appendPQExpBuffer(query,
11552 "SELECT proretset, prosrc, probin, "
11553 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11554 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11555 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11556 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11557 "provolatile, proisstrict, prosecdef, "
11558 "false AS proleakproof, "
11559 " proconfig, procost, prorows, "
11560 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11561 "FROM pg_catalog.pg_proc "
11562 "WHERE oid = '%u'::pg_catalog.oid",
11563 finfo->dobj.catId.oid);
11565 else if (fout->remoteVersion >= 80300)
11567 appendPQExpBuffer(query,
11568 "SELECT proretset, prosrc, probin, "
11569 "proallargtypes, proargmodes, proargnames, "
11571 "provolatile, proisstrict, prosecdef, "
11572 "false AS proleakproof, "
11573 "proconfig, procost, prorows, "
11574 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11575 "FROM pg_catalog.pg_proc "
11576 "WHERE oid = '%u'::pg_catalog.oid",
11577 finfo->dobj.catId.oid);
11579 else if (fout->remoteVersion >= 80100)
11581 appendPQExpBuffer(query,
11582 "SELECT proretset, prosrc, probin, "
11583 "proallargtypes, proargmodes, proargnames, "
11585 "provolatile, proisstrict, prosecdef, "
11586 "false AS proleakproof, "
11587 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11588 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11589 "FROM pg_catalog.pg_proc "
11590 "WHERE oid = '%u'::pg_catalog.oid",
11591 finfo->dobj.catId.oid);
11595 appendPQExpBuffer(query,
11596 "SELECT proretset, prosrc, probin, "
11597 "null AS proallargtypes, "
11598 "null AS proargmodes, "
11601 "provolatile, proisstrict, prosecdef, "
11602 "false AS proleakproof, "
11603 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11604 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11605 "FROM pg_catalog.pg_proc "
11606 "WHERE oid = '%u'::pg_catalog.oid",
11607 finfo->dobj.catId.oid);
11610 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11612 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11613 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11614 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11615 if (fout->remoteVersion >= 80400)
11617 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11618 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11619 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11620 proallargtypes = proargmodes = proargnames = NULL;
11624 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11625 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11626 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11627 funcargs = funciargs = funcresult = NULL;
11629 if (PQfnumber(res, "protrftypes") != -1)
11630 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11632 protrftypes = NULL;
11633 prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11634 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11635 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11636 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11637 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11638 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11639 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11640 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11642 if (PQfnumber(res, "proparallel") != -1)
11643 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11645 proparallel = NULL;
11647 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11650 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11651 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11652 * versions would set it to "-". There are no known cases in which prosrc
11653 * is unused, so the tests below for "-" are probably useless.
11655 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11657 appendPQExpBufferStr(asPart, "AS ");
11658 appendStringLiteralAH(asPart, probin, fout);
11659 if (strcmp(prosrc, "-") != 0)
11661 appendPQExpBufferStr(asPart, ", ");
11664 * where we have bin, use dollar quoting if allowed and src
11665 * contains quote or backslash; else use regular quoting.
11667 if (dopt->disable_dollar_quoting ||
11668 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11669 appendStringLiteralAH(asPart, prosrc, fout);
11671 appendStringLiteralDQ(asPart, prosrc, NULL);
11676 if (strcmp(prosrc, "-") != 0)
11678 appendPQExpBufferStr(asPart, "AS ");
11679 /* with no bin, dollar quote src unconditionally if allowed */
11680 if (dopt->disable_dollar_quoting)
11681 appendStringLiteralAH(asPart, prosrc, fout);
11683 appendStringLiteralDQ(asPart, prosrc, NULL);
11687 nallargs = finfo->nargs; /* unless we learn different from allargs */
11689 if (proallargtypes && *proallargtypes)
11693 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11694 nitems < finfo->nargs)
11696 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11699 allargtypes = NULL;
11705 if (proargmodes && *proargmodes)
11709 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11710 nitems != nallargs)
11712 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11719 if (proargnames && *proargnames)
11723 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11724 nitems != nallargs)
11726 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11733 if (proconfig && *proconfig)
11735 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11737 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11740 configitems = NULL;
11747 /* 8.4 or later; we rely on server-side code for most of the work */
11748 funcfullsig = format_function_arguments(finfo, funcargs, false);
11749 funcsig = format_function_arguments(finfo, funciargs, false);
11752 /* pre-8.4, do it ourselves */
11753 funcsig = format_function_arguments_old(fout,
11754 finfo, nallargs, allargtypes,
11755 argmodes, argnames);
11757 funcsig_tag = format_function_signature(fout, finfo, false);
11759 if (prokind[0] == PROKIND_PROCEDURE)
11760 keyword = "PROCEDURE";
11762 keyword = "FUNCTION"; /* works for window functions too */
11764 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11766 fmtId(finfo->dobj.namespace->dobj.name),
11769 appendPQExpBuffer(q, "CREATE %s %s.%s",
11771 fmtId(finfo->dobj.namespace->dobj.name),
11772 funcfullsig ? funcfullsig :
11775 if (prokind[0] == PROKIND_PROCEDURE)
11776 /* no result type to output */ ;
11777 else if (funcresult)
11778 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11781 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11783 appendPQExpBuffer(q, " RETURNS %s%s",
11784 (proretset[0] == 't') ? "SETOF " : "",
11789 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11791 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11793 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11796 appendPQExpBufferStr(q, " TRANSFORM ");
11797 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11798 for (i = 0; typeids[i]; i++)
11801 appendPQExpBufferStr(q, ", ");
11802 appendPQExpBuffer(q, "FOR TYPE %s",
11803 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11807 if (prokind[0] == PROKIND_WINDOW)
11808 appendPQExpBufferStr(q, " WINDOW");
11810 if (provolatile[0] != PROVOLATILE_VOLATILE)
11812 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11813 appendPQExpBufferStr(q, " IMMUTABLE");
11814 else if (provolatile[0] == PROVOLATILE_STABLE)
11815 appendPQExpBufferStr(q, " STABLE");
11816 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11817 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11821 if (proisstrict[0] == 't')
11822 appendPQExpBufferStr(q, " STRICT");
11824 if (prosecdef[0] == 't')
11825 appendPQExpBufferStr(q, " SECURITY DEFINER");
11827 if (proleakproof[0] == 't')
11828 appendPQExpBufferStr(q, " LEAKPROOF");
11831 * COST and ROWS are emitted only if present and not default, so as not to
11832 * break backwards-compatibility of the dump without need. Keep this code
11833 * in sync with the defaults in functioncmds.c.
11835 if (strcmp(procost, "0") != 0)
11837 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11839 /* default cost is 1 */
11840 if (strcmp(procost, "1") != 0)
11841 appendPQExpBuffer(q, " COST %s", procost);
11845 /* default cost is 100 */
11846 if (strcmp(procost, "100") != 0)
11847 appendPQExpBuffer(q, " COST %s", procost);
11850 if (proretset[0] == 't' &&
11851 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11852 appendPQExpBuffer(q, " ROWS %s", prorows);
11854 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11856 if (proparallel[0] == PROPARALLEL_SAFE)
11857 appendPQExpBufferStr(q, " PARALLEL SAFE");
11858 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11859 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11860 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11861 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11865 for (i = 0; i < nconfigitems; i++)
11867 /* we feel free to scribble on configitems[] here */
11868 char *configitem = configitems[i];
11871 pos = strchr(configitem, '=');
11875 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
11878 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11879 * by flatten_set_variable_args() before they were put into the
11880 * proconfig array. However, because the quoting rules used there
11881 * aren't exactly like SQL's, we have to break the list value apart
11882 * and then quote the elements as string literals. (The elements may
11883 * be double-quoted as-is, but we can't just feed them to the SQL
11884 * parser; it would do the wrong thing with elements that are
11885 * zero-length or longer than NAMEDATALEN.)
11887 * Variables that are not so marked should just be emitted as simple
11888 * string literals. If the variable is not known to
11889 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
11890 * to use GUC_LIST_QUOTE for extension variables.
11892 if (variable_is_guc_list_quote(configitem))
11897 /* Parse string into list of identifiers */
11898 /* this shouldn't fail really */
11899 if (SplitGUCList(pos, ',', &namelist))
11901 for (nameptr = namelist; *nameptr; nameptr++)
11903 if (nameptr != namelist)
11904 appendPQExpBufferStr(q, ", ");
11905 appendStringLiteralAH(q, *nameptr, fout);
11911 appendStringLiteralAH(q, pos, fout);
11914 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
11916 if (dopt->binary_upgrade)
11917 binary_upgrade_extension_member(q, &finfo->dobj,
11919 finfo->dobj.namespace->dobj.name);
11921 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11922 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
11924 finfo->dobj.namespace->dobj.name,
11927 keyword, SECTION_PRE_DATA,
11928 q->data, delqry->data, NULL,
11932 /* Dump Function Comments and Security Labels */
11933 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11934 dumpComment(fout, keyword, funcsig,
11935 finfo->dobj.namespace->dobj.name, finfo->rolname,
11936 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11938 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11939 dumpSecLabel(fout, keyword, funcsig,
11940 finfo->dobj.namespace->dobj.name, finfo->rolname,
11941 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11943 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
11944 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
11946 finfo->dobj.namespace->dobj.name,
11947 finfo->rolname, finfo->proacl, finfo->rproacl,
11948 finfo->initproacl, finfo->initrproacl);
11952 destroyPQExpBuffer(query);
11953 destroyPQExpBuffer(q);
11954 destroyPQExpBuffer(delqry);
11955 destroyPQExpBuffer(asPart);
11972 * Dump a user-defined cast
11975 dumpCast(Archive *fout, CastInfo *cast)
11977 DumpOptions *dopt = fout->dopt;
11978 PQExpBuffer defqry;
11979 PQExpBuffer delqry;
11980 PQExpBuffer labelq;
11981 PQExpBuffer castargs;
11982 FuncInfo *funcInfo = NULL;
11986 /* Skip if not to be dumped */
11987 if (!cast->dobj.dump || dopt->dataOnly)
11990 /* Cannot dump if we don't have the cast function's info */
11991 if (OidIsValid(cast->castfunc))
11993 funcInfo = findFuncByOid(cast->castfunc);
11994 if (funcInfo == NULL)
11995 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11999 defqry = createPQExpBuffer();
12000 delqry = createPQExpBuffer();
12001 labelq = createPQExpBuffer();
12002 castargs = createPQExpBuffer();
12004 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12005 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12006 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12007 sourceType, targetType);
12009 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12010 sourceType, targetType);
12012 switch (cast->castmethod)
12014 case COERCION_METHOD_BINARY:
12015 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12017 case COERCION_METHOD_INOUT:
12018 appendPQExpBufferStr(defqry, "WITH INOUT");
12020 case COERCION_METHOD_FUNCTION:
12023 char *fsig = format_function_signature(fout, funcInfo, true);
12026 * Always qualify the function name (format_function_signature
12027 * won't qualify it).
12029 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12030 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12034 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12037 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12040 if (cast->castcontext == 'a')
12041 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12042 else if (cast->castcontext == 'i')
12043 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12044 appendPQExpBufferStr(defqry, ";\n");
12046 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12047 sourceType, targetType);
12049 appendPQExpBuffer(castargs, "(%s AS %s)",
12050 sourceType, targetType);
12052 if (dopt->binary_upgrade)
12053 binary_upgrade_extension_member(defqry, &cast->dobj,
12054 "CAST", castargs->data, NULL);
12056 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12057 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12060 "CAST", SECTION_PRE_DATA,
12061 defqry->data, delqry->data, NULL,
12065 /* Dump Cast Comments */
12066 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12067 dumpComment(fout, "CAST", castargs->data,
12069 cast->dobj.catId, 0, cast->dobj.dumpId);
12074 destroyPQExpBuffer(defqry);
12075 destroyPQExpBuffer(delqry);
12076 destroyPQExpBuffer(labelq);
12077 destroyPQExpBuffer(castargs);
12084 dumpTransform(Archive *fout, TransformInfo *transform)
12086 DumpOptions *dopt = fout->dopt;
12087 PQExpBuffer defqry;
12088 PQExpBuffer delqry;
12089 PQExpBuffer labelq;
12090 PQExpBuffer transformargs;
12091 FuncInfo *fromsqlFuncInfo = NULL;
12092 FuncInfo *tosqlFuncInfo = NULL;
12094 char *transformType;
12096 /* Skip if not to be dumped */
12097 if (!transform->dobj.dump || dopt->dataOnly)
12100 /* Cannot dump if we don't have the transform functions' info */
12101 if (OidIsValid(transform->trffromsql))
12103 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12104 if (fromsqlFuncInfo == NULL)
12105 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12106 transform->trffromsql);
12108 if (OidIsValid(transform->trftosql))
12110 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12111 if (tosqlFuncInfo == NULL)
12112 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12113 transform->trftosql);
12116 defqry = createPQExpBuffer();
12117 delqry = createPQExpBuffer();
12118 labelq = createPQExpBuffer();
12119 transformargs = createPQExpBuffer();
12121 lanname = get_language_name(fout, transform->trflang);
12122 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12124 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12125 transformType, lanname);
12127 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12128 transformType, lanname);
12130 if (!transform->trffromsql && !transform->trftosql)
12131 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12133 if (transform->trffromsql)
12135 if (fromsqlFuncInfo)
12137 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12140 * Always qualify the function name (format_function_signature
12141 * won't qualify it).
12143 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12144 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12148 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12151 if (transform->trftosql)
12153 if (transform->trffromsql)
12154 appendPQExpBuffer(defqry, ", ");
12158 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12161 * Always qualify the function name (format_function_signature
12162 * won't qualify it).
12164 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12165 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12169 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12172 appendPQExpBuffer(defqry, ");\n");
12174 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12175 transformType, lanname);
12177 appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12178 transformType, lanname);
12180 if (dopt->binary_upgrade)
12181 binary_upgrade_extension_member(defqry, &transform->dobj,
12182 "TRANSFORM", transformargs->data, NULL);
12184 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12185 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12188 "TRANSFORM", SECTION_PRE_DATA,
12189 defqry->data, delqry->data, NULL,
12190 transform->dobj.dependencies, transform->dobj.nDeps,
12193 /* Dump Transform Comments */
12194 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12195 dumpComment(fout, "TRANSFORM", transformargs->data,
12197 transform->dobj.catId, 0, transform->dobj.dumpId);
12200 free(transformType);
12201 destroyPQExpBuffer(defqry);
12202 destroyPQExpBuffer(delqry);
12203 destroyPQExpBuffer(labelq);
12204 destroyPQExpBuffer(transformargs);
12210 * write out a single operator definition
12213 dumpOpr(Archive *fout, OprInfo *oprinfo)
12215 DumpOptions *dopt = fout->dopt;
12220 PQExpBuffer details;
12245 /* Skip if not to be dumped */
12246 if (!oprinfo->dobj.dump || dopt->dataOnly)
12250 * some operators are invalid because they were the result of user
12251 * defining operators before commutators exist
12253 if (!OidIsValid(oprinfo->oprcode))
12256 query = createPQExpBuffer();
12257 q = createPQExpBuffer();
12258 delq = createPQExpBuffer();
12259 oprid = createPQExpBuffer();
12260 details = createPQExpBuffer();
12262 if (fout->remoteVersion >= 80300)
12264 appendPQExpBuffer(query, "SELECT oprkind, "
12265 "oprcode::pg_catalog.regprocedure, "
12266 "oprleft::pg_catalog.regtype, "
12267 "oprright::pg_catalog.regtype, "
12270 "oprrest::pg_catalog.regprocedure, "
12271 "oprjoin::pg_catalog.regprocedure, "
12272 "oprcanmerge, oprcanhash "
12273 "FROM pg_catalog.pg_operator "
12274 "WHERE oid = '%u'::pg_catalog.oid",
12275 oprinfo->dobj.catId.oid);
12279 appendPQExpBuffer(query, "SELECT oprkind, "
12280 "oprcode::pg_catalog.regprocedure, "
12281 "oprleft::pg_catalog.regtype, "
12282 "oprright::pg_catalog.regtype, "
12285 "oprrest::pg_catalog.regprocedure, "
12286 "oprjoin::pg_catalog.regprocedure, "
12287 "(oprlsortop != 0) AS oprcanmerge, "
12289 "FROM pg_catalog.pg_operator "
12290 "WHERE oid = '%u'::pg_catalog.oid",
12291 oprinfo->dobj.catId.oid);
12294 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12296 i_oprkind = PQfnumber(res, "oprkind");
12297 i_oprcode = PQfnumber(res, "oprcode");
12298 i_oprleft = PQfnumber(res, "oprleft");
12299 i_oprright = PQfnumber(res, "oprright");
12300 i_oprcom = PQfnumber(res, "oprcom");
12301 i_oprnegate = PQfnumber(res, "oprnegate");
12302 i_oprrest = PQfnumber(res, "oprrest");
12303 i_oprjoin = PQfnumber(res, "oprjoin");
12304 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12305 i_oprcanhash = PQfnumber(res, "oprcanhash");
12307 oprkind = PQgetvalue(res, 0, i_oprkind);
12308 oprcode = PQgetvalue(res, 0, i_oprcode);
12309 oprleft = PQgetvalue(res, 0, i_oprleft);
12310 oprright = PQgetvalue(res, 0, i_oprright);
12311 oprcom = PQgetvalue(res, 0, i_oprcom);
12312 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12313 oprrest = PQgetvalue(res, 0, i_oprrest);
12314 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12315 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12316 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12318 oprregproc = convertRegProcReference(fout, oprcode);
12321 appendPQExpBuffer(details, " FUNCTION = %s", oprregproc);
12325 appendPQExpBuffer(oprid, "%s (",
12326 oprinfo->dobj.name);
12329 * right unary means there's a left arg and left unary means there's a
12332 if (strcmp(oprkind, "r") == 0 ||
12333 strcmp(oprkind, "b") == 0)
12335 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12336 appendPQExpBufferStr(oprid, oprleft);
12339 appendPQExpBufferStr(oprid, "NONE");
12341 if (strcmp(oprkind, "l") == 0 ||
12342 strcmp(oprkind, "b") == 0)
12344 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12345 appendPQExpBuffer(oprid, ", %s)", oprright);
12348 appendPQExpBufferStr(oprid, ", NONE)");
12350 oprref = getFormattedOperatorName(fout, oprcom);
12353 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12357 oprref = getFormattedOperatorName(fout, oprnegate);
12360 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12364 if (strcmp(oprcanmerge, "t") == 0)
12365 appendPQExpBufferStr(details, ",\n MERGES");
12367 if (strcmp(oprcanhash, "t") == 0)
12368 appendPQExpBufferStr(details, ",\n HASHES");
12370 oprregproc = convertRegProcReference(fout, oprrest);
12373 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12377 oprregproc = convertRegProcReference(fout, oprjoin);
12380 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12384 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12385 fmtId(oprinfo->dobj.namespace->dobj.name),
12388 appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12389 fmtId(oprinfo->dobj.namespace->dobj.name),
12390 oprinfo->dobj.name, details->data);
12392 if (dopt->binary_upgrade)
12393 binary_upgrade_extension_member(q, &oprinfo->dobj,
12394 "OPERATOR", oprid->data,
12395 oprinfo->dobj.namespace->dobj.name);
12397 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12398 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12399 oprinfo->dobj.name,
12400 oprinfo->dobj.namespace->dobj.name,
12403 "OPERATOR", SECTION_PRE_DATA,
12404 q->data, delq->data, NULL,
12408 /* Dump Operator Comments */
12409 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12410 dumpComment(fout, "OPERATOR", oprid->data,
12411 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12412 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12416 destroyPQExpBuffer(query);
12417 destroyPQExpBuffer(q);
12418 destroyPQExpBuffer(delq);
12419 destroyPQExpBuffer(oprid);
12420 destroyPQExpBuffer(details);
12424 * Convert a function reference obtained from pg_operator
12426 * Returns allocated string of what to print, or NULL if function references
12427 * is InvalidOid. Returned string is expected to be free'd by the caller.
12429 * The input is a REGPROCEDURE display; we have to strip the argument-types
12433 convertRegProcReference(Archive *fout, const char *proc)
12439 /* In all cases "-" means a null reference */
12440 if (strcmp(proc, "-") == 0)
12443 name = pg_strdup(proc);
12444 /* find non-double-quoted left paren */
12446 for (paren = name; *paren; paren++)
12448 if (*paren == '(' && !inquote)
12454 inquote = !inquote;
12460 * getFormattedOperatorName - retrieve the operator name for the
12461 * given operator OID (presented in string form).
12463 * Returns an allocated string, or NULL if the given OID is invalid.
12464 * Caller is responsible for free'ing result string.
12466 * What we produce has the format "OPERATOR(schema.oprname)". This is only
12467 * useful in commands where the operator's argument types can be inferred from
12468 * context. We always schema-qualify the name, though. The predecessor to
12469 * this code tried to skip the schema qualification if possible, but that led
12470 * to wrong results in corner cases, such as if an operator and its negator
12471 * are in different schemas.
12474 getFormattedOperatorName(Archive *fout, const char *oproid)
12478 /* In all cases "0" means a null reference */
12479 if (strcmp(oproid, "0") == 0)
12482 oprInfo = findOprByOid(atooid(oproid));
12483 if (oprInfo == NULL)
12485 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12490 return psprintf("OPERATOR(%s.%s)",
12491 fmtId(oprInfo->dobj.namespace->dobj.name),
12492 oprInfo->dobj.name);
12496 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12498 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12499 * argument lists of these functions are predetermined. Note that the
12500 * caller should ensure we are in the proper schema, because the results
12501 * are search path dependent!
12504 convertTSFunction(Archive *fout, Oid funcOid)
12510 snprintf(query, sizeof(query),
12511 "SELECT '%u'::pg_catalog.regproc", funcOid);
12512 res = ExecuteSqlQueryForSingleRow(fout, query);
12514 result = pg_strdup(PQgetvalue(res, 0, 0));
12523 * write out a single access method definition
12526 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12528 DumpOptions *dopt = fout->dopt;
12533 /* Skip if not to be dumped */
12534 if (!aminfo->dobj.dump || dopt->dataOnly)
12537 q = createPQExpBuffer();
12538 delq = createPQExpBuffer();
12540 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12542 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12544 switch (aminfo->amtype)
12547 appendPQExpBuffer(q, "TYPE INDEX ");
12550 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12551 aminfo->amtype, qamname);
12552 destroyPQExpBuffer(q);
12553 destroyPQExpBuffer(delq);
12558 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12560 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12563 if (dopt->binary_upgrade)
12564 binary_upgrade_extension_member(q, &aminfo->dobj,
12565 "ACCESS METHOD", qamname, NULL);
12567 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12568 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12573 "ACCESS METHOD", SECTION_PRE_DATA,
12574 q->data, delq->data, NULL,
12578 /* Dump Access Method Comments */
12579 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12580 dumpComment(fout, "ACCESS METHOD", qamname,
12582 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12584 destroyPQExpBuffer(q);
12585 destroyPQExpBuffer(delq);
12591 * write out a single operator class definition
12594 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12596 DumpOptions *dopt = fout->dopt;
12600 PQExpBuffer nameusing;
12607 int i_opcfamilyname;
12608 int i_opcfamilynsp;
12610 int i_amopstrategy;
12611 int i_amopreqcheck;
12614 int i_sortfamilynsp;
12617 int i_amproclefttype;
12618 int i_amprocrighttype;
12623 char *opcfamilyname;
12624 char *opcfamilynsp;
12626 char *amopstrategy;
12627 char *amopreqcheck;
12630 char *sortfamilynsp;
12633 char *amproclefttype;
12634 char *amprocrighttype;
12638 /* Skip if not to be dumped */
12639 if (!opcinfo->dobj.dump || dopt->dataOnly)
12642 query = createPQExpBuffer();
12643 q = createPQExpBuffer();
12644 delq = createPQExpBuffer();
12645 nameusing = createPQExpBuffer();
12647 /* Get additional fields from the pg_opclass row */
12648 if (fout->remoteVersion >= 80300)
12650 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12651 "opckeytype::pg_catalog.regtype, "
12652 "opcdefault, opcfamily, "
12653 "opfname AS opcfamilyname, "
12654 "nspname AS opcfamilynsp, "
12655 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12656 "FROM pg_catalog.pg_opclass c "
12657 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12658 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12659 "WHERE c.oid = '%u'::pg_catalog.oid",
12660 opcinfo->dobj.catId.oid);
12664 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12665 "opckeytype::pg_catalog.regtype, "
12666 "opcdefault, NULL AS opcfamily, "
12667 "NULL AS opcfamilyname, "
12668 "NULL AS opcfamilynsp, "
12669 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12670 "FROM pg_catalog.pg_opclass "
12671 "WHERE oid = '%u'::pg_catalog.oid",
12672 opcinfo->dobj.catId.oid);
12675 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12677 i_opcintype = PQfnumber(res, "opcintype");
12678 i_opckeytype = PQfnumber(res, "opckeytype");
12679 i_opcdefault = PQfnumber(res, "opcdefault");
12680 i_opcfamily = PQfnumber(res, "opcfamily");
12681 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12682 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12683 i_amname = PQfnumber(res, "amname");
12685 /* opcintype may still be needed after we PQclear res */
12686 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12687 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12688 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12689 /* opcfamily will still be needed after we PQclear res */
12690 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12691 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12692 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12693 /* amname will still be needed after we PQclear res */
12694 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12696 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12697 fmtQualifiedDumpable(opcinfo));
12698 appendPQExpBuffer(delq, " USING %s;\n",
12701 /* Build the fixed portion of the CREATE command */
12702 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12703 fmtQualifiedDumpable(opcinfo));
12704 if (strcmp(opcdefault, "t") == 0)
12705 appendPQExpBufferStr(q, "DEFAULT ");
12706 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12709 if (strlen(opcfamilyname) > 0)
12711 appendPQExpBufferStr(q, " FAMILY ");
12712 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12713 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12715 appendPQExpBufferStr(q, " AS\n ");
12719 if (strcmp(opckeytype, "-") != 0)
12721 appendPQExpBuffer(q, "STORAGE %s",
12729 * Now fetch and print the OPERATOR entries (pg_amop rows).
12731 * Print only those opfamily members that are tied to the opclass by
12732 * pg_depend entries.
12734 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12735 * older server's opclass in which it is used. This is to avoid
12736 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12737 * older server and then reload into that old version. This can go away
12738 * once 8.3 is so old as to not be of interest to anyone.
12740 resetPQExpBuffer(query);
12742 if (fout->remoteVersion >= 90100)
12744 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12745 "amopopr::pg_catalog.regoperator, "
12746 "opfname AS sortfamily, "
12747 "nspname AS sortfamilynsp "
12748 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12749 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12750 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12751 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12752 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12753 "AND refobjid = '%u'::pg_catalog.oid "
12754 "AND amopfamily = '%s'::pg_catalog.oid "
12755 "ORDER BY amopstrategy",
12756 opcinfo->dobj.catId.oid,
12759 else if (fout->remoteVersion >= 80400)
12761 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12762 "amopopr::pg_catalog.regoperator, "
12763 "NULL AS sortfamily, "
12764 "NULL AS sortfamilynsp "
12765 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12766 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12767 "AND refobjid = '%u'::pg_catalog.oid "
12768 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12769 "AND objid = ao.oid "
12770 "ORDER BY amopstrategy",
12771 opcinfo->dobj.catId.oid);
12773 else if (fout->remoteVersion >= 80300)
12775 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12776 "amopopr::pg_catalog.regoperator, "
12777 "NULL AS sortfamily, "
12778 "NULL AS sortfamilynsp "
12779 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12780 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12781 "AND refobjid = '%u'::pg_catalog.oid "
12782 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12783 "AND objid = ao.oid "
12784 "ORDER BY amopstrategy",
12785 opcinfo->dobj.catId.oid);
12790 * Here, we print all entries since there are no opfamilies and hence
12791 * no loose operators to worry about.
12793 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12794 "amopopr::pg_catalog.regoperator, "
12795 "NULL AS sortfamily, "
12796 "NULL AS sortfamilynsp "
12797 "FROM pg_catalog.pg_amop "
12798 "WHERE amopclaid = '%u'::pg_catalog.oid "
12799 "ORDER BY amopstrategy",
12800 opcinfo->dobj.catId.oid);
12803 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12805 ntups = PQntuples(res);
12807 i_amopstrategy = PQfnumber(res, "amopstrategy");
12808 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12809 i_amopopr = PQfnumber(res, "amopopr");
12810 i_sortfamily = PQfnumber(res, "sortfamily");
12811 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12813 for (i = 0; i < ntups; i++)
12815 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12816 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12817 amopopr = PQgetvalue(res, i, i_amopopr);
12818 sortfamily = PQgetvalue(res, i, i_sortfamily);
12819 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12822 appendPQExpBufferStr(q, " ,\n ");
12824 appendPQExpBuffer(q, "OPERATOR %s %s",
12825 amopstrategy, amopopr);
12827 if (strlen(sortfamily) > 0)
12829 appendPQExpBufferStr(q, " FOR ORDER BY ");
12830 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12831 appendPQExpBufferStr(q, fmtId(sortfamily));
12834 if (strcmp(amopreqcheck, "t") == 0)
12835 appendPQExpBufferStr(q, " RECHECK");
12843 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12845 * Print only those opfamily members that are tied to the opclass by
12846 * pg_depend entries.
12848 * We print the amproclefttype/amprocrighttype even though in most cases
12849 * the backend could deduce the right values, because of the corner case
12850 * of a btree sort support function for a cross-type comparison. That's
12851 * only allowed in 9.2 and later, but for simplicity print them in all
12852 * versions that have the columns.
12854 resetPQExpBuffer(query);
12856 if (fout->remoteVersion >= 80300)
12858 appendPQExpBuffer(query, "SELECT amprocnum, "
12859 "amproc::pg_catalog.regprocedure, "
12860 "amproclefttype::pg_catalog.regtype, "
12861 "amprocrighttype::pg_catalog.regtype "
12862 "FROM pg_catalog.pg_amproc ap, 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_amproc'::pg_catalog.regclass "
12866 "AND objid = ap.oid "
12867 "ORDER BY amprocnum",
12868 opcinfo->dobj.catId.oid);
12872 appendPQExpBuffer(query, "SELECT amprocnum, "
12873 "amproc::pg_catalog.regprocedure, "
12874 "'' AS amproclefttype, "
12875 "'' AS amprocrighttype "
12876 "FROM pg_catalog.pg_amproc "
12877 "WHERE amopclaid = '%u'::pg_catalog.oid "
12878 "ORDER BY amprocnum",
12879 opcinfo->dobj.catId.oid);
12882 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12884 ntups = PQntuples(res);
12886 i_amprocnum = PQfnumber(res, "amprocnum");
12887 i_amproc = PQfnumber(res, "amproc");
12888 i_amproclefttype = PQfnumber(res, "amproclefttype");
12889 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12891 for (i = 0; i < ntups; i++)
12893 amprocnum = PQgetvalue(res, i, i_amprocnum);
12894 amproc = PQgetvalue(res, i, i_amproc);
12895 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12896 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12899 appendPQExpBufferStr(q, " ,\n ");
12901 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12903 if (*amproclefttype && *amprocrighttype)
12904 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12906 appendPQExpBuffer(q, " %s", amproc);
12914 * If needComma is still false it means we haven't added anything after
12915 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
12916 * clause with the same datatype. This isn't sanctioned by the
12917 * documentation, but actually DefineOpClass will treat it as a no-op.
12920 appendPQExpBuffer(q, "STORAGE %s", opcintype);
12922 appendPQExpBufferStr(q, ";\n");
12924 appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
12925 appendPQExpBuffer(nameusing, " USING %s",
12928 if (dopt->binary_upgrade)
12929 binary_upgrade_extension_member(q, &opcinfo->dobj,
12930 "OPERATOR CLASS", nameusing->data,
12931 opcinfo->dobj.namespace->dobj.name);
12933 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12934 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
12935 opcinfo->dobj.name,
12936 opcinfo->dobj.namespace->dobj.name,
12939 "OPERATOR CLASS", SECTION_PRE_DATA,
12940 q->data, delq->data, NULL,
12944 /* Dump Operator Class Comments */
12945 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12946 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
12947 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
12948 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
12953 destroyPQExpBuffer(query);
12954 destroyPQExpBuffer(q);
12955 destroyPQExpBuffer(delq);
12956 destroyPQExpBuffer(nameusing);
12961 * write out a single operator family definition
12963 * Note: this also dumps any "loose" operator members that aren't bound to a
12964 * specific opclass within the opfamily.
12967 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
12969 DumpOptions *dopt = fout->dopt;
12973 PQExpBuffer nameusing;
12976 PGresult *res_procs;
12979 int i_amopstrategy;
12980 int i_amopreqcheck;
12983 int i_sortfamilynsp;
12986 int i_amproclefttype;
12987 int i_amprocrighttype;
12989 char *amopstrategy;
12990 char *amopreqcheck;
12993 char *sortfamilynsp;
12996 char *amproclefttype;
12997 char *amprocrighttype;
13001 /* Skip if not to be dumped */
13002 if (!opfinfo->dobj.dump || dopt->dataOnly)
13005 query = createPQExpBuffer();
13006 q = createPQExpBuffer();
13007 delq = createPQExpBuffer();
13008 nameusing = createPQExpBuffer();
13011 * Fetch only those opfamily members that are tied directly to the
13012 * opfamily by pg_depend entries.
13014 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13015 * older server's opclass in which it is used. This is to avoid
13016 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13017 * older server and then reload into that old version. This can go away
13018 * once 8.3 is so old as to not be of interest to anyone.
13020 if (fout->remoteVersion >= 90100)
13022 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13023 "amopopr::pg_catalog.regoperator, "
13024 "opfname AS sortfamily, "
13025 "nspname AS sortfamilynsp "
13026 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13027 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13028 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13029 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13030 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13031 "AND refobjid = '%u'::pg_catalog.oid "
13032 "AND amopfamily = '%u'::pg_catalog.oid "
13033 "ORDER BY amopstrategy",
13034 opfinfo->dobj.catId.oid,
13035 opfinfo->dobj.catId.oid);
13037 else if (fout->remoteVersion >= 80400)
13039 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13040 "amopopr::pg_catalog.regoperator, "
13041 "NULL AS sortfamily, "
13042 "NULL AS sortfamilynsp "
13043 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13044 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13045 "AND refobjid = '%u'::pg_catalog.oid "
13046 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13047 "AND objid = ao.oid "
13048 "ORDER BY amopstrategy",
13049 opfinfo->dobj.catId.oid);
13053 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13054 "amopopr::pg_catalog.regoperator, "
13055 "NULL AS sortfamily, "
13056 "NULL AS sortfamilynsp "
13057 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13058 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13059 "AND refobjid = '%u'::pg_catalog.oid "
13060 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13061 "AND objid = ao.oid "
13062 "ORDER BY amopstrategy",
13063 opfinfo->dobj.catId.oid);
13066 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13068 resetPQExpBuffer(query);
13070 appendPQExpBuffer(query, "SELECT amprocnum, "
13071 "amproc::pg_catalog.regprocedure, "
13072 "amproclefttype::pg_catalog.regtype, "
13073 "amprocrighttype::pg_catalog.regtype "
13074 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13075 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13076 "AND refobjid = '%u'::pg_catalog.oid "
13077 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13078 "AND objid = ap.oid "
13079 "ORDER BY amprocnum",
13080 opfinfo->dobj.catId.oid);
13082 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13084 /* Get additional fields from the pg_opfamily row */
13085 resetPQExpBuffer(query);
13087 appendPQExpBuffer(query, "SELECT "
13088 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13089 "FROM pg_catalog.pg_opfamily "
13090 "WHERE oid = '%u'::pg_catalog.oid",
13091 opfinfo->dobj.catId.oid);
13093 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13095 i_amname = PQfnumber(res, "amname");
13097 /* amname will still be needed after we PQclear res */
13098 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13100 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13101 fmtQualifiedDumpable(opfinfo));
13102 appendPQExpBuffer(delq, " USING %s;\n",
13105 /* Build the fixed portion of the CREATE command */
13106 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13107 fmtQualifiedDumpable(opfinfo));
13108 appendPQExpBuffer(q, " USING %s;\n",
13113 /* Do we need an ALTER to add loose members? */
13114 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13116 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13117 fmtQualifiedDumpable(opfinfo));
13118 appendPQExpBuffer(q, " USING %s ADD\n ",
13124 * Now fetch and print the OPERATOR entries (pg_amop rows).
13126 ntups = PQntuples(res_ops);
13128 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13129 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13130 i_amopopr = PQfnumber(res_ops, "amopopr");
13131 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13132 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13134 for (i = 0; i < ntups; i++)
13136 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13137 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13138 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13139 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13140 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13143 appendPQExpBufferStr(q, " ,\n ");
13145 appendPQExpBuffer(q, "OPERATOR %s %s",
13146 amopstrategy, amopopr);
13148 if (strlen(sortfamily) > 0)
13150 appendPQExpBufferStr(q, " FOR ORDER BY ");
13151 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13152 appendPQExpBufferStr(q, fmtId(sortfamily));
13155 if (strcmp(amopreqcheck, "t") == 0)
13156 appendPQExpBufferStr(q, " RECHECK");
13162 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13164 ntups = PQntuples(res_procs);
13166 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13167 i_amproc = PQfnumber(res_procs, "amproc");
13168 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13169 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13171 for (i = 0; i < ntups; i++)
13173 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13174 amproc = PQgetvalue(res_procs, i, i_amproc);
13175 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13176 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13179 appendPQExpBufferStr(q, " ,\n ");
13181 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13182 amprocnum, amproclefttype, amprocrighttype,
13188 appendPQExpBufferStr(q, ";\n");
13191 appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13192 appendPQExpBuffer(nameusing, " USING %s",
13195 if (dopt->binary_upgrade)
13196 binary_upgrade_extension_member(q, &opfinfo->dobj,
13197 "OPERATOR FAMILY", nameusing->data,
13198 opfinfo->dobj.namespace->dobj.name);
13200 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13201 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13202 opfinfo->dobj.name,
13203 opfinfo->dobj.namespace->dobj.name,
13206 "OPERATOR FAMILY", SECTION_PRE_DATA,
13207 q->data, delq->data, NULL,
13211 /* Dump Operator Family Comments */
13212 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13213 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13214 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13215 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13219 PQclear(res_procs);
13220 destroyPQExpBuffer(query);
13221 destroyPQExpBuffer(q);
13222 destroyPQExpBuffer(delq);
13223 destroyPQExpBuffer(nameusing);
13228 * write out a single collation definition
13231 dumpCollation(Archive *fout, CollInfo *collinfo)
13233 DumpOptions *dopt = fout->dopt;
13239 int i_collprovider;
13242 const char *collprovider;
13243 const char *collcollate;
13244 const char *collctype;
13246 /* Skip if not to be dumped */
13247 if (!collinfo->dobj.dump || dopt->dataOnly)
13250 query = createPQExpBuffer();
13251 q = createPQExpBuffer();
13252 delq = createPQExpBuffer();
13254 qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13256 /* Get collation-specific details */
13257 if (fout->remoteVersion >= 100000)
13258 appendPQExpBuffer(query, "SELECT "
13263 "FROM pg_catalog.pg_collation c "
13264 "WHERE c.oid = '%u'::pg_catalog.oid",
13265 collinfo->dobj.catId.oid);
13267 appendPQExpBuffer(query, "SELECT "
13268 "'c' AS collprovider, "
13271 "NULL AS collversion "
13272 "FROM pg_catalog.pg_collation c "
13273 "WHERE c.oid = '%u'::pg_catalog.oid",
13274 collinfo->dobj.catId.oid);
13276 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13278 i_collprovider = PQfnumber(res, "collprovider");
13279 i_collcollate = PQfnumber(res, "collcollate");
13280 i_collctype = PQfnumber(res, "collctype");
13282 collprovider = PQgetvalue(res, 0, i_collprovider);
13283 collcollate = PQgetvalue(res, 0, i_collcollate);
13284 collctype = PQgetvalue(res, 0, i_collctype);
13286 appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13287 fmtQualifiedDumpable(collinfo));
13289 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13290 fmtQualifiedDumpable(collinfo));
13292 appendPQExpBufferStr(q, "provider = ");
13293 if (collprovider[0] == 'c')
13294 appendPQExpBufferStr(q, "libc");
13295 else if (collprovider[0] == 'i')
13296 appendPQExpBufferStr(q, "icu");
13297 else if (collprovider[0] == 'd')
13298 /* to allow dumping pg_catalog; not accepted on input */
13299 appendPQExpBufferStr(q, "default");
13301 exit_horribly(NULL,
13302 "unrecognized collation provider: %s\n",
13305 if (strcmp(collcollate, collctype) == 0)
13307 appendPQExpBufferStr(q, ", locale = ");
13308 appendStringLiteralAH(q, collcollate, fout);
13312 appendPQExpBufferStr(q, ", lc_collate = ");
13313 appendStringLiteralAH(q, collcollate, fout);
13314 appendPQExpBufferStr(q, ", lc_ctype = ");
13315 appendStringLiteralAH(q, collctype, fout);
13319 * For binary upgrade, carry over the collation version. For normal
13320 * dump/restore, omit the version, so that it is computed upon restore.
13322 if (dopt->binary_upgrade)
13326 i_collversion = PQfnumber(res, "collversion");
13327 if (!PQgetisnull(res, 0, i_collversion))
13329 appendPQExpBufferStr(q, ", version = ");
13330 appendStringLiteralAH(q,
13331 PQgetvalue(res, 0, i_collversion),
13336 appendPQExpBufferStr(q, ");\n");
13338 if (dopt->binary_upgrade)
13339 binary_upgrade_extension_member(q, &collinfo->dobj,
13340 "COLLATION", qcollname,
13341 collinfo->dobj.namespace->dobj.name);
13343 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13344 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13345 collinfo->dobj.name,
13346 collinfo->dobj.namespace->dobj.name,
13349 "COLLATION", SECTION_PRE_DATA,
13350 q->data, delq->data, NULL,
13354 /* Dump Collation Comments */
13355 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13356 dumpComment(fout, "COLLATION", qcollname,
13357 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13358 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13362 destroyPQExpBuffer(query);
13363 destroyPQExpBuffer(q);
13364 destroyPQExpBuffer(delq);
13370 * write out a single conversion definition
13373 dumpConversion(Archive *fout, ConvInfo *convinfo)
13375 DumpOptions *dopt = fout->dopt;
13381 int i_conforencoding;
13382 int i_contoencoding;
13385 const char *conforencoding;
13386 const char *contoencoding;
13387 const char *conproc;
13390 /* Skip if not to be dumped */
13391 if (!convinfo->dobj.dump || dopt->dataOnly)
13394 query = createPQExpBuffer();
13395 q = createPQExpBuffer();
13396 delq = createPQExpBuffer();
13398 qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13400 /* Get conversion-specific details */
13401 appendPQExpBuffer(query, "SELECT "
13402 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13403 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13404 "conproc, condefault "
13405 "FROM pg_catalog.pg_conversion c "
13406 "WHERE c.oid = '%u'::pg_catalog.oid",
13407 convinfo->dobj.catId.oid);
13409 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13411 i_conforencoding = PQfnumber(res, "conforencoding");
13412 i_contoencoding = PQfnumber(res, "contoencoding");
13413 i_conproc = PQfnumber(res, "conproc");
13414 i_condefault = PQfnumber(res, "condefault");
13416 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13417 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13418 conproc = PQgetvalue(res, 0, i_conproc);
13419 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13421 appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13422 fmtQualifiedDumpable(convinfo));
13424 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13425 (condefault) ? "DEFAULT " : "",
13426 fmtQualifiedDumpable(convinfo));
13427 appendStringLiteralAH(q, conforencoding, fout);
13428 appendPQExpBufferStr(q, " TO ");
13429 appendStringLiteralAH(q, contoencoding, fout);
13430 /* regproc output is already sufficiently quoted */
13431 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13433 if (dopt->binary_upgrade)
13434 binary_upgrade_extension_member(q, &convinfo->dobj,
13435 "CONVERSION", qconvname,
13436 convinfo->dobj.namespace->dobj.name);
13438 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13439 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13440 convinfo->dobj.name,
13441 convinfo->dobj.namespace->dobj.name,
13444 "CONVERSION", SECTION_PRE_DATA,
13445 q->data, delq->data, NULL,
13449 /* Dump Conversion Comments */
13450 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13451 dumpComment(fout, "CONVERSION", qconvname,
13452 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13453 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13457 destroyPQExpBuffer(query);
13458 destroyPQExpBuffer(q);
13459 destroyPQExpBuffer(delq);
13464 * format_aggregate_signature: generate aggregate name and argument list
13466 * The argument type names are qualified if needed. The aggregate name
13467 * is never qualified.
13470 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13472 PQExpBufferData buf;
13475 initPQExpBuffer(&buf);
13477 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13479 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13481 if (agginfo->aggfn.nargs == 0)
13482 appendPQExpBuffer(&buf, "(*)");
13485 appendPQExpBufferChar(&buf, '(');
13486 for (j = 0; j < agginfo->aggfn.nargs; j++)
13490 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13493 appendPQExpBuffer(&buf, "%s%s",
13494 (j > 0) ? ", " : "",
13498 appendPQExpBufferChar(&buf, ')');
13505 * write out a single aggregate definition
13508 dumpAgg(Archive *fout, AggInfo *agginfo)
13510 DumpOptions *dopt = fout->dopt;
13514 PQExpBuffer details;
13515 char *aggsig; /* identity signature */
13516 char *aggfullsig = NULL; /* full signature */
13521 int i_aggcombinefn;
13523 int i_aggdeserialfn;
13525 int i_aggminvtransfn;
13527 int i_aggfinalextra;
13528 int i_aggmfinalextra;
13529 int i_aggfinalmodify;
13530 int i_aggmfinalmodify;
13533 int i_aggtranstype;
13534 int i_aggtransspace;
13535 int i_aggmtranstype;
13536 int i_aggmtransspace;
13541 const char *aggtransfn;
13542 const char *aggfinalfn;
13543 const char *aggcombinefn;
13544 const char *aggserialfn;
13545 const char *aggdeserialfn;
13546 const char *aggmtransfn;
13547 const char *aggminvtransfn;
13548 const char *aggmfinalfn;
13549 bool aggfinalextra;
13550 bool aggmfinalextra;
13551 char aggfinalmodify;
13552 char aggmfinalmodify;
13553 const char *aggsortop;
13554 char *aggsortconvop;
13556 const char *aggtranstype;
13557 const char *aggtransspace;
13558 const char *aggmtranstype;
13559 const char *aggmtransspace;
13560 const char *agginitval;
13561 const char *aggminitval;
13563 const char *proparallel;
13564 char defaultfinalmodify;
13566 /* Skip if not to be dumped */
13567 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13570 query = createPQExpBuffer();
13571 q = createPQExpBuffer();
13572 delq = createPQExpBuffer();
13573 details = createPQExpBuffer();
13575 /* Get aggregate-specific details */
13576 if (fout->remoteVersion >= 110000)
13578 appendPQExpBuffer(query, "SELECT aggtransfn, "
13579 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13580 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13581 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13582 "aggfinalextra, aggmfinalextra, "
13583 "aggfinalmodify, aggmfinalmodify, "
13586 "aggtransspace, agginitval, "
13587 "aggmtransspace, aggminitval, "
13588 "true AS convertok, "
13589 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13590 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13592 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13593 "WHERE a.aggfnoid = p.oid "
13594 "AND p.oid = '%u'::pg_catalog.oid",
13595 agginfo->aggfn.dobj.catId.oid);
13597 else if (fout->remoteVersion >= 90600)
13599 appendPQExpBuffer(query, "SELECT aggtransfn, "
13600 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13601 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13602 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13603 "aggfinalextra, aggmfinalextra, "
13604 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13607 "aggtransspace, agginitval, "
13608 "aggmtransspace, aggminitval, "
13609 "true AS convertok, "
13610 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13611 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13613 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13614 "WHERE a.aggfnoid = p.oid "
13615 "AND p.oid = '%u'::pg_catalog.oid",
13616 agginfo->aggfn.dobj.catId.oid);
13618 else if (fout->remoteVersion >= 90400)
13620 appendPQExpBuffer(query, "SELECT aggtransfn, "
13621 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13622 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13623 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13624 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13625 "aggfinalextra, aggmfinalextra, "
13626 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13629 "aggtransspace, agginitval, "
13630 "aggmtransspace, aggminitval, "
13631 "true AS convertok, "
13632 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13633 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13634 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13635 "WHERE a.aggfnoid = p.oid "
13636 "AND p.oid = '%u'::pg_catalog.oid",
13637 agginfo->aggfn.dobj.catId.oid);
13639 else if (fout->remoteVersion >= 80400)
13641 appendPQExpBuffer(query, "SELECT aggtransfn, "
13642 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13643 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13644 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13645 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13646 "0 AS aggmtranstype, false AS aggfinalextra, "
13647 "false AS aggmfinalextra, "
13648 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13651 "0 AS aggtransspace, agginitval, "
13652 "0 AS aggmtransspace, NULL AS aggminitval, "
13653 "true AS convertok, "
13654 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13655 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13656 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13657 "WHERE a.aggfnoid = p.oid "
13658 "AND p.oid = '%u'::pg_catalog.oid",
13659 agginfo->aggfn.dobj.catId.oid);
13661 else if (fout->remoteVersion >= 80100)
13663 appendPQExpBuffer(query, "SELECT aggtransfn, "
13664 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13665 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13666 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13667 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13668 "0 AS aggmtranstype, false AS aggfinalextra, "
13669 "false AS aggmfinalextra, "
13670 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13673 "0 AS aggtransspace, agginitval, "
13674 "0 AS aggmtransspace, NULL AS aggminitval, "
13675 "true AS convertok "
13676 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13677 "WHERE a.aggfnoid = p.oid "
13678 "AND p.oid = '%u'::pg_catalog.oid",
13679 agginfo->aggfn.dobj.catId.oid);
13683 appendPQExpBuffer(query, "SELECT aggtransfn, "
13684 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13685 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13686 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13687 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13688 "0 AS aggmtranstype, false AS aggfinalextra, "
13689 "false AS aggmfinalextra, "
13690 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13693 "0 AS aggtransspace, agginitval, "
13694 "0 AS aggmtransspace, NULL AS aggminitval, "
13695 "true AS convertok "
13696 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13697 "WHERE a.aggfnoid = p.oid "
13698 "AND p.oid = '%u'::pg_catalog.oid",
13699 agginfo->aggfn.dobj.catId.oid);
13702 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13704 i_aggtransfn = PQfnumber(res, "aggtransfn");
13705 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13706 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13707 i_aggserialfn = PQfnumber(res, "aggserialfn");
13708 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13709 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13710 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13711 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13712 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13713 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13714 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13715 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13716 i_aggsortop = PQfnumber(res, "aggsortop");
13717 i_aggkind = PQfnumber(res, "aggkind");
13718 i_aggtranstype = PQfnumber(res, "aggtranstype");
13719 i_aggtransspace = PQfnumber(res, "aggtransspace");
13720 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13721 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13722 i_agginitval = PQfnumber(res, "agginitval");
13723 i_aggminitval = PQfnumber(res, "aggminitval");
13724 i_convertok = PQfnumber(res, "convertok");
13725 i_proparallel = PQfnumber(res, "proparallel");
13727 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13728 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13729 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13730 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13731 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13732 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13733 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13734 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13735 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13736 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13737 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13738 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13739 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13740 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13741 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13742 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13743 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13744 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13745 agginitval = PQgetvalue(res, 0, i_agginitval);
13746 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13747 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13749 if (fout->remoteVersion >= 80400)
13751 /* 8.4 or later; we rely on server-side code for most of the work */
13755 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13756 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13757 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13758 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13761 /* pre-8.4, do it ourselves */
13762 aggsig = format_aggregate_signature(agginfo, fout, true);
13764 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13766 if (i_proparallel != -1)
13767 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13769 proparallel = NULL;
13773 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13784 /* identify default modify flag for aggkind (must match DefineAggregate) */
13785 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13786 /* replace omitted flags for old versions */
13787 if (aggfinalmodify == '0')
13788 aggfinalmodify = defaultfinalmodify;
13789 if (aggmfinalmodify == '0')
13790 aggmfinalmodify = defaultfinalmodify;
13792 /* regproc and regtype output is already sufficiently quoted */
13793 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13794 aggtransfn, aggtranstype);
13796 if (strcmp(aggtransspace, "0") != 0)
13798 appendPQExpBuffer(details, ",\n SSPACE = %s",
13802 if (!PQgetisnull(res, 0, i_agginitval))
13804 appendPQExpBufferStr(details, ",\n INITCOND = ");
13805 appendStringLiteralAH(details, agginitval, fout);
13808 if (strcmp(aggfinalfn, "-") != 0)
13810 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13813 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13814 if (aggfinalmodify != defaultfinalmodify)
13816 switch (aggfinalmodify)
13818 case AGGMODIFY_READ_ONLY:
13819 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
13821 case AGGMODIFY_SHAREABLE:
13822 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
13824 case AGGMODIFY_READ_WRITE:
13825 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
13828 exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13829 agginfo->aggfn.dobj.name);
13835 if (strcmp(aggcombinefn, "-") != 0)
13836 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
13838 if (strcmp(aggserialfn, "-") != 0)
13839 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
13841 if (strcmp(aggdeserialfn, "-") != 0)
13842 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
13844 if (strcmp(aggmtransfn, "-") != 0)
13846 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
13852 if (strcmp(aggmtransspace, "0") != 0)
13854 appendPQExpBuffer(details, ",\n MSSPACE = %s",
13858 if (!PQgetisnull(res, 0, i_aggminitval))
13860 appendPQExpBufferStr(details, ",\n MINITCOND = ");
13861 appendStringLiteralAH(details, aggminitval, fout);
13864 if (strcmp(aggmfinalfn, "-") != 0)
13866 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
13868 if (aggmfinalextra)
13869 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
13870 if (aggmfinalmodify != defaultfinalmodify)
13872 switch (aggmfinalmodify)
13874 case AGGMODIFY_READ_ONLY:
13875 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
13877 case AGGMODIFY_SHAREABLE:
13878 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
13880 case AGGMODIFY_READ_WRITE:
13881 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
13884 exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13885 agginfo->aggfn.dobj.name);
13891 aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13894 appendPQExpBuffer(details, ",\n SORTOP = %s",
13896 free(aggsortconvop);
13899 if (aggkind == AGGKIND_HYPOTHETICAL)
13900 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
13902 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13904 if (proparallel[0] == PROPARALLEL_SAFE)
13905 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
13906 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13907 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
13908 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13909 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13910 agginfo->aggfn.dobj.name);
13913 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13914 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13917 appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
13918 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13919 aggfullsig ? aggfullsig : aggsig, details->data);
13921 if (dopt->binary_upgrade)
13922 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
13923 "AGGREGATE", aggsig,
13924 agginfo->aggfn.dobj.namespace->dobj.name);
13926 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
13927 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
13928 agginfo->aggfn.dobj.dumpId,
13930 agginfo->aggfn.dobj.namespace->dobj.name,
13932 agginfo->aggfn.rolname,
13933 "AGGREGATE", SECTION_PRE_DATA,
13934 q->data, delq->data, NULL,
13938 /* Dump Aggregate Comments */
13939 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
13940 dumpComment(fout, "AGGREGATE", aggsig,
13941 agginfo->aggfn.dobj.namespace->dobj.name,
13942 agginfo->aggfn.rolname,
13943 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13945 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
13946 dumpSecLabel(fout, "AGGREGATE", aggsig,
13947 agginfo->aggfn.dobj.namespace->dobj.name,
13948 agginfo->aggfn.rolname,
13949 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13952 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
13953 * command look like a function's GRANT; in particular this affects the
13954 * syntax for zero-argument aggregates and ordered-set aggregates.
13958 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
13960 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
13961 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
13962 "FUNCTION", aggsig, NULL,
13963 agginfo->aggfn.dobj.namespace->dobj.name,
13964 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
13965 agginfo->aggfn.rproacl,
13966 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
13975 destroyPQExpBuffer(query);
13976 destroyPQExpBuffer(q);
13977 destroyPQExpBuffer(delq);
13978 destroyPQExpBuffer(details);
13983 * write out a single text search parser
13986 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
13988 DumpOptions *dopt = fout->dopt;
13993 /* Skip if not to be dumped */
13994 if (!prsinfo->dobj.dump || dopt->dataOnly)
13997 q = createPQExpBuffer();
13998 delq = createPQExpBuffer();
14000 qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14002 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14003 fmtQualifiedDumpable(prsinfo));
14005 appendPQExpBuffer(q, " START = %s,\n",
14006 convertTSFunction(fout, prsinfo->prsstart));
14007 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14008 convertTSFunction(fout, prsinfo->prstoken));
14009 appendPQExpBuffer(q, " END = %s,\n",
14010 convertTSFunction(fout, prsinfo->prsend));
14011 if (prsinfo->prsheadline != InvalidOid)
14012 appendPQExpBuffer(q, " HEADLINE = %s,\n",
14013 convertTSFunction(fout, prsinfo->prsheadline));
14014 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14015 convertTSFunction(fout, prsinfo->prslextype));
14017 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14018 fmtQualifiedDumpable(prsinfo));
14020 if (dopt->binary_upgrade)
14021 binary_upgrade_extension_member(q, &prsinfo->dobj,
14022 "TEXT SEARCH PARSER", qprsname,
14023 prsinfo->dobj.namespace->dobj.name);
14025 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14026 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14027 prsinfo->dobj.name,
14028 prsinfo->dobj.namespace->dobj.name,
14031 "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14032 q->data, delq->data, NULL,
14036 /* Dump Parser Comments */
14037 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14038 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14039 prsinfo->dobj.namespace->dobj.name, "",
14040 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14042 destroyPQExpBuffer(q);
14043 destroyPQExpBuffer(delq);
14049 * write out a single text search dictionary
14052 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14054 DumpOptions *dopt = fout->dopt;
14063 /* Skip if not to be dumped */
14064 if (!dictinfo->dobj.dump || dopt->dataOnly)
14067 q = createPQExpBuffer();
14068 delq = createPQExpBuffer();
14069 query = createPQExpBuffer();
14071 qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14073 /* Fetch name and namespace of the dictionary's template */
14074 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14075 "FROM pg_ts_template p, pg_namespace n "
14076 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14077 dictinfo->dicttemplate);
14078 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14079 nspname = PQgetvalue(res, 0, 0);
14080 tmplname = PQgetvalue(res, 0, 1);
14082 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14083 fmtQualifiedDumpable(dictinfo));
14085 appendPQExpBufferStr(q, " TEMPLATE = ");
14086 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14087 appendPQExpBufferStr(q, fmtId(tmplname));
14091 /* the dictinitoption can be dumped straight into the command */
14092 if (dictinfo->dictinitoption)
14093 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14095 appendPQExpBufferStr(q, " );\n");
14097 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14098 fmtQualifiedDumpable(dictinfo));
14100 if (dopt->binary_upgrade)
14101 binary_upgrade_extension_member(q, &dictinfo->dobj,
14102 "TEXT SEARCH DICTIONARY", qdictname,
14103 dictinfo->dobj.namespace->dobj.name);
14105 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14106 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14107 dictinfo->dobj.name,
14108 dictinfo->dobj.namespace->dobj.name,
14111 "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14112 q->data, delq->data, NULL,
14116 /* Dump Dictionary Comments */
14117 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14118 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14119 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14120 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14122 destroyPQExpBuffer(q);
14123 destroyPQExpBuffer(delq);
14124 destroyPQExpBuffer(query);
14130 * write out a single text search template
14133 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14135 DumpOptions *dopt = fout->dopt;
14140 /* Skip if not to be dumped */
14141 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14144 q = createPQExpBuffer();
14145 delq = createPQExpBuffer();
14147 qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14149 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14150 fmtQualifiedDumpable(tmplinfo));
14152 if (tmplinfo->tmplinit != InvalidOid)
14153 appendPQExpBuffer(q, " INIT = %s,\n",
14154 convertTSFunction(fout, tmplinfo->tmplinit));
14155 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14156 convertTSFunction(fout, tmplinfo->tmpllexize));
14158 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14159 fmtQualifiedDumpable(tmplinfo));
14161 if (dopt->binary_upgrade)
14162 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14163 "TEXT SEARCH TEMPLATE", qtmplname,
14164 tmplinfo->dobj.namespace->dobj.name);
14166 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14167 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14168 tmplinfo->dobj.name,
14169 tmplinfo->dobj.namespace->dobj.name,
14172 "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14173 q->data, delq->data, NULL,
14177 /* Dump Template Comments */
14178 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14179 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14180 tmplinfo->dobj.namespace->dobj.name, "",
14181 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14183 destroyPQExpBuffer(q);
14184 destroyPQExpBuffer(delq);
14190 * write out a single text search configuration
14193 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14195 DumpOptions *dopt = fout->dopt;
14208 /* Skip if not to be dumped */
14209 if (!cfginfo->dobj.dump || dopt->dataOnly)
14212 q = createPQExpBuffer();
14213 delq = createPQExpBuffer();
14214 query = createPQExpBuffer();
14216 qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14218 /* Fetch name and namespace of the config's parser */
14219 appendPQExpBuffer(query, "SELECT nspname, prsname "
14220 "FROM pg_ts_parser p, pg_namespace n "
14221 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14222 cfginfo->cfgparser);
14223 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14224 nspname = PQgetvalue(res, 0, 0);
14225 prsname = PQgetvalue(res, 0, 1);
14227 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14228 fmtQualifiedDumpable(cfginfo));
14230 appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14231 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14235 resetPQExpBuffer(query);
14236 appendPQExpBuffer(query,
14238 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14239 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14240 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14241 "FROM pg_catalog.pg_ts_config_map AS m\n"
14242 "WHERE m.mapcfg = '%u'\n"
14243 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14244 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14246 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14247 ntups = PQntuples(res);
14249 i_tokenname = PQfnumber(res, "tokenname");
14250 i_dictname = PQfnumber(res, "dictname");
14252 for (i = 0; i < ntups; i++)
14254 char *tokenname = PQgetvalue(res, i, i_tokenname);
14255 char *dictname = PQgetvalue(res, i, i_dictname);
14258 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14260 /* starting a new token type, so start a new command */
14262 appendPQExpBufferStr(q, ";\n");
14263 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14264 fmtQualifiedDumpable(cfginfo));
14265 /* tokenname needs quoting, dictname does NOT */
14266 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14267 fmtId(tokenname), dictname);
14270 appendPQExpBuffer(q, ", %s", dictname);
14274 appendPQExpBufferStr(q, ";\n");
14278 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14279 fmtQualifiedDumpable(cfginfo));
14281 if (dopt->binary_upgrade)
14282 binary_upgrade_extension_member(q, &cfginfo->dobj,
14283 "TEXT SEARCH CONFIGURATION", qcfgname,
14284 cfginfo->dobj.namespace->dobj.name);
14286 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14287 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14288 cfginfo->dobj.name,
14289 cfginfo->dobj.namespace->dobj.name,
14292 "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14293 q->data, delq->data, NULL,
14297 /* Dump Configuration Comments */
14298 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14299 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14300 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14301 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14303 destroyPQExpBuffer(q);
14304 destroyPQExpBuffer(delq);
14305 destroyPQExpBuffer(query);
14310 * dumpForeignDataWrapper
14311 * write out a single foreign-data wrapper definition
14314 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14316 DumpOptions *dopt = fout->dopt;
14321 /* Skip if not to be dumped */
14322 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14325 q = createPQExpBuffer();
14326 delq = createPQExpBuffer();
14328 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14330 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14333 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14334 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14336 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14337 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14339 if (strlen(fdwinfo->fdwoptions) > 0)
14340 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14342 appendPQExpBufferStr(q, ";\n");
14344 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14347 if (dopt->binary_upgrade)
14348 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14349 "FOREIGN DATA WRAPPER", qfdwname,
14352 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14353 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14354 fdwinfo->dobj.name,
14358 "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14359 q->data, delq->data, NULL,
14363 /* Dump Foreign Data Wrapper Comments */
14364 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14365 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14366 NULL, fdwinfo->rolname,
14367 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14369 /* Handle the ACL */
14370 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14371 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14372 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14373 NULL, fdwinfo->rolname,
14374 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14375 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14379 destroyPQExpBuffer(q);
14380 destroyPQExpBuffer(delq);
14384 * dumpForeignServer
14385 * write out a foreign server definition
14388 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14390 DumpOptions *dopt = fout->dopt;
14398 /* Skip if not to be dumped */
14399 if (!srvinfo->dobj.dump || dopt->dataOnly)
14402 q = createPQExpBuffer();
14403 delq = createPQExpBuffer();
14404 query = createPQExpBuffer();
14406 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14408 /* look up the foreign-data wrapper */
14409 appendPQExpBuffer(query, "SELECT fdwname "
14410 "FROM pg_foreign_data_wrapper w "
14411 "WHERE w.oid = '%u'",
14413 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14414 fdwname = PQgetvalue(res, 0, 0);
14416 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14417 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14419 appendPQExpBufferStr(q, " TYPE ");
14420 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14422 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14424 appendPQExpBufferStr(q, " VERSION ");
14425 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14428 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14429 appendPQExpBufferStr(q, fmtId(fdwname));
14431 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14432 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14434 appendPQExpBufferStr(q, ";\n");
14436 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14439 if (dopt->binary_upgrade)
14440 binary_upgrade_extension_member(q, &srvinfo->dobj,
14441 "SERVER", qsrvname, NULL);
14443 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14444 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14445 srvinfo->dobj.name,
14449 "SERVER", SECTION_PRE_DATA,
14450 q->data, delq->data, NULL,
14454 /* Dump Foreign Server Comments */
14455 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14456 dumpComment(fout, "SERVER", qsrvname,
14457 NULL, srvinfo->rolname,
14458 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14460 /* Handle the ACL */
14461 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14462 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14463 "FOREIGN SERVER", qsrvname, NULL,
14464 NULL, srvinfo->rolname,
14465 srvinfo->srvacl, srvinfo->rsrvacl,
14466 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14468 /* Dump user mappings */
14469 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14470 dumpUserMappings(fout,
14471 srvinfo->dobj.name, NULL,
14473 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14477 destroyPQExpBuffer(q);
14478 destroyPQExpBuffer(delq);
14479 destroyPQExpBuffer(query);
14485 * This routine is used to dump any user mappings associated with the
14486 * server handed to this routine. Should be called after ArchiveEntry()
14490 dumpUserMappings(Archive *fout,
14491 const char *servername, const char *namespace,
14493 CatalogId catalogId, DumpId dumpId)
14505 q = createPQExpBuffer();
14506 tag = createPQExpBuffer();
14507 delq = createPQExpBuffer();
14508 query = createPQExpBuffer();
14511 * We read from the publicly accessible view pg_user_mappings, so as not
14512 * to fail if run by a non-superuser. Note that the view will show
14513 * umoptions as null if the user hasn't got privileges for the associated
14514 * server; this means that pg_dump will dump such a mapping, but with no
14515 * OPTIONS clause. A possible alternative is to skip such mappings
14516 * altogether, but it's not clear that that's an improvement.
14518 appendPQExpBuffer(query,
14520 "array_to_string(ARRAY("
14521 "SELECT quote_ident(option_name) || ' ' || "
14522 "quote_literal(option_value) "
14523 "FROM pg_options_to_table(umoptions) "
14524 "ORDER BY option_name"
14525 "), E',\n ') AS umoptions "
14526 "FROM pg_user_mappings "
14527 "WHERE srvid = '%u' "
14528 "ORDER BY usename",
14531 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14533 ntups = PQntuples(res);
14534 i_usename = PQfnumber(res, "usename");
14535 i_umoptions = PQfnumber(res, "umoptions");
14537 for (i = 0; i < ntups; i++)
14542 usename = PQgetvalue(res, i, i_usename);
14543 umoptions = PQgetvalue(res, i, i_umoptions);
14545 resetPQExpBuffer(q);
14546 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14547 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14549 if (umoptions && strlen(umoptions) > 0)
14550 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14552 appendPQExpBufferStr(q, ";\n");
14554 resetPQExpBuffer(delq);
14555 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14556 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14558 resetPQExpBuffer(tag);
14559 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14560 usename, servername);
14562 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14567 "USER MAPPING", SECTION_PRE_DATA,
14568 q->data, delq->data, NULL,
14575 destroyPQExpBuffer(query);
14576 destroyPQExpBuffer(delq);
14577 destroyPQExpBuffer(tag);
14578 destroyPQExpBuffer(q);
14582 * Write out default privileges information
14585 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14587 DumpOptions *dopt = fout->dopt;
14592 /* Skip if not to be dumped */
14593 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14596 q = createPQExpBuffer();
14597 tag = createPQExpBuffer();
14599 switch (daclinfo->defaclobjtype)
14601 case DEFACLOBJ_RELATION:
14604 case DEFACLOBJ_SEQUENCE:
14605 type = "SEQUENCES";
14607 case DEFACLOBJ_FUNCTION:
14608 type = "FUNCTIONS";
14610 case DEFACLOBJ_TYPE:
14613 case DEFACLOBJ_NAMESPACE:
14617 /* shouldn't get here */
14618 exit_horribly(NULL,
14619 "unrecognized object type in default privileges: %d\n",
14620 (int) daclinfo->defaclobjtype);
14621 type = ""; /* keep compiler quiet */
14624 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14626 /* build the actual command(s) for this tuple */
14627 if (!buildDefaultACLCommands(type,
14628 daclinfo->dobj.namespace != NULL ?
14629 daclinfo->dobj.namespace->dobj.name : NULL,
14630 daclinfo->defaclacl,
14631 daclinfo->rdefaclacl,
14632 daclinfo->initdefaclacl,
14633 daclinfo->initrdefaclacl,
14634 daclinfo->defaclrole,
14635 fout->remoteVersion,
14637 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14638 daclinfo->defaclacl);
14640 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14641 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14643 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14645 daclinfo->defaclrole,
14646 "DEFAULT ACL", SECTION_POST_DATA,
14651 destroyPQExpBuffer(tag);
14652 destroyPQExpBuffer(q);
14656 * Write out grant/revoke information
14658 * 'objCatId' is the catalog ID of the underlying object.
14659 * 'objDumpId' is the dump ID of the underlying object.
14660 * 'type' must be one of
14661 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14662 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14663 * 'name' is the formatted name of the object. Must be quoted etc. already.
14664 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14665 * (Currently we assume that subname is only provided for table columns.)
14666 * 'nspname' is the namespace the object is in (NULL if none).
14667 * 'owner' is the owner, NULL if there is no owner (for languages).
14668 * 'acls' contains the ACL string of the object from the appropriate system
14669 * catalog field; it will be passed to buildACLCommands for building the
14670 * appropriate GRANT commands.
14671 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14672 * object; it will be passed to buildACLCommands for building the
14673 * appropriate REVOKE commands.
14674 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14675 * privileges, to be recorded into pg_init_privs
14676 * 'initracls' In binary-upgrade mode, ACL string of the object's
14677 * revoked-from-default privileges, to be recorded into pg_init_privs
14679 * NB: initacls/initracls are needed because extensions can set privileges on
14680 * an object during the extension's script file and we record those into
14681 * pg_init_privs as that object's initial privileges.
14685 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14686 const char *type, const char *name, const char *subname,
14687 const char *nspname, const char *owner,
14688 const char *acls, const char *racls,
14689 const char *initacls, const char *initracls)
14691 DumpOptions *dopt = fout->dopt;
14694 /* Do nothing if ACL dump is not enabled */
14695 if (dopt->aclsSkip)
14698 /* --data-only skips ACLs *except* BLOB ACLs */
14699 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14702 sql = createPQExpBuffer();
14705 * Check to see if this object has had any initial ACLs included for it.
14706 * If so, we are in binary upgrade mode and these are the ACLs to turn
14707 * into GRANT and REVOKE statements to set and record the initial
14708 * privileges for an extension object. Let the backend know that these
14709 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14710 * before and after.
14712 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14714 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14715 if (!buildACLCommands(name, subname, nspname, type,
14716 initacls, initracls, owner,
14717 "", fout->remoteVersion, sql))
14718 exit_horribly(NULL,
14719 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14720 initacls, initracls, name, type);
14721 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14724 if (!buildACLCommands(name, subname, nspname, type,
14725 acls, racls, owner,
14726 "", fout->remoteVersion, sql))
14727 exit_horribly(NULL,
14728 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14729 acls, racls, name, type);
14733 PQExpBuffer tag = createPQExpBuffer();
14736 appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14738 appendPQExpBuffer(tag, "%s %s", type, name);
14740 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14741 tag->data, nspname,
14743 owner ? owner : "",
14744 "ACL", SECTION_NONE,
14745 sql->data, "", NULL,
14748 destroyPQExpBuffer(tag);
14751 destroyPQExpBuffer(sql);
14757 * This routine is used to dump any security labels associated with the
14758 * object handed to this routine. The routine takes the object type
14759 * and object name (ready to print, except for schema decoration), plus
14760 * the namespace and owner of the object (for labeling the ArchiveEntry),
14761 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14762 * plus the dump ID for the object (for setting a dependency).
14763 * If a matching pg_seclabel entry is found, it is dumped.
14765 * Note: although this routine takes a dumpId for dependency purposes,
14766 * that purpose is just to mark the dependency in the emitted dump file
14767 * for possible future use by pg_restore. We do NOT use it for determining
14768 * ordering of the label in the dump file, because this routine is called
14769 * after dependency sorting occurs. This routine should be called just after
14770 * calling ArchiveEntry() for the specified object.
14773 dumpSecLabel(Archive *fout, const char *type, const char *name,
14774 const char *namespace, const char *owner,
14775 CatalogId catalogId, int subid, DumpId dumpId)
14777 DumpOptions *dopt = fout->dopt;
14778 SecLabelItem *labels;
14783 /* do nothing, if --no-security-labels is supplied */
14784 if (dopt->no_security_labels)
14787 /* Security labels are schema not data ... except blob labels are data */
14788 if (strcmp(type, "LARGE OBJECT") != 0)
14790 if (dopt->dataOnly)
14795 /* We do dump blob security labels in binary-upgrade mode */
14796 if (dopt->schemaOnly && !dopt->binary_upgrade)
14800 /* Search for security labels associated with catalogId, using table */
14801 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14803 query = createPQExpBuffer();
14805 for (i = 0; i < nlabels; i++)
14808 * Ignore label entries for which the subid doesn't match.
14810 if (labels[i].objsubid != subid)
14813 appendPQExpBuffer(query,
14814 "SECURITY LABEL FOR %s ON %s ",
14815 fmtId(labels[i].provider), type);
14816 if (namespace && *namespace)
14817 appendPQExpBuffer(query, "%s.", fmtId(namespace));
14818 appendPQExpBuffer(query, "%s IS ", name);
14819 appendStringLiteralAH(query, labels[i].label, fout);
14820 appendPQExpBufferStr(query, ";\n");
14823 if (query->len > 0)
14825 PQExpBuffer tag = createPQExpBuffer();
14827 appendPQExpBuffer(tag, "%s %s", type, name);
14828 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14829 tag->data, namespace, NULL, owner,
14830 "SECURITY LABEL", SECTION_NONE,
14831 query->data, "", NULL,
14834 destroyPQExpBuffer(tag);
14837 destroyPQExpBuffer(query);
14841 * dumpTableSecLabel
14843 * As above, but dump security label for both the specified table (or view)
14847 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14849 DumpOptions *dopt = fout->dopt;
14850 SecLabelItem *labels;
14854 PQExpBuffer target;
14856 /* do nothing, if --no-security-labels is supplied */
14857 if (dopt->no_security_labels)
14860 /* SecLabel are SCHEMA not data */
14861 if (dopt->dataOnly)
14864 /* Search for comments associated with relation, using table */
14865 nlabels = findSecLabels(fout,
14866 tbinfo->dobj.catId.tableoid,
14867 tbinfo->dobj.catId.oid,
14870 /* If security labels exist, build SECURITY LABEL statements */
14874 query = createPQExpBuffer();
14875 target = createPQExpBuffer();
14877 for (i = 0; i < nlabels; i++)
14879 const char *colname;
14880 const char *provider = labels[i].provider;
14881 const char *label = labels[i].label;
14882 int objsubid = labels[i].objsubid;
14884 resetPQExpBuffer(target);
14887 appendPQExpBuffer(target, "%s %s", reltypename,
14888 fmtQualifiedDumpable(tbinfo));
14892 colname = getAttrName(objsubid, tbinfo);
14893 /* first fmtXXX result must be consumed before calling again */
14894 appendPQExpBuffer(target, "COLUMN %s",
14895 fmtQualifiedDumpable(tbinfo));
14896 appendPQExpBuffer(target, ".%s", fmtId(colname));
14898 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14899 fmtId(provider), target->data);
14900 appendStringLiteralAH(query, label, fout);
14901 appendPQExpBufferStr(query, ";\n");
14903 if (query->len > 0)
14905 resetPQExpBuffer(target);
14906 appendPQExpBuffer(target, "%s %s", reltypename,
14907 fmtId(tbinfo->dobj.name));
14908 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14910 tbinfo->dobj.namespace->dobj.name,
14911 NULL, tbinfo->rolname,
14912 "SECURITY LABEL", SECTION_NONE,
14913 query->data, "", NULL,
14914 &(tbinfo->dobj.dumpId), 1,
14917 destroyPQExpBuffer(query);
14918 destroyPQExpBuffer(target);
14924 * Find the security label(s), if any, associated with the given object.
14925 * All the objsubid values associated with the given classoid/objoid are
14926 * found with one search.
14929 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
14931 /* static storage for table of security labels */
14932 static SecLabelItem *labels = NULL;
14933 static int nlabels = -1;
14935 SecLabelItem *middle = NULL;
14937 SecLabelItem *high;
14940 /* Get security labels if we didn't already */
14942 nlabels = collectSecLabels(fout, &labels);
14944 if (nlabels <= 0) /* no labels, so no match is possible */
14951 * Do binary search to find some item matching the object.
14954 high = &labels[nlabels - 1];
14955 while (low <= high)
14957 middle = low + (high - low) / 2;
14959 if (classoid < middle->classoid)
14961 else if (classoid > middle->classoid)
14963 else if (objoid < middle->objoid)
14965 else if (objoid > middle->objoid)
14968 break; /* found a match */
14971 if (low > high) /* no matches */
14978 * Now determine how many items match the object. The search loop
14979 * invariant still holds: only items between low and high inclusive could
14983 while (middle > low)
14985 if (classoid != middle[-1].classoid ||
14986 objoid != middle[-1].objoid)
14995 while (middle <= high)
14997 if (classoid != middle->classoid ||
14998 objoid != middle->objoid)
15010 * Construct a table of all security labels available for database objects.
15011 * It's much faster to pull them all at once.
15013 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15016 collectSecLabels(Archive *fout, SecLabelItem **items)
15027 SecLabelItem *labels;
15029 query = createPQExpBuffer();
15031 appendPQExpBufferStr(query,
15032 "SELECT label, provider, classoid, objoid, objsubid "
15033 "FROM pg_catalog.pg_seclabel "
15034 "ORDER BY classoid, objoid, objsubid");
15036 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15038 /* Construct lookup table containing OIDs in numeric form */
15039 i_label = PQfnumber(res, "label");
15040 i_provider = PQfnumber(res, "provider");
15041 i_classoid = PQfnumber(res, "classoid");
15042 i_objoid = PQfnumber(res, "objoid");
15043 i_objsubid = PQfnumber(res, "objsubid");
15045 ntups = PQntuples(res);
15047 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15049 for (i = 0; i < ntups; i++)
15051 labels[i].label = PQgetvalue(res, i, i_label);
15052 labels[i].provider = PQgetvalue(res, i, i_provider);
15053 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15054 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15055 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15058 /* Do NOT free the PGresult since we are keeping pointers into it */
15059 destroyPQExpBuffer(query);
15067 * write out to fout the declarations (not data) of a user-defined table
15070 dumpTable(Archive *fout, TableInfo *tbinfo)
15072 DumpOptions *dopt = fout->dopt;
15076 * noop if we are not dumping anything about this table, or if we are
15077 * doing a data-only dump
15079 if (!tbinfo->dobj.dump || dopt->dataOnly)
15082 if (tbinfo->relkind == RELKIND_SEQUENCE)
15083 dumpSequence(fout, tbinfo);
15085 dumpTableSchema(fout, tbinfo);
15087 /* Handle the ACL here */
15088 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15089 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15091 const char *objtype =
15092 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15094 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15095 objtype, namecopy, NULL,
15096 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15097 tbinfo->relacl, tbinfo->rrelacl,
15098 tbinfo->initrelacl, tbinfo->initrrelacl);
15102 * Handle column ACLs, if any. Note: we pull these with a separate query
15103 * rather than trying to fetch them during getTableAttrs, so that we won't
15104 * miss ACLs on system columns.
15106 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15108 PQExpBuffer query = createPQExpBuffer();
15112 if (fout->remoteVersion >= 90600)
15114 PQExpBuffer acl_subquery = createPQExpBuffer();
15115 PQExpBuffer racl_subquery = createPQExpBuffer();
15116 PQExpBuffer initacl_subquery = createPQExpBuffer();
15117 PQExpBuffer initracl_subquery = createPQExpBuffer();
15119 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15120 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15121 dopt->binary_upgrade);
15123 appendPQExpBuffer(query,
15124 "SELECT at.attname, "
15127 "%s AS initattacl, "
15128 "%s AS initrattacl "
15129 "FROM pg_catalog.pg_attribute at "
15130 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15131 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15132 "(at.attrelid = pip.objoid "
15133 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15134 "AND at.attnum = pip.objsubid) "
15135 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15136 "NOT at.attisdropped "
15138 "%s IS NOT NULL OR "
15139 "%s IS NOT NULL OR "
15140 "%s IS NOT NULL OR "
15142 "ORDER BY at.attnum",
15143 acl_subquery->data,
15144 racl_subquery->data,
15145 initacl_subquery->data,
15146 initracl_subquery->data,
15147 tbinfo->dobj.catId.oid,
15148 acl_subquery->data,
15149 racl_subquery->data,
15150 initacl_subquery->data,
15151 initracl_subquery->data);
15153 destroyPQExpBuffer(acl_subquery);
15154 destroyPQExpBuffer(racl_subquery);
15155 destroyPQExpBuffer(initacl_subquery);
15156 destroyPQExpBuffer(initracl_subquery);
15160 appendPQExpBuffer(query,
15161 "SELECT attname, attacl, NULL as rattacl, "
15162 "NULL AS initattacl, NULL AS initrattacl "
15163 "FROM pg_catalog.pg_attribute "
15164 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15165 "AND attacl IS NOT NULL "
15167 tbinfo->dobj.catId.oid);
15170 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15172 for (i = 0; i < PQntuples(res); i++)
15174 char *attname = PQgetvalue(res, i, 0);
15175 char *attacl = PQgetvalue(res, i, 1);
15176 char *rattacl = PQgetvalue(res, i, 2);
15177 char *initattacl = PQgetvalue(res, i, 3);
15178 char *initrattacl = PQgetvalue(res, i, 4);
15181 attnamecopy = pg_strdup(fmtId(attname));
15182 /* Column's GRANT type is always TABLE */
15183 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15184 "TABLE", namecopy, attnamecopy,
15185 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15186 attacl, rattacl, initattacl, initrattacl);
15190 destroyPQExpBuffer(query);
15199 * Create the AS clause for a view or materialized view. The semicolon is
15200 * stripped because a materialized view must add a WITH NO DATA clause.
15202 * This returns a new buffer which must be freed by the caller.
15205 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15207 PQExpBuffer query = createPQExpBuffer();
15208 PQExpBuffer result = createPQExpBuffer();
15212 /* Fetch the view definition */
15213 appendPQExpBuffer(query,
15214 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15215 tbinfo->dobj.catId.oid);
15217 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15219 if (PQntuples(res) != 1)
15221 if (PQntuples(res) < 1)
15222 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15223 tbinfo->dobj.name);
15225 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15226 tbinfo->dobj.name);
15229 len = PQgetlength(res, 0, 0);
15232 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15233 tbinfo->dobj.name);
15235 /* Strip off the trailing semicolon so that other things may follow. */
15236 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15237 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15240 destroyPQExpBuffer(query);
15246 * Create a dummy AS clause for a view. This is used when the real view
15247 * definition has to be postponed because of circular dependencies.
15248 * We must duplicate the view's external properties -- column names and types
15249 * (including collation) -- so that it works for subsequent references.
15251 * This returns a new buffer which must be freed by the caller.
15254 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15256 PQExpBuffer result = createPQExpBuffer();
15259 appendPQExpBufferStr(result, "SELECT");
15261 for (j = 0; j < tbinfo->numatts; j++)
15264 appendPQExpBufferChar(result, ',');
15265 appendPQExpBufferStr(result, "\n ");
15267 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15270 * Must add collation if not default for the type, because CREATE OR
15271 * REPLACE VIEW won't change it
15273 if (OidIsValid(tbinfo->attcollation[j]))
15277 coll = findCollationByOid(tbinfo->attcollation[j]);
15279 appendPQExpBuffer(result, " COLLATE %s",
15280 fmtQualifiedDumpable(coll));
15283 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15291 * write the declaration (not data) of one user-defined table or view
15294 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15296 DumpOptions *dopt = fout->dopt;
15297 PQExpBuffer q = createPQExpBuffer();
15298 PQExpBuffer delq = createPQExpBuffer();
15302 TableInfo **parents;
15303 int actual_atts; /* number of attrs in this CREATE statement */
15304 const char *reltypename;
15309 qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15310 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15313 if (tbinfo->hasoids)
15315 "WARNING: WITH OIDS is not supported anymore (table \"%s\")\n",
15318 if (dopt->binary_upgrade)
15319 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15320 tbinfo->dobj.catId.oid);
15322 /* Is it a table or a view? */
15323 if (tbinfo->relkind == RELKIND_VIEW)
15325 PQExpBuffer result;
15328 * Note: keep this code in sync with the is_view case in dumpRule()
15331 reltypename = "VIEW";
15333 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15335 if (dopt->binary_upgrade)
15336 binary_upgrade_set_pg_class_oids(fout, q,
15337 tbinfo->dobj.catId.oid, false);
15339 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15341 if (tbinfo->dummy_view)
15342 result = createDummyViewAsClause(fout, tbinfo);
15345 if (nonemptyReloptions(tbinfo->reloptions))
15347 appendPQExpBufferStr(q, " WITH (");
15348 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15349 appendPQExpBufferChar(q, ')');
15351 result = createViewAsClause(fout, tbinfo);
15353 appendPQExpBuffer(q, " AS\n%s", result->data);
15354 destroyPQExpBuffer(result);
15356 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15357 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15358 appendPQExpBufferStr(q, ";\n");
15362 char *ftoptions = NULL;
15363 char *srvname = NULL;
15365 switch (tbinfo->relkind)
15367 case RELKIND_FOREIGN_TABLE:
15369 PQExpBuffer query = createPQExpBuffer();
15374 reltypename = "FOREIGN TABLE";
15376 /* retrieve name of foreign server and generic options */
15377 appendPQExpBuffer(query,
15378 "SELECT fs.srvname, "
15379 "pg_catalog.array_to_string(ARRAY("
15380 "SELECT pg_catalog.quote_ident(option_name) || "
15381 "' ' || pg_catalog.quote_literal(option_value) "
15382 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15383 "ORDER BY option_name"
15384 "), E',\n ') AS ftoptions "
15385 "FROM pg_catalog.pg_foreign_table ft "
15386 "JOIN pg_catalog.pg_foreign_server fs "
15387 "ON (fs.oid = ft.ftserver) "
15388 "WHERE ft.ftrelid = '%u'",
15389 tbinfo->dobj.catId.oid);
15390 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15391 i_srvname = PQfnumber(res, "srvname");
15392 i_ftoptions = PQfnumber(res, "ftoptions");
15393 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15394 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15396 destroyPQExpBuffer(query);
15399 case RELKIND_MATVIEW:
15400 reltypename = "MATERIALIZED VIEW";
15403 reltypename = "TABLE";
15406 numParents = tbinfo->numParents;
15407 parents = tbinfo->parents;
15409 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15411 if (dopt->binary_upgrade)
15412 binary_upgrade_set_pg_class_oids(fout, q,
15413 tbinfo->dobj.catId.oid, false);
15415 appendPQExpBuffer(q, "CREATE %s%s %s",
15416 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15422 * Attach to type, if reloftype; except in case of a binary upgrade,
15423 * we dump the table normally and attach it to the type afterward.
15425 if (tbinfo->reloftype && !dopt->binary_upgrade)
15426 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15429 * If the table is a partition, dump it as such; except in the case of
15430 * a binary upgrade, we dump the table normally and attach it to the
15431 * parent afterward.
15433 if (tbinfo->ispartition && !dopt->binary_upgrade)
15435 TableInfo *parentRel = tbinfo->parents[0];
15438 * With partitions, unlike inheritance, there can only be one
15441 if (tbinfo->numParents != 1)
15442 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15443 tbinfo->numParents, tbinfo->dobj.name);
15445 appendPQExpBuffer(q, " PARTITION OF %s",
15446 fmtQualifiedDumpable(parentRel));
15449 if (tbinfo->relkind != RELKIND_MATVIEW)
15451 /* Dump the attributes */
15453 for (j = 0; j < tbinfo->numatts; j++)
15456 * Normally, dump if it's locally defined in this table, and
15457 * not dropped. But for binary upgrade, we'll dump all the
15458 * columns, and then fix up the dropped and nonlocal cases
15461 if (shouldPrintColumn(dopt, tbinfo, j))
15464 * Default value --- suppress if to be printed separately.
15466 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15467 !tbinfo->attrdefs[j]->separate);
15470 * Not Null constraint --- suppress if inherited, except
15471 * in binary-upgrade case where that won't work.
15473 bool has_notnull = (tbinfo->notnull[j] &&
15474 (!tbinfo->inhNotNull[j] ||
15475 dopt->binary_upgrade));
15478 * Skip column if fully defined by reloftype or the
15479 * partition parent.
15481 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15482 !has_default && !has_notnull && !dopt->binary_upgrade)
15485 /* Format properly if not first attr */
15486 if (actual_atts == 0)
15487 appendPQExpBufferStr(q, " (");
15489 appendPQExpBufferChar(q, ',');
15490 appendPQExpBufferStr(q, "\n ");
15493 /* Attribute name */
15494 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15496 if (tbinfo->attisdropped[j])
15499 * ALTER TABLE DROP COLUMN clears
15500 * pg_attribute.atttypid, so we will not have gotten a
15501 * valid type name; insert INTEGER as a stopgap. We'll
15502 * clean things up later.
15504 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15505 /* Skip all the rest, too */
15512 * In binary-upgrade mode, we always include the type. If
15513 * we aren't in binary-upgrade mode, then we skip the type
15514 * when creating a typed table ('OF type_name') or a
15515 * partition ('PARTITION OF'), since the type comes from
15516 * the parent/partitioned table.
15518 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15520 appendPQExpBuffer(q, " %s",
15521 tbinfo->atttypnames[j]);
15524 /* Add collation if not default for the type */
15525 if (OidIsValid(tbinfo->attcollation[j]))
15529 coll = findCollationByOid(tbinfo->attcollation[j]);
15531 appendPQExpBuffer(q, " COLLATE %s",
15532 fmtQualifiedDumpable(coll));
15536 appendPQExpBuffer(q, " DEFAULT %s",
15537 tbinfo->attrdefs[j]->adef_expr);
15540 appendPQExpBufferStr(q, " NOT NULL");
15545 * Add non-inherited CHECK constraints, if any.
15547 for (j = 0; j < tbinfo->ncheck; j++)
15549 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15551 if (constr->separate || !constr->conislocal)
15554 if (actual_atts == 0)
15555 appendPQExpBufferStr(q, " (\n ");
15557 appendPQExpBufferStr(q, ",\n ");
15559 appendPQExpBuffer(q, "CONSTRAINT %s ",
15560 fmtId(constr->dobj.name));
15561 appendPQExpBufferStr(q, constr->condef);
15567 appendPQExpBufferStr(q, "\n)");
15568 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15569 !dopt->binary_upgrade))
15572 * We must have a parenthesized attribute list, even though
15573 * empty, when not using the OF TYPE or PARTITION OF syntax.
15575 appendPQExpBufferStr(q, " (\n)");
15578 if (tbinfo->ispartition && !dopt->binary_upgrade)
15580 appendPQExpBufferChar(q, '\n');
15581 appendPQExpBufferStr(q, tbinfo->partbound);
15584 /* Emit the INHERITS clause, except if this is a partition. */
15585 if (numParents > 0 &&
15586 !tbinfo->ispartition &&
15587 !dopt->binary_upgrade)
15589 appendPQExpBufferStr(q, "\nINHERITS (");
15590 for (k = 0; k < numParents; k++)
15592 TableInfo *parentRel = parents[k];
15595 appendPQExpBufferStr(q, ", ");
15596 appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15598 appendPQExpBufferChar(q, ')');
15601 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15602 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15604 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15605 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15608 if (nonemptyReloptions(tbinfo->reloptions) ||
15609 nonemptyReloptions(tbinfo->toast_reloptions))
15611 bool addcomma = false;
15613 appendPQExpBufferStr(q, "\nWITH (");
15614 if (nonemptyReloptions(tbinfo->reloptions))
15617 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15619 if (nonemptyReloptions(tbinfo->toast_reloptions))
15622 appendPQExpBufferStr(q, ", ");
15623 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15626 appendPQExpBufferChar(q, ')');
15629 /* Dump generic options if any */
15630 if (ftoptions && ftoptions[0])
15631 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15634 * For materialized views, create the AS clause just like a view. At
15635 * this point, we always mark the view as not populated.
15637 if (tbinfo->relkind == RELKIND_MATVIEW)
15639 PQExpBuffer result;
15641 result = createViewAsClause(fout, tbinfo);
15642 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15644 destroyPQExpBuffer(result);
15647 appendPQExpBufferStr(q, ";\n");
15650 * in binary upgrade mode, update the catalog with any missing values
15651 * that might be present.
15653 if (dopt->binary_upgrade)
15655 for (j = 0; j < tbinfo->numatts; j++)
15657 if (tbinfo->attmissingval[j][0] != '\0')
15659 appendPQExpBufferStr(q, "\n-- set missing value.\n");
15660 appendPQExpBufferStr(q,
15661 "SELECT pg_catalog.binary_upgrade_set_missing_value(");
15662 appendStringLiteralAH(q, qualrelname, fout);
15663 appendPQExpBufferStr(q, "::pg_catalog.regclass,");
15664 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15665 appendPQExpBufferStr(q, ",");
15666 appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
15667 appendPQExpBufferStr(q, ");\n\n");
15673 * To create binary-compatible heap files, we have to ensure the same
15674 * physical column order, including dropped columns, as in the
15675 * original. Therefore, we create dropped columns above and drop them
15676 * here, also updating their attlen/attalign values so that the
15677 * dropped column can be skipped properly. (We do not bother with
15678 * restoring the original attbyval setting.) Also, inheritance
15679 * relationships are set up by doing ALTER TABLE INHERIT rather than
15680 * using an INHERITS clause --- the latter would possibly mess up the
15681 * column order. That also means we have to take care about setting
15682 * attislocal correctly, plus fix up any inherited CHECK constraints.
15683 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15685 * We process foreign and partitioned tables here, even though they
15686 * lack heap storage, because they can participate in inheritance
15687 * relationships and we want this stuff to be consistent across the
15688 * inheritance tree. We can exclude indexes, toast tables, sequences
15689 * and matviews, even though they have storage, because we don't
15690 * support altering or dropping columns in them, nor can they be part
15691 * of inheritance trees.
15693 if (dopt->binary_upgrade &&
15694 (tbinfo->relkind == RELKIND_RELATION ||
15695 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15696 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15698 for (j = 0; j < tbinfo->numatts; j++)
15700 if (tbinfo->attisdropped[j])
15702 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15703 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15704 "SET attlen = %d, "
15705 "attalign = '%c', attbyval = false\n"
15706 "WHERE attname = ",
15708 tbinfo->attalign[j]);
15709 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15710 appendPQExpBufferStr(q, "\n AND attrelid = ");
15711 appendStringLiteralAH(q, qualrelname, fout);
15712 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15714 if (tbinfo->relkind == RELKIND_RELATION ||
15715 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15716 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15719 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15721 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15722 fmtId(tbinfo->attnames[j]));
15724 else if (!tbinfo->attislocal[j])
15726 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15727 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15728 "SET attislocal = false\n"
15729 "WHERE attname = ");
15730 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15731 appendPQExpBufferStr(q, "\n AND attrelid = ");
15732 appendStringLiteralAH(q, qualrelname, fout);
15733 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15737 for (k = 0; k < tbinfo->ncheck; k++)
15739 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15741 if (constr->separate || constr->conislocal)
15744 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15745 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15747 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15748 fmtId(constr->dobj.name));
15749 appendPQExpBuffer(q, "%s;\n", constr->condef);
15750 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15751 "SET conislocal = false\n"
15752 "WHERE contype = 'c' AND conname = ");
15753 appendStringLiteralAH(q, constr->dobj.name, fout);
15754 appendPQExpBufferStr(q, "\n AND conrelid = ");
15755 appendStringLiteralAH(q, qualrelname, fout);
15756 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15759 if (numParents > 0)
15761 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15762 for (k = 0; k < numParents; k++)
15764 TableInfo *parentRel = parents[k];
15766 /* In the partitioning case, we alter the parent */
15767 if (tbinfo->ispartition)
15768 appendPQExpBuffer(q,
15769 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15770 fmtQualifiedDumpable(parentRel));
15772 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15775 /* Partition needs specifying the bounds */
15776 if (tbinfo->ispartition)
15777 appendPQExpBuffer(q, "%s %s;\n",
15779 tbinfo->partbound);
15781 appendPQExpBuffer(q, "%s;\n",
15782 fmtQualifiedDumpable(parentRel));
15786 if (tbinfo->reloftype)
15788 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15789 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15791 tbinfo->reloftype);
15796 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15797 * relminmxid of all vacuumable relations. (While vacuum.c processes
15798 * TOAST tables semi-independently, here we see them only as children
15799 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15800 * child toast table is handled below.)
15802 if (dopt->binary_upgrade &&
15803 (tbinfo->relkind == RELKIND_RELATION ||
15804 tbinfo->relkind == RELKIND_MATVIEW))
15806 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15807 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15808 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15810 tbinfo->frozenxid, tbinfo->minmxid);
15811 appendStringLiteralAH(q, qualrelname, fout);
15812 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15814 if (tbinfo->toast_oid)
15817 * The toast table will have the same OID at restore, so we
15818 * can safely target it by OID.
15820 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15821 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15822 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15823 "WHERE oid = '%u';\n",
15824 tbinfo->toast_frozenxid,
15825 tbinfo->toast_minmxid, tbinfo->toast_oid);
15830 * In binary_upgrade mode, restore matviews' populated status by
15831 * poking pg_class directly. This is pretty ugly, but we can't use
15832 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15833 * matview is not populated even though this matview is; in any case,
15834 * we want to transfer the matview's heap storage, not run REFRESH.
15836 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15837 tbinfo->relispopulated)
15839 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15840 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15841 "SET relispopulated = 't'\n"
15843 appendStringLiteralAH(q, qualrelname, fout);
15844 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15848 * Dump additional per-column properties that we can't handle in the
15849 * main CREATE TABLE command.
15851 for (j = 0; j < tbinfo->numatts; j++)
15853 /* None of this applies to dropped columns */
15854 if (tbinfo->attisdropped[j])
15858 * If we didn't dump the column definition explicitly above, and
15859 * it is NOT NULL and did not inherit that property from a parent,
15860 * we have to mark it separately.
15862 if (!shouldPrintColumn(dopt, tbinfo, j) &&
15863 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15865 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15867 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15868 fmtId(tbinfo->attnames[j]));
15872 * Dump per-column statistics information. We only issue an ALTER
15873 * TABLE statement if the attstattarget entry for this column is
15874 * non-negative (i.e. it's not the default value)
15876 if (tbinfo->attstattarget[j] >= 0)
15878 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15880 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15881 fmtId(tbinfo->attnames[j]));
15882 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15883 tbinfo->attstattarget[j]);
15887 * Dump per-column storage information. The statement is only
15888 * dumped if the storage has been changed from the type's default.
15890 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15892 switch (tbinfo->attstorage[j])
15898 storage = "EXTERNAL";
15904 storage = "EXTENDED";
15911 * Only dump the statement if it's a storage type we recognize
15913 if (storage != NULL)
15915 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15917 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15918 fmtId(tbinfo->attnames[j]));
15919 appendPQExpBuffer(q, "SET STORAGE %s;\n",
15925 * Dump per-column attributes.
15927 if (tbinfo->attoptions[j][0] != '\0')
15929 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15931 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15932 fmtId(tbinfo->attnames[j]));
15933 appendPQExpBuffer(q, "SET (%s);\n",
15934 tbinfo->attoptions[j]);
15938 * Dump per-column fdw options.
15940 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
15941 tbinfo->attfdwoptions[j][0] != '\0')
15943 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
15945 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15946 fmtId(tbinfo->attnames[j]));
15947 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
15948 tbinfo->attfdwoptions[j]);
15959 * dump properties we only have ALTER TABLE syntax for
15961 if ((tbinfo->relkind == RELKIND_RELATION ||
15962 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
15963 tbinfo->relkind == RELKIND_MATVIEW) &&
15964 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
15966 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
15968 /* nothing to do, will be set when the index is dumped */
15970 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
15972 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
15975 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
15977 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
15982 if (tbinfo->forcerowsec)
15983 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
15986 if (dopt->binary_upgrade)
15987 binary_upgrade_extension_member(q, &tbinfo->dobj,
15988 reltypename, qrelname,
15989 tbinfo->dobj.namespace->dobj.name);
15991 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15992 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15994 tbinfo->dobj.namespace->dobj.name,
15995 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
15998 tbinfo->postponed_def ?
15999 SECTION_POST_DATA : SECTION_PRE_DATA,
16000 q->data, delq->data, NULL,
16005 /* Dump Table Comments */
16006 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16007 dumpTableComment(fout, tbinfo, reltypename);
16009 /* Dump Table Security Labels */
16010 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16011 dumpTableSecLabel(fout, tbinfo, reltypename);
16013 /* Dump comments on inlined table constraints */
16014 for (j = 0; j < tbinfo->ncheck; j++)
16016 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16018 if (constr->separate || !constr->conislocal)
16021 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16022 dumpTableConstraintComment(fout, constr);
16025 destroyPQExpBuffer(q);
16026 destroyPQExpBuffer(delq);
16032 * dumpAttrDef --- dump an attribute's default-value declaration
16035 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16037 DumpOptions *dopt = fout->dopt;
16038 TableInfo *tbinfo = adinfo->adtable;
16039 int adnum = adinfo->adnum;
16045 /* Skip if table definition not to be dumped */
16046 if (!tbinfo->dobj.dump || dopt->dataOnly)
16049 /* Skip if not "separate"; it was dumped in the table's definition */
16050 if (!adinfo->separate)
16053 q = createPQExpBuffer();
16054 delq = createPQExpBuffer();
16056 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16058 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16060 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16061 fmtId(tbinfo->attnames[adnum - 1]),
16062 adinfo->adef_expr);
16064 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16066 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16067 fmtId(tbinfo->attnames[adnum - 1]));
16069 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16071 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16072 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16074 tbinfo->dobj.namespace->dobj.name,
16077 "DEFAULT", SECTION_PRE_DATA,
16078 q->data, delq->data, NULL,
16083 destroyPQExpBuffer(q);
16084 destroyPQExpBuffer(delq);
16089 * getAttrName: extract the correct name for an attribute
16091 * The array tblInfo->attnames[] only provides names of user attributes;
16092 * if a system attribute number is supplied, we have to fake it.
16093 * We also do a little bit of bounds checking for safety's sake.
16095 static const char *
16096 getAttrName(int attrnum, TableInfo *tblInfo)
16098 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16099 return tblInfo->attnames[attrnum - 1];
16102 case SelfItemPointerAttributeNumber:
16104 case MinTransactionIdAttributeNumber:
16106 case MinCommandIdAttributeNumber:
16108 case MaxTransactionIdAttributeNumber:
16110 case MaxCommandIdAttributeNumber:
16112 case TableOidAttributeNumber:
16115 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16116 attrnum, tblInfo->dobj.name);
16117 return NULL; /* keep compiler quiet */
16122 * write out to fout a user-defined index
16125 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16127 DumpOptions *dopt = fout->dopt;
16128 TableInfo *tbinfo = indxinfo->indextable;
16129 bool is_constraint = (indxinfo->indexconstraint != 0);
16134 if (dopt->dataOnly)
16137 q = createPQExpBuffer();
16138 delq = createPQExpBuffer();
16140 qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16143 * If there's an associated constraint, don't dump the index per se, but
16144 * do dump any comment for it. (This is safe because dependency ordering
16145 * will have ensured the constraint is emitted first.) Note that the
16146 * emitted comment has to be shown as depending on the constraint, not the
16147 * index, in such cases.
16149 if (!is_constraint)
16151 if (dopt->binary_upgrade)
16152 binary_upgrade_set_pg_class_oids(fout, q,
16153 indxinfo->dobj.catId.oid, true);
16155 /* Plain secondary index */
16156 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16159 * Append ALTER TABLE commands as needed to set properties that we
16160 * only have ALTER TABLE syntax for. Keep this in sync with the
16161 * similar code in dumpConstraint!
16164 /* If the index is clustered, we need to record that. */
16165 if (indxinfo->indisclustered)
16167 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16168 fmtQualifiedDumpable(tbinfo));
16169 /* index name is not qualified in this syntax */
16170 appendPQExpBuffer(q, " ON %s;\n",
16174 /* If the index defines identity, we need to record that. */
16175 if (indxinfo->indisreplident)
16177 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16178 fmtQualifiedDumpable(tbinfo));
16179 /* index name is not qualified in this syntax */
16180 appendPQExpBuffer(q, " INDEX %s;\n",
16184 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16185 fmtQualifiedDumpable(indxinfo));
16187 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16188 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16189 indxinfo->dobj.name,
16190 tbinfo->dobj.namespace->dobj.name,
16191 indxinfo->tablespace,
16193 "INDEX", SECTION_POST_DATA,
16194 q->data, delq->data, NULL,
16199 /* Dump Index Comments */
16200 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16201 dumpComment(fout, "INDEX", qindxname,
16202 tbinfo->dobj.namespace->dobj.name,
16204 indxinfo->dobj.catId, 0,
16205 is_constraint ? indxinfo->indexconstraint :
16206 indxinfo->dobj.dumpId);
16208 destroyPQExpBuffer(q);
16209 destroyPQExpBuffer(delq);
16215 * write out to fout a partitioned-index attachment clause
16218 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16220 if (fout->dopt->dataOnly)
16223 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16225 PQExpBuffer q = createPQExpBuffer();
16227 appendPQExpBuffer(q, "ALTER INDEX %s ",
16228 fmtQualifiedDumpable(attachinfo->parentIdx));
16229 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16230 fmtQualifiedDumpable(attachinfo->partitionIdx));
16232 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16233 attachinfo->dobj.name,
16234 attachinfo->dobj.namespace->dobj.name,
16237 "INDEX ATTACH", SECTION_POST_DATA,
16242 destroyPQExpBuffer(q);
16247 * dumpStatisticsExt
16248 * write out to fout an extended statistics object
16251 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16253 DumpOptions *dopt = fout->dopt;
16257 char *qstatsextname;
16261 /* Skip if not to be dumped */
16262 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16265 q = createPQExpBuffer();
16266 delq = createPQExpBuffer();
16267 query = createPQExpBuffer();
16269 qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16271 appendPQExpBuffer(query, "SELECT "
16272 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16273 statsextinfo->dobj.catId.oid);
16275 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16277 stxdef = PQgetvalue(res, 0, 0);
16279 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16280 appendPQExpBuffer(q, "%s;\n", stxdef);
16282 appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16283 fmtQualifiedDumpable(statsextinfo));
16285 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16286 ArchiveEntry(fout, statsextinfo->dobj.catId,
16287 statsextinfo->dobj.dumpId,
16288 statsextinfo->dobj.name,
16289 statsextinfo->dobj.namespace->dobj.name,
16291 statsextinfo->rolname,
16292 "STATISTICS", SECTION_POST_DATA,
16293 q->data, delq->data, NULL,
16297 /* Dump Statistics Comments */
16298 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16299 dumpComment(fout, "STATISTICS", qstatsextname,
16300 statsextinfo->dobj.namespace->dobj.name,
16301 statsextinfo->rolname,
16302 statsextinfo->dobj.catId, 0,
16303 statsextinfo->dobj.dumpId);
16306 destroyPQExpBuffer(q);
16307 destroyPQExpBuffer(delq);
16308 destroyPQExpBuffer(query);
16309 free(qstatsextname);
16314 * write out to fout a user-defined constraint
16317 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16319 DumpOptions *dopt = fout->dopt;
16320 TableInfo *tbinfo = coninfo->contable;
16325 /* Skip if not to be dumped */
16326 if (!coninfo->dobj.dump || dopt->dataOnly)
16329 q = createPQExpBuffer();
16330 delq = createPQExpBuffer();
16332 if (coninfo->contype == 'p' ||
16333 coninfo->contype == 'u' ||
16334 coninfo->contype == 'x')
16336 /* Index-related constraint */
16337 IndxInfo *indxinfo;
16340 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16342 if (indxinfo == NULL)
16343 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16344 coninfo->dobj.name);
16346 if (dopt->binary_upgrade)
16347 binary_upgrade_set_pg_class_oids(fout, q,
16348 indxinfo->dobj.catId.oid, true);
16350 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16351 fmtQualifiedDumpable(tbinfo));
16352 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16353 fmtId(coninfo->dobj.name));
16355 if (coninfo->condef)
16357 /* pg_get_constraintdef should have provided everything */
16358 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16362 appendPQExpBuffer(q, "%s (",
16363 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16364 for (k = 0; k < indxinfo->indnkeyattrs; k++)
16366 int indkey = (int) indxinfo->indkeys[k];
16367 const char *attname;
16369 if (indkey == InvalidAttrNumber)
16371 attname = getAttrName(indkey, tbinfo);
16373 appendPQExpBuffer(q, "%s%s",
16374 (k == 0) ? "" : ", ",
16378 if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
16379 appendPQExpBuffer(q, ") INCLUDE (");
16381 for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
16383 int indkey = (int) indxinfo->indkeys[k];
16384 const char *attname;
16386 if (indkey == InvalidAttrNumber)
16388 attname = getAttrName(indkey, tbinfo);
16390 appendPQExpBuffer(q, "%s%s",
16391 (k == indxinfo->indnkeyattrs) ? "" : ", ",
16395 appendPQExpBufferChar(q, ')');
16397 if (nonemptyReloptions(indxinfo->indreloptions))
16399 appendPQExpBufferStr(q, " WITH (");
16400 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16401 appendPQExpBufferChar(q, ')');
16404 if (coninfo->condeferrable)
16406 appendPQExpBufferStr(q, " DEFERRABLE");
16407 if (coninfo->condeferred)
16408 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16411 appendPQExpBufferStr(q, ";\n");
16415 * Append ALTER TABLE commands as needed to set properties that we
16416 * only have ALTER TABLE syntax for. Keep this in sync with the
16417 * similar code in dumpIndex!
16420 /* If the index is clustered, we need to record that. */
16421 if (indxinfo->indisclustered)
16423 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16424 fmtQualifiedDumpable(tbinfo));
16425 /* index name is not qualified in this syntax */
16426 appendPQExpBuffer(q, " ON %s;\n",
16427 fmtId(indxinfo->dobj.name));
16430 /* If the index defines identity, we need to record that. */
16431 if (indxinfo->indisreplident)
16433 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16434 fmtQualifiedDumpable(tbinfo));
16435 /* index name is not qualified in this syntax */
16436 appendPQExpBuffer(q, " INDEX %s;\n",
16437 fmtId(indxinfo->dobj.name));
16440 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16441 fmtQualifiedDumpable(tbinfo));
16442 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16443 fmtId(coninfo->dobj.name));
16445 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16447 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16448 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16450 tbinfo->dobj.namespace->dobj.name,
16451 indxinfo->tablespace,
16453 "CONSTRAINT", SECTION_POST_DATA,
16454 q->data, delq->data, NULL,
16458 else if (coninfo->contype == 'f')
16463 * Foreign keys on partitioned tables are always declared as
16464 * inheriting to partitions; for all other cases, emit them as
16465 * applying ONLY directly to the named table, because that's how they
16466 * work for regular inherited tables.
16468 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
16471 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16472 * current table data is not processed
16474 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
16475 only, fmtQualifiedDumpable(tbinfo));
16476 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16477 fmtId(coninfo->dobj.name),
16480 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
16481 only, fmtQualifiedDumpable(tbinfo));
16482 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16483 fmtId(coninfo->dobj.name));
16485 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16487 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16488 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16490 tbinfo->dobj.namespace->dobj.name,
16493 "FK CONSTRAINT", SECTION_POST_DATA,
16494 q->data, delq->data, NULL,
16498 else if (coninfo->contype == 'c' && tbinfo)
16500 /* CHECK constraint on a table */
16502 /* Ignore if not to be dumped separately, or if it was inherited */
16503 if (coninfo->separate && coninfo->conislocal)
16505 /* not ONLY since we want it to propagate to children */
16506 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16507 fmtQualifiedDumpable(tbinfo));
16508 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16509 fmtId(coninfo->dobj.name),
16512 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16513 fmtQualifiedDumpable(tbinfo));
16514 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16515 fmtId(coninfo->dobj.name));
16517 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16519 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16520 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16522 tbinfo->dobj.namespace->dobj.name,
16525 "CHECK CONSTRAINT", SECTION_POST_DATA,
16526 q->data, delq->data, NULL,
16531 else if (coninfo->contype == 'c' && tbinfo == NULL)
16533 /* CHECK constraint on a domain */
16534 TypeInfo *tyinfo = coninfo->condomain;
16536 /* Ignore if not to be dumped separately */
16537 if (coninfo->separate)
16539 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16540 fmtQualifiedDumpable(tyinfo));
16541 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16542 fmtId(coninfo->dobj.name),
16545 appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16546 fmtQualifiedDumpable(tyinfo));
16547 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16548 fmtId(coninfo->dobj.name));
16550 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16552 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16553 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16555 tyinfo->dobj.namespace->dobj.name,
16558 "CHECK CONSTRAINT", SECTION_POST_DATA,
16559 q->data, delq->data, NULL,
16566 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16570 /* Dump Constraint Comments --- only works for table constraints */
16571 if (tbinfo && coninfo->separate &&
16572 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16573 dumpTableConstraintComment(fout, coninfo);
16576 destroyPQExpBuffer(q);
16577 destroyPQExpBuffer(delq);
16581 * dumpTableConstraintComment --- dump a constraint's comment if any
16583 * This is split out because we need the function in two different places
16584 * depending on whether the constraint is dumped as part of CREATE TABLE
16585 * or as a separate ALTER command.
16588 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16590 TableInfo *tbinfo = coninfo->contable;
16591 PQExpBuffer conprefix = createPQExpBuffer();
16594 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16596 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16597 fmtId(coninfo->dobj.name));
16599 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16600 dumpComment(fout, conprefix->data, qtabname,
16601 tbinfo->dobj.namespace->dobj.name,
16603 coninfo->dobj.catId, 0,
16604 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16606 destroyPQExpBuffer(conprefix);
16611 * findLastBuiltinOid_V71 -
16613 * find the last built in oid
16615 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16616 * pg_database entry for the current database. (Note: current_database()
16617 * requires 7.3; pg_dump requires 8.0 now.)
16620 findLastBuiltinOid_V71(Archive *fout)
16625 res = ExecuteSqlQueryForSingleRow(fout,
16626 "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
16627 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16635 * write the declaration (not data) of one user-defined sequence
16638 dumpSequence(Archive *fout, TableInfo *tbinfo)
16640 DumpOptions *dopt = fout->dopt;
16650 int64 default_minv,
16654 PQExpBuffer query = createPQExpBuffer();
16655 PQExpBuffer delqry = createPQExpBuffer();
16658 qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16660 if (fout->remoteVersion >= 100000)
16662 appendPQExpBuffer(query,
16663 "SELECT format_type(seqtypid, NULL), "
16664 "seqstart, seqincrement, "
16666 "seqcache, seqcycle "
16667 "FROM pg_catalog.pg_sequence "
16668 "WHERE seqrelid = '%u'::oid",
16669 tbinfo->dobj.catId.oid);
16671 else if (fout->remoteVersion >= 80400)
16674 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16676 * Note: it might seem that 'bigint' potentially needs to be
16677 * schema-qualified, but actually that's a keyword.
16679 appendPQExpBuffer(query,
16680 "SELECT 'bigint' AS sequence_type, "
16681 "start_value, increment_by, max_value, min_value, "
16682 "cache_value, is_cycled FROM %s",
16683 fmtQualifiedDumpable(tbinfo));
16687 appendPQExpBuffer(query,
16688 "SELECT 'bigint' AS sequence_type, "
16689 "0 AS start_value, increment_by, max_value, min_value, "
16690 "cache_value, is_cycled FROM %s",
16691 fmtQualifiedDumpable(tbinfo));
16694 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16696 if (PQntuples(res) != 1)
16698 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16699 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16701 tbinfo->dobj.name, PQntuples(res));
16705 seqtype = PQgetvalue(res, 0, 0);
16706 startv = PQgetvalue(res, 0, 1);
16707 incby = PQgetvalue(res, 0, 2);
16708 maxv = PQgetvalue(res, 0, 3);
16709 minv = PQgetvalue(res, 0, 4);
16710 cache = PQgetvalue(res, 0, 5);
16711 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16713 /* Calculate default limits for a sequence of this type */
16714 is_ascending = (incby[0] != '-');
16715 if (strcmp(seqtype, "smallint") == 0)
16717 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16718 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16720 else if (strcmp(seqtype, "integer") == 0)
16722 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16723 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16725 else if (strcmp(seqtype, "bigint") == 0)
16727 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16728 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16732 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16733 default_minv = default_maxv = 0; /* keep compiler quiet */
16737 * 64-bit strtol() isn't very portable, so convert the limits to strings
16738 * and compare that way.
16740 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16741 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16743 /* Don't print minv/maxv if they match the respective default limit */
16744 if (strcmp(minv, bufm) == 0)
16746 if (strcmp(maxv, bufx) == 0)
16750 * Identity sequences are not to be dropped separately.
16752 if (!tbinfo->is_identity_sequence)
16754 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16755 fmtQualifiedDumpable(tbinfo));
16758 resetPQExpBuffer(query);
16760 if (dopt->binary_upgrade)
16762 binary_upgrade_set_pg_class_oids(fout, query,
16763 tbinfo->dobj.catId.oid, false);
16764 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16765 tbinfo->dobj.catId.oid);
16768 if (tbinfo->is_identity_sequence)
16770 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16772 appendPQExpBuffer(query,
16774 fmtQualifiedDumpable(owning_tab));
16775 appendPQExpBuffer(query,
16776 "ALTER COLUMN %s ADD GENERATED ",
16777 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16778 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16779 appendPQExpBuffer(query, "ALWAYS");
16780 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16781 appendPQExpBuffer(query, "BY DEFAULT");
16782 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16783 fmtQualifiedDumpable(tbinfo));
16787 appendPQExpBuffer(query,
16788 "CREATE SEQUENCE %s\n",
16789 fmtQualifiedDumpable(tbinfo));
16791 if (strcmp(seqtype, "bigint") != 0)
16792 appendPQExpBuffer(query, " AS %s\n", seqtype);
16795 if (fout->remoteVersion >= 80400)
16796 appendPQExpBuffer(query, " START WITH %s\n", startv);
16798 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
16801 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
16803 appendPQExpBufferStr(query, " NO MINVALUE\n");
16806 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
16808 appendPQExpBufferStr(query, " NO MAXVALUE\n");
16810 appendPQExpBuffer(query,
16812 cache, (cycled ? "\n CYCLE" : ""));
16814 if (tbinfo->is_identity_sequence)
16815 appendPQExpBufferStr(query, "\n);\n");
16817 appendPQExpBufferStr(query, ";\n");
16819 /* binary_upgrade: no need to clear TOAST table oid */
16821 if (dopt->binary_upgrade)
16822 binary_upgrade_extension_member(query, &tbinfo->dobj,
16823 "SEQUENCE", qseqname,
16824 tbinfo->dobj.namespace->dobj.name);
16826 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16827 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16829 tbinfo->dobj.namespace->dobj.name,
16832 "SEQUENCE", SECTION_PRE_DATA,
16833 query->data, delqry->data, NULL,
16838 * If the sequence is owned by a table column, emit the ALTER for it as a
16839 * separate TOC entry immediately following the sequence's own entry. It's
16840 * OK to do this rather than using full sorting logic, because the
16841 * dependency that tells us it's owned will have forced the table to be
16842 * created first. We can't just include the ALTER in the TOC entry
16843 * because it will fail if we haven't reassigned the sequence owner to
16844 * match the table's owner.
16846 * We need not schema-qualify the table reference because both sequence
16847 * and table must be in the same schema.
16849 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16851 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16853 if (owning_tab == NULL)
16854 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16855 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16857 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16859 resetPQExpBuffer(query);
16860 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16861 fmtQualifiedDumpable(tbinfo));
16862 appendPQExpBuffer(query, " OWNED BY %s",
16863 fmtQualifiedDumpable(owning_tab));
16864 appendPQExpBuffer(query, ".%s;\n",
16865 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16867 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16868 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16870 tbinfo->dobj.namespace->dobj.name,
16873 "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16874 query->data, "", NULL,
16875 &(tbinfo->dobj.dumpId), 1,
16880 /* Dump Sequence Comments and Security Labels */
16881 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16882 dumpComment(fout, "SEQUENCE", qseqname,
16883 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16884 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16886 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16887 dumpSecLabel(fout, "SEQUENCE", qseqname,
16888 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16889 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16893 destroyPQExpBuffer(query);
16894 destroyPQExpBuffer(delqry);
16900 * write the data of one user-defined sequence
16903 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16905 TableInfo *tbinfo = tdinfo->tdtable;
16909 PQExpBuffer query = createPQExpBuffer();
16911 appendPQExpBuffer(query,
16912 "SELECT last_value, is_called FROM %s",
16913 fmtQualifiedDumpable(tbinfo));
16915 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16917 if (PQntuples(res) != 1)
16919 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16920 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16922 tbinfo->dobj.name, PQntuples(res));
16926 last = PQgetvalue(res, 0, 0);
16927 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
16929 resetPQExpBuffer(query);
16930 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
16931 appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
16932 appendPQExpBuffer(query, ", %s, %s);\n",
16933 last, (called ? "true" : "false"));
16935 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
16936 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16938 tbinfo->dobj.namespace->dobj.name,
16941 "SEQUENCE SET", SECTION_DATA,
16942 query->data, "", NULL,
16943 &(tbinfo->dobj.dumpId), 1,
16948 destroyPQExpBuffer(query);
16953 * write the declaration of one user-defined table trigger
16956 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
16958 DumpOptions *dopt = fout->dopt;
16959 TableInfo *tbinfo = tginfo->tgtable;
16961 PQExpBuffer delqry;
16962 PQExpBuffer trigprefix;
16971 * we needn't check dobj.dump because TriggerInfo wouldn't have been
16972 * created in the first place for non-dumpable triggers
16974 if (dopt->dataOnly)
16977 query = createPQExpBuffer();
16978 delqry = createPQExpBuffer();
16979 trigprefix = createPQExpBuffer();
16981 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16983 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
16984 fmtId(tginfo->dobj.name));
16985 appendPQExpBuffer(delqry, "ON %s;\n",
16986 fmtQualifiedDumpable(tbinfo));
16990 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
16994 if (tginfo->tgisconstraint)
16996 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
16997 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17001 appendPQExpBufferStr(query, "CREATE TRIGGER ");
17002 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17004 appendPQExpBufferStr(query, "\n ");
17007 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17008 appendPQExpBufferStr(query, "BEFORE");
17009 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17010 appendPQExpBufferStr(query, "AFTER");
17011 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17012 appendPQExpBufferStr(query, "INSTEAD OF");
17015 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17020 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17022 appendPQExpBufferStr(query, " INSERT");
17025 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17028 appendPQExpBufferStr(query, " OR DELETE");
17030 appendPQExpBufferStr(query, " DELETE");
17033 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17036 appendPQExpBufferStr(query, " OR UPDATE");
17038 appendPQExpBufferStr(query, " UPDATE");
17041 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17044 appendPQExpBufferStr(query, " OR TRUNCATE");
17046 appendPQExpBufferStr(query, " TRUNCATE");
17049 appendPQExpBuffer(query, " ON %s\n",
17050 fmtQualifiedDumpable(tbinfo));
17052 if (tginfo->tgisconstraint)
17054 if (OidIsValid(tginfo->tgconstrrelid))
17056 /* regclass output is already quoted */
17057 appendPQExpBuffer(query, " FROM %s\n ",
17058 tginfo->tgconstrrelname);
17060 if (!tginfo->tgdeferrable)
17061 appendPQExpBufferStr(query, "NOT ");
17062 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17063 if (tginfo->tginitdeferred)
17064 appendPQExpBufferStr(query, "DEFERRED\n");
17066 appendPQExpBufferStr(query, "IMMEDIATE\n");
17069 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17070 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
17072 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
17074 /* regproc output is already sufficiently quoted */
17075 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17078 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17081 for (findx = 0; findx < tginfo->tgnargs; findx++)
17083 /* find the embedded null that terminates this trigger argument */
17084 size_t tlen = strlen(p);
17086 if (p + tlen >= tgargs + lentgargs)
17088 /* hm, not found before end of bytea value... */
17089 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17092 tbinfo->dobj.name);
17097 appendPQExpBufferStr(query, ", ");
17098 appendStringLiteralAH(query, p, fout);
17102 appendPQExpBufferStr(query, ");\n");
17105 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17107 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17108 fmtQualifiedDumpable(tbinfo));
17109 switch (tginfo->tgenabled)
17113 appendPQExpBufferStr(query, "DISABLE");
17116 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17119 appendPQExpBufferStr(query, "ENABLE REPLICA");
17122 appendPQExpBufferStr(query, "ENABLE");
17125 appendPQExpBuffer(query, " TRIGGER %s;\n",
17126 fmtId(tginfo->dobj.name));
17129 appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17130 fmtId(tginfo->dobj.name));
17132 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17134 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17135 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17137 tbinfo->dobj.namespace->dobj.name,
17140 "TRIGGER", SECTION_POST_DATA,
17141 query->data, delqry->data, NULL,
17145 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17146 dumpComment(fout, trigprefix->data, qtabname,
17147 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17148 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17151 destroyPQExpBuffer(query);
17152 destroyPQExpBuffer(delqry);
17153 destroyPQExpBuffer(trigprefix);
17159 * write the declaration of one user-defined event trigger
17162 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17164 DumpOptions *dopt = fout->dopt;
17166 PQExpBuffer delqry;
17169 /* Skip if not to be dumped */
17170 if (!evtinfo->dobj.dump || dopt->dataOnly)
17173 query = createPQExpBuffer();
17174 delqry = createPQExpBuffer();
17176 qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17178 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17179 appendPQExpBufferStr(query, qevtname);
17180 appendPQExpBufferStr(query, " ON ");
17181 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17183 if (strcmp("", evtinfo->evttags) != 0)
17185 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17186 appendPQExpBufferStr(query, evtinfo->evttags);
17187 appendPQExpBufferChar(query, ')');
17190 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
17191 appendPQExpBufferStr(query, evtinfo->evtfname);
17192 appendPQExpBufferStr(query, "();\n");
17194 if (evtinfo->evtenabled != 'O')
17196 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17198 switch (evtinfo->evtenabled)
17201 appendPQExpBufferStr(query, "DISABLE");
17204 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17207 appendPQExpBufferStr(query, "ENABLE REPLICA");
17210 appendPQExpBufferStr(query, "ENABLE");
17213 appendPQExpBufferStr(query, ";\n");
17216 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17219 if (dopt->binary_upgrade)
17220 binary_upgrade_extension_member(query, &evtinfo->dobj,
17221 "EVENT TRIGGER", qevtname, NULL);
17223 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17224 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17225 evtinfo->dobj.name, NULL, NULL,
17227 "EVENT TRIGGER", SECTION_POST_DATA,
17228 query->data, delqry->data, NULL,
17232 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17233 dumpComment(fout, "EVENT TRIGGER", qevtname,
17234 NULL, evtinfo->evtowner,
17235 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17237 destroyPQExpBuffer(query);
17238 destroyPQExpBuffer(delqry);
17247 dumpRule(Archive *fout, RuleInfo *rinfo)
17249 DumpOptions *dopt = fout->dopt;
17250 TableInfo *tbinfo = rinfo->ruletable;
17254 PQExpBuffer delcmd;
17255 PQExpBuffer ruleprefix;
17260 /* Skip if not to be dumped */
17261 if (!rinfo->dobj.dump || dopt->dataOnly)
17265 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17266 * we do not want to dump it as a separate object.
17268 if (!rinfo->separate)
17272 * If it's an ON SELECT rule, we want to print it as a view definition,
17273 * instead of a rule.
17275 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17277 query = createPQExpBuffer();
17278 cmd = createPQExpBuffer();
17279 delcmd = createPQExpBuffer();
17280 ruleprefix = createPQExpBuffer();
17282 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17286 PQExpBuffer result;
17289 * We need OR REPLACE here because we'll be replacing a dummy view.
17290 * Otherwise this should look largely like the regular view dump code.
17292 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17293 fmtQualifiedDumpable(tbinfo));
17294 if (nonemptyReloptions(tbinfo->reloptions))
17296 appendPQExpBufferStr(cmd, " WITH (");
17297 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17298 appendPQExpBufferChar(cmd, ')');
17300 result = createViewAsClause(fout, tbinfo);
17301 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17302 destroyPQExpBuffer(result);
17303 if (tbinfo->checkoption != NULL)
17304 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
17305 tbinfo->checkoption);
17306 appendPQExpBufferStr(cmd, ";\n");
17310 /* In the rule case, just print pg_get_ruledef's result verbatim */
17311 appendPQExpBuffer(query,
17312 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17313 rinfo->dobj.catId.oid);
17315 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17317 if (PQntuples(res) != 1)
17319 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17320 rinfo->dobj.name, tbinfo->dobj.name);
17324 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17330 * Add the command to alter the rules replication firing semantics if it
17331 * differs from the default.
17333 if (rinfo->ev_enabled != 'O')
17335 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17336 switch (rinfo->ev_enabled)
17339 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17340 fmtId(rinfo->dobj.name));
17343 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17344 fmtId(rinfo->dobj.name));
17347 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17348 fmtId(rinfo->dobj.name));
17356 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17357 * REPLACE VIEW to replace the rule with something with minimal
17360 PQExpBuffer result;
17362 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17363 fmtQualifiedDumpable(tbinfo));
17364 result = createDummyViewAsClause(fout, tbinfo);
17365 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17366 destroyPQExpBuffer(result);
17370 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17371 fmtId(rinfo->dobj.name));
17372 appendPQExpBuffer(delcmd, "ON %s;\n",
17373 fmtQualifiedDumpable(tbinfo));
17376 appendPQExpBuffer(ruleprefix, "RULE %s ON",
17377 fmtId(rinfo->dobj.name));
17379 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17381 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17382 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17384 tbinfo->dobj.namespace->dobj.name,
17387 "RULE", SECTION_POST_DATA,
17388 cmd->data, delcmd->data, NULL,
17392 /* Dump rule comments */
17393 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17394 dumpComment(fout, ruleprefix->data, qtabname,
17395 tbinfo->dobj.namespace->dobj.name,
17397 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17400 destroyPQExpBuffer(query);
17401 destroyPQExpBuffer(cmd);
17402 destroyPQExpBuffer(delcmd);
17403 destroyPQExpBuffer(ruleprefix);
17408 * getExtensionMembership --- obtain extension membership data
17410 * We need to identify objects that are extension members as soon as they're
17411 * loaded, so that we can correctly determine whether they need to be dumped.
17412 * Generally speaking, extension member objects will get marked as *not* to
17413 * be dumped, as they will be recreated by the single CREATE EXTENSION
17414 * command. However, in binary upgrade mode we still need to dump the members
17418 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17429 ExtensionMemberId *extmembers;
17430 ExtensionInfo *ext;
17432 /* Nothing to do if no extensions */
17433 if (numExtensions == 0)
17436 query = createPQExpBuffer();
17438 /* refclassid constraint is redundant but may speed the search */
17439 appendPQExpBufferStr(query, "SELECT "
17440 "classid, objid, refobjid "
17442 "WHERE refclassid = 'pg_extension'::regclass "
17443 "AND deptype = 'e' "
17446 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17448 ntups = PQntuples(res);
17450 i_classid = PQfnumber(res, "classid");
17451 i_objid = PQfnumber(res, "objid");
17452 i_refobjid = PQfnumber(res, "refobjid");
17454 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17458 * Accumulate data into extmembers[].
17460 * Since we ordered the SELECT by referenced ID, we can expect that
17461 * multiple entries for the same extension will appear together; this
17462 * saves on searches.
17466 for (i = 0; i < ntups; i++)
17471 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17472 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17473 extId = atooid(PQgetvalue(res, i, i_refobjid));
17476 ext->dobj.catId.oid != extId)
17477 ext = findExtensionByOid(extId);
17481 /* shouldn't happen */
17482 fprintf(stderr, "could not find referenced extension %u\n", extId);
17486 extmembers[nextmembers].catId = objId;
17487 extmembers[nextmembers].ext = ext;
17493 /* Remember the data for use later */
17494 setExtensionMembership(extmembers, nextmembers);
17496 destroyPQExpBuffer(query);
17500 * processExtensionTables --- deal with extension configuration tables
17502 * There are two parts to this process:
17504 * 1. Identify and create dump records for extension configuration tables.
17506 * Extensions can mark tables as "configuration", which means that the user
17507 * is able and expected to modify those tables after the extension has been
17508 * loaded. For these tables, we dump out only the data- the structure is
17509 * expected to be handled at CREATE EXTENSION time, including any indexes or
17510 * foreign keys, which brings us to-
17512 * 2. Record FK dependencies between configuration tables.
17514 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17515 * the data is loaded, we have to work out what the best order for reloading
17516 * the data is, to avoid FK violations when the tables are restored. This is
17517 * not perfect- we can't handle circular dependencies and if any exist they
17518 * will cause an invalid dump to be produced (though at least all of the data
17519 * is included for a user to manually restore). This is currently documented
17520 * but perhaps we can provide a better solution in the future.
17523 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17526 DumpOptions *dopt = fout->dopt;
17534 /* Nothing to do if no extensions */
17535 if (numExtensions == 0)
17539 * Identify extension configuration tables and create TableDataInfo
17540 * objects for them, ensuring their data will be dumped even though the
17541 * tables themselves won't be.
17543 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17544 * user data in a configuration table is treated like schema data. This
17545 * seems appropriate since system data in a config table would get
17546 * reloaded by CREATE EXTENSION.
17548 for (i = 0; i < numExtensions; i++)
17550 ExtensionInfo *curext = &(extinfo[i]);
17551 char *extconfig = curext->extconfig;
17552 char *extcondition = curext->extcondition;
17553 char **extconfigarray = NULL;
17554 char **extconditionarray = NULL;
17556 int nconditionitems;
17558 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17559 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17560 nconfigitems == nconditionitems)
17564 for (j = 0; j < nconfigitems; j++)
17566 TableInfo *configtbl;
17567 Oid configtbloid = atooid(extconfigarray[j]);
17569 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17571 configtbl = findTableByOid(configtbloid);
17572 if (configtbl == NULL)
17576 * Tables of not-to-be-dumped extensions shouldn't be dumped
17577 * unless the table or its schema is explicitly included
17579 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17581 /* check table explicitly requested */
17582 if (table_include_oids.head != NULL &&
17583 simple_oid_list_member(&table_include_oids,
17587 /* check table's schema explicitly requested */
17588 if (configtbl->dobj.namespace->dobj.dump &
17589 DUMP_COMPONENT_DATA)
17593 /* check table excluded by an exclusion switch */
17594 if (table_exclude_oids.head != NULL &&
17595 simple_oid_list_member(&table_exclude_oids,
17599 /* check schema excluded by an exclusion switch */
17600 if (simple_oid_list_member(&schema_exclude_oids,
17601 configtbl->dobj.namespace->dobj.catId.oid))
17606 makeTableDataInfo(dopt, configtbl);
17607 if (configtbl->dataObj != NULL)
17609 if (strlen(extconditionarray[j]) > 0)
17610 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17615 if (extconfigarray)
17616 free(extconfigarray);
17617 if (extconditionarray)
17618 free(extconditionarray);
17622 * Now that all the TableInfoData objects have been created for all the
17623 * extensions, check their FK dependencies and register them to try and
17624 * dump the data out in an order that they can be restored in.
17626 * Note that this is not a problem for user tables as their FKs are
17627 * recreated after the data has been loaded.
17630 query = createPQExpBuffer();
17632 printfPQExpBuffer(query,
17633 "SELECT conrelid, confrelid "
17634 "FROM pg_constraint "
17635 "JOIN pg_depend ON (objid = confrelid) "
17636 "WHERE contype = 'f' "
17637 "AND refclassid = 'pg_extension'::regclass "
17638 "AND classid = 'pg_class'::regclass;");
17640 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17641 ntups = PQntuples(res);
17643 i_conrelid = PQfnumber(res, "conrelid");
17644 i_confrelid = PQfnumber(res, "confrelid");
17646 /* Now get the dependencies and register them */
17647 for (i = 0; i < ntups; i++)
17651 TableInfo *reftable,
17654 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17655 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17656 contable = findTableByOid(conrelid);
17657 reftable = findTableByOid(confrelid);
17659 if (reftable == NULL ||
17660 reftable->dataObj == NULL ||
17661 contable == NULL ||
17662 contable->dataObj == NULL)
17666 * Make referencing TABLE_DATA object depend on the referenced table's
17667 * TABLE_DATA object.
17669 addObjectDependency(&contable->dataObj->dobj,
17670 reftable->dataObj->dobj.dumpId);
17673 destroyPQExpBuffer(query);
17677 * getDependencies --- obtain available dependency data
17680 getDependencies(Archive *fout)
17691 DumpableObject *dobj,
17695 write_msg(NULL, "reading dependency data\n");
17697 query = createPQExpBuffer();
17700 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17701 * already processed by getExtensionMembership.
17703 appendPQExpBufferStr(query, "SELECT "
17704 "classid, objid, refclassid, refobjid, deptype "
17706 "WHERE deptype != 'p' AND deptype != 'e' "
17709 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17711 ntups = PQntuples(res);
17713 i_classid = PQfnumber(res, "classid");
17714 i_objid = PQfnumber(res, "objid");
17715 i_refclassid = PQfnumber(res, "refclassid");
17716 i_refobjid = PQfnumber(res, "refobjid");
17717 i_deptype = PQfnumber(res, "deptype");
17720 * Since we ordered the SELECT by referencing ID, we can expect that
17721 * multiple entries for the same object will appear together; this saves
17726 for (i = 0; i < ntups; i++)
17729 CatalogId refobjId;
17732 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17733 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17734 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17735 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17736 deptype = *(PQgetvalue(res, i, i_deptype));
17738 if (dobj == NULL ||
17739 dobj->catId.tableoid != objId.tableoid ||
17740 dobj->catId.oid != objId.oid)
17741 dobj = findObjectByCatalogId(objId);
17744 * Failure to find objects mentioned in pg_depend is not unexpected,
17745 * since for example we don't collect info about TOAST tables.
17750 fprintf(stderr, "no referencing object %u %u\n",
17751 objId.tableoid, objId.oid);
17756 refdobj = findObjectByCatalogId(refobjId);
17758 if (refdobj == NULL)
17761 fprintf(stderr, "no referenced object %u %u\n",
17762 refobjId.tableoid, refobjId.oid);
17768 * Ordinarily, table rowtypes have implicit dependencies on their
17769 * tables. However, for a composite type the implicit dependency goes
17770 * the other way in pg_depend; which is the right thing for DROP but
17771 * it doesn't produce the dependency ordering we need. So in that one
17772 * case, we reverse the direction of the dependency.
17774 if (deptype == 'i' &&
17775 dobj->objType == DO_TABLE &&
17776 refdobj->objType == DO_TYPE)
17777 addObjectDependency(refdobj, dobj->dumpId);
17780 addObjectDependency(dobj, refdobj->dumpId);
17785 destroyPQExpBuffer(query);
17790 * createBoundaryObjects - create dummy DumpableObjects to represent
17791 * dump section boundaries.
17793 static DumpableObject *
17794 createBoundaryObjects(void)
17796 DumpableObject *dobjs;
17798 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17800 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17801 dobjs[0].catId = nilCatalogId;
17802 AssignDumpId(dobjs + 0);
17803 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17805 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17806 dobjs[1].catId = nilCatalogId;
17807 AssignDumpId(dobjs + 1);
17808 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17814 * addBoundaryDependencies - add dependencies as needed to enforce the dump
17815 * section boundaries.
17818 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17819 DumpableObject *boundaryObjs)
17821 DumpableObject *preDataBound = boundaryObjs + 0;
17822 DumpableObject *postDataBound = boundaryObjs + 1;
17825 for (i = 0; i < numObjs; i++)
17827 DumpableObject *dobj = dobjs[i];
17830 * The classification of object types here must match the SECTION_xxx
17831 * values assigned during subsequent ArchiveEntry calls!
17833 switch (dobj->objType)
17838 case DO_SHELL_TYPE:
17842 case DO_ACCESS_METHOD:
17846 case DO_CONVERSION:
17851 case DO_DUMMY_TYPE:
17854 case DO_TSTEMPLATE:
17857 case DO_FOREIGN_SERVER:
17860 /* Pre-data objects: must come before the pre-data boundary */
17861 addObjectDependency(preDataBound, dobj->dumpId);
17863 case DO_TABLE_DATA:
17864 case DO_SEQUENCE_SET:
17866 /* Data objects: must come between the boundaries */
17867 addObjectDependency(dobj, preDataBound->dumpId);
17868 addObjectDependency(postDataBound, dobj->dumpId);
17871 case DO_INDEX_ATTACH:
17873 case DO_REFRESH_MATVIEW:
17875 case DO_EVENT_TRIGGER:
17876 case DO_DEFAULT_ACL:
17878 case DO_PUBLICATION:
17879 case DO_PUBLICATION_REL:
17880 case DO_SUBSCRIPTION:
17881 /* Post-data objects: must come after the post-data boundary */
17882 addObjectDependency(dobj, postDataBound->dumpId);
17885 /* Rules are post-data, but only if dumped separately */
17886 if (((RuleInfo *) dobj)->separate)
17887 addObjectDependency(dobj, postDataBound->dumpId);
17889 case DO_CONSTRAINT:
17890 case DO_FK_CONSTRAINT:
17891 /* Constraints are post-data, but only if dumped separately */
17892 if (((ConstraintInfo *) dobj)->separate)
17893 addObjectDependency(dobj, postDataBound->dumpId);
17895 case DO_PRE_DATA_BOUNDARY:
17896 /* nothing to do */
17898 case DO_POST_DATA_BOUNDARY:
17899 /* must come after the pre-data boundary */
17900 addObjectDependency(dobj, preDataBound->dumpId);
17908 * BuildArchiveDependencies - create dependency data for archive TOC entries
17910 * The raw dependency data obtained by getDependencies() is not terribly
17911 * useful in an archive dump, because in many cases there are dependency
17912 * chains linking through objects that don't appear explicitly in the dump.
17913 * For example, a view will depend on its _RETURN rule while the _RETURN rule
17914 * will depend on other objects --- but the rule will not appear as a separate
17915 * object in the dump. We need to adjust the view's dependencies to include
17916 * whatever the rule depends on that is included in the dump.
17918 * Just to make things more complicated, there are also "special" dependencies
17919 * such as the dependency of a TABLE DATA item on its TABLE, which we must
17920 * not rearrange because pg_restore knows that TABLE DATA only depends on
17921 * its table. In these cases we must leave the dependencies strictly as-is
17922 * even if they refer to not-to-be-dumped objects.
17924 * To handle this, the convention is that "special" dependencies are created
17925 * during ArchiveEntry calls, and an archive TOC item that has any such
17926 * entries will not be touched here. Otherwise, we recursively search the
17927 * DumpableObject data structures to build the correct dependencies for each
17928 * archive TOC item.
17931 BuildArchiveDependencies(Archive *fout)
17933 ArchiveHandle *AH = (ArchiveHandle *) fout;
17936 /* Scan all TOC entries in the archive */
17937 for (te = AH->toc->next; te != AH->toc; te = te->next)
17939 DumpableObject *dobj;
17940 DumpId *dependencies;
17944 /* No need to process entries that will not be dumped */
17947 /* Ignore entries that already have "special" dependencies */
17950 /* Otherwise, look up the item's original DumpableObject, if any */
17951 dobj = findObjectByDumpId(te->dumpId);
17954 /* No work if it has no dependencies */
17955 if (dobj->nDeps <= 0)
17957 /* Set up work array */
17959 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
17961 /* Recursively find all dumpable dependencies */
17962 findDumpableDependencies(AH, dobj,
17963 &dependencies, &nDeps, &allocDeps);
17964 /* And save 'em ... */
17967 dependencies = (DumpId *) pg_realloc(dependencies,
17968 nDeps * sizeof(DumpId));
17969 te->dependencies = dependencies;
17973 free(dependencies);
17977 /* Recursive search subroutine for BuildArchiveDependencies */
17979 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
17980 DumpId **dependencies, int *nDeps, int *allocDeps)
17985 * Ignore section boundary objects: if we search through them, we'll
17986 * report lots of bogus dependencies.
17988 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
17989 dobj->objType == DO_POST_DATA_BOUNDARY)
17992 for (i = 0; i < dobj->nDeps; i++)
17994 DumpId depid = dobj->dependencies[i];
17996 if (TocIDRequired(AH, depid) != 0)
17998 /* Object will be dumped, so just reference it as a dependency */
17999 if (*nDeps >= *allocDeps)
18002 *dependencies = (DumpId *) pg_realloc(*dependencies,
18003 *allocDeps * sizeof(DumpId));
18005 (*dependencies)[*nDeps] = depid;
18011 * Object will not be dumped, so recursively consider its deps. We
18012 * rely on the assumption that sortDumpableObjects already broke
18013 * any dependency loops, else we might recurse infinitely.
18015 DumpableObject *otherdobj = findObjectByDumpId(depid);
18018 findDumpableDependencies(AH, otherdobj,
18019 dependencies, nDeps, allocDeps);
18026 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18029 * This does not guarantee to schema-qualify the output, so it should not
18030 * be used to create the target object name for CREATE or ALTER commands.
18032 * TODO: there might be some value in caching the results.
18035 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18043 if ((opts & zeroAsOpaque) != 0)
18044 return pg_strdup(g_opaque_type);
18045 else if ((opts & zeroAsAny) != 0)
18046 return pg_strdup("'any'");
18047 else if ((opts & zeroAsStar) != 0)
18048 return pg_strdup("*");
18049 else if ((opts & zeroAsNone) != 0)
18050 return pg_strdup("NONE");
18053 query = createPQExpBuffer();
18054 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18057 res = ExecuteSqlQueryForSingleRow(fout, query->data);
18059 /* result of format_type is already quoted */
18060 result = pg_strdup(PQgetvalue(res, 0, 0));
18063 destroyPQExpBuffer(query);
18069 * Return a column list clause for the given relation.
18071 * Special case: if there are no undropped columns in the relation, return
18072 * "", not an invalid "()" column list.
18074 static const char *
18075 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18077 int numatts = ti->numatts;
18078 char **attnames = ti->attnames;
18079 bool *attisdropped = ti->attisdropped;
18083 appendPQExpBufferChar(buffer, '(');
18085 for (i = 0; i < numatts; i++)
18087 if (attisdropped[i])
18090 appendPQExpBufferStr(buffer, ", ");
18091 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18096 return ""; /* no undropped columns */
18098 appendPQExpBufferChar(buffer, ')');
18099 return buffer->data;
18103 * Check if a reloptions array is nonempty.
18106 nonemptyReloptions(const char *reloptions)
18108 /* Don't want to print it if it's just "{}" */
18109 return (reloptions != NULL && strlen(reloptions) > 2);
18113 * Format a reloptions array and append it to the given buffer.
18115 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18118 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18119 const char *prefix, Archive *fout)
18123 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18124 fout->std_strings);
18126 write_msg(NULL, "WARNING: could not parse reloptions array\n");