1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2019, 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@lists.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;
6720 for (i = 0; i < numTables; i++)
6722 TableInfo *tbinfo = &tblinfo[i];
6724 if (!tbinfo->hasindex)
6728 * Ignore indexes of tables whose definitions are not to be dumped.
6730 * We also need indexes on partitioned tables which have partitions to
6731 * be dumped, in order to dump the indexes on the partitions.
6733 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6734 !tbinfo->interesting)
6738 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6739 tbinfo->dobj.namespace->dobj.name,
6743 * The point of the messy-looking outer join is to find a constraint
6744 * that is related by an internal dependency link to the index. If we
6745 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6746 * assume an index won't have more than one internal dependency.
6748 * As of 9.0 we don't need to look at pg_depend but can check for a
6749 * match to pg_constraint.conindid. The check on conrelid is
6750 * redundant but useful because that column is indexed while conindid
6753 resetPQExpBuffer(query);
6754 if (fout->remoteVersion >= 110000)
6756 appendPQExpBuffer(query,
6757 "SELECT t.tableoid, t.oid, "
6758 "t.relname AS indexname, "
6759 "inh.inhparent AS parentidx, "
6760 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6761 "i.indnkeyatts AS indnkeyatts, "
6762 "i.indnatts AS indnatts, "
6763 "i.indkey, i.indisclustered, "
6764 "i.indisreplident, "
6765 "c.contype, c.conname, "
6766 "c.condeferrable, c.condeferred, "
6767 "c.tableoid AS contableoid, "
6769 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6770 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6771 "t.reloptions AS indreloptions, "
6772 "(SELECT pg_catalog.array_agg(attnum ORDER BY attnum) "
6773 " FROM pg_catalog.pg_attribute "
6774 " WHERE attrelid = i.indexrelid AND "
6775 " attstattarget >= 0) AS indstatcols,"
6776 "(SELECT pg_catalog.array_agg(attstattarget ORDER BY attnum) "
6777 " FROM pg_catalog.pg_attribute "
6778 " WHERE attrelid = i.indexrelid AND "
6779 " attstattarget >= 0) AS indstatvals "
6780 "FROM pg_catalog.pg_index i "
6781 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6782 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6783 "LEFT JOIN pg_catalog.pg_constraint c "
6784 "ON (i.indrelid = c.conrelid AND "
6785 "i.indexrelid = c.conindid AND "
6786 "c.contype IN ('p','u','x')) "
6787 "LEFT JOIN pg_catalog.pg_inherits inh "
6788 "ON (inh.inhrelid = indexrelid) "
6789 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6790 "AND (i.indisvalid OR t2.relkind = 'p') "
6792 "ORDER BY indexname",
6793 tbinfo->dobj.catId.oid);
6795 else if (fout->remoteVersion >= 90400)
6798 * the test on indisready is necessary in 9.2, and harmless in
6799 * earlier/later versions
6801 appendPQExpBuffer(query,
6802 "SELECT t.tableoid, t.oid, "
6803 "t.relname AS indexname, "
6805 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6806 "i.indnatts AS indnkeyatts, "
6807 "i.indnatts AS indnatts, "
6808 "i.indkey, i.indisclustered, "
6809 "i.indisreplident, "
6810 "c.contype, c.conname, "
6811 "c.condeferrable, c.condeferred, "
6812 "c.tableoid AS contableoid, "
6814 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6815 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6816 "t.reloptions AS indreloptions, "
6817 "'' AS indstatcols, "
6818 "'' AS indstatvals "
6819 "FROM pg_catalog.pg_index i "
6820 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6821 "LEFT JOIN pg_catalog.pg_constraint c "
6822 "ON (i.indrelid = c.conrelid AND "
6823 "i.indexrelid = c.conindid AND "
6824 "c.contype IN ('p','u','x')) "
6825 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6826 "AND i.indisvalid AND i.indisready "
6827 "ORDER BY indexname",
6828 tbinfo->dobj.catId.oid);
6830 else if (fout->remoteVersion >= 90000)
6833 * the test on indisready is necessary in 9.2, and harmless in
6834 * earlier/later versions
6836 appendPQExpBuffer(query,
6837 "SELECT t.tableoid, t.oid, "
6838 "t.relname AS indexname, "
6840 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6841 "i.indnatts AS indnkeyatts, "
6842 "i.indnatts AS indnatts, "
6843 "i.indkey, i.indisclustered, "
6844 "false AS indisreplident, "
6845 "c.contype, c.conname, "
6846 "c.condeferrable, c.condeferred, "
6847 "c.tableoid AS contableoid, "
6849 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6850 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6851 "t.reloptions AS indreloptions, "
6852 "'' AS indstatcols, "
6853 "'' AS indstatvals "
6854 "FROM pg_catalog.pg_index i "
6855 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6856 "LEFT JOIN pg_catalog.pg_constraint c "
6857 "ON (i.indrelid = c.conrelid AND "
6858 "i.indexrelid = c.conindid AND "
6859 "c.contype IN ('p','u','x')) "
6860 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6861 "AND i.indisvalid AND i.indisready "
6862 "ORDER BY indexname",
6863 tbinfo->dobj.catId.oid);
6865 else if (fout->remoteVersion >= 80200)
6867 appendPQExpBuffer(query,
6868 "SELECT t.tableoid, t.oid, "
6869 "t.relname AS indexname, "
6871 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6872 "i.indnatts AS indnkeyatts, "
6873 "i.indnatts AS indnatts, "
6874 "i.indkey, i.indisclustered, "
6875 "false AS indisreplident, "
6876 "c.contype, c.conname, "
6877 "c.condeferrable, c.condeferred, "
6878 "c.tableoid AS contableoid, "
6881 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6882 "t.reloptions AS indreloptions, "
6883 "'' AS indstatcols, "
6884 "'' AS indstatvals "
6885 "FROM pg_catalog.pg_index i "
6886 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6887 "LEFT JOIN pg_catalog.pg_depend d "
6888 "ON (d.classid = t.tableoid "
6889 "AND d.objid = t.oid "
6890 "AND d.deptype = 'i') "
6891 "LEFT JOIN pg_catalog.pg_constraint c "
6892 "ON (d.refclassid = c.tableoid "
6893 "AND d.refobjid = c.oid) "
6894 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6896 "ORDER BY indexname",
6897 tbinfo->dobj.catId.oid);
6901 appendPQExpBuffer(query,
6902 "SELECT t.tableoid, t.oid, "
6903 "t.relname AS indexname, "
6905 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6906 "t.relnatts AS indnkeyatts, "
6907 "t.relnatts AS indnatts, "
6908 "i.indkey, i.indisclustered, "
6909 "false AS indisreplident, "
6910 "c.contype, c.conname, "
6911 "c.condeferrable, c.condeferred, "
6912 "c.tableoid AS contableoid, "
6915 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6916 "null AS indreloptions, "
6917 "'' AS indstatcols, "
6918 "'' AS indstatvals "
6919 "FROM pg_catalog.pg_index i "
6920 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6921 "LEFT JOIN pg_catalog.pg_depend d "
6922 "ON (d.classid = t.tableoid "
6923 "AND d.objid = t.oid "
6924 "AND d.deptype = 'i') "
6925 "LEFT JOIN pg_catalog.pg_constraint c "
6926 "ON (d.refclassid = c.tableoid "
6927 "AND d.refobjid = c.oid) "
6928 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6929 "ORDER BY indexname",
6930 tbinfo->dobj.catId.oid);
6933 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6935 ntups = PQntuples(res);
6937 i_tableoid = PQfnumber(res, "tableoid");
6938 i_oid = PQfnumber(res, "oid");
6939 i_indexname = PQfnumber(res, "indexname");
6940 i_parentidx = PQfnumber(res, "parentidx");
6941 i_indexdef = PQfnumber(res, "indexdef");
6942 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
6943 i_indnatts = PQfnumber(res, "indnatts");
6944 i_indkey = PQfnumber(res, "indkey");
6945 i_indisclustered = PQfnumber(res, "indisclustered");
6946 i_indisreplident = PQfnumber(res, "indisreplident");
6947 i_contype = PQfnumber(res, "contype");
6948 i_conname = PQfnumber(res, "conname");
6949 i_condeferrable = PQfnumber(res, "condeferrable");
6950 i_condeferred = PQfnumber(res, "condeferred");
6951 i_contableoid = PQfnumber(res, "contableoid");
6952 i_conoid = PQfnumber(res, "conoid");
6953 i_condef = PQfnumber(res, "condef");
6954 i_tablespace = PQfnumber(res, "tablespace");
6955 i_indreloptions = PQfnumber(res, "indreloptions");
6956 i_indstatcols = PQfnumber(res, "indstatcols");
6957 i_indstatvals = PQfnumber(res, "indstatvals");
6959 tbinfo->indexes = indxinfo =
6960 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6961 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6962 tbinfo->numIndexes = ntups;
6964 for (j = 0; j < ntups; j++)
6968 indxinfo[j].dobj.objType = DO_INDEX;
6969 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6970 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6971 AssignDumpId(&indxinfo[j].dobj);
6972 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6973 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6974 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6975 indxinfo[j].indextable = tbinfo;
6976 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6977 indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
6978 indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
6979 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6980 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6981 indxinfo[j].indstatcols = pg_strdup(PQgetvalue(res, j, i_indstatcols));
6982 indxinfo[j].indstatvals = pg_strdup(PQgetvalue(res, j, i_indstatvals));
6983 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
6984 parseOidArray(PQgetvalue(res, j, i_indkey),
6985 indxinfo[j].indkeys, indxinfo[j].indnattrs);
6986 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6987 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6988 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6989 contype = *(PQgetvalue(res, j, i_contype));
6991 if (contype == 'p' || contype == 'u' || contype == 'x')
6994 * If we found a constraint matching the index, create an
6997 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6998 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6999 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7000 AssignDumpId(&constrinfo[j].dobj);
7001 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
7002 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7003 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7004 constrinfo[j].contable = tbinfo;
7005 constrinfo[j].condomain = NULL;
7006 constrinfo[j].contype = contype;
7008 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7010 constrinfo[j].condef = NULL;
7011 constrinfo[j].confrelid = InvalidOid;
7012 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7013 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7014 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7015 constrinfo[j].conislocal = true;
7016 constrinfo[j].separate = true;
7018 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7022 /* Plain secondary index */
7023 indxinfo[j].indexconstraint = 0;
7030 destroyPQExpBuffer(query);
7034 * getExtendedStatistics
7035 * get information about extended-statistics objects.
7037 * Note: extended statistics data is not returned directly to the caller, but
7038 * it does get entered into the DumpableObject tables.
7041 getExtendedStatistics(Archive *fout)
7045 StatsExtInfo *statsextinfo;
7054 /* Extended statistics were new in v10 */
7055 if (fout->remoteVersion < 100000)
7058 query = createPQExpBuffer();
7060 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7061 "stxnamespace, (%s stxowner) AS rolname "
7062 "FROM pg_catalog.pg_statistic_ext",
7065 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7067 ntups = PQntuples(res);
7069 i_tableoid = PQfnumber(res, "tableoid");
7070 i_oid = PQfnumber(res, "oid");
7071 i_stxname = PQfnumber(res, "stxname");
7072 i_stxnamespace = PQfnumber(res, "stxnamespace");
7073 i_rolname = PQfnumber(res, "rolname");
7075 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7077 for (i = 0; i < ntups; i++)
7079 statsextinfo[i].dobj.objType = DO_STATSEXT;
7080 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7081 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7082 AssignDumpId(&statsextinfo[i].dobj);
7083 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7084 statsextinfo[i].dobj.namespace =
7086 atooid(PQgetvalue(res, i, i_stxnamespace)));
7087 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7089 /* Decide whether we want to dump it */
7090 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7092 /* Stats objects do not currently have ACLs. */
7093 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7097 destroyPQExpBuffer(query);
7103 * Get info about constraints on dumpable tables.
7105 * Currently handles foreign keys only.
7106 * Unique and primary key constraints are handled with indexes,
7107 * while check constraints are processed in getTableAttrs().
7110 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7114 ConstraintInfo *constrinfo;
7124 query = createPQExpBuffer();
7126 for (i = 0; i < numTables; i++)
7128 TableInfo *tbinfo = &tblinfo[i];
7131 * For partitioned tables, foreign keys have no triggers so they must
7132 * be included anyway in case some foreign keys are defined.
7134 if ((!tbinfo->hastriggers &&
7135 tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7136 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7140 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7141 tbinfo->dobj.namespace->dobj.name,
7144 resetPQExpBuffer(query);
7145 if (fout->remoteVersion >= 110000)
7146 appendPQExpBuffer(query,
7147 "SELECT tableoid, oid, conname, confrelid, "
7148 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7149 "FROM pg_catalog.pg_constraint "
7150 "WHERE conrelid = '%u'::pg_catalog.oid "
7151 "AND conparentid = 0 "
7152 "AND contype = 'f'",
7153 tbinfo->dobj.catId.oid);
7155 appendPQExpBuffer(query,
7156 "SELECT tableoid, oid, conname, confrelid, "
7157 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7158 "FROM pg_catalog.pg_constraint "
7159 "WHERE conrelid = '%u'::pg_catalog.oid "
7160 "AND contype = 'f'",
7161 tbinfo->dobj.catId.oid);
7162 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7164 ntups = PQntuples(res);
7166 i_contableoid = PQfnumber(res, "tableoid");
7167 i_conoid = PQfnumber(res, "oid");
7168 i_conname = PQfnumber(res, "conname");
7169 i_confrelid = PQfnumber(res, "confrelid");
7170 i_condef = PQfnumber(res, "condef");
7172 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7174 for (j = 0; j < ntups; j++)
7176 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7177 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7178 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7179 AssignDumpId(&constrinfo[j].dobj);
7180 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7181 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7182 constrinfo[j].contable = tbinfo;
7183 constrinfo[j].condomain = NULL;
7184 constrinfo[j].contype = 'f';
7185 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7186 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7187 constrinfo[j].conindex = 0;
7188 constrinfo[j].condeferrable = false;
7189 constrinfo[j].condeferred = false;
7190 constrinfo[j].conislocal = true;
7191 constrinfo[j].separate = true;
7197 destroyPQExpBuffer(query);
7201 * getDomainConstraints
7203 * Get info about constraints on a domain.
7206 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7209 ConstraintInfo *constrinfo;
7218 query = createPQExpBuffer();
7220 if (fout->remoteVersion >= 90100)
7221 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7222 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7224 "FROM pg_catalog.pg_constraint "
7225 "WHERE contypid = '%u'::pg_catalog.oid "
7227 tyinfo->dobj.catId.oid);
7230 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7231 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7232 "true as convalidated "
7233 "FROM pg_catalog.pg_constraint "
7234 "WHERE contypid = '%u'::pg_catalog.oid "
7236 tyinfo->dobj.catId.oid);
7238 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7240 ntups = PQntuples(res);
7242 i_tableoid = PQfnumber(res, "tableoid");
7243 i_oid = PQfnumber(res, "oid");
7244 i_conname = PQfnumber(res, "conname");
7245 i_consrc = PQfnumber(res, "consrc");
7247 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7249 tyinfo->nDomChecks = ntups;
7250 tyinfo->domChecks = constrinfo;
7252 for (i = 0; i < ntups; i++)
7254 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7256 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7257 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7258 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7259 AssignDumpId(&constrinfo[i].dobj);
7260 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7261 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7262 constrinfo[i].contable = NULL;
7263 constrinfo[i].condomain = tyinfo;
7264 constrinfo[i].contype = 'c';
7265 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7266 constrinfo[i].confrelid = InvalidOid;
7267 constrinfo[i].conindex = 0;
7268 constrinfo[i].condeferrable = false;
7269 constrinfo[i].condeferred = false;
7270 constrinfo[i].conislocal = true;
7272 constrinfo[i].separate = !validated;
7275 * Make the domain depend on the constraint, ensuring it won't be
7276 * output till any constraint dependencies are OK. If the constraint
7277 * has not been validated, it's going to be dumped after the domain
7278 * anyway, so this doesn't matter.
7281 addObjectDependency(&tyinfo->dobj,
7282 constrinfo[i].dobj.dumpId);
7287 destroyPQExpBuffer(query);
7292 * get basic information about every rule in the system
7294 * numRules is set to the number of rules read in
7297 getRules(Archive *fout, int *numRules)
7302 PQExpBuffer query = createPQExpBuffer();
7312 if (fout->remoteVersion >= 80300)
7314 appendPQExpBufferStr(query, "SELECT "
7315 "tableoid, oid, rulename, "
7316 "ev_class AS ruletable, ev_type, is_instead, "
7323 appendPQExpBufferStr(query, "SELECT "
7324 "tableoid, oid, rulename, "
7325 "ev_class AS ruletable, ev_type, is_instead, "
7326 "'O'::char AS ev_enabled "
7331 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7333 ntups = PQntuples(res);
7337 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7339 i_tableoid = PQfnumber(res, "tableoid");
7340 i_oid = PQfnumber(res, "oid");
7341 i_rulename = PQfnumber(res, "rulename");
7342 i_ruletable = PQfnumber(res, "ruletable");
7343 i_ev_type = PQfnumber(res, "ev_type");
7344 i_is_instead = PQfnumber(res, "is_instead");
7345 i_ev_enabled = PQfnumber(res, "ev_enabled");
7347 for (i = 0; i < ntups; i++)
7351 ruleinfo[i].dobj.objType = DO_RULE;
7352 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7353 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7354 AssignDumpId(&ruleinfo[i].dobj);
7355 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7356 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7357 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7358 if (ruleinfo[i].ruletable == NULL)
7359 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7360 ruletableoid, ruleinfo[i].dobj.catId.oid);
7361 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7362 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7363 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7364 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7365 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7366 if (ruleinfo[i].ruletable)
7369 * If the table is a view or materialized view, force its ON
7370 * SELECT rule to be sorted before the view itself --- this
7371 * ensures that any dependencies for the rule affect the table's
7372 * positioning. Other rules are forced to appear after their
7375 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7376 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7377 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7379 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7380 ruleinfo[i].dobj.dumpId);
7381 /* We'll merge the rule into CREATE VIEW, if possible */
7382 ruleinfo[i].separate = false;
7386 addObjectDependency(&ruleinfo[i].dobj,
7387 ruleinfo[i].ruletable->dobj.dumpId);
7388 ruleinfo[i].separate = true;
7392 ruleinfo[i].separate = true;
7397 destroyPQExpBuffer(query);
7404 * get information about every trigger on a dumpable table
7406 * Note: trigger data is not returned directly to the caller, but it
7407 * does get entered into the DumpableObject tables.
7410 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7414 PQExpBuffer query = createPQExpBuffer();
7416 TriggerInfo *tginfo;
7434 for (i = 0; i < numTables; i++)
7436 TableInfo *tbinfo = &tblinfo[i];
7438 if (!tbinfo->hastriggers ||
7439 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7443 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7444 tbinfo->dobj.namespace->dobj.name,
7447 resetPQExpBuffer(query);
7448 if (fout->remoteVersion >= 90000)
7451 * NB: think not to use pretty=true in pg_get_triggerdef. It
7452 * could result in non-forward-compatible dumps of WHEN clauses
7453 * due to under-parenthesization.
7455 appendPQExpBuffer(query,
7457 "tgfoid::pg_catalog.regproc AS tgfname, "
7458 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7459 "tgenabled, tableoid, oid "
7460 "FROM pg_catalog.pg_trigger t "
7461 "WHERE tgrelid = '%u'::pg_catalog.oid "
7462 "AND NOT tgisinternal",
7463 tbinfo->dobj.catId.oid);
7465 else if (fout->remoteVersion >= 80300)
7468 * We ignore triggers that are tied to a foreign-key constraint
7470 appendPQExpBuffer(query,
7472 "tgfoid::pg_catalog.regproc AS tgfname, "
7473 "tgtype, tgnargs, tgargs, tgenabled, "
7474 "tgisconstraint, tgconstrname, tgdeferrable, "
7475 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7476 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7477 "FROM pg_catalog.pg_trigger t "
7478 "WHERE tgrelid = '%u'::pg_catalog.oid "
7479 "AND tgconstraint = 0",
7480 tbinfo->dobj.catId.oid);
7485 * We ignore triggers that are tied to a foreign-key constraint,
7486 * but in these versions we have to grovel through pg_constraint
7489 appendPQExpBuffer(query,
7491 "tgfoid::pg_catalog.regproc AS tgfname, "
7492 "tgtype, tgnargs, tgargs, tgenabled, "
7493 "tgisconstraint, tgconstrname, tgdeferrable, "
7494 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7495 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7496 "FROM pg_catalog.pg_trigger t "
7497 "WHERE tgrelid = '%u'::pg_catalog.oid "
7498 "AND (NOT tgisconstraint "
7500 " (SELECT 1 FROM pg_catalog.pg_depend d "
7501 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7502 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7503 tbinfo->dobj.catId.oid);
7506 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7508 ntups = PQntuples(res);
7510 i_tableoid = PQfnumber(res, "tableoid");
7511 i_oid = PQfnumber(res, "oid");
7512 i_tgname = PQfnumber(res, "tgname");
7513 i_tgfname = PQfnumber(res, "tgfname");
7514 i_tgtype = PQfnumber(res, "tgtype");
7515 i_tgnargs = PQfnumber(res, "tgnargs");
7516 i_tgargs = PQfnumber(res, "tgargs");
7517 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7518 i_tgconstrname = PQfnumber(res, "tgconstrname");
7519 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7520 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7521 i_tgenabled = PQfnumber(res, "tgenabled");
7522 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7523 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7524 i_tgdef = PQfnumber(res, "tgdef");
7526 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7528 tbinfo->numTriggers = ntups;
7529 tbinfo->triggers = tginfo;
7531 for (j = 0; j < ntups; j++)
7533 tginfo[j].dobj.objType = DO_TRIGGER;
7534 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7535 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7536 AssignDumpId(&tginfo[j].dobj);
7537 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7538 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7539 tginfo[j].tgtable = tbinfo;
7540 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7543 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7545 /* remaining fields are not valid if we have tgdef */
7546 tginfo[j].tgfname = NULL;
7547 tginfo[j].tgtype = 0;
7548 tginfo[j].tgnargs = 0;
7549 tginfo[j].tgargs = NULL;
7550 tginfo[j].tgisconstraint = false;
7551 tginfo[j].tgdeferrable = false;
7552 tginfo[j].tginitdeferred = false;
7553 tginfo[j].tgconstrname = NULL;
7554 tginfo[j].tgconstrrelid = InvalidOid;
7555 tginfo[j].tgconstrrelname = NULL;
7559 tginfo[j].tgdef = NULL;
7561 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7562 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7563 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7564 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7565 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7566 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7567 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7569 if (tginfo[j].tgisconstraint)
7571 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7572 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7573 if (OidIsValid(tginfo[j].tgconstrrelid))
7575 if (PQgetisnull(res, j, i_tgconstrrelname))
7576 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7577 tginfo[j].dobj.name,
7579 tginfo[j].tgconstrrelid);
7580 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7583 tginfo[j].tgconstrrelname = NULL;
7587 tginfo[j].tgconstrname = NULL;
7588 tginfo[j].tgconstrrelid = InvalidOid;
7589 tginfo[j].tgconstrrelname = NULL;
7597 destroyPQExpBuffer(query);
7602 * get information about event triggers
7605 getEventTriggers(Archive *fout, int *numEventTriggers)
7610 EventTriggerInfo *evtinfo;
7621 /* Before 9.3, there are no event triggers */
7622 if (fout->remoteVersion < 90300)
7624 *numEventTriggers = 0;
7628 query = createPQExpBuffer();
7630 appendPQExpBuffer(query,
7631 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7632 "evtevent, (%s evtowner) AS evtowner, "
7633 "array_to_string(array("
7634 "select quote_literal(x) "
7635 " from unnest(evttags) as t(x)), ', ') as evttags, "
7636 "e.evtfoid::regproc as evtfname "
7637 "FROM pg_event_trigger e "
7641 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7643 ntups = PQntuples(res);
7645 *numEventTriggers = ntups;
7647 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7649 i_tableoid = PQfnumber(res, "tableoid");
7650 i_oid = PQfnumber(res, "oid");
7651 i_evtname = PQfnumber(res, "evtname");
7652 i_evtevent = PQfnumber(res, "evtevent");
7653 i_evtowner = PQfnumber(res, "evtowner");
7654 i_evttags = PQfnumber(res, "evttags");
7655 i_evtfname = PQfnumber(res, "evtfname");
7656 i_evtenabled = PQfnumber(res, "evtenabled");
7658 for (i = 0; i < ntups; i++)
7660 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7661 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7662 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7663 AssignDumpId(&evtinfo[i].dobj);
7664 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7665 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7666 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7667 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7668 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7669 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7670 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7672 /* Decide whether we want to dump it */
7673 selectDumpableObject(&(evtinfo[i].dobj), fout);
7675 /* Event Triggers do not currently have ACLs. */
7676 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7681 destroyPQExpBuffer(query);
7688 * get basic information about every procedural language in the system
7690 * numProcLangs is set to the number of langs read in
7692 * NB: this must run after getFuncs() because we assume we can do
7696 getProcLangs(Archive *fout, int *numProcLangs)
7698 DumpOptions *dopt = fout->dopt;
7702 PQExpBuffer query = createPQExpBuffer();
7703 ProcLangInfo *planginfo;
7708 int i_lanplcallfoid;
7717 if (fout->remoteVersion >= 90600)
7719 PQExpBuffer acl_subquery = createPQExpBuffer();
7720 PQExpBuffer racl_subquery = createPQExpBuffer();
7721 PQExpBuffer initacl_subquery = createPQExpBuffer();
7722 PQExpBuffer initracl_subquery = createPQExpBuffer();
7724 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7725 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7726 dopt->binary_upgrade);
7728 /* pg_language has a laninline column */
7729 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7730 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7731 "l.laninline, l.lanvalidator, "
7734 "%s AS initlanacl, "
7735 "%s AS initrlanacl, "
7736 "(%s l.lanowner) AS lanowner "
7737 "FROM pg_language l "
7738 "LEFT JOIN pg_init_privs pip ON "
7739 "(l.oid = pip.objoid "
7740 "AND pip.classoid = 'pg_language'::regclass "
7741 "AND pip.objsubid = 0) "
7745 racl_subquery->data,
7746 initacl_subquery->data,
7747 initracl_subquery->data,
7750 destroyPQExpBuffer(acl_subquery);
7751 destroyPQExpBuffer(racl_subquery);
7752 destroyPQExpBuffer(initacl_subquery);
7753 destroyPQExpBuffer(initracl_subquery);
7755 else if (fout->remoteVersion >= 90000)
7757 /* pg_language has a laninline column */
7758 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7759 "lanname, lanpltrusted, lanplcallfoid, "
7760 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7761 "NULL AS initlanacl, NULL AS initrlanacl, "
7762 "(%s lanowner) AS lanowner "
7768 else if (fout->remoteVersion >= 80300)
7770 /* pg_language has a lanowner column */
7771 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7772 "lanname, lanpltrusted, lanplcallfoid, "
7773 "0 AS laninline, lanvalidator, lanacl, "
7775 "NULL AS initlanacl, NULL AS initrlanacl, "
7776 "(%s lanowner) AS lanowner "
7782 else if (fout->remoteVersion >= 80100)
7784 /* Languages are owned by the bootstrap superuser, OID 10 */
7785 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7786 "lanname, lanpltrusted, lanplcallfoid, "
7787 "0 AS laninline, lanvalidator, lanacl, "
7789 "NULL AS initlanacl, NULL AS initrlanacl, "
7790 "(%s '10') AS lanowner "
7798 /* Languages are owned by the bootstrap superuser, sysid 1 */
7799 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7800 "lanname, lanpltrusted, lanplcallfoid, "
7801 "0 AS laninline, lanvalidator, lanacl, "
7803 "NULL AS initlanacl, NULL AS initrlanacl, "
7804 "(%s '1') AS lanowner "
7811 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7813 ntups = PQntuples(res);
7815 *numProcLangs = ntups;
7817 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7819 i_tableoid = PQfnumber(res, "tableoid");
7820 i_oid = PQfnumber(res, "oid");
7821 i_lanname = PQfnumber(res, "lanname");
7822 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7823 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7824 i_laninline = PQfnumber(res, "laninline");
7825 i_lanvalidator = PQfnumber(res, "lanvalidator");
7826 i_lanacl = PQfnumber(res, "lanacl");
7827 i_rlanacl = PQfnumber(res, "rlanacl");
7828 i_initlanacl = PQfnumber(res, "initlanacl");
7829 i_initrlanacl = PQfnumber(res, "initrlanacl");
7830 i_lanowner = PQfnumber(res, "lanowner");
7832 for (i = 0; i < ntups; i++)
7834 planginfo[i].dobj.objType = DO_PROCLANG;
7835 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7836 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7837 AssignDumpId(&planginfo[i].dobj);
7839 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7840 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7841 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7842 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7843 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7844 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7845 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7846 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7847 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7848 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7850 /* Decide whether we want to dump it */
7851 selectDumpableProcLang(&(planginfo[i]), fout);
7853 /* Do not try to dump ACL if no ACL exists. */
7854 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7855 PQgetisnull(res, i, i_initlanacl) &&
7856 PQgetisnull(res, i, i_initrlanacl))
7857 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7862 destroyPQExpBuffer(query);
7869 * get basic information about every cast in the system
7871 * numCasts is set to the number of casts read in
7874 getCasts(Archive *fout, int *numCasts)
7879 PQExpBuffer query = createPQExpBuffer();
7889 if (fout->remoteVersion >= 80400)
7891 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7892 "castsource, casttarget, castfunc, castcontext, "
7894 "FROM pg_cast ORDER BY 3,4");
7898 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7899 "castsource, casttarget, castfunc, castcontext, "
7900 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7901 "FROM pg_cast ORDER BY 3,4");
7904 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7906 ntups = PQntuples(res);
7910 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7912 i_tableoid = PQfnumber(res, "tableoid");
7913 i_oid = PQfnumber(res, "oid");
7914 i_castsource = PQfnumber(res, "castsource");
7915 i_casttarget = PQfnumber(res, "casttarget");
7916 i_castfunc = PQfnumber(res, "castfunc");
7917 i_castcontext = PQfnumber(res, "castcontext");
7918 i_castmethod = PQfnumber(res, "castmethod");
7920 for (i = 0; i < ntups; i++)
7922 PQExpBufferData namebuf;
7923 TypeInfo *sTypeInfo;
7924 TypeInfo *tTypeInfo;
7926 castinfo[i].dobj.objType = DO_CAST;
7927 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7928 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7929 AssignDumpId(&castinfo[i].dobj);
7930 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7931 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7932 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7933 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7934 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7937 * Try to name cast as concatenation of typnames. This is only used
7938 * for purposes of sorting. If we fail to find either type, the name
7939 * will be an empty string.
7941 initPQExpBuffer(&namebuf);
7942 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7943 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7944 if (sTypeInfo && tTypeInfo)
7945 appendPQExpBuffer(&namebuf, "%s %s",
7946 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7947 castinfo[i].dobj.name = namebuf.data;
7949 /* Decide whether we want to dump it */
7950 selectDumpableCast(&(castinfo[i]), fout);
7952 /* Casts do not currently have ACLs. */
7953 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7958 destroyPQExpBuffer(query);
7964 get_language_name(Archive *fout, Oid langid)
7970 query = createPQExpBuffer();
7971 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7972 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7973 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7974 destroyPQExpBuffer(query);
7982 * get basic information about every transform in the system
7984 * numTransforms is set to the number of transforms read in
7987 getTransforms(Archive *fout, int *numTransforms)
7993 TransformInfo *transforminfo;
8001 /* Transforms didn't exist pre-9.5 */
8002 if (fout->remoteVersion < 90500)
8008 query = createPQExpBuffer();
8010 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8011 "trftype, trflang, trffromsql::oid, trftosql::oid "
8012 "FROM pg_transform "
8015 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8017 ntups = PQntuples(res);
8019 *numTransforms = ntups;
8021 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8023 i_tableoid = PQfnumber(res, "tableoid");
8024 i_oid = PQfnumber(res, "oid");
8025 i_trftype = PQfnumber(res, "trftype");
8026 i_trflang = PQfnumber(res, "trflang");
8027 i_trffromsql = PQfnumber(res, "trffromsql");
8028 i_trftosql = PQfnumber(res, "trftosql");
8030 for (i = 0; i < ntups; i++)
8032 PQExpBufferData namebuf;
8036 transforminfo[i].dobj.objType = DO_TRANSFORM;
8037 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8038 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8039 AssignDumpId(&transforminfo[i].dobj);
8040 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8041 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8042 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8043 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8046 * Try to name transform as concatenation of type and language name.
8047 * This is only used for purposes of sorting. If we fail to find
8048 * either, the name will be an empty string.
8050 initPQExpBuffer(&namebuf);
8051 typeInfo = findTypeByOid(transforminfo[i].trftype);
8052 lanname = get_language_name(fout, transforminfo[i].trflang);
8053 if (typeInfo && lanname)
8054 appendPQExpBuffer(&namebuf, "%s %s",
8055 typeInfo->dobj.name, lanname);
8056 transforminfo[i].dobj.name = namebuf.data;
8059 /* Decide whether we want to dump it */
8060 selectDumpableObject(&(transforminfo[i].dobj), fout);
8065 destroyPQExpBuffer(query);
8067 return transforminfo;
8072 * for each interesting table, read info about its attributes
8073 * (names, types, default values, CHECK constraints, etc)
8075 * This is implemented in a very inefficient way right now, looping
8076 * through the tblinfo and doing a join per table to find the attrs and their
8077 * types. However, because we want type names and so forth to be named
8078 * relative to the schema of each table, we couldn't do it in just one
8079 * query. (Maybe one query per schema?)
8084 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8086 DumpOptions *dopt = fout->dopt;
8089 PQExpBuffer q = createPQExpBuffer();
8094 int i_attstattarget;
8106 int i_attfdwoptions;
8107 int i_attmissingval;
8112 for (i = 0; i < numTables; i++)
8114 TableInfo *tbinfo = &tblinfo[i];
8116 /* Don't bother to collect info for sequences */
8117 if (tbinfo->relkind == RELKIND_SEQUENCE)
8120 /* Don't bother with uninteresting tables, either */
8121 if (!tbinfo->interesting)
8124 /* find all the user attributes and their types */
8127 * we must read the attribute names in attribute number order! because
8128 * we will use the attnum to index into the attnames array later.
8131 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8132 tbinfo->dobj.namespace->dobj.name,
8135 resetPQExpBuffer(q);
8137 appendPQExpBuffer(q,
8142 "a.attstattarget,\n"
8151 "pg_catalog.format_type(t.oid, a.atttypmod) AS atttypname,\n");
8153 if (fout->remoteVersion >= 110000)
8154 appendPQExpBuffer(q,
8155 "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8156 "THEN a.attmissingval ELSE null END AS attmissingval,\n");
8158 appendPQExpBuffer(q,
8159 "NULL AS attmissingval,\n");
8161 if (fout->remoteVersion >= 100000)
8162 appendPQExpBuffer(q,
8163 "a.attidentity,\n");
8165 appendPQExpBuffer(q,
8166 "'' AS attidentity,\n");
8168 if (fout->remoteVersion >= 90200)
8169 appendPQExpBuffer(q,
8170 "pg_catalog.array_to_string(ARRAY("
8171 "SELECT pg_catalog.quote_ident(option_name) || "
8172 "' ' || pg_catalog.quote_literal(option_value) "
8173 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8174 "ORDER BY option_name"
8175 "), E',\n ') AS attfdwoptions,\n");
8177 appendPQExpBuffer(q,
8178 "'' AS attfdwoptions,\n");
8180 if (fout->remoteVersion >= 90100)
8183 * Since we only want to dump COLLATE clauses for attributes whose
8184 * collation is different from their type's default, we use a CASE
8185 * here to suppress uninteresting attcollations cheaply.
8187 appendPQExpBuffer(q,
8188 "CASE WHEN a.attcollation <> t.typcollation "
8189 "THEN a.attcollation ELSE 0 END AS attcollation,\n");
8192 appendPQExpBuffer(q,
8193 "0 AS attcollation,\n");
8195 if (fout->remoteVersion >= 90000)
8196 appendPQExpBuffer(q,
8197 "array_to_string(a.attoptions, ', ') AS attoptions\n");
8199 appendPQExpBuffer(q,
8200 "'' AS attoptions\n");
8202 /* need left join here to not fail on dropped columns ... */
8203 appendPQExpBuffer(q,
8204 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8205 "ON a.atttypid = t.oid\n"
8206 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8207 "AND a.attnum > 0::pg_catalog.int2\n"
8208 "ORDER BY a.attnum",
8209 tbinfo->dobj.catId.oid);
8211 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8213 ntups = PQntuples(res);
8215 i_attnum = PQfnumber(res, "attnum");
8216 i_attname = PQfnumber(res, "attname");
8217 i_atttypname = PQfnumber(res, "atttypname");
8218 i_atttypmod = PQfnumber(res, "atttypmod");
8219 i_attstattarget = PQfnumber(res, "attstattarget");
8220 i_attstorage = PQfnumber(res, "attstorage");
8221 i_typstorage = PQfnumber(res, "typstorage");
8222 i_attnotnull = PQfnumber(res, "attnotnull");
8223 i_atthasdef = PQfnumber(res, "atthasdef");
8224 i_attidentity = PQfnumber(res, "attidentity");
8225 i_attisdropped = PQfnumber(res, "attisdropped");
8226 i_attlen = PQfnumber(res, "attlen");
8227 i_attalign = PQfnumber(res, "attalign");
8228 i_attislocal = PQfnumber(res, "attislocal");
8229 i_attoptions = PQfnumber(res, "attoptions");
8230 i_attcollation = PQfnumber(res, "attcollation");
8231 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8232 i_attmissingval = PQfnumber(res, "attmissingval");
8234 tbinfo->numatts = ntups;
8235 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8236 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8237 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8238 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8239 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8240 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8241 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8242 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8243 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8244 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8245 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8246 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8247 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8248 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8249 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8250 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8251 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8252 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8253 hasdefaults = false;
8255 for (j = 0; j < ntups; j++)
8257 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8259 "invalid column numbering in table \"%s\"\n",
8261 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8262 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8263 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8264 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8265 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8266 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8267 tbinfo->attidentity[j] = *(PQgetvalue(res, j, i_attidentity));
8268 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8269 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8270 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8271 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8272 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8273 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8274 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8275 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8276 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8277 tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8278 tbinfo->attrdefs[j] = NULL; /* fix below */
8279 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8281 /* these flags will be set in flagInhAttrs() */
8282 tbinfo->inhNotNull[j] = false;
8288 * Get info about column defaults
8292 AttrDefInfo *attrdefs;
8296 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8297 tbinfo->dobj.namespace->dobj.name,
8300 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8301 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8302 "FROM pg_catalog.pg_attrdef "
8303 "WHERE adrelid = '%u'::pg_catalog.oid",
8304 tbinfo->dobj.catId.oid);
8306 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8308 numDefaults = PQntuples(res);
8309 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8311 for (j = 0; j < numDefaults; j++)
8315 adnum = atoi(PQgetvalue(res, j, 2));
8317 if (adnum <= 0 || adnum > ntups)
8319 "invalid adnum value %d for table \"%s\"\n",
8320 adnum, tbinfo->dobj.name);
8323 * dropped columns shouldn't have defaults, but just in case,
8326 if (tbinfo->attisdropped[adnum - 1])
8329 attrdefs[j].dobj.objType = DO_ATTRDEF;
8330 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8331 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8332 AssignDumpId(&attrdefs[j].dobj);
8333 attrdefs[j].adtable = tbinfo;
8334 attrdefs[j].adnum = adnum;
8335 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8337 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8338 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8340 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8343 * Defaults on a VIEW must always be dumped as separate ALTER
8344 * TABLE commands. Defaults on regular tables are dumped as
8345 * part of the CREATE TABLE if possible, which it won't be if
8346 * the column is not going to be emitted explicitly.
8348 if (tbinfo->relkind == RELKIND_VIEW)
8350 attrdefs[j].separate = true;
8352 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8354 /* column will be suppressed, print default separately */
8355 attrdefs[j].separate = true;
8359 attrdefs[j].separate = false;
8362 * Mark the default as needing to appear before the table,
8363 * so that any dependencies it has must be emitted before
8364 * the CREATE TABLE. If this is not possible, we'll
8365 * change to "separate" mode while sorting dependencies.
8367 addObjectDependency(&tbinfo->dobj,
8368 attrdefs[j].dobj.dumpId);
8371 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8377 * Get info about table CHECK constraints
8379 if (tbinfo->ncheck > 0)
8381 ConstraintInfo *constrs;
8385 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8386 tbinfo->dobj.namespace->dobj.name,
8389 resetPQExpBuffer(q);
8390 if (fout->remoteVersion >= 90200)
8393 * convalidated is new in 9.2 (actually, it is there in 9.1,
8394 * but it wasn't ever false for check constraints until 9.2).
8396 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8397 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8398 "conislocal, convalidated "
8399 "FROM pg_catalog.pg_constraint "
8400 "WHERE conrelid = '%u'::pg_catalog.oid "
8401 " AND contype = 'c' "
8403 tbinfo->dobj.catId.oid);
8405 else if (fout->remoteVersion >= 80400)
8407 /* conislocal is new in 8.4 */
8408 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8409 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8410 "conislocal, true AS convalidated "
8411 "FROM pg_catalog.pg_constraint "
8412 "WHERE conrelid = '%u'::pg_catalog.oid "
8413 " AND contype = 'c' "
8415 tbinfo->dobj.catId.oid);
8419 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8420 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8421 "true AS conislocal, true AS convalidated "
8422 "FROM pg_catalog.pg_constraint "
8423 "WHERE conrelid = '%u'::pg_catalog.oid "
8424 " AND contype = 'c' "
8426 tbinfo->dobj.catId.oid);
8429 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8431 numConstrs = PQntuples(res);
8432 if (numConstrs != tbinfo->ncheck)
8434 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8435 "expected %d check constraints on table \"%s\" but found %d\n",
8437 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8438 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8442 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8443 tbinfo->checkexprs = constrs;
8445 for (j = 0; j < numConstrs; j++)
8447 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8449 constrs[j].dobj.objType = DO_CONSTRAINT;
8450 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8451 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8452 AssignDumpId(&constrs[j].dobj);
8453 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8454 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8455 constrs[j].contable = tbinfo;
8456 constrs[j].condomain = NULL;
8457 constrs[j].contype = 'c';
8458 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8459 constrs[j].confrelid = InvalidOid;
8460 constrs[j].conindex = 0;
8461 constrs[j].condeferrable = false;
8462 constrs[j].condeferred = false;
8463 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8466 * An unvalidated constraint needs to be dumped separately, so
8467 * that potentially-violating existing data is loaded before
8470 constrs[j].separate = !validated;
8472 constrs[j].dobj.dump = tbinfo->dobj.dump;
8475 * Mark the constraint as needing to appear before the table
8476 * --- this is so that any other dependencies of the
8477 * constraint will be emitted before we try to create the
8478 * table. If the constraint is to be dumped separately, it
8479 * will be dumped after data is loaded anyway, so don't do it.
8480 * (There's an automatic dependency in the opposite direction
8481 * anyway, so don't need to add one manually here.)
8483 if (!constrs[j].separate)
8484 addObjectDependency(&tbinfo->dobj,
8485 constrs[j].dobj.dumpId);
8488 * If the constraint is inherited, this will be detected later
8489 * (in pre-8.4 databases). We also detect later if the
8490 * constraint must be split out from the table definition.
8497 destroyPQExpBuffer(q);
8501 * Test whether a column should be printed as part of table's CREATE TABLE.
8502 * Column number is zero-based.
8504 * Normally this is always true, but it's false for dropped columns, as well
8505 * as those that were inherited without any local definition. (If we print
8506 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8507 * However, in binary_upgrade mode, we must print all such columns anyway and
8508 * fix the attislocal/attisdropped state later, so as to keep control of the
8509 * physical column order.
8511 * This function exists because there are scattered nonobvious places that
8512 * must be kept in sync with this decision.
8515 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8517 if (dopt->binary_upgrade)
8519 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8525 * read all text search parsers in the system catalogs and return them
8526 * in the TSParserInfo* structure
8528 * numTSParsers is set to the number of parsers read in
8531 getTSParsers(Archive *fout, int *numTSParsers)
8537 TSParserInfo *prsinfo;
8548 /* Before 8.3, there is no built-in text search support */
8549 if (fout->remoteVersion < 80300)
8555 query = createPQExpBuffer();
8558 * find all text search objects, including builtin ones; we filter out
8559 * system-defined objects at dump-out time.
8562 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8563 "prsstart::oid, prstoken::oid, "
8564 "prsend::oid, prsheadline::oid, prslextype::oid "
8565 "FROM pg_ts_parser");
8567 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8569 ntups = PQntuples(res);
8570 *numTSParsers = ntups;
8572 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8574 i_tableoid = PQfnumber(res, "tableoid");
8575 i_oid = PQfnumber(res, "oid");
8576 i_prsname = PQfnumber(res, "prsname");
8577 i_prsnamespace = PQfnumber(res, "prsnamespace");
8578 i_prsstart = PQfnumber(res, "prsstart");
8579 i_prstoken = PQfnumber(res, "prstoken");
8580 i_prsend = PQfnumber(res, "prsend");
8581 i_prsheadline = PQfnumber(res, "prsheadline");
8582 i_prslextype = PQfnumber(res, "prslextype");
8584 for (i = 0; i < ntups; i++)
8586 prsinfo[i].dobj.objType = DO_TSPARSER;
8587 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8588 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8589 AssignDumpId(&prsinfo[i].dobj);
8590 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8591 prsinfo[i].dobj.namespace =
8593 atooid(PQgetvalue(res, i, i_prsnamespace)));
8594 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8595 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8596 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8597 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8598 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8600 /* Decide whether we want to dump it */
8601 selectDumpableObject(&(prsinfo[i].dobj), fout);
8603 /* Text Search Parsers do not currently have ACLs. */
8604 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8609 destroyPQExpBuffer(query);
8615 * getTSDictionaries:
8616 * read all text search dictionaries in the system catalogs and return them
8617 * in the TSDictInfo* structure
8619 * numTSDicts is set to the number of dictionaries read in
8622 getTSDictionaries(Archive *fout, int *numTSDicts)
8628 TSDictInfo *dictinfo;
8632 int i_dictnamespace;
8635 int i_dictinitoption;
8637 /* Before 8.3, there is no built-in text search support */
8638 if (fout->remoteVersion < 80300)
8644 query = createPQExpBuffer();
8646 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8647 "dictnamespace, (%s dictowner) AS rolname, "
8648 "dicttemplate, dictinitoption "
8652 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8654 ntups = PQntuples(res);
8655 *numTSDicts = ntups;
8657 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8659 i_tableoid = PQfnumber(res, "tableoid");
8660 i_oid = PQfnumber(res, "oid");
8661 i_dictname = PQfnumber(res, "dictname");
8662 i_dictnamespace = PQfnumber(res, "dictnamespace");
8663 i_rolname = PQfnumber(res, "rolname");
8664 i_dictinitoption = PQfnumber(res, "dictinitoption");
8665 i_dicttemplate = PQfnumber(res, "dicttemplate");
8667 for (i = 0; i < ntups; i++)
8669 dictinfo[i].dobj.objType = DO_TSDICT;
8670 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8671 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8672 AssignDumpId(&dictinfo[i].dobj);
8673 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8674 dictinfo[i].dobj.namespace =
8676 atooid(PQgetvalue(res, i, i_dictnamespace)));
8677 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8678 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8679 if (PQgetisnull(res, i, i_dictinitoption))
8680 dictinfo[i].dictinitoption = NULL;
8682 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8684 /* Decide whether we want to dump it */
8685 selectDumpableObject(&(dictinfo[i].dobj), fout);
8687 /* Text Search Dictionaries do not currently have ACLs. */
8688 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8693 destroyPQExpBuffer(query);
8700 * read all text search templates in the system catalogs and return them
8701 * in the TSTemplateInfo* structure
8703 * numTSTemplates is set to the number of templates read in
8706 getTSTemplates(Archive *fout, int *numTSTemplates)
8712 TSTemplateInfo *tmplinfo;
8716 int i_tmplnamespace;
8720 /* Before 8.3, there is no built-in text search support */
8721 if (fout->remoteVersion < 80300)
8723 *numTSTemplates = 0;
8727 query = createPQExpBuffer();
8729 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8730 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8731 "FROM pg_ts_template");
8733 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8735 ntups = PQntuples(res);
8736 *numTSTemplates = ntups;
8738 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8740 i_tableoid = PQfnumber(res, "tableoid");
8741 i_oid = PQfnumber(res, "oid");
8742 i_tmplname = PQfnumber(res, "tmplname");
8743 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8744 i_tmplinit = PQfnumber(res, "tmplinit");
8745 i_tmpllexize = PQfnumber(res, "tmpllexize");
8747 for (i = 0; i < ntups; i++)
8749 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8750 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8751 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8752 AssignDumpId(&tmplinfo[i].dobj);
8753 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8754 tmplinfo[i].dobj.namespace =
8756 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8757 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8758 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8760 /* Decide whether we want to dump it */
8761 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8763 /* Text Search Templates do not currently have ACLs. */
8764 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8769 destroyPQExpBuffer(query);
8775 * getTSConfigurations:
8776 * read all text search configurations in the system catalogs and return
8777 * them in the TSConfigInfo* structure
8779 * numTSConfigs is set to the number of configurations read in
8782 getTSConfigurations(Archive *fout, int *numTSConfigs)
8788 TSConfigInfo *cfginfo;
8796 /* Before 8.3, there is no built-in text search support */
8797 if (fout->remoteVersion < 80300)
8803 query = createPQExpBuffer();
8805 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8806 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8807 "FROM pg_ts_config",
8810 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8812 ntups = PQntuples(res);
8813 *numTSConfigs = ntups;
8815 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8817 i_tableoid = PQfnumber(res, "tableoid");
8818 i_oid = PQfnumber(res, "oid");
8819 i_cfgname = PQfnumber(res, "cfgname");
8820 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8821 i_rolname = PQfnumber(res, "rolname");
8822 i_cfgparser = PQfnumber(res, "cfgparser");
8824 for (i = 0; i < ntups; i++)
8826 cfginfo[i].dobj.objType = DO_TSCONFIG;
8827 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8828 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8829 AssignDumpId(&cfginfo[i].dobj);
8830 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8831 cfginfo[i].dobj.namespace =
8833 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8834 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8835 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8837 /* Decide whether we want to dump it */
8838 selectDumpableObject(&(cfginfo[i].dobj), fout);
8840 /* Text Search Configurations do not currently have ACLs. */
8841 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8846 destroyPQExpBuffer(query);
8852 * getForeignDataWrappers:
8853 * read all foreign-data wrappers in the system catalogs and return
8854 * them in the FdwInfo* structure
8856 * numForeignDataWrappers is set to the number of fdws read in
8859 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8861 DumpOptions *dopt = fout->dopt;
8879 /* Before 8.4, there are no foreign-data wrappers */
8880 if (fout->remoteVersion < 80400)
8882 *numForeignDataWrappers = 0;
8886 query = createPQExpBuffer();
8888 if (fout->remoteVersion >= 90600)
8890 PQExpBuffer acl_subquery = createPQExpBuffer();
8891 PQExpBuffer racl_subquery = createPQExpBuffer();
8892 PQExpBuffer initacl_subquery = createPQExpBuffer();
8893 PQExpBuffer initracl_subquery = createPQExpBuffer();
8895 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8896 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8897 dopt->binary_upgrade);
8899 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8900 "(%s f.fdwowner) AS rolname, "
8901 "f.fdwhandler::pg_catalog.regproc, "
8902 "f.fdwvalidator::pg_catalog.regproc, "
8905 "%s AS initfdwacl, "
8906 "%s AS initrfdwacl, "
8907 "array_to_string(ARRAY("
8908 "SELECT quote_ident(option_name) || ' ' || "
8909 "quote_literal(option_value) "
8910 "FROM pg_options_to_table(f.fdwoptions) "
8911 "ORDER BY option_name"
8912 "), E',\n ') AS fdwoptions "
8913 "FROM pg_foreign_data_wrapper f "
8914 "LEFT JOIN pg_init_privs pip ON "
8915 "(f.oid = pip.objoid "
8916 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8917 "AND pip.objsubid = 0) ",
8920 racl_subquery->data,
8921 initacl_subquery->data,
8922 initracl_subquery->data);
8924 destroyPQExpBuffer(acl_subquery);
8925 destroyPQExpBuffer(racl_subquery);
8926 destroyPQExpBuffer(initacl_subquery);
8927 destroyPQExpBuffer(initracl_subquery);
8929 else if (fout->remoteVersion >= 90100)
8931 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8932 "(%s fdwowner) AS rolname, "
8933 "fdwhandler::pg_catalog.regproc, "
8934 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8936 "NULL as initfdwacl, NULL AS initrfdwacl, "
8937 "array_to_string(ARRAY("
8938 "SELECT quote_ident(option_name) || ' ' || "
8939 "quote_literal(option_value) "
8940 "FROM pg_options_to_table(fdwoptions) "
8941 "ORDER BY option_name"
8942 "), E',\n ') AS fdwoptions "
8943 "FROM pg_foreign_data_wrapper",
8948 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8949 "(%s fdwowner) AS rolname, "
8950 "'-' AS fdwhandler, "
8951 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8953 "NULL as initfdwacl, NULL AS initrfdwacl, "
8954 "array_to_string(ARRAY("
8955 "SELECT quote_ident(option_name) || ' ' || "
8956 "quote_literal(option_value) "
8957 "FROM pg_options_to_table(fdwoptions) "
8958 "ORDER BY option_name"
8959 "), E',\n ') AS fdwoptions "
8960 "FROM pg_foreign_data_wrapper",
8964 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8966 ntups = PQntuples(res);
8967 *numForeignDataWrappers = ntups;
8969 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
8971 i_tableoid = PQfnumber(res, "tableoid");
8972 i_oid = PQfnumber(res, "oid");
8973 i_fdwname = PQfnumber(res, "fdwname");
8974 i_rolname = PQfnumber(res, "rolname");
8975 i_fdwhandler = PQfnumber(res, "fdwhandler");
8976 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
8977 i_fdwacl = PQfnumber(res, "fdwacl");
8978 i_rfdwacl = PQfnumber(res, "rfdwacl");
8979 i_initfdwacl = PQfnumber(res, "initfdwacl");
8980 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
8981 i_fdwoptions = PQfnumber(res, "fdwoptions");
8983 for (i = 0; i < ntups; i++)
8985 fdwinfo[i].dobj.objType = DO_FDW;
8986 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8987 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8988 AssignDumpId(&fdwinfo[i].dobj);
8989 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
8990 fdwinfo[i].dobj.namespace = NULL;
8991 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8992 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
8993 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
8994 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
8995 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
8996 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
8997 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
8998 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9000 /* Decide whether we want to dump it */
9001 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9003 /* Do not try to dump ACL if no ACL exists. */
9004 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9005 PQgetisnull(res, i, i_initfdwacl) &&
9006 PQgetisnull(res, i, i_initrfdwacl))
9007 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9012 destroyPQExpBuffer(query);
9018 * getForeignServers:
9019 * read all foreign servers in the system catalogs and return
9020 * them in the ForeignServerInfo * structure
9022 * numForeignServers is set to the number of servers read in
9025 getForeignServers(Archive *fout, int *numForeignServers)
9027 DumpOptions *dopt = fout->dopt;
9032 ForeignServerInfo *srvinfo;
9046 /* Before 8.4, there are no foreign servers */
9047 if (fout->remoteVersion < 80400)
9049 *numForeignServers = 0;
9053 query = createPQExpBuffer();
9055 if (fout->remoteVersion >= 90600)
9057 PQExpBuffer acl_subquery = createPQExpBuffer();
9058 PQExpBuffer racl_subquery = createPQExpBuffer();
9059 PQExpBuffer initacl_subquery = createPQExpBuffer();
9060 PQExpBuffer initracl_subquery = createPQExpBuffer();
9062 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9063 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9064 dopt->binary_upgrade);
9066 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9067 "(%s f.srvowner) AS rolname, "
9068 "f.srvfdw, f.srvtype, f.srvversion, "
9071 "%s AS initsrvacl, "
9072 "%s AS initrsrvacl, "
9073 "array_to_string(ARRAY("
9074 "SELECT quote_ident(option_name) || ' ' || "
9075 "quote_literal(option_value) "
9076 "FROM pg_options_to_table(f.srvoptions) "
9077 "ORDER BY option_name"
9078 "), E',\n ') AS srvoptions "
9079 "FROM pg_foreign_server f "
9080 "LEFT JOIN pg_init_privs pip "
9081 "ON (f.oid = pip.objoid "
9082 "AND pip.classoid = 'pg_foreign_server'::regclass "
9083 "AND pip.objsubid = 0) ",
9086 racl_subquery->data,
9087 initacl_subquery->data,
9088 initracl_subquery->data);
9090 destroyPQExpBuffer(acl_subquery);
9091 destroyPQExpBuffer(racl_subquery);
9092 destroyPQExpBuffer(initacl_subquery);
9093 destroyPQExpBuffer(initracl_subquery);
9097 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9098 "(%s srvowner) AS rolname, "
9099 "srvfdw, srvtype, srvversion, srvacl, "
9101 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9102 "array_to_string(ARRAY("
9103 "SELECT quote_ident(option_name) || ' ' || "
9104 "quote_literal(option_value) "
9105 "FROM pg_options_to_table(srvoptions) "
9106 "ORDER BY option_name"
9107 "), E',\n ') AS srvoptions "
9108 "FROM pg_foreign_server",
9112 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9114 ntups = PQntuples(res);
9115 *numForeignServers = ntups;
9117 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9119 i_tableoid = PQfnumber(res, "tableoid");
9120 i_oid = PQfnumber(res, "oid");
9121 i_srvname = PQfnumber(res, "srvname");
9122 i_rolname = PQfnumber(res, "rolname");
9123 i_srvfdw = PQfnumber(res, "srvfdw");
9124 i_srvtype = PQfnumber(res, "srvtype");
9125 i_srvversion = PQfnumber(res, "srvversion");
9126 i_srvacl = PQfnumber(res, "srvacl");
9127 i_rsrvacl = PQfnumber(res, "rsrvacl");
9128 i_initsrvacl = PQfnumber(res, "initsrvacl");
9129 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9130 i_srvoptions = PQfnumber(res, "srvoptions");
9132 for (i = 0; i < ntups; i++)
9134 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9135 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9136 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9137 AssignDumpId(&srvinfo[i].dobj);
9138 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9139 srvinfo[i].dobj.namespace = NULL;
9140 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9141 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9142 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9143 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9144 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9145 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9146 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9147 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9148 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9150 /* Decide whether we want to dump it */
9151 selectDumpableObject(&(srvinfo[i].dobj), fout);
9153 /* Do not try to dump ACL if no ACL exists. */
9154 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9155 PQgetisnull(res, i, i_initsrvacl) &&
9156 PQgetisnull(res, i, i_initrsrvacl))
9157 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9162 destroyPQExpBuffer(query);
9169 * read all default ACL information in the system catalogs and return
9170 * them in the DefaultACLInfo structure
9172 * numDefaultACLs is set to the number of ACLs read in
9175 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9177 DumpOptions *dopt = fout->dopt;
9178 DefaultACLInfo *daclinfo;
9184 int i_defaclnamespace;
9185 int i_defaclobjtype;
9188 int i_initdefaclacl;
9189 int i_initrdefaclacl;
9193 if (fout->remoteVersion < 90000)
9195 *numDefaultACLs = 0;
9199 query = createPQExpBuffer();
9201 if (fout->remoteVersion >= 90600)
9203 PQExpBuffer acl_subquery = createPQExpBuffer();
9204 PQExpBuffer racl_subquery = createPQExpBuffer();
9205 PQExpBuffer initacl_subquery = createPQExpBuffer();
9206 PQExpBuffer initracl_subquery = createPQExpBuffer();
9208 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9209 initracl_subquery, "defaclacl", "defaclrole",
9210 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9211 dopt->binary_upgrade);
9213 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9214 "(%s d.defaclrole) AS defaclrole, "
9215 "d.defaclnamespace, "
9218 "%s AS rdefaclacl, "
9219 "%s AS initdefaclacl, "
9220 "%s AS initrdefaclacl "
9221 "FROM pg_default_acl d "
9222 "LEFT JOIN pg_init_privs pip ON "
9223 "(d.oid = pip.objoid "
9224 "AND pip.classoid = 'pg_default_acl'::regclass "
9225 "AND pip.objsubid = 0) ",
9228 racl_subquery->data,
9229 initacl_subquery->data,
9230 initracl_subquery->data);
9234 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9235 "(%s defaclrole) AS defaclrole, "
9239 "NULL AS rdefaclacl, "
9240 "NULL AS initdefaclacl, "
9241 "NULL AS initrdefaclacl "
9242 "FROM pg_default_acl",
9246 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9248 ntups = PQntuples(res);
9249 *numDefaultACLs = ntups;
9251 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9253 i_oid = PQfnumber(res, "oid");
9254 i_tableoid = PQfnumber(res, "tableoid");
9255 i_defaclrole = PQfnumber(res, "defaclrole");
9256 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9257 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9258 i_defaclacl = PQfnumber(res, "defaclacl");
9259 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9260 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9261 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9263 for (i = 0; i < ntups; i++)
9265 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9267 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9268 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9269 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9270 AssignDumpId(&daclinfo[i].dobj);
9271 /* cheesy ... is it worth coming up with a better object name? */
9272 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9274 if (nspid != InvalidOid)
9275 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9277 daclinfo[i].dobj.namespace = NULL;
9279 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9280 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9281 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9282 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9283 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9284 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9286 /* Decide whether we want to dump it */
9287 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9292 destroyPQExpBuffer(query);
9300 * This routine is used to dump any comments associated with the
9301 * object handed to this routine. The routine takes the object type
9302 * and object name (ready to print, except for schema decoration), plus
9303 * the namespace and owner of the object (for labeling the ArchiveEntry),
9304 * plus catalog ID and subid which are the lookup key for pg_description,
9305 * plus the dump ID for the object (for setting a dependency).
9306 * If a matching pg_description entry is found, it is dumped.
9308 * Note: in some cases, such as comments for triggers and rules, the "type"
9309 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9310 * but it doesn't seem worth complicating the API for all callers to make
9313 * Note: although this routine takes a dumpId for dependency purposes,
9314 * that purpose is just to mark the dependency in the emitted dump file
9315 * for possible future use by pg_restore. We do NOT use it for determining
9316 * ordering of the comment in the dump file, because this routine is called
9317 * after dependency sorting occurs. This routine should be called just after
9318 * calling ArchiveEntry() for the specified object.
9321 dumpComment(Archive *fout, const char *type, const char *name,
9322 const char *namespace, const char *owner,
9323 CatalogId catalogId, int subid, DumpId dumpId)
9325 DumpOptions *dopt = fout->dopt;
9326 CommentItem *comments;
9329 /* do nothing, if --no-comments is supplied */
9330 if (dopt->no_comments)
9333 /* Comments are schema not data ... except blob comments are data */
9334 if (strcmp(type, "LARGE OBJECT") != 0)
9341 /* We do dump blob comments in binary-upgrade mode */
9342 if (dopt->schemaOnly && !dopt->binary_upgrade)
9346 /* Search for comments associated with catalogId, using table */
9347 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9350 /* Is there one matching the subid? */
9351 while (ncomments > 0)
9353 if (comments->objsubid == subid)
9359 /* If a comment exists, build COMMENT ON statement */
9362 PQExpBuffer query = createPQExpBuffer();
9363 PQExpBuffer tag = createPQExpBuffer();
9365 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9366 if (namespace && *namespace)
9367 appendPQExpBuffer(query, "%s.", fmtId(namespace));
9368 appendPQExpBuffer(query, "%s IS ", name);
9369 appendStringLiteralAH(query, comments->descr, fout);
9370 appendPQExpBufferStr(query, ";\n");
9372 appendPQExpBuffer(tag, "%s %s", type, name);
9375 * We mark comments as SECTION_NONE because they really belong in the
9376 * same section as their parent, whether that is pre-data or
9379 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9380 tag->data, namespace, NULL, owner,
9381 "COMMENT", SECTION_NONE,
9382 query->data, "", NULL,
9386 destroyPQExpBuffer(query);
9387 destroyPQExpBuffer(tag);
9392 * dumpTableComment --
9394 * As above, but dump comments for both the specified table (or view)
9398 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9399 const char *reltypename)
9401 DumpOptions *dopt = fout->dopt;
9402 CommentItem *comments;
9407 /* do nothing, if --no-comments is supplied */
9408 if (dopt->no_comments)
9411 /* Comments are SCHEMA not data */
9415 /* Search for comments associated with relation, using table */
9416 ncomments = findComments(fout,
9417 tbinfo->dobj.catId.tableoid,
9418 tbinfo->dobj.catId.oid,
9421 /* If comments exist, build COMMENT ON statements */
9425 query = createPQExpBuffer();
9426 tag = createPQExpBuffer();
9428 while (ncomments > 0)
9430 const char *descr = comments->descr;
9431 int objsubid = comments->objsubid;
9435 resetPQExpBuffer(tag);
9436 appendPQExpBuffer(tag, "%s %s", reltypename,
9437 fmtId(tbinfo->dobj.name));
9439 resetPQExpBuffer(query);
9440 appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9441 fmtQualifiedDumpable(tbinfo));
9442 appendStringLiteralAH(query, descr, fout);
9443 appendPQExpBufferStr(query, ";\n");
9445 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9447 tbinfo->dobj.namespace->dobj.name,
9448 NULL, tbinfo->rolname,
9449 "COMMENT", SECTION_NONE,
9450 query->data, "", NULL,
9451 &(tbinfo->dobj.dumpId), 1,
9454 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9456 resetPQExpBuffer(tag);
9457 appendPQExpBuffer(tag, "COLUMN %s.",
9458 fmtId(tbinfo->dobj.name));
9459 appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9461 resetPQExpBuffer(query);
9462 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9463 fmtQualifiedDumpable(tbinfo));
9464 appendPQExpBuffer(query, "%s IS ",
9465 fmtId(tbinfo->attnames[objsubid - 1]));
9466 appendStringLiteralAH(query, descr, fout);
9467 appendPQExpBufferStr(query, ";\n");
9469 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9471 tbinfo->dobj.namespace->dobj.name,
9472 NULL, tbinfo->rolname,
9473 "COMMENT", SECTION_NONE,
9474 query->data, "", NULL,
9475 &(tbinfo->dobj.dumpId), 1,
9483 destroyPQExpBuffer(query);
9484 destroyPQExpBuffer(tag);
9490 * Find the comment(s), if any, associated with the given object. All the
9491 * objsubid values associated with the given classoid/objoid are found with
9495 findComments(Archive *fout, Oid classoid, Oid objoid,
9496 CommentItem **items)
9498 /* static storage for table of comments */
9499 static CommentItem *comments = NULL;
9500 static int ncomments = -1;
9502 CommentItem *middle = NULL;
9507 /* Get comments if we didn't already */
9509 ncomments = collectComments(fout, &comments);
9512 * Do binary search to find some item matching the object.
9515 high = &comments[ncomments - 1];
9518 middle = low + (high - low) / 2;
9520 if (classoid < middle->classoid)
9522 else if (classoid > middle->classoid)
9524 else if (objoid < middle->objoid)
9526 else if (objoid > middle->objoid)
9529 break; /* found a match */
9532 if (low > high) /* no matches */
9539 * Now determine how many items match the object. The search loop
9540 * invariant still holds: only items between low and high inclusive could
9544 while (middle > low)
9546 if (classoid != middle[-1].classoid ||
9547 objoid != middle[-1].objoid)
9556 while (middle <= high)
9558 if (classoid != middle->classoid ||
9559 objoid != middle->objoid)
9569 * collectComments --
9571 * Construct a table of all comments available for database objects.
9572 * We used to do per-object queries for the comments, but it's much faster
9573 * to pull them all over at once, and on most databases the memory cost
9576 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9579 collectComments(Archive *fout, CommentItem **items)
9589 CommentItem *comments;
9591 query = createPQExpBuffer();
9593 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9594 "FROM pg_catalog.pg_description "
9595 "ORDER BY classoid, objoid, objsubid");
9597 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9599 /* Construct lookup table containing OIDs in numeric form */
9601 i_description = PQfnumber(res, "description");
9602 i_classoid = PQfnumber(res, "classoid");
9603 i_objoid = PQfnumber(res, "objoid");
9604 i_objsubid = PQfnumber(res, "objsubid");
9606 ntups = PQntuples(res);
9608 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9610 for (i = 0; i < ntups; i++)
9612 comments[i].descr = PQgetvalue(res, i, i_description);
9613 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9614 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9615 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9618 /* Do NOT free the PGresult since we are keeping pointers into it */
9619 destroyPQExpBuffer(query);
9626 * dumpDumpableObject
9628 * This routine and its subsidiaries are responsible for creating
9629 * ArchiveEntries (TOC objects) for each object to be dumped.
9632 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9634 switch (dobj->objType)
9637 dumpNamespace(fout, (NamespaceInfo *) dobj);
9640 dumpExtension(fout, (ExtensionInfo *) dobj);
9643 dumpType(fout, (TypeInfo *) dobj);
9646 dumpShellType(fout, (ShellTypeInfo *) dobj);
9649 dumpFunc(fout, (FuncInfo *) dobj);
9652 dumpAgg(fout, (AggInfo *) dobj);
9655 dumpOpr(fout, (OprInfo *) dobj);
9657 case DO_ACCESS_METHOD:
9658 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9661 dumpOpclass(fout, (OpclassInfo *) dobj);
9664 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9667 dumpCollation(fout, (CollInfo *) dobj);
9670 dumpConversion(fout, (ConvInfo *) dobj);
9673 dumpTable(fout, (TableInfo *) dobj);
9676 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9679 dumpIndex(fout, (IndxInfo *) dobj);
9681 case DO_INDEX_ATTACH:
9682 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9685 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9687 case DO_REFRESH_MATVIEW:
9688 refreshMatViewData(fout, (TableDataInfo *) dobj);
9691 dumpRule(fout, (RuleInfo *) dobj);
9694 dumpTrigger(fout, (TriggerInfo *) dobj);
9696 case DO_EVENT_TRIGGER:
9697 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9700 dumpConstraint(fout, (ConstraintInfo *) dobj);
9702 case DO_FK_CONSTRAINT:
9703 dumpConstraint(fout, (ConstraintInfo *) dobj);
9706 dumpProcLang(fout, (ProcLangInfo *) dobj);
9709 dumpCast(fout, (CastInfo *) dobj);
9712 dumpTransform(fout, (TransformInfo *) dobj);
9714 case DO_SEQUENCE_SET:
9715 dumpSequenceData(fout, (TableDataInfo *) dobj);
9718 dumpTableData(fout, (TableDataInfo *) dobj);
9721 /* table rowtypes and array types are never dumped separately */
9724 dumpTSParser(fout, (TSParserInfo *) dobj);
9727 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9730 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9733 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9736 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9738 case DO_FOREIGN_SERVER:
9739 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9741 case DO_DEFAULT_ACL:
9742 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9745 dumpBlob(fout, (BlobInfo *) dobj);
9748 if (dobj->dump & DUMP_COMPONENT_DATA)
9752 te = ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9753 dobj->name, NULL, NULL, "",
9754 "BLOBS", SECTION_DATA,
9760 * Set the TocEntry's dataLength in case we are doing a
9761 * parallel dump and want to order dump jobs by table size.
9762 * (We need some size estimate for every TocEntry with a
9763 * DataDumper function.) We don't currently have any cheap
9764 * way to estimate the size of blobs, but it doesn't matter;
9765 * let's just set the size to a large value so parallel dumps
9766 * will launch this job first. If there's lots of blobs, we
9767 * win, and if there aren't, we don't lose much. (If you want
9768 * to improve on this, really what you should be thinking
9769 * about is allowing blob dumping to be parallelized, not just
9770 * getting a smarter estimate for the single TOC entry.)
9772 te->dataLength = MaxBlockNumber;
9776 dumpPolicy(fout, (PolicyInfo *) dobj);
9778 case DO_PUBLICATION:
9779 dumpPublication(fout, (PublicationInfo *) dobj);
9781 case DO_PUBLICATION_REL:
9782 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9784 case DO_SUBSCRIPTION:
9785 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9787 case DO_PRE_DATA_BOUNDARY:
9788 case DO_POST_DATA_BOUNDARY:
9789 /* never dumped, nothing to do */
9796 * writes out to fout the queries to recreate a user-defined namespace
9799 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9801 DumpOptions *dopt = fout->dopt;
9806 /* Skip if not to be dumped */
9807 if (!nspinfo->dobj.dump || dopt->dataOnly)
9810 q = createPQExpBuffer();
9811 delq = createPQExpBuffer();
9813 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9815 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9817 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9819 if (dopt->binary_upgrade)
9820 binary_upgrade_extension_member(q, &nspinfo->dobj,
9821 "SCHEMA", qnspname, NULL);
9823 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9824 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9828 "SCHEMA", SECTION_PRE_DATA,
9829 q->data, delq->data, NULL,
9833 /* Dump Schema Comments and Security Labels */
9834 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9835 dumpComment(fout, "SCHEMA", qnspname,
9836 NULL, nspinfo->rolname,
9837 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9839 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9840 dumpSecLabel(fout, "SCHEMA", qnspname,
9841 NULL, nspinfo->rolname,
9842 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9844 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9845 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9846 qnspname, NULL, NULL,
9847 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9848 nspinfo->initnspacl, nspinfo->initrnspacl);
9852 destroyPQExpBuffer(q);
9853 destroyPQExpBuffer(delq);
9858 * writes out to fout the queries to recreate an extension
9861 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9863 DumpOptions *dopt = fout->dopt;
9868 /* Skip if not to be dumped */
9869 if (!extinfo->dobj.dump || dopt->dataOnly)
9872 q = createPQExpBuffer();
9873 delq = createPQExpBuffer();
9875 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9877 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9879 if (!dopt->binary_upgrade)
9882 * In a regular dump, we simply create the extension, intentionally
9883 * not specifying a version, so that the destination installation's
9884 * default version is used.
9886 * Use of IF NOT EXISTS here is unlike our behavior for other object
9887 * types; but there are various scenarios in which it's convenient to
9888 * manually create the desired extension before restoring, so we
9889 * prefer to allow it to exist already.
9891 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9892 qextname, fmtId(extinfo->namespace));
9897 * In binary-upgrade mode, it's critical to reproduce the state of the
9898 * database exactly, so our procedure is to create an empty extension,
9899 * restore all the contained objects normally, and add them to the
9900 * extension one by one. This function performs just the first of
9901 * those steps. binary_upgrade_extension_member() takes care of
9902 * adding member objects as they're created.
9907 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9910 * We unconditionally create the extension, so we must drop it if it
9911 * exists. This could happen if the user deleted 'plpgsql' and then
9912 * readded it, causing its oid to be greater than g_last_builtin_oid.
9914 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9916 appendPQExpBufferStr(q,
9917 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9918 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9919 appendPQExpBufferStr(q, ", ");
9920 appendStringLiteralAH(q, extinfo->namespace, fout);
9921 appendPQExpBufferStr(q, ", ");
9922 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9923 appendStringLiteralAH(q, extinfo->extversion, fout);
9924 appendPQExpBufferStr(q, ", ");
9927 * Note that we're pushing extconfig (an OID array) back into
9928 * pg_extension exactly as-is. This is OK because pg_class OIDs are
9929 * preserved in binary upgrade.
9931 if (strlen(extinfo->extconfig) > 2)
9932 appendStringLiteralAH(q, extinfo->extconfig, fout);
9934 appendPQExpBufferStr(q, "NULL");
9935 appendPQExpBufferStr(q, ", ");
9936 if (strlen(extinfo->extcondition) > 2)
9937 appendStringLiteralAH(q, extinfo->extcondition, fout);
9939 appendPQExpBufferStr(q, "NULL");
9940 appendPQExpBufferStr(q, ", ");
9941 appendPQExpBufferStr(q, "ARRAY[");
9943 for (i = 0; i < extinfo->dobj.nDeps; i++)
9945 DumpableObject *extobj;
9947 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9948 if (extobj && extobj->objType == DO_EXTENSION)
9951 appendPQExpBufferChar(q, ',');
9952 appendStringLiteralAH(q, extobj->name, fout);
9955 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
9956 appendPQExpBufferStr(q, ");\n");
9959 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9960 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
9964 "EXTENSION", SECTION_PRE_DATA,
9965 q->data, delq->data, NULL,
9969 /* Dump Extension Comments and Security Labels */
9970 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9971 dumpComment(fout, "EXTENSION", qextname,
9973 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9975 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9976 dumpSecLabel(fout, "EXTENSION", qextname,
9978 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9982 destroyPQExpBuffer(q);
9983 destroyPQExpBuffer(delq);
9988 * writes out to fout the queries to recreate a user-defined type
9991 dumpType(Archive *fout, TypeInfo *tyinfo)
9993 DumpOptions *dopt = fout->dopt;
9995 /* Skip if not to be dumped */
9996 if (!tyinfo->dobj.dump || dopt->dataOnly)
9999 /* Dump out in proper style */
10000 if (tyinfo->typtype == TYPTYPE_BASE)
10001 dumpBaseType(fout, tyinfo);
10002 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10003 dumpDomain(fout, tyinfo);
10004 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10005 dumpCompositeType(fout, tyinfo);
10006 else if (tyinfo->typtype == TYPTYPE_ENUM)
10007 dumpEnumType(fout, tyinfo);
10008 else if (tyinfo->typtype == TYPTYPE_RANGE)
10009 dumpRangeType(fout, tyinfo);
10010 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10011 dumpUndefinedType(fout, tyinfo);
10013 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10014 tyinfo->dobj.name);
10019 * writes out to fout the queries to recreate a user-defined enum type
10022 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10024 DumpOptions *dopt = fout->dopt;
10025 PQExpBuffer q = createPQExpBuffer();
10026 PQExpBuffer delq = createPQExpBuffer();
10027 PQExpBuffer query = createPQExpBuffer();
10036 if (fout->remoteVersion >= 90100)
10037 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10038 "FROM pg_catalog.pg_enum "
10039 "WHERE enumtypid = '%u'"
10040 "ORDER BY enumsortorder",
10041 tyinfo->dobj.catId.oid);
10043 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10044 "FROM pg_catalog.pg_enum "
10045 "WHERE enumtypid = '%u'"
10047 tyinfo->dobj.catId.oid);
10049 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10051 num = PQntuples(res);
10053 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10054 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10057 * CASCADE shouldn't be required here as for normal types since the I/O
10058 * functions are generic and do not get dropped.
10060 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10062 if (dopt->binary_upgrade)
10063 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10064 tyinfo->dobj.catId.oid,
10067 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10070 if (!dopt->binary_upgrade)
10072 /* Labels with server-assigned oids */
10073 for (i = 0; i < num; i++)
10075 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10077 appendPQExpBufferChar(q, ',');
10078 appendPQExpBufferStr(q, "\n ");
10079 appendStringLiteralAH(q, label, fout);
10083 appendPQExpBufferStr(q, "\n);\n");
10085 if (dopt->binary_upgrade)
10087 /* Labels with dump-assigned (preserved) oids */
10088 for (i = 0; i < num; i++)
10090 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10091 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10094 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10095 appendPQExpBuffer(q,
10096 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10098 appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10099 appendStringLiteralAH(q, label, fout);
10100 appendPQExpBufferStr(q, ";\n\n");
10104 if (dopt->binary_upgrade)
10105 binary_upgrade_extension_member(q, &tyinfo->dobj,
10107 tyinfo->dobj.namespace->dobj.name);
10109 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10110 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10112 tyinfo->dobj.namespace->dobj.name,
10115 "TYPE", SECTION_PRE_DATA,
10116 q->data, delq->data, NULL,
10120 /* Dump Type Comments and Security Labels */
10121 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10122 dumpComment(fout, "TYPE", qtypname,
10123 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10124 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10126 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10127 dumpSecLabel(fout, "TYPE", qtypname,
10128 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10129 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10131 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10132 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10134 tyinfo->dobj.namespace->dobj.name,
10135 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10136 tyinfo->inittypacl, tyinfo->initrtypacl);
10139 destroyPQExpBuffer(q);
10140 destroyPQExpBuffer(delq);
10141 destroyPQExpBuffer(query);
10148 * writes out to fout the queries to recreate a user-defined range type
10151 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10153 DumpOptions *dopt = fout->dopt;
10154 PQExpBuffer q = createPQExpBuffer();
10155 PQExpBuffer delq = createPQExpBuffer();
10156 PQExpBuffer query = createPQExpBuffer();
10163 appendPQExpBuffer(query,
10164 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10165 "opc.opcname AS opcname, "
10166 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10167 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10169 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10170 " ELSE rngcollation END AS collation, "
10171 "rngcanonical, rngsubdiff "
10172 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10173 " pg_catalog.pg_opclass opc "
10174 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10176 tyinfo->dobj.catId.oid);
10178 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10180 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10181 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10184 * CASCADE shouldn't be required here as for normal types since the I/O
10185 * functions are generic and do not get dropped.
10187 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10189 if (dopt->binary_upgrade)
10190 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10191 tyinfo->dobj.catId.oid,
10194 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10197 appendPQExpBuffer(q, "\n subtype = %s",
10198 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10200 /* print subtype_opclass only if not default for subtype */
10201 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10203 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10204 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10206 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10208 appendPQExpBufferStr(q, fmtId(opcname));
10211 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10212 if (OidIsValid(collationOid))
10214 CollInfo *coll = findCollationByOid(collationOid);
10217 appendPQExpBuffer(q, ",\n collation = %s",
10218 fmtQualifiedDumpable(coll));
10221 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10222 if (strcmp(procname, "-") != 0)
10223 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10225 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10226 if (strcmp(procname, "-") != 0)
10227 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10229 appendPQExpBufferStr(q, "\n);\n");
10231 if (dopt->binary_upgrade)
10232 binary_upgrade_extension_member(q, &tyinfo->dobj,
10234 tyinfo->dobj.namespace->dobj.name);
10236 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10237 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10239 tyinfo->dobj.namespace->dobj.name,
10242 "TYPE", SECTION_PRE_DATA,
10243 q->data, delq->data, NULL,
10247 /* Dump Type Comments and Security Labels */
10248 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10249 dumpComment(fout, "TYPE", qtypname,
10250 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10251 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10253 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10254 dumpSecLabel(fout, "TYPE", qtypname,
10255 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10256 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10258 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10259 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10261 tyinfo->dobj.namespace->dobj.name,
10262 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10263 tyinfo->inittypacl, tyinfo->initrtypacl);
10266 destroyPQExpBuffer(q);
10267 destroyPQExpBuffer(delq);
10268 destroyPQExpBuffer(query);
10274 * dumpUndefinedType
10275 * writes out to fout the queries to recreate a !typisdefined type
10277 * This is a shell type, but we use different terminology to distinguish
10278 * this case from where we have to emit a shell type definition to break
10279 * circular dependencies. An undefined type shouldn't ever have anything
10283 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10285 DumpOptions *dopt = fout->dopt;
10286 PQExpBuffer q = createPQExpBuffer();
10287 PQExpBuffer delq = createPQExpBuffer();
10291 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10292 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10294 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10296 if (dopt->binary_upgrade)
10297 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10298 tyinfo->dobj.catId.oid,
10301 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10304 if (dopt->binary_upgrade)
10305 binary_upgrade_extension_member(q, &tyinfo->dobj,
10307 tyinfo->dobj.namespace->dobj.name);
10309 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10310 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10312 tyinfo->dobj.namespace->dobj.name,
10315 "TYPE", SECTION_PRE_DATA,
10316 q->data, delq->data, NULL,
10320 /* Dump Type Comments and Security Labels */
10321 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10322 dumpComment(fout, "TYPE", qtypname,
10323 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10324 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10326 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10327 dumpSecLabel(fout, "TYPE", qtypname,
10328 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10329 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10331 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10332 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10334 tyinfo->dobj.namespace->dobj.name,
10335 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10336 tyinfo->inittypacl, tyinfo->initrtypacl);
10338 destroyPQExpBuffer(q);
10339 destroyPQExpBuffer(delq);
10346 * writes out to fout the queries to recreate a user-defined base type
10349 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10351 DumpOptions *dopt = fout->dopt;
10352 PQExpBuffer q = createPQExpBuffer();
10353 PQExpBuffer delq = createPQExpBuffer();
10354 PQExpBuffer query = createPQExpBuffer();
10372 char *typispreferred;
10377 char *typcollatable;
10379 bool typdefault_is_literal = false;
10381 /* Fetch type-specific details */
10382 if (fout->remoteVersion >= 90100)
10384 appendPQExpBuffer(query, "SELECT typlen, "
10385 "typinput, typoutput, typreceive, typsend, "
10386 "typmodin, typmodout, typanalyze, "
10387 "typreceive::pg_catalog.oid AS typreceiveoid, "
10388 "typsend::pg_catalog.oid AS typsendoid, "
10389 "typmodin::pg_catalog.oid AS typmodinoid, "
10390 "typmodout::pg_catalog.oid AS typmodoutoid, "
10391 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10392 "typcategory, typispreferred, "
10393 "typdelim, typbyval, typalign, typstorage, "
10394 "(typcollation <> 0) AS typcollatable, "
10395 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10396 "FROM pg_catalog.pg_type "
10397 "WHERE oid = '%u'::pg_catalog.oid",
10398 tyinfo->dobj.catId.oid);
10400 else if (fout->remoteVersion >= 80400)
10402 appendPQExpBuffer(query, "SELECT typlen, "
10403 "typinput, typoutput, typreceive, typsend, "
10404 "typmodin, typmodout, typanalyze, "
10405 "typreceive::pg_catalog.oid AS typreceiveoid, "
10406 "typsend::pg_catalog.oid AS typsendoid, "
10407 "typmodin::pg_catalog.oid AS typmodinoid, "
10408 "typmodout::pg_catalog.oid AS typmodoutoid, "
10409 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10410 "typcategory, typispreferred, "
10411 "typdelim, typbyval, typalign, typstorage, "
10412 "false AS typcollatable, "
10413 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10414 "FROM pg_catalog.pg_type "
10415 "WHERE oid = '%u'::pg_catalog.oid",
10416 tyinfo->dobj.catId.oid);
10418 else if (fout->remoteVersion >= 80300)
10420 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10421 appendPQExpBuffer(query, "SELECT typlen, "
10422 "typinput, typoutput, typreceive, typsend, "
10423 "typmodin, typmodout, typanalyze, "
10424 "typreceive::pg_catalog.oid AS typreceiveoid, "
10425 "typsend::pg_catalog.oid AS typsendoid, "
10426 "typmodin::pg_catalog.oid AS typmodinoid, "
10427 "typmodout::pg_catalog.oid AS typmodoutoid, "
10428 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10429 "'U' AS typcategory, false AS typispreferred, "
10430 "typdelim, typbyval, typalign, typstorage, "
10431 "false AS typcollatable, "
10432 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10433 "FROM pg_catalog.pg_type "
10434 "WHERE oid = '%u'::pg_catalog.oid",
10435 tyinfo->dobj.catId.oid);
10439 appendPQExpBuffer(query, "SELECT typlen, "
10440 "typinput, typoutput, typreceive, typsend, "
10441 "'-' AS typmodin, '-' AS typmodout, "
10443 "typreceive::pg_catalog.oid AS typreceiveoid, "
10444 "typsend::pg_catalog.oid AS typsendoid, "
10445 "0 AS typmodinoid, 0 AS typmodoutoid, "
10446 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10447 "'U' AS typcategory, false AS typispreferred, "
10448 "typdelim, typbyval, typalign, typstorage, "
10449 "false AS typcollatable, "
10450 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10451 "FROM pg_catalog.pg_type "
10452 "WHERE oid = '%u'::pg_catalog.oid",
10453 tyinfo->dobj.catId.oid);
10456 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10458 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10459 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10460 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10461 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10462 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10463 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10464 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10465 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10466 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10467 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10468 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10469 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10470 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10471 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10472 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10473 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10474 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10475 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10476 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10477 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10478 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10479 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10480 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10482 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10483 typdefault_is_literal = true; /* it needs quotes */
10488 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10489 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10492 * The reason we include CASCADE is that the circular dependency between
10493 * the type and its I/O functions makes it impossible to drop the type any
10496 appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10499 * We might already have a shell type, but setting pg_type_oid is
10500 * harmless, and in any case we'd better set the array type OID.
10502 if (dopt->binary_upgrade)
10503 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10504 tyinfo->dobj.catId.oid,
10507 appendPQExpBuffer(q,
10508 "CREATE TYPE %s (\n"
10509 " INTERNALLENGTH = %s",
10511 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10513 /* regproc result is sufficiently quoted already */
10514 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10515 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10516 if (OidIsValid(typreceiveoid))
10517 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10518 if (OidIsValid(typsendoid))
10519 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10520 if (OidIsValid(typmodinoid))
10521 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10522 if (OidIsValid(typmodoutoid))
10523 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10524 if (OidIsValid(typanalyzeoid))
10525 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10527 if (strcmp(typcollatable, "t") == 0)
10528 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10530 if (typdefault != NULL)
10532 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10533 if (typdefault_is_literal)
10534 appendStringLiteralAH(q, typdefault, fout);
10536 appendPQExpBufferStr(q, typdefault);
10539 if (OidIsValid(tyinfo->typelem))
10543 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10544 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10548 if (strcmp(typcategory, "U") != 0)
10550 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10551 appendStringLiteralAH(q, typcategory, fout);
10554 if (strcmp(typispreferred, "t") == 0)
10555 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10557 if (typdelim && strcmp(typdelim, ",") != 0)
10559 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10560 appendStringLiteralAH(q, typdelim, fout);
10563 if (strcmp(typalign, "c") == 0)
10564 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10565 else if (strcmp(typalign, "s") == 0)
10566 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10567 else if (strcmp(typalign, "i") == 0)
10568 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10569 else if (strcmp(typalign, "d") == 0)
10570 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10572 if (strcmp(typstorage, "p") == 0)
10573 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10574 else if (strcmp(typstorage, "e") == 0)
10575 appendPQExpBufferStr(q, ",\n STORAGE = external");
10576 else if (strcmp(typstorage, "x") == 0)
10577 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10578 else if (strcmp(typstorage, "m") == 0)
10579 appendPQExpBufferStr(q, ",\n STORAGE = main");
10581 if (strcmp(typbyval, "t") == 0)
10582 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10584 appendPQExpBufferStr(q, "\n);\n");
10586 if (dopt->binary_upgrade)
10587 binary_upgrade_extension_member(q, &tyinfo->dobj,
10589 tyinfo->dobj.namespace->dobj.name);
10591 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10592 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10594 tyinfo->dobj.namespace->dobj.name,
10597 "TYPE", SECTION_PRE_DATA,
10598 q->data, delq->data, NULL,
10602 /* Dump Type Comments and Security Labels */
10603 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10604 dumpComment(fout, "TYPE", qtypname,
10605 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10606 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10608 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10609 dumpSecLabel(fout, "TYPE", qtypname,
10610 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10611 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10613 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10614 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10616 tyinfo->dobj.namespace->dobj.name,
10617 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10618 tyinfo->inittypacl, tyinfo->initrtypacl);
10621 destroyPQExpBuffer(q);
10622 destroyPQExpBuffer(delq);
10623 destroyPQExpBuffer(query);
10630 * writes out to fout the queries to recreate a user-defined domain
10633 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10635 DumpOptions *dopt = fout->dopt;
10636 PQExpBuffer q = createPQExpBuffer();
10637 PQExpBuffer delq = createPQExpBuffer();
10638 PQExpBuffer query = createPQExpBuffer();
10647 bool typdefault_is_literal = false;
10649 /* Fetch domain specific details */
10650 if (fout->remoteVersion >= 90100)
10652 /* typcollation is new in 9.1 */
10653 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10654 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10655 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10657 "CASE WHEN t.typcollation <> u.typcollation "
10658 "THEN t.typcollation ELSE 0 END AS typcollation "
10659 "FROM pg_catalog.pg_type t "
10660 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10661 "WHERE t.oid = '%u'::pg_catalog.oid",
10662 tyinfo->dobj.catId.oid);
10666 appendPQExpBuffer(query, "SELECT typnotnull, "
10667 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10668 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10669 "typdefault, 0 AS typcollation "
10670 "FROM pg_catalog.pg_type "
10671 "WHERE oid = '%u'::pg_catalog.oid",
10672 tyinfo->dobj.catId.oid);
10675 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10677 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10678 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10679 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10680 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10681 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10683 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10684 typdefault_is_literal = true; /* it needs quotes */
10688 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10690 if (dopt->binary_upgrade)
10691 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10692 tyinfo->dobj.catId.oid,
10693 true); /* force array type */
10695 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10696 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10698 appendPQExpBuffer(q,
10699 "CREATE DOMAIN %s AS %s",
10703 /* Print collation only if different from base type's collation */
10704 if (OidIsValid(typcollation))
10708 coll = findCollationByOid(typcollation);
10710 appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10713 if (typnotnull[0] == 't')
10714 appendPQExpBufferStr(q, " NOT NULL");
10716 if (typdefault != NULL)
10718 appendPQExpBufferStr(q, " DEFAULT ");
10719 if (typdefault_is_literal)
10720 appendStringLiteralAH(q, typdefault, fout);
10722 appendPQExpBufferStr(q, typdefault);
10728 * Add any CHECK constraints for the domain
10730 for (i = 0; i < tyinfo->nDomChecks; i++)
10732 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10734 if (!domcheck->separate)
10735 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10736 fmtId(domcheck->dobj.name), domcheck->condef);
10739 appendPQExpBufferStr(q, ";\n");
10741 appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10743 if (dopt->binary_upgrade)
10744 binary_upgrade_extension_member(q, &tyinfo->dobj,
10745 "DOMAIN", qtypname,
10746 tyinfo->dobj.namespace->dobj.name);
10748 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10749 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10751 tyinfo->dobj.namespace->dobj.name,
10754 "DOMAIN", SECTION_PRE_DATA,
10755 q->data, delq->data, NULL,
10759 /* Dump Domain Comments and Security Labels */
10760 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10761 dumpComment(fout, "DOMAIN", qtypname,
10762 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10763 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10765 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10766 dumpSecLabel(fout, "DOMAIN", qtypname,
10767 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10768 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10770 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10771 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10773 tyinfo->dobj.namespace->dobj.name,
10774 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10775 tyinfo->inittypacl, tyinfo->initrtypacl);
10777 /* Dump any per-constraint comments */
10778 for (i = 0; i < tyinfo->nDomChecks; i++)
10780 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10781 PQExpBuffer conprefix = createPQExpBuffer();
10783 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10784 fmtId(domcheck->dobj.name));
10786 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10787 dumpComment(fout, conprefix->data, qtypname,
10788 tyinfo->dobj.namespace->dobj.name,
10790 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10792 destroyPQExpBuffer(conprefix);
10795 destroyPQExpBuffer(q);
10796 destroyPQExpBuffer(delq);
10797 destroyPQExpBuffer(query);
10803 * dumpCompositeType
10804 * writes out to fout the queries to recreate a user-defined stand-alone
10808 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10810 DumpOptions *dopt = fout->dopt;
10811 PQExpBuffer q = createPQExpBuffer();
10812 PQExpBuffer dropped = createPQExpBuffer();
10813 PQExpBuffer delq = createPQExpBuffer();
10814 PQExpBuffer query = createPQExpBuffer();
10823 int i_attisdropped;
10824 int i_attcollation;
10828 /* Fetch type specific details */
10829 if (fout->remoteVersion >= 90100)
10832 * attcollation is new in 9.1. Since we only want to dump COLLATE
10833 * clauses for attributes whose collation is different from their
10834 * type's default, we use a CASE here to suppress uninteresting
10835 * attcollations cheaply. atttypid will be 0 for dropped columns;
10836 * collation does not matter for those.
10838 appendPQExpBuffer(query, "SELECT a.attname, "
10839 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10840 "a.attlen, a.attalign, a.attisdropped, "
10841 "CASE WHEN a.attcollation <> at.typcollation "
10842 "THEN a.attcollation ELSE 0 END AS attcollation "
10843 "FROM pg_catalog.pg_type ct "
10844 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10845 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10846 "WHERE ct.oid = '%u'::pg_catalog.oid "
10847 "ORDER BY a.attnum ",
10848 tyinfo->dobj.catId.oid);
10853 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10854 * should always be false.
10856 appendPQExpBuffer(query, "SELECT a.attname, "
10857 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10858 "a.attlen, a.attalign, a.attisdropped, "
10859 "0 AS attcollation "
10860 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10861 "WHERE ct.oid = '%u'::pg_catalog.oid "
10862 "AND a.attrelid = ct.typrelid "
10863 "ORDER BY a.attnum ",
10864 tyinfo->dobj.catId.oid);
10867 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10869 ntups = PQntuples(res);
10871 i_attname = PQfnumber(res, "attname");
10872 i_atttypdefn = PQfnumber(res, "atttypdefn");
10873 i_attlen = PQfnumber(res, "attlen");
10874 i_attalign = PQfnumber(res, "attalign");
10875 i_attisdropped = PQfnumber(res, "attisdropped");
10876 i_attcollation = PQfnumber(res, "attcollation");
10878 if (dopt->binary_upgrade)
10880 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10881 tyinfo->dobj.catId.oid,
10883 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10886 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10887 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10889 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10893 for (i = 0; i < ntups; i++)
10902 attname = PQgetvalue(res, i, i_attname);
10903 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10904 attlen = PQgetvalue(res, i, i_attlen);
10905 attalign = PQgetvalue(res, i, i_attalign);
10906 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10907 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10909 if (attisdropped && !dopt->binary_upgrade)
10912 /* Format properly if not first attr */
10913 if (actual_atts++ > 0)
10914 appendPQExpBufferChar(q, ',');
10915 appendPQExpBufferStr(q, "\n\t");
10919 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10921 /* Add collation if not default for the column type */
10922 if (OidIsValid(attcollation))
10926 coll = findCollationByOid(attcollation);
10928 appendPQExpBuffer(q, " COLLATE %s",
10929 fmtQualifiedDumpable(coll));
10935 * This is a dropped attribute and we're in binary_upgrade mode.
10936 * Insert a placeholder for it in the CREATE TYPE command, and set
10937 * length and alignment with direct UPDATE to the catalogs
10938 * afterwards. See similar code in dumpTableSchema().
10940 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
10942 /* stash separately for insertion after the CREATE TYPE */
10943 appendPQExpBufferStr(dropped,
10944 "\n-- For binary upgrade, recreate dropped column.\n");
10945 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
10946 "SET attlen = %s, "
10947 "attalign = '%s', attbyval = false\n"
10948 "WHERE attname = ", attlen, attalign);
10949 appendStringLiteralAH(dropped, attname, fout);
10950 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
10951 appendStringLiteralAH(dropped, qualtypname, fout);
10952 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
10954 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
10956 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
10960 appendPQExpBufferStr(q, "\n);\n");
10961 appendPQExpBufferStr(q, dropped->data);
10963 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10965 if (dopt->binary_upgrade)
10966 binary_upgrade_extension_member(q, &tyinfo->dobj,
10968 tyinfo->dobj.namespace->dobj.name);
10970 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10971 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10973 tyinfo->dobj.namespace->dobj.name,
10976 "TYPE", SECTION_PRE_DATA,
10977 q->data, delq->data, NULL,
10982 /* Dump Type Comments and Security Labels */
10983 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10984 dumpComment(fout, "TYPE", qtypname,
10985 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10986 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10988 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10989 dumpSecLabel(fout, "TYPE", qtypname,
10990 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10991 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10993 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10994 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10996 tyinfo->dobj.namespace->dobj.name,
10997 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10998 tyinfo->inittypacl, tyinfo->initrtypacl);
11001 destroyPQExpBuffer(q);
11002 destroyPQExpBuffer(dropped);
11003 destroyPQExpBuffer(delq);
11004 destroyPQExpBuffer(query);
11008 /* Dump any per-column comments */
11009 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11010 dumpCompositeTypeColComments(fout, tyinfo);
11014 * dumpCompositeTypeColComments
11015 * writes out to fout the queries to recreate comments on the columns of
11016 * a user-defined stand-alone composite type
11019 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11021 CommentItem *comments;
11025 PQExpBuffer target;
11032 /* do nothing, if --no-comments is supplied */
11033 if (fout->dopt->no_comments)
11036 query = createPQExpBuffer();
11038 appendPQExpBuffer(query,
11039 "SELECT c.tableoid, a.attname, a.attnum "
11040 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11041 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11042 " AND NOT a.attisdropped "
11043 "ORDER BY a.attnum ",
11046 /* Fetch column attnames */
11047 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11049 ntups = PQntuples(res);
11053 destroyPQExpBuffer(query);
11057 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11059 /* Search for comments associated with type's pg_class OID */
11060 ncomments = findComments(fout,
11065 /* If no comments exist, we're done */
11066 if (ncomments <= 0)
11069 destroyPQExpBuffer(query);
11073 /* Build COMMENT ON statements */
11074 target = createPQExpBuffer();
11076 i_attnum = PQfnumber(res, "attnum");
11077 i_attname = PQfnumber(res, "attname");
11078 while (ncomments > 0)
11080 const char *attname;
11083 for (i = 0; i < ntups; i++)
11085 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11087 attname = PQgetvalue(res, i, i_attname);
11091 if (attname) /* just in case we don't find it */
11093 const char *descr = comments->descr;
11095 resetPQExpBuffer(target);
11096 appendPQExpBuffer(target, "COLUMN %s.",
11097 fmtId(tyinfo->dobj.name));
11098 appendPQExpBufferStr(target, fmtId(attname));
11100 resetPQExpBuffer(query);
11101 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11102 fmtQualifiedDumpable(tyinfo));
11103 appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11104 appendStringLiteralAH(query, descr, fout);
11105 appendPQExpBufferStr(query, ";\n");
11107 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11109 tyinfo->dobj.namespace->dobj.name,
11110 NULL, tyinfo->rolname,
11111 "COMMENT", SECTION_NONE,
11112 query->data, "", NULL,
11113 &(tyinfo->dobj.dumpId), 1,
11122 destroyPQExpBuffer(query);
11123 destroyPQExpBuffer(target);
11128 * writes out to fout the queries to create a shell type
11130 * We dump a shell definition in advance of the I/O functions for the type.
11133 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11135 DumpOptions *dopt = fout->dopt;
11138 /* Skip if not to be dumped */
11139 if (!stinfo->dobj.dump || dopt->dataOnly)
11142 q = createPQExpBuffer();
11145 * Note the lack of a DROP command for the shell type; any required DROP
11146 * is driven off the base type entry, instead. This interacts with
11147 * _printTocEntry()'s use of the presence of a DROP command to decide
11148 * whether an entry needs an ALTER OWNER command. We don't want to alter
11149 * the shell type's owner immediately on creation; that should happen only
11150 * after it's filled in, otherwise the backend complains.
11153 if (dopt->binary_upgrade)
11154 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11155 stinfo->baseType->dobj.catId.oid,
11158 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11159 fmtQualifiedDumpable(stinfo));
11161 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11162 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11164 stinfo->dobj.namespace->dobj.name,
11166 stinfo->baseType->rolname,
11167 "SHELL TYPE", SECTION_PRE_DATA,
11172 destroyPQExpBuffer(q);
11177 * writes out to fout the queries to recreate a user-defined
11178 * procedural language
11181 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11183 DumpOptions *dopt = fout->dopt;
11184 PQExpBuffer defqry;
11185 PQExpBuffer delqry;
11188 FuncInfo *funcInfo;
11189 FuncInfo *inlineInfo = NULL;
11190 FuncInfo *validatorInfo = NULL;
11192 /* Skip if not to be dumped */
11193 if (!plang->dobj.dump || dopt->dataOnly)
11197 * Try to find the support function(s). It is not an error if we don't
11198 * find them --- if the functions are in the pg_catalog schema, as is
11199 * standard in 8.1 and up, then we won't have loaded them. (In this case
11200 * we will emit a parameterless CREATE LANGUAGE command, which will
11201 * require PL template knowledge in the backend to reload.)
11204 funcInfo = findFuncByOid(plang->lanplcallfoid);
11205 if (funcInfo != NULL && !funcInfo->dobj.dump)
11206 funcInfo = NULL; /* treat not-dumped same as not-found */
11208 if (OidIsValid(plang->laninline))
11210 inlineInfo = findFuncByOid(plang->laninline);
11211 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11215 if (OidIsValid(plang->lanvalidator))
11217 validatorInfo = findFuncByOid(plang->lanvalidator);
11218 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11219 validatorInfo = NULL;
11223 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11224 * with parameters. Otherwise, we'll write a parameterless command, which
11225 * will rely on data from pg_pltemplate.
11227 useParams = (funcInfo != NULL &&
11228 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11229 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11231 defqry = createPQExpBuffer();
11232 delqry = createPQExpBuffer();
11234 qlanname = pg_strdup(fmtId(plang->dobj.name));
11236 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11241 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11242 plang->lanpltrusted ? "TRUSTED " : "",
11244 appendPQExpBuffer(defqry, " HANDLER %s",
11245 fmtQualifiedDumpable(funcInfo));
11246 if (OidIsValid(plang->laninline))
11247 appendPQExpBuffer(defqry, " INLINE %s",
11248 fmtQualifiedDumpable(inlineInfo));
11249 if (OidIsValid(plang->lanvalidator))
11250 appendPQExpBuffer(defqry, " VALIDATOR %s",
11251 fmtQualifiedDumpable(validatorInfo));
11256 * If not dumping parameters, then use CREATE OR REPLACE so that the
11257 * command will not fail if the language is preinstalled in the target
11258 * database. We restrict the use of REPLACE to this case so as to
11259 * eliminate the risk of replacing a language with incompatible
11260 * parameter settings: this command will only succeed at all if there
11261 * is a pg_pltemplate entry, and if there is one, the existing entry
11262 * must match it too.
11264 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11267 appendPQExpBufferStr(defqry, ";\n");
11269 if (dopt->binary_upgrade)
11270 binary_upgrade_extension_member(defqry, &plang->dobj,
11271 "LANGUAGE", qlanname, NULL);
11273 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11274 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11276 NULL, NULL, plang->lanowner,
11277 "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11278 defqry->data, delqry->data, NULL,
11282 /* Dump Proc Lang Comments and Security Labels */
11283 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11284 dumpComment(fout, "LANGUAGE", qlanname,
11285 NULL, plang->lanowner,
11286 plang->dobj.catId, 0, plang->dobj.dumpId);
11288 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11289 dumpSecLabel(fout, "LANGUAGE", qlanname,
11290 NULL, plang->lanowner,
11291 plang->dobj.catId, 0, plang->dobj.dumpId);
11293 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11294 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11295 qlanname, NULL, NULL,
11296 plang->lanowner, plang->lanacl, plang->rlanacl,
11297 plang->initlanacl, plang->initrlanacl);
11301 destroyPQExpBuffer(defqry);
11302 destroyPQExpBuffer(delqry);
11306 * format_function_arguments: generate function name and argument list
11308 * This is used when we can rely on pg_get_function_arguments to format
11309 * the argument list. Note, however, that pg_get_function_arguments
11310 * does not special-case zero-argument aggregates.
11313 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11315 PQExpBufferData fn;
11317 initPQExpBuffer(&fn);
11318 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11319 if (is_agg && finfo->nargs == 0)
11320 appendPQExpBufferStr(&fn, "(*)");
11322 appendPQExpBuffer(&fn, "(%s)", funcargs);
11327 * format_function_arguments_old: generate function name and argument list
11329 * The argument type names are qualified if needed. The function name
11330 * is never qualified.
11332 * This is used only with pre-8.4 servers, so we aren't expecting to see
11333 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11335 * Any or all of allargtypes, argmodes, argnames may be NULL.
11338 format_function_arguments_old(Archive *fout,
11339 FuncInfo *finfo, int nallargs,
11340 char **allargtypes,
11344 PQExpBufferData fn;
11347 initPQExpBuffer(&fn);
11348 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11349 for (j = 0; j < nallargs; j++)
11353 const char *argmode;
11354 const char *argname;
11356 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11357 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11361 switch (argmodes[j][0])
11363 case PROARGMODE_IN:
11366 case PROARGMODE_OUT:
11369 case PROARGMODE_INOUT:
11370 argmode = "INOUT ";
11373 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11381 argname = argnames ? argnames[j] : (char *) NULL;
11382 if (argname && argname[0] == '\0')
11385 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11386 (j > 0) ? ", " : "",
11388 argname ? fmtId(argname) : "",
11389 argname ? " " : "",
11393 appendPQExpBufferChar(&fn, ')');
11398 * format_function_signature: generate function name and argument list
11400 * This is like format_function_arguments_old except that only a minimal
11401 * list of input argument types is generated; this is sufficient to
11402 * reference the function, but not to define it.
11404 * If honor_quotes is false then the function name is never quoted.
11405 * This is appropriate for use in TOC tags, but not in SQL commands.
11408 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11410 PQExpBufferData fn;
11413 initPQExpBuffer(&fn);
11415 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11417 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11418 for (j = 0; j < finfo->nargs; j++)
11423 appendPQExpBufferStr(&fn, ", ");
11425 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11427 appendPQExpBufferStr(&fn, typname);
11430 appendPQExpBufferChar(&fn, ')');
11437 * dump out one function
11440 dumpFunc(Archive *fout, FuncInfo *finfo)
11442 DumpOptions *dopt = fout->dopt;
11445 PQExpBuffer delqry;
11446 PQExpBuffer asPart;
11448 char *funcsig; /* identity signature */
11449 char *funcfullsig = NULL; /* full signature */
11457 char *proallargtypes;
11465 char *proleakproof;
11473 char **allargtypes = NULL;
11474 char **argmodes = NULL;
11475 char **argnames = NULL;
11476 char **configitems = NULL;
11477 int nconfigitems = 0;
11478 const char *keyword;
11481 /* Skip if not to be dumped */
11482 if (!finfo->dobj.dump || dopt->dataOnly)
11485 query = createPQExpBuffer();
11486 q = createPQExpBuffer();
11487 delqry = createPQExpBuffer();
11488 asPart = createPQExpBuffer();
11490 /* Fetch function-specific details */
11491 if (fout->remoteVersion >= 110000)
11494 * prokind was added in 11
11496 appendPQExpBuffer(query,
11497 "SELECT proretset, prosrc, probin, "
11498 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11499 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11500 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11501 "array_to_string(protrftypes, ' ') AS protrftypes, "
11502 "prokind, provolatile, proisstrict, prosecdef, "
11503 "proleakproof, proconfig, procost, prorows, "
11505 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11506 "FROM pg_catalog.pg_proc "
11507 "WHERE oid = '%u'::pg_catalog.oid",
11508 finfo->dobj.catId.oid);
11510 else if (fout->remoteVersion >= 90600)
11513 * proparallel was added in 9.6
11515 appendPQExpBuffer(query,
11516 "SELECT proretset, prosrc, probin, "
11517 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11518 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11519 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11520 "array_to_string(protrftypes, ' ') AS protrftypes, "
11521 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11522 "provolatile, proisstrict, prosecdef, "
11523 "proleakproof, proconfig, procost, prorows, "
11525 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11526 "FROM pg_catalog.pg_proc "
11527 "WHERE oid = '%u'::pg_catalog.oid",
11528 finfo->dobj.catId.oid);
11530 else if (fout->remoteVersion >= 90500)
11533 * protrftypes was added in 9.5
11535 appendPQExpBuffer(query,
11536 "SELECT proretset, prosrc, probin, "
11537 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11538 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11539 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11540 "array_to_string(protrftypes, ' ') AS protrftypes, "
11541 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11542 "provolatile, proisstrict, prosecdef, "
11543 "proleakproof, proconfig, procost, prorows, "
11544 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11545 "FROM pg_catalog.pg_proc "
11546 "WHERE oid = '%u'::pg_catalog.oid",
11547 finfo->dobj.catId.oid);
11549 else if (fout->remoteVersion >= 90200)
11552 * proleakproof was added in 9.2
11554 appendPQExpBuffer(query,
11555 "SELECT proretset, prosrc, probin, "
11556 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11557 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11558 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11559 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11560 "provolatile, proisstrict, prosecdef, "
11561 "proleakproof, proconfig, procost, prorows, "
11562 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11563 "FROM pg_catalog.pg_proc "
11564 "WHERE oid = '%u'::pg_catalog.oid",
11565 finfo->dobj.catId.oid);
11567 else if (fout->remoteVersion >= 80400)
11570 * In 8.4 and up we rely on pg_get_function_arguments and
11571 * pg_get_function_result instead of examining proallargtypes etc.
11573 appendPQExpBuffer(query,
11574 "SELECT proretset, prosrc, probin, "
11575 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11576 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11577 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11578 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11579 "provolatile, proisstrict, prosecdef, "
11580 "false AS proleakproof, "
11581 " proconfig, procost, prorows, "
11582 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11583 "FROM pg_catalog.pg_proc "
11584 "WHERE oid = '%u'::pg_catalog.oid",
11585 finfo->dobj.catId.oid);
11587 else if (fout->remoteVersion >= 80300)
11589 appendPQExpBuffer(query,
11590 "SELECT proretset, prosrc, probin, "
11591 "proallargtypes, proargmodes, proargnames, "
11593 "provolatile, proisstrict, prosecdef, "
11594 "false AS proleakproof, "
11595 "proconfig, procost, prorows, "
11596 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11597 "FROM pg_catalog.pg_proc "
11598 "WHERE oid = '%u'::pg_catalog.oid",
11599 finfo->dobj.catId.oid);
11601 else if (fout->remoteVersion >= 80100)
11603 appendPQExpBuffer(query,
11604 "SELECT proretset, prosrc, probin, "
11605 "proallargtypes, proargmodes, proargnames, "
11607 "provolatile, proisstrict, prosecdef, "
11608 "false AS proleakproof, "
11609 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11610 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11611 "FROM pg_catalog.pg_proc "
11612 "WHERE oid = '%u'::pg_catalog.oid",
11613 finfo->dobj.catId.oid);
11617 appendPQExpBuffer(query,
11618 "SELECT proretset, prosrc, probin, "
11619 "null AS proallargtypes, "
11620 "null AS proargmodes, "
11623 "provolatile, proisstrict, prosecdef, "
11624 "false AS proleakproof, "
11625 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11626 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11627 "FROM pg_catalog.pg_proc "
11628 "WHERE oid = '%u'::pg_catalog.oid",
11629 finfo->dobj.catId.oid);
11632 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11634 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11635 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11636 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11637 if (fout->remoteVersion >= 80400)
11639 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11640 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11641 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11642 proallargtypes = proargmodes = proargnames = NULL;
11646 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11647 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11648 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11649 funcargs = funciargs = funcresult = NULL;
11651 if (PQfnumber(res, "protrftypes") != -1)
11652 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11654 protrftypes = NULL;
11655 prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11656 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11657 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11658 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11659 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11660 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11661 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11662 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11664 if (PQfnumber(res, "proparallel") != -1)
11665 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11667 proparallel = NULL;
11669 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11672 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11673 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11674 * versions would set it to "-". There are no known cases in which prosrc
11675 * is unused, so the tests below for "-" are probably useless.
11677 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11679 appendPQExpBufferStr(asPart, "AS ");
11680 appendStringLiteralAH(asPart, probin, fout);
11681 if (strcmp(prosrc, "-") != 0)
11683 appendPQExpBufferStr(asPart, ", ");
11686 * where we have bin, use dollar quoting if allowed and src
11687 * contains quote or backslash; else use regular quoting.
11689 if (dopt->disable_dollar_quoting ||
11690 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11691 appendStringLiteralAH(asPart, prosrc, fout);
11693 appendStringLiteralDQ(asPart, prosrc, NULL);
11698 if (strcmp(prosrc, "-") != 0)
11700 appendPQExpBufferStr(asPart, "AS ");
11701 /* with no bin, dollar quote src unconditionally if allowed */
11702 if (dopt->disable_dollar_quoting)
11703 appendStringLiteralAH(asPart, prosrc, fout);
11705 appendStringLiteralDQ(asPart, prosrc, NULL);
11709 nallargs = finfo->nargs; /* unless we learn different from allargs */
11711 if (proallargtypes && *proallargtypes)
11715 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11716 nitems < finfo->nargs)
11718 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11721 allargtypes = NULL;
11727 if (proargmodes && *proargmodes)
11731 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11732 nitems != nallargs)
11734 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11741 if (proargnames && *proargnames)
11745 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11746 nitems != nallargs)
11748 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11755 if (proconfig && *proconfig)
11757 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11759 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11762 configitems = NULL;
11769 /* 8.4 or later; we rely on server-side code for most of the work */
11770 funcfullsig = format_function_arguments(finfo, funcargs, false);
11771 funcsig = format_function_arguments(finfo, funciargs, false);
11774 /* pre-8.4, do it ourselves */
11775 funcsig = format_function_arguments_old(fout,
11776 finfo, nallargs, allargtypes,
11777 argmodes, argnames);
11779 funcsig_tag = format_function_signature(fout, finfo, false);
11781 if (prokind[0] == PROKIND_PROCEDURE)
11782 keyword = "PROCEDURE";
11784 keyword = "FUNCTION"; /* works for window functions too */
11786 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11788 fmtId(finfo->dobj.namespace->dobj.name),
11791 appendPQExpBuffer(q, "CREATE %s %s.%s",
11793 fmtId(finfo->dobj.namespace->dobj.name),
11794 funcfullsig ? funcfullsig :
11797 if (prokind[0] == PROKIND_PROCEDURE)
11798 /* no result type to output */ ;
11799 else if (funcresult)
11800 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11803 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11805 appendPQExpBuffer(q, " RETURNS %s%s",
11806 (proretset[0] == 't') ? "SETOF " : "",
11811 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11813 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11815 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11818 appendPQExpBufferStr(q, " TRANSFORM ");
11819 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11820 for (i = 0; typeids[i]; i++)
11823 appendPQExpBufferStr(q, ", ");
11824 appendPQExpBuffer(q, "FOR TYPE %s",
11825 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11829 if (prokind[0] == PROKIND_WINDOW)
11830 appendPQExpBufferStr(q, " WINDOW");
11832 if (provolatile[0] != PROVOLATILE_VOLATILE)
11834 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11835 appendPQExpBufferStr(q, " IMMUTABLE");
11836 else if (provolatile[0] == PROVOLATILE_STABLE)
11837 appendPQExpBufferStr(q, " STABLE");
11838 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11839 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11843 if (proisstrict[0] == 't')
11844 appendPQExpBufferStr(q, " STRICT");
11846 if (prosecdef[0] == 't')
11847 appendPQExpBufferStr(q, " SECURITY DEFINER");
11849 if (proleakproof[0] == 't')
11850 appendPQExpBufferStr(q, " LEAKPROOF");
11853 * COST and ROWS are emitted only if present and not default, so as not to
11854 * break backwards-compatibility of the dump without need. Keep this code
11855 * in sync with the defaults in functioncmds.c.
11857 if (strcmp(procost, "0") != 0)
11859 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11861 /* default cost is 1 */
11862 if (strcmp(procost, "1") != 0)
11863 appendPQExpBuffer(q, " COST %s", procost);
11867 /* default cost is 100 */
11868 if (strcmp(procost, "100") != 0)
11869 appendPQExpBuffer(q, " COST %s", procost);
11872 if (proretset[0] == 't' &&
11873 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11874 appendPQExpBuffer(q, " ROWS %s", prorows);
11876 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11878 if (proparallel[0] == PROPARALLEL_SAFE)
11879 appendPQExpBufferStr(q, " PARALLEL SAFE");
11880 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11881 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11882 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11883 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11887 for (i = 0; i < nconfigitems; i++)
11889 /* we feel free to scribble on configitems[] here */
11890 char *configitem = configitems[i];
11893 pos = strchr(configitem, '=');
11897 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
11900 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11901 * by flatten_set_variable_args() before they were put into the
11902 * proconfig array. However, because the quoting rules used there
11903 * aren't exactly like SQL's, we have to break the list value apart
11904 * and then quote the elements as string literals. (The elements may
11905 * be double-quoted as-is, but we can't just feed them to the SQL
11906 * parser; it would do the wrong thing with elements that are
11907 * zero-length or longer than NAMEDATALEN.)
11909 * Variables that are not so marked should just be emitted as simple
11910 * string literals. If the variable is not known to
11911 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
11912 * to use GUC_LIST_QUOTE for extension variables.
11914 if (variable_is_guc_list_quote(configitem))
11919 /* Parse string into list of identifiers */
11920 /* this shouldn't fail really */
11921 if (SplitGUCList(pos, ',', &namelist))
11923 for (nameptr = namelist; *nameptr; nameptr++)
11925 if (nameptr != namelist)
11926 appendPQExpBufferStr(q, ", ");
11927 appendStringLiteralAH(q, *nameptr, fout);
11933 appendStringLiteralAH(q, pos, fout);
11936 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
11938 if (dopt->binary_upgrade)
11939 binary_upgrade_extension_member(q, &finfo->dobj,
11941 finfo->dobj.namespace->dobj.name);
11943 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11944 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
11946 finfo->dobj.namespace->dobj.name,
11949 keyword, SECTION_PRE_DATA,
11950 q->data, delqry->data, NULL,
11954 /* Dump Function Comments and Security Labels */
11955 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11956 dumpComment(fout, keyword, funcsig,
11957 finfo->dobj.namespace->dobj.name, finfo->rolname,
11958 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11960 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11961 dumpSecLabel(fout, keyword, funcsig,
11962 finfo->dobj.namespace->dobj.name, finfo->rolname,
11963 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11965 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
11966 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
11968 finfo->dobj.namespace->dobj.name,
11969 finfo->rolname, finfo->proacl, finfo->rproacl,
11970 finfo->initproacl, finfo->initrproacl);
11974 destroyPQExpBuffer(query);
11975 destroyPQExpBuffer(q);
11976 destroyPQExpBuffer(delqry);
11977 destroyPQExpBuffer(asPart);
11994 * Dump a user-defined cast
11997 dumpCast(Archive *fout, CastInfo *cast)
11999 DumpOptions *dopt = fout->dopt;
12000 PQExpBuffer defqry;
12001 PQExpBuffer delqry;
12002 PQExpBuffer labelq;
12003 PQExpBuffer castargs;
12004 FuncInfo *funcInfo = NULL;
12008 /* Skip if not to be dumped */
12009 if (!cast->dobj.dump || dopt->dataOnly)
12012 /* Cannot dump if we don't have the cast function's info */
12013 if (OidIsValid(cast->castfunc))
12015 funcInfo = findFuncByOid(cast->castfunc);
12016 if (funcInfo == NULL)
12017 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12021 defqry = createPQExpBuffer();
12022 delqry = createPQExpBuffer();
12023 labelq = createPQExpBuffer();
12024 castargs = createPQExpBuffer();
12026 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12027 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12028 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12029 sourceType, targetType);
12031 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12032 sourceType, targetType);
12034 switch (cast->castmethod)
12036 case COERCION_METHOD_BINARY:
12037 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12039 case COERCION_METHOD_INOUT:
12040 appendPQExpBufferStr(defqry, "WITH INOUT");
12042 case COERCION_METHOD_FUNCTION:
12045 char *fsig = format_function_signature(fout, funcInfo, true);
12048 * Always qualify the function name (format_function_signature
12049 * won't qualify it).
12051 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12052 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12056 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12059 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12062 if (cast->castcontext == 'a')
12063 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12064 else if (cast->castcontext == 'i')
12065 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12066 appendPQExpBufferStr(defqry, ";\n");
12068 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12069 sourceType, targetType);
12071 appendPQExpBuffer(castargs, "(%s AS %s)",
12072 sourceType, targetType);
12074 if (dopt->binary_upgrade)
12075 binary_upgrade_extension_member(defqry, &cast->dobj,
12076 "CAST", castargs->data, NULL);
12078 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12079 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12082 "CAST", SECTION_PRE_DATA,
12083 defqry->data, delqry->data, NULL,
12087 /* Dump Cast Comments */
12088 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12089 dumpComment(fout, "CAST", castargs->data,
12091 cast->dobj.catId, 0, cast->dobj.dumpId);
12096 destroyPQExpBuffer(defqry);
12097 destroyPQExpBuffer(delqry);
12098 destroyPQExpBuffer(labelq);
12099 destroyPQExpBuffer(castargs);
12106 dumpTransform(Archive *fout, TransformInfo *transform)
12108 DumpOptions *dopt = fout->dopt;
12109 PQExpBuffer defqry;
12110 PQExpBuffer delqry;
12111 PQExpBuffer labelq;
12112 PQExpBuffer transformargs;
12113 FuncInfo *fromsqlFuncInfo = NULL;
12114 FuncInfo *tosqlFuncInfo = NULL;
12116 char *transformType;
12118 /* Skip if not to be dumped */
12119 if (!transform->dobj.dump || dopt->dataOnly)
12122 /* Cannot dump if we don't have the transform functions' info */
12123 if (OidIsValid(transform->trffromsql))
12125 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12126 if (fromsqlFuncInfo == NULL)
12127 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12128 transform->trffromsql);
12130 if (OidIsValid(transform->trftosql))
12132 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12133 if (tosqlFuncInfo == NULL)
12134 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12135 transform->trftosql);
12138 defqry = createPQExpBuffer();
12139 delqry = createPQExpBuffer();
12140 labelq = createPQExpBuffer();
12141 transformargs = createPQExpBuffer();
12143 lanname = get_language_name(fout, transform->trflang);
12144 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12146 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12147 transformType, lanname);
12149 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12150 transformType, lanname);
12152 if (!transform->trffromsql && !transform->trftosql)
12153 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12155 if (transform->trffromsql)
12157 if (fromsqlFuncInfo)
12159 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12162 * Always qualify the function name (format_function_signature
12163 * won't qualify it).
12165 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12166 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12170 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12173 if (transform->trftosql)
12175 if (transform->trffromsql)
12176 appendPQExpBuffer(defqry, ", ");
12180 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12183 * Always qualify the function name (format_function_signature
12184 * won't qualify it).
12186 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12187 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12191 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12194 appendPQExpBuffer(defqry, ");\n");
12196 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12197 transformType, lanname);
12199 appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12200 transformType, lanname);
12202 if (dopt->binary_upgrade)
12203 binary_upgrade_extension_member(defqry, &transform->dobj,
12204 "TRANSFORM", transformargs->data, NULL);
12206 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12207 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12210 "TRANSFORM", SECTION_PRE_DATA,
12211 defqry->data, delqry->data, NULL,
12212 transform->dobj.dependencies, transform->dobj.nDeps,
12215 /* Dump Transform Comments */
12216 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12217 dumpComment(fout, "TRANSFORM", transformargs->data,
12219 transform->dobj.catId, 0, transform->dobj.dumpId);
12222 free(transformType);
12223 destroyPQExpBuffer(defqry);
12224 destroyPQExpBuffer(delqry);
12225 destroyPQExpBuffer(labelq);
12226 destroyPQExpBuffer(transformargs);
12232 * write out a single operator definition
12235 dumpOpr(Archive *fout, OprInfo *oprinfo)
12237 DumpOptions *dopt = fout->dopt;
12242 PQExpBuffer details;
12267 /* Skip if not to be dumped */
12268 if (!oprinfo->dobj.dump || dopt->dataOnly)
12272 * some operators are invalid because they were the result of user
12273 * defining operators before commutators exist
12275 if (!OidIsValid(oprinfo->oprcode))
12278 query = createPQExpBuffer();
12279 q = createPQExpBuffer();
12280 delq = createPQExpBuffer();
12281 oprid = createPQExpBuffer();
12282 details = createPQExpBuffer();
12284 if (fout->remoteVersion >= 80300)
12286 appendPQExpBuffer(query, "SELECT oprkind, "
12287 "oprcode::pg_catalog.regprocedure, "
12288 "oprleft::pg_catalog.regtype, "
12289 "oprright::pg_catalog.regtype, "
12292 "oprrest::pg_catalog.regprocedure, "
12293 "oprjoin::pg_catalog.regprocedure, "
12294 "oprcanmerge, oprcanhash "
12295 "FROM pg_catalog.pg_operator "
12296 "WHERE oid = '%u'::pg_catalog.oid",
12297 oprinfo->dobj.catId.oid);
12301 appendPQExpBuffer(query, "SELECT oprkind, "
12302 "oprcode::pg_catalog.regprocedure, "
12303 "oprleft::pg_catalog.regtype, "
12304 "oprright::pg_catalog.regtype, "
12307 "oprrest::pg_catalog.regprocedure, "
12308 "oprjoin::pg_catalog.regprocedure, "
12309 "(oprlsortop != 0) AS oprcanmerge, "
12311 "FROM pg_catalog.pg_operator "
12312 "WHERE oid = '%u'::pg_catalog.oid",
12313 oprinfo->dobj.catId.oid);
12316 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12318 i_oprkind = PQfnumber(res, "oprkind");
12319 i_oprcode = PQfnumber(res, "oprcode");
12320 i_oprleft = PQfnumber(res, "oprleft");
12321 i_oprright = PQfnumber(res, "oprright");
12322 i_oprcom = PQfnumber(res, "oprcom");
12323 i_oprnegate = PQfnumber(res, "oprnegate");
12324 i_oprrest = PQfnumber(res, "oprrest");
12325 i_oprjoin = PQfnumber(res, "oprjoin");
12326 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12327 i_oprcanhash = PQfnumber(res, "oprcanhash");
12329 oprkind = PQgetvalue(res, 0, i_oprkind);
12330 oprcode = PQgetvalue(res, 0, i_oprcode);
12331 oprleft = PQgetvalue(res, 0, i_oprleft);
12332 oprright = PQgetvalue(res, 0, i_oprright);
12333 oprcom = PQgetvalue(res, 0, i_oprcom);
12334 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12335 oprrest = PQgetvalue(res, 0, i_oprrest);
12336 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12337 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12338 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12340 oprregproc = convertRegProcReference(fout, oprcode);
12343 appendPQExpBuffer(details, " FUNCTION = %s", oprregproc);
12347 appendPQExpBuffer(oprid, "%s (",
12348 oprinfo->dobj.name);
12351 * right unary means there's a left arg and left unary means there's a
12354 if (strcmp(oprkind, "r") == 0 ||
12355 strcmp(oprkind, "b") == 0)
12357 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12358 appendPQExpBufferStr(oprid, oprleft);
12361 appendPQExpBufferStr(oprid, "NONE");
12363 if (strcmp(oprkind, "l") == 0 ||
12364 strcmp(oprkind, "b") == 0)
12366 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12367 appendPQExpBuffer(oprid, ", %s)", oprright);
12370 appendPQExpBufferStr(oprid, ", NONE)");
12372 oprref = getFormattedOperatorName(fout, oprcom);
12375 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12379 oprref = getFormattedOperatorName(fout, oprnegate);
12382 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12386 if (strcmp(oprcanmerge, "t") == 0)
12387 appendPQExpBufferStr(details, ",\n MERGES");
12389 if (strcmp(oprcanhash, "t") == 0)
12390 appendPQExpBufferStr(details, ",\n HASHES");
12392 oprregproc = convertRegProcReference(fout, oprrest);
12395 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12399 oprregproc = convertRegProcReference(fout, oprjoin);
12402 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12406 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12407 fmtId(oprinfo->dobj.namespace->dobj.name),
12410 appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12411 fmtId(oprinfo->dobj.namespace->dobj.name),
12412 oprinfo->dobj.name, details->data);
12414 if (dopt->binary_upgrade)
12415 binary_upgrade_extension_member(q, &oprinfo->dobj,
12416 "OPERATOR", oprid->data,
12417 oprinfo->dobj.namespace->dobj.name);
12419 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12420 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12421 oprinfo->dobj.name,
12422 oprinfo->dobj.namespace->dobj.name,
12425 "OPERATOR", SECTION_PRE_DATA,
12426 q->data, delq->data, NULL,
12430 /* Dump Operator Comments */
12431 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12432 dumpComment(fout, "OPERATOR", oprid->data,
12433 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12434 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12438 destroyPQExpBuffer(query);
12439 destroyPQExpBuffer(q);
12440 destroyPQExpBuffer(delq);
12441 destroyPQExpBuffer(oprid);
12442 destroyPQExpBuffer(details);
12446 * Convert a function reference obtained from pg_operator
12448 * Returns allocated string of what to print, or NULL if function references
12449 * is InvalidOid. Returned string is expected to be free'd by the caller.
12451 * The input is a REGPROCEDURE display; we have to strip the argument-types
12455 convertRegProcReference(Archive *fout, const char *proc)
12461 /* In all cases "-" means a null reference */
12462 if (strcmp(proc, "-") == 0)
12465 name = pg_strdup(proc);
12466 /* find non-double-quoted left paren */
12468 for (paren = name; *paren; paren++)
12470 if (*paren == '(' && !inquote)
12476 inquote = !inquote;
12482 * getFormattedOperatorName - retrieve the operator name for the
12483 * given operator OID (presented in string form).
12485 * Returns an allocated string, or NULL if the given OID is invalid.
12486 * Caller is responsible for free'ing result string.
12488 * What we produce has the format "OPERATOR(schema.oprname)". This is only
12489 * useful in commands where the operator's argument types can be inferred from
12490 * context. We always schema-qualify the name, though. The predecessor to
12491 * this code tried to skip the schema qualification if possible, but that led
12492 * to wrong results in corner cases, such as if an operator and its negator
12493 * are in different schemas.
12496 getFormattedOperatorName(Archive *fout, const char *oproid)
12500 /* In all cases "0" means a null reference */
12501 if (strcmp(oproid, "0") == 0)
12504 oprInfo = findOprByOid(atooid(oproid));
12505 if (oprInfo == NULL)
12507 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12512 return psprintf("OPERATOR(%s.%s)",
12513 fmtId(oprInfo->dobj.namespace->dobj.name),
12514 oprInfo->dobj.name);
12518 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12520 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12521 * argument lists of these functions are predetermined. Note that the
12522 * caller should ensure we are in the proper schema, because the results
12523 * are search path dependent!
12526 convertTSFunction(Archive *fout, Oid funcOid)
12532 snprintf(query, sizeof(query),
12533 "SELECT '%u'::pg_catalog.regproc", funcOid);
12534 res = ExecuteSqlQueryForSingleRow(fout, query);
12536 result = pg_strdup(PQgetvalue(res, 0, 0));
12545 * write out a single access method definition
12548 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12550 DumpOptions *dopt = fout->dopt;
12555 /* Skip if not to be dumped */
12556 if (!aminfo->dobj.dump || dopt->dataOnly)
12559 q = createPQExpBuffer();
12560 delq = createPQExpBuffer();
12562 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12564 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12566 switch (aminfo->amtype)
12569 appendPQExpBuffer(q, "TYPE INDEX ");
12572 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12573 aminfo->amtype, qamname);
12574 destroyPQExpBuffer(q);
12575 destroyPQExpBuffer(delq);
12580 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12582 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12585 if (dopt->binary_upgrade)
12586 binary_upgrade_extension_member(q, &aminfo->dobj,
12587 "ACCESS METHOD", qamname, NULL);
12589 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12590 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12595 "ACCESS METHOD", SECTION_PRE_DATA,
12596 q->data, delq->data, NULL,
12600 /* Dump Access Method Comments */
12601 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12602 dumpComment(fout, "ACCESS METHOD", qamname,
12604 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12606 destroyPQExpBuffer(q);
12607 destroyPQExpBuffer(delq);
12613 * write out a single operator class definition
12616 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12618 DumpOptions *dopt = fout->dopt;
12622 PQExpBuffer nameusing;
12629 int i_opcfamilyname;
12630 int i_opcfamilynsp;
12632 int i_amopstrategy;
12633 int i_amopreqcheck;
12636 int i_sortfamilynsp;
12639 int i_amproclefttype;
12640 int i_amprocrighttype;
12645 char *opcfamilyname;
12646 char *opcfamilynsp;
12648 char *amopstrategy;
12649 char *amopreqcheck;
12652 char *sortfamilynsp;
12655 char *amproclefttype;
12656 char *amprocrighttype;
12660 /* Skip if not to be dumped */
12661 if (!opcinfo->dobj.dump || dopt->dataOnly)
12664 query = createPQExpBuffer();
12665 q = createPQExpBuffer();
12666 delq = createPQExpBuffer();
12667 nameusing = createPQExpBuffer();
12669 /* Get additional fields from the pg_opclass row */
12670 if (fout->remoteVersion >= 80300)
12672 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12673 "opckeytype::pg_catalog.regtype, "
12674 "opcdefault, opcfamily, "
12675 "opfname AS opcfamilyname, "
12676 "nspname AS opcfamilynsp, "
12677 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12678 "FROM pg_catalog.pg_opclass c "
12679 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12680 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12681 "WHERE c.oid = '%u'::pg_catalog.oid",
12682 opcinfo->dobj.catId.oid);
12686 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12687 "opckeytype::pg_catalog.regtype, "
12688 "opcdefault, NULL AS opcfamily, "
12689 "NULL AS opcfamilyname, "
12690 "NULL AS opcfamilynsp, "
12691 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12692 "FROM pg_catalog.pg_opclass "
12693 "WHERE oid = '%u'::pg_catalog.oid",
12694 opcinfo->dobj.catId.oid);
12697 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12699 i_opcintype = PQfnumber(res, "opcintype");
12700 i_opckeytype = PQfnumber(res, "opckeytype");
12701 i_opcdefault = PQfnumber(res, "opcdefault");
12702 i_opcfamily = PQfnumber(res, "opcfamily");
12703 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12704 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12705 i_amname = PQfnumber(res, "amname");
12707 /* opcintype may still be needed after we PQclear res */
12708 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12709 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12710 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12711 /* opcfamily will still be needed after we PQclear res */
12712 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12713 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12714 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12715 /* amname will still be needed after we PQclear res */
12716 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12718 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12719 fmtQualifiedDumpable(opcinfo));
12720 appendPQExpBuffer(delq, " USING %s;\n",
12723 /* Build the fixed portion of the CREATE command */
12724 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12725 fmtQualifiedDumpable(opcinfo));
12726 if (strcmp(opcdefault, "t") == 0)
12727 appendPQExpBufferStr(q, "DEFAULT ");
12728 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12731 if (strlen(opcfamilyname) > 0)
12733 appendPQExpBufferStr(q, " FAMILY ");
12734 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12735 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12737 appendPQExpBufferStr(q, " AS\n ");
12741 if (strcmp(opckeytype, "-") != 0)
12743 appendPQExpBuffer(q, "STORAGE %s",
12751 * Now fetch and print the OPERATOR entries (pg_amop rows).
12753 * Print only those opfamily members that are tied to the opclass by
12754 * pg_depend entries.
12756 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12757 * older server's opclass in which it is used. This is to avoid
12758 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12759 * older server and then reload into that old version. This can go away
12760 * once 8.3 is so old as to not be of interest to anyone.
12762 resetPQExpBuffer(query);
12764 if (fout->remoteVersion >= 90100)
12766 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12767 "amopopr::pg_catalog.regoperator, "
12768 "opfname AS sortfamily, "
12769 "nspname AS sortfamilynsp "
12770 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12771 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12772 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12773 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12774 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12775 "AND refobjid = '%u'::pg_catalog.oid "
12776 "AND amopfamily = '%s'::pg_catalog.oid "
12777 "ORDER BY amopstrategy",
12778 opcinfo->dobj.catId.oid,
12781 else if (fout->remoteVersion >= 80400)
12783 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12784 "amopopr::pg_catalog.regoperator, "
12785 "NULL AS sortfamily, "
12786 "NULL AS sortfamilynsp "
12787 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12788 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12789 "AND refobjid = '%u'::pg_catalog.oid "
12790 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12791 "AND objid = ao.oid "
12792 "ORDER BY amopstrategy",
12793 opcinfo->dobj.catId.oid);
12795 else if (fout->remoteVersion >= 80300)
12797 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12798 "amopopr::pg_catalog.regoperator, "
12799 "NULL AS sortfamily, "
12800 "NULL AS sortfamilynsp "
12801 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12802 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12803 "AND refobjid = '%u'::pg_catalog.oid "
12804 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12805 "AND objid = ao.oid "
12806 "ORDER BY amopstrategy",
12807 opcinfo->dobj.catId.oid);
12812 * Here, we print all entries since there are no opfamilies and hence
12813 * no loose operators to worry about.
12815 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12816 "amopopr::pg_catalog.regoperator, "
12817 "NULL AS sortfamily, "
12818 "NULL AS sortfamilynsp "
12819 "FROM pg_catalog.pg_amop "
12820 "WHERE amopclaid = '%u'::pg_catalog.oid "
12821 "ORDER BY amopstrategy",
12822 opcinfo->dobj.catId.oid);
12825 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12827 ntups = PQntuples(res);
12829 i_amopstrategy = PQfnumber(res, "amopstrategy");
12830 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12831 i_amopopr = PQfnumber(res, "amopopr");
12832 i_sortfamily = PQfnumber(res, "sortfamily");
12833 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12835 for (i = 0; i < ntups; i++)
12837 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12838 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12839 amopopr = PQgetvalue(res, i, i_amopopr);
12840 sortfamily = PQgetvalue(res, i, i_sortfamily);
12841 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12844 appendPQExpBufferStr(q, " ,\n ");
12846 appendPQExpBuffer(q, "OPERATOR %s %s",
12847 amopstrategy, amopopr);
12849 if (strlen(sortfamily) > 0)
12851 appendPQExpBufferStr(q, " FOR ORDER BY ");
12852 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12853 appendPQExpBufferStr(q, fmtId(sortfamily));
12856 if (strcmp(amopreqcheck, "t") == 0)
12857 appendPQExpBufferStr(q, " RECHECK");
12865 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12867 * Print only those opfamily members that are tied to the opclass by
12868 * pg_depend entries.
12870 * We print the amproclefttype/amprocrighttype even though in most cases
12871 * the backend could deduce the right values, because of the corner case
12872 * of a btree sort support function for a cross-type comparison. That's
12873 * only allowed in 9.2 and later, but for simplicity print them in all
12874 * versions that have the columns.
12876 resetPQExpBuffer(query);
12878 if (fout->remoteVersion >= 80300)
12880 appendPQExpBuffer(query, "SELECT amprocnum, "
12881 "amproc::pg_catalog.regprocedure, "
12882 "amproclefttype::pg_catalog.regtype, "
12883 "amprocrighttype::pg_catalog.regtype "
12884 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12885 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12886 "AND refobjid = '%u'::pg_catalog.oid "
12887 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12888 "AND objid = ap.oid "
12889 "ORDER BY amprocnum",
12890 opcinfo->dobj.catId.oid);
12894 appendPQExpBuffer(query, "SELECT amprocnum, "
12895 "amproc::pg_catalog.regprocedure, "
12896 "'' AS amproclefttype, "
12897 "'' AS amprocrighttype "
12898 "FROM pg_catalog.pg_amproc "
12899 "WHERE amopclaid = '%u'::pg_catalog.oid "
12900 "ORDER BY amprocnum",
12901 opcinfo->dobj.catId.oid);
12904 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12906 ntups = PQntuples(res);
12908 i_amprocnum = PQfnumber(res, "amprocnum");
12909 i_amproc = PQfnumber(res, "amproc");
12910 i_amproclefttype = PQfnumber(res, "amproclefttype");
12911 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12913 for (i = 0; i < ntups; i++)
12915 amprocnum = PQgetvalue(res, i, i_amprocnum);
12916 amproc = PQgetvalue(res, i, i_amproc);
12917 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12918 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12921 appendPQExpBufferStr(q, " ,\n ");
12923 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12925 if (*amproclefttype && *amprocrighttype)
12926 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12928 appendPQExpBuffer(q, " %s", amproc);
12936 * If needComma is still false it means we haven't added anything after
12937 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
12938 * clause with the same datatype. This isn't sanctioned by the
12939 * documentation, but actually DefineOpClass will treat it as a no-op.
12942 appendPQExpBuffer(q, "STORAGE %s", opcintype);
12944 appendPQExpBufferStr(q, ";\n");
12946 appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
12947 appendPQExpBuffer(nameusing, " USING %s",
12950 if (dopt->binary_upgrade)
12951 binary_upgrade_extension_member(q, &opcinfo->dobj,
12952 "OPERATOR CLASS", nameusing->data,
12953 opcinfo->dobj.namespace->dobj.name);
12955 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12956 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
12957 opcinfo->dobj.name,
12958 opcinfo->dobj.namespace->dobj.name,
12961 "OPERATOR CLASS", SECTION_PRE_DATA,
12962 q->data, delq->data, NULL,
12966 /* Dump Operator Class Comments */
12967 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12968 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
12969 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
12970 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
12975 destroyPQExpBuffer(query);
12976 destroyPQExpBuffer(q);
12977 destroyPQExpBuffer(delq);
12978 destroyPQExpBuffer(nameusing);
12983 * write out a single operator family definition
12985 * Note: this also dumps any "loose" operator members that aren't bound to a
12986 * specific opclass within the opfamily.
12989 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
12991 DumpOptions *dopt = fout->dopt;
12995 PQExpBuffer nameusing;
12998 PGresult *res_procs;
13001 int i_amopstrategy;
13002 int i_amopreqcheck;
13005 int i_sortfamilynsp;
13008 int i_amproclefttype;
13009 int i_amprocrighttype;
13011 char *amopstrategy;
13012 char *amopreqcheck;
13015 char *sortfamilynsp;
13018 char *amproclefttype;
13019 char *amprocrighttype;
13023 /* Skip if not to be dumped */
13024 if (!opfinfo->dobj.dump || dopt->dataOnly)
13027 query = createPQExpBuffer();
13028 q = createPQExpBuffer();
13029 delq = createPQExpBuffer();
13030 nameusing = createPQExpBuffer();
13033 * Fetch only those opfamily members that are tied directly to the
13034 * opfamily by pg_depend entries.
13036 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13037 * older server's opclass in which it is used. This is to avoid
13038 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13039 * older server and then reload into that old version. This can go away
13040 * once 8.3 is so old as to not be of interest to anyone.
13042 if (fout->remoteVersion >= 90100)
13044 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13045 "amopopr::pg_catalog.regoperator, "
13046 "opfname AS sortfamily, "
13047 "nspname AS sortfamilynsp "
13048 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13049 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13050 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13051 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13052 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13053 "AND refobjid = '%u'::pg_catalog.oid "
13054 "AND amopfamily = '%u'::pg_catalog.oid "
13055 "ORDER BY amopstrategy",
13056 opfinfo->dobj.catId.oid,
13057 opfinfo->dobj.catId.oid);
13059 else if (fout->remoteVersion >= 80400)
13061 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13062 "amopopr::pg_catalog.regoperator, "
13063 "NULL AS sortfamily, "
13064 "NULL AS sortfamilynsp "
13065 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13066 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13067 "AND refobjid = '%u'::pg_catalog.oid "
13068 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13069 "AND objid = ao.oid "
13070 "ORDER BY amopstrategy",
13071 opfinfo->dobj.catId.oid);
13075 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13076 "amopopr::pg_catalog.regoperator, "
13077 "NULL AS sortfamily, "
13078 "NULL AS sortfamilynsp "
13079 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13080 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13081 "AND refobjid = '%u'::pg_catalog.oid "
13082 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13083 "AND objid = ao.oid "
13084 "ORDER BY amopstrategy",
13085 opfinfo->dobj.catId.oid);
13088 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13090 resetPQExpBuffer(query);
13092 appendPQExpBuffer(query, "SELECT amprocnum, "
13093 "amproc::pg_catalog.regprocedure, "
13094 "amproclefttype::pg_catalog.regtype, "
13095 "amprocrighttype::pg_catalog.regtype "
13096 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13097 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13098 "AND refobjid = '%u'::pg_catalog.oid "
13099 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13100 "AND objid = ap.oid "
13101 "ORDER BY amprocnum",
13102 opfinfo->dobj.catId.oid);
13104 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13106 /* Get additional fields from the pg_opfamily row */
13107 resetPQExpBuffer(query);
13109 appendPQExpBuffer(query, "SELECT "
13110 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13111 "FROM pg_catalog.pg_opfamily "
13112 "WHERE oid = '%u'::pg_catalog.oid",
13113 opfinfo->dobj.catId.oid);
13115 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13117 i_amname = PQfnumber(res, "amname");
13119 /* amname will still be needed after we PQclear res */
13120 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13122 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13123 fmtQualifiedDumpable(opfinfo));
13124 appendPQExpBuffer(delq, " USING %s;\n",
13127 /* Build the fixed portion of the CREATE command */
13128 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13129 fmtQualifiedDumpable(opfinfo));
13130 appendPQExpBuffer(q, " USING %s;\n",
13135 /* Do we need an ALTER to add loose members? */
13136 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13138 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13139 fmtQualifiedDumpable(opfinfo));
13140 appendPQExpBuffer(q, " USING %s ADD\n ",
13146 * Now fetch and print the OPERATOR entries (pg_amop rows).
13148 ntups = PQntuples(res_ops);
13150 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13151 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13152 i_amopopr = PQfnumber(res_ops, "amopopr");
13153 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13154 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13156 for (i = 0; i < ntups; i++)
13158 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13159 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13160 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13161 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13162 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13165 appendPQExpBufferStr(q, " ,\n ");
13167 appendPQExpBuffer(q, "OPERATOR %s %s",
13168 amopstrategy, amopopr);
13170 if (strlen(sortfamily) > 0)
13172 appendPQExpBufferStr(q, " FOR ORDER BY ");
13173 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13174 appendPQExpBufferStr(q, fmtId(sortfamily));
13177 if (strcmp(amopreqcheck, "t") == 0)
13178 appendPQExpBufferStr(q, " RECHECK");
13184 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13186 ntups = PQntuples(res_procs);
13188 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13189 i_amproc = PQfnumber(res_procs, "amproc");
13190 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13191 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13193 for (i = 0; i < ntups; i++)
13195 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13196 amproc = PQgetvalue(res_procs, i, i_amproc);
13197 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13198 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13201 appendPQExpBufferStr(q, " ,\n ");
13203 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13204 amprocnum, amproclefttype, amprocrighttype,
13210 appendPQExpBufferStr(q, ";\n");
13213 appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13214 appendPQExpBuffer(nameusing, " USING %s",
13217 if (dopt->binary_upgrade)
13218 binary_upgrade_extension_member(q, &opfinfo->dobj,
13219 "OPERATOR FAMILY", nameusing->data,
13220 opfinfo->dobj.namespace->dobj.name);
13222 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13223 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13224 opfinfo->dobj.name,
13225 opfinfo->dobj.namespace->dobj.name,
13228 "OPERATOR FAMILY", SECTION_PRE_DATA,
13229 q->data, delq->data, NULL,
13233 /* Dump Operator Family Comments */
13234 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13235 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13236 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13237 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13241 PQclear(res_procs);
13242 destroyPQExpBuffer(query);
13243 destroyPQExpBuffer(q);
13244 destroyPQExpBuffer(delq);
13245 destroyPQExpBuffer(nameusing);
13250 * write out a single collation definition
13253 dumpCollation(Archive *fout, CollInfo *collinfo)
13255 DumpOptions *dopt = fout->dopt;
13261 int i_collprovider;
13264 const char *collprovider;
13265 const char *collcollate;
13266 const char *collctype;
13268 /* Skip if not to be dumped */
13269 if (!collinfo->dobj.dump || dopt->dataOnly)
13272 query = createPQExpBuffer();
13273 q = createPQExpBuffer();
13274 delq = createPQExpBuffer();
13276 qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13278 /* Get collation-specific details */
13279 if (fout->remoteVersion >= 100000)
13280 appendPQExpBuffer(query, "SELECT "
13285 "FROM pg_catalog.pg_collation c "
13286 "WHERE c.oid = '%u'::pg_catalog.oid",
13287 collinfo->dobj.catId.oid);
13289 appendPQExpBuffer(query, "SELECT "
13290 "'c' AS collprovider, "
13293 "NULL AS collversion "
13294 "FROM pg_catalog.pg_collation c "
13295 "WHERE c.oid = '%u'::pg_catalog.oid",
13296 collinfo->dobj.catId.oid);
13298 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13300 i_collprovider = PQfnumber(res, "collprovider");
13301 i_collcollate = PQfnumber(res, "collcollate");
13302 i_collctype = PQfnumber(res, "collctype");
13304 collprovider = PQgetvalue(res, 0, i_collprovider);
13305 collcollate = PQgetvalue(res, 0, i_collcollate);
13306 collctype = PQgetvalue(res, 0, i_collctype);
13308 appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13309 fmtQualifiedDumpable(collinfo));
13311 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13312 fmtQualifiedDumpable(collinfo));
13314 appendPQExpBufferStr(q, "provider = ");
13315 if (collprovider[0] == 'c')
13316 appendPQExpBufferStr(q, "libc");
13317 else if (collprovider[0] == 'i')
13318 appendPQExpBufferStr(q, "icu");
13319 else if (collprovider[0] == 'd')
13320 /* to allow dumping pg_catalog; not accepted on input */
13321 appendPQExpBufferStr(q, "default");
13323 exit_horribly(NULL,
13324 "unrecognized collation provider: %s\n",
13327 if (strcmp(collcollate, collctype) == 0)
13329 appendPQExpBufferStr(q, ", locale = ");
13330 appendStringLiteralAH(q, collcollate, fout);
13334 appendPQExpBufferStr(q, ", lc_collate = ");
13335 appendStringLiteralAH(q, collcollate, fout);
13336 appendPQExpBufferStr(q, ", lc_ctype = ");
13337 appendStringLiteralAH(q, collctype, fout);
13341 * For binary upgrade, carry over the collation version. For normal
13342 * dump/restore, omit the version, so that it is computed upon restore.
13344 if (dopt->binary_upgrade)
13348 i_collversion = PQfnumber(res, "collversion");
13349 if (!PQgetisnull(res, 0, i_collversion))
13351 appendPQExpBufferStr(q, ", version = ");
13352 appendStringLiteralAH(q,
13353 PQgetvalue(res, 0, i_collversion),
13358 appendPQExpBufferStr(q, ");\n");
13360 if (dopt->binary_upgrade)
13361 binary_upgrade_extension_member(q, &collinfo->dobj,
13362 "COLLATION", qcollname,
13363 collinfo->dobj.namespace->dobj.name);
13365 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13366 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13367 collinfo->dobj.name,
13368 collinfo->dobj.namespace->dobj.name,
13371 "COLLATION", SECTION_PRE_DATA,
13372 q->data, delq->data, NULL,
13376 /* Dump Collation Comments */
13377 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13378 dumpComment(fout, "COLLATION", qcollname,
13379 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13380 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13384 destroyPQExpBuffer(query);
13385 destroyPQExpBuffer(q);
13386 destroyPQExpBuffer(delq);
13392 * write out a single conversion definition
13395 dumpConversion(Archive *fout, ConvInfo *convinfo)
13397 DumpOptions *dopt = fout->dopt;
13403 int i_conforencoding;
13404 int i_contoencoding;
13407 const char *conforencoding;
13408 const char *contoencoding;
13409 const char *conproc;
13412 /* Skip if not to be dumped */
13413 if (!convinfo->dobj.dump || dopt->dataOnly)
13416 query = createPQExpBuffer();
13417 q = createPQExpBuffer();
13418 delq = createPQExpBuffer();
13420 qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13422 /* Get conversion-specific details */
13423 appendPQExpBuffer(query, "SELECT "
13424 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13425 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13426 "conproc, condefault "
13427 "FROM pg_catalog.pg_conversion c "
13428 "WHERE c.oid = '%u'::pg_catalog.oid",
13429 convinfo->dobj.catId.oid);
13431 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13433 i_conforencoding = PQfnumber(res, "conforencoding");
13434 i_contoencoding = PQfnumber(res, "contoencoding");
13435 i_conproc = PQfnumber(res, "conproc");
13436 i_condefault = PQfnumber(res, "condefault");
13438 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13439 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13440 conproc = PQgetvalue(res, 0, i_conproc);
13441 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13443 appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13444 fmtQualifiedDumpable(convinfo));
13446 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13447 (condefault) ? "DEFAULT " : "",
13448 fmtQualifiedDumpable(convinfo));
13449 appendStringLiteralAH(q, conforencoding, fout);
13450 appendPQExpBufferStr(q, " TO ");
13451 appendStringLiteralAH(q, contoencoding, fout);
13452 /* regproc output is already sufficiently quoted */
13453 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13455 if (dopt->binary_upgrade)
13456 binary_upgrade_extension_member(q, &convinfo->dobj,
13457 "CONVERSION", qconvname,
13458 convinfo->dobj.namespace->dobj.name);
13460 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13461 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13462 convinfo->dobj.name,
13463 convinfo->dobj.namespace->dobj.name,
13466 "CONVERSION", SECTION_PRE_DATA,
13467 q->data, delq->data, NULL,
13471 /* Dump Conversion Comments */
13472 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13473 dumpComment(fout, "CONVERSION", qconvname,
13474 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13475 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13479 destroyPQExpBuffer(query);
13480 destroyPQExpBuffer(q);
13481 destroyPQExpBuffer(delq);
13486 * format_aggregate_signature: generate aggregate name and argument list
13488 * The argument type names are qualified if needed. The aggregate name
13489 * is never qualified.
13492 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13494 PQExpBufferData buf;
13497 initPQExpBuffer(&buf);
13499 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13501 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13503 if (agginfo->aggfn.nargs == 0)
13504 appendPQExpBuffer(&buf, "(*)");
13507 appendPQExpBufferChar(&buf, '(');
13508 for (j = 0; j < agginfo->aggfn.nargs; j++)
13512 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13515 appendPQExpBuffer(&buf, "%s%s",
13516 (j > 0) ? ", " : "",
13520 appendPQExpBufferChar(&buf, ')');
13527 * write out a single aggregate definition
13530 dumpAgg(Archive *fout, AggInfo *agginfo)
13532 DumpOptions *dopt = fout->dopt;
13536 PQExpBuffer details;
13537 char *aggsig; /* identity signature */
13538 char *aggfullsig = NULL; /* full signature */
13543 int i_aggcombinefn;
13545 int i_aggdeserialfn;
13547 int i_aggminvtransfn;
13549 int i_aggfinalextra;
13550 int i_aggmfinalextra;
13551 int i_aggfinalmodify;
13552 int i_aggmfinalmodify;
13555 int i_aggtranstype;
13556 int i_aggtransspace;
13557 int i_aggmtranstype;
13558 int i_aggmtransspace;
13563 const char *aggtransfn;
13564 const char *aggfinalfn;
13565 const char *aggcombinefn;
13566 const char *aggserialfn;
13567 const char *aggdeserialfn;
13568 const char *aggmtransfn;
13569 const char *aggminvtransfn;
13570 const char *aggmfinalfn;
13571 bool aggfinalextra;
13572 bool aggmfinalextra;
13573 char aggfinalmodify;
13574 char aggmfinalmodify;
13575 const char *aggsortop;
13576 char *aggsortconvop;
13578 const char *aggtranstype;
13579 const char *aggtransspace;
13580 const char *aggmtranstype;
13581 const char *aggmtransspace;
13582 const char *agginitval;
13583 const char *aggminitval;
13585 const char *proparallel;
13586 char defaultfinalmodify;
13588 /* Skip if not to be dumped */
13589 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13592 query = createPQExpBuffer();
13593 q = createPQExpBuffer();
13594 delq = createPQExpBuffer();
13595 details = createPQExpBuffer();
13597 /* Get aggregate-specific details */
13598 if (fout->remoteVersion >= 110000)
13600 appendPQExpBuffer(query, "SELECT aggtransfn, "
13601 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13602 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13603 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13604 "aggfinalextra, aggmfinalextra, "
13605 "aggfinalmodify, aggmfinalmodify, "
13608 "aggtransspace, agginitval, "
13609 "aggmtransspace, aggminitval, "
13610 "true AS convertok, "
13611 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13612 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13614 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13615 "WHERE a.aggfnoid = p.oid "
13616 "AND p.oid = '%u'::pg_catalog.oid",
13617 agginfo->aggfn.dobj.catId.oid);
13619 else if (fout->remoteVersion >= 90600)
13621 appendPQExpBuffer(query, "SELECT aggtransfn, "
13622 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13623 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13624 "aggminvtransfn, 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, "
13635 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13636 "WHERE a.aggfnoid = p.oid "
13637 "AND p.oid = '%u'::pg_catalog.oid",
13638 agginfo->aggfn.dobj.catId.oid);
13640 else if (fout->remoteVersion >= 90400)
13642 appendPQExpBuffer(query, "SELECT aggtransfn, "
13643 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13644 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13645 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13646 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13647 "aggfinalextra, aggmfinalextra, "
13648 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13651 "aggtransspace, agginitval, "
13652 "aggmtransspace, 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 >= 80400)
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 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13677 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13678 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13679 "WHERE a.aggfnoid = p.oid "
13680 "AND p.oid = '%u'::pg_catalog.oid",
13681 agginfo->aggfn.dobj.catId.oid);
13683 else if (fout->remoteVersion >= 80100)
13685 appendPQExpBuffer(query, "SELECT aggtransfn, "
13686 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13687 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13688 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13689 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13690 "0 AS aggmtranstype, false AS aggfinalextra, "
13691 "false AS aggmfinalextra, "
13692 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13695 "0 AS aggtransspace, agginitval, "
13696 "0 AS aggmtransspace, NULL AS aggminitval, "
13697 "true AS convertok "
13698 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13699 "WHERE a.aggfnoid = p.oid "
13700 "AND p.oid = '%u'::pg_catalog.oid",
13701 agginfo->aggfn.dobj.catId.oid);
13705 appendPQExpBuffer(query, "SELECT aggtransfn, "
13706 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13707 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13708 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13709 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13710 "0 AS aggmtranstype, false AS aggfinalextra, "
13711 "false AS aggmfinalextra, "
13712 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13715 "0 AS aggtransspace, agginitval, "
13716 "0 AS aggmtransspace, NULL AS aggminitval, "
13717 "true AS convertok "
13718 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13719 "WHERE a.aggfnoid = p.oid "
13720 "AND p.oid = '%u'::pg_catalog.oid",
13721 agginfo->aggfn.dobj.catId.oid);
13724 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13726 i_aggtransfn = PQfnumber(res, "aggtransfn");
13727 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13728 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13729 i_aggserialfn = PQfnumber(res, "aggserialfn");
13730 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13731 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13732 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13733 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13734 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13735 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13736 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13737 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13738 i_aggsortop = PQfnumber(res, "aggsortop");
13739 i_aggkind = PQfnumber(res, "aggkind");
13740 i_aggtranstype = PQfnumber(res, "aggtranstype");
13741 i_aggtransspace = PQfnumber(res, "aggtransspace");
13742 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13743 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13744 i_agginitval = PQfnumber(res, "agginitval");
13745 i_aggminitval = PQfnumber(res, "aggminitval");
13746 i_convertok = PQfnumber(res, "convertok");
13747 i_proparallel = PQfnumber(res, "proparallel");
13749 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13750 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13751 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13752 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13753 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13754 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13755 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13756 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13757 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13758 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13759 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13760 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13761 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13762 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13763 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13764 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13765 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13766 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13767 agginitval = PQgetvalue(res, 0, i_agginitval);
13768 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13769 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13771 if (fout->remoteVersion >= 80400)
13773 /* 8.4 or later; we rely on server-side code for most of the work */
13777 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13778 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13779 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13780 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13783 /* pre-8.4, do it ourselves */
13784 aggsig = format_aggregate_signature(agginfo, fout, true);
13786 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13788 if (i_proparallel != -1)
13789 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13791 proparallel = NULL;
13795 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13806 /* identify default modify flag for aggkind (must match DefineAggregate) */
13807 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13808 /* replace omitted flags for old versions */
13809 if (aggfinalmodify == '0')
13810 aggfinalmodify = defaultfinalmodify;
13811 if (aggmfinalmodify == '0')
13812 aggmfinalmodify = defaultfinalmodify;
13814 /* regproc and regtype output is already sufficiently quoted */
13815 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13816 aggtransfn, aggtranstype);
13818 if (strcmp(aggtransspace, "0") != 0)
13820 appendPQExpBuffer(details, ",\n SSPACE = %s",
13824 if (!PQgetisnull(res, 0, i_agginitval))
13826 appendPQExpBufferStr(details, ",\n INITCOND = ");
13827 appendStringLiteralAH(details, agginitval, fout);
13830 if (strcmp(aggfinalfn, "-") != 0)
13832 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13835 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13836 if (aggfinalmodify != defaultfinalmodify)
13838 switch (aggfinalmodify)
13840 case AGGMODIFY_READ_ONLY:
13841 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
13843 case AGGMODIFY_SHAREABLE:
13844 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
13846 case AGGMODIFY_READ_WRITE:
13847 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
13850 exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13851 agginfo->aggfn.dobj.name);
13857 if (strcmp(aggcombinefn, "-") != 0)
13858 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
13860 if (strcmp(aggserialfn, "-") != 0)
13861 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
13863 if (strcmp(aggdeserialfn, "-") != 0)
13864 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
13866 if (strcmp(aggmtransfn, "-") != 0)
13868 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
13874 if (strcmp(aggmtransspace, "0") != 0)
13876 appendPQExpBuffer(details, ",\n MSSPACE = %s",
13880 if (!PQgetisnull(res, 0, i_aggminitval))
13882 appendPQExpBufferStr(details, ",\n MINITCOND = ");
13883 appendStringLiteralAH(details, aggminitval, fout);
13886 if (strcmp(aggmfinalfn, "-") != 0)
13888 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
13890 if (aggmfinalextra)
13891 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
13892 if (aggmfinalmodify != defaultfinalmodify)
13894 switch (aggmfinalmodify)
13896 case AGGMODIFY_READ_ONLY:
13897 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
13899 case AGGMODIFY_SHAREABLE:
13900 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
13902 case AGGMODIFY_READ_WRITE:
13903 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
13906 exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13907 agginfo->aggfn.dobj.name);
13913 aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13916 appendPQExpBuffer(details, ",\n SORTOP = %s",
13918 free(aggsortconvop);
13921 if (aggkind == AGGKIND_HYPOTHETICAL)
13922 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
13924 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13926 if (proparallel[0] == PROPARALLEL_SAFE)
13927 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
13928 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13929 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
13930 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13931 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13932 agginfo->aggfn.dobj.name);
13935 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13936 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13939 appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
13940 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13941 aggfullsig ? aggfullsig : aggsig, details->data);
13943 if (dopt->binary_upgrade)
13944 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
13945 "AGGREGATE", aggsig,
13946 agginfo->aggfn.dobj.namespace->dobj.name);
13948 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
13949 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
13950 agginfo->aggfn.dobj.dumpId,
13952 agginfo->aggfn.dobj.namespace->dobj.name,
13954 agginfo->aggfn.rolname,
13955 "AGGREGATE", SECTION_PRE_DATA,
13956 q->data, delq->data, NULL,
13960 /* Dump Aggregate Comments */
13961 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
13962 dumpComment(fout, "AGGREGATE", aggsig,
13963 agginfo->aggfn.dobj.namespace->dobj.name,
13964 agginfo->aggfn.rolname,
13965 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13967 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
13968 dumpSecLabel(fout, "AGGREGATE", aggsig,
13969 agginfo->aggfn.dobj.namespace->dobj.name,
13970 agginfo->aggfn.rolname,
13971 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13974 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
13975 * command look like a function's GRANT; in particular this affects the
13976 * syntax for zero-argument aggregates and ordered-set aggregates.
13980 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
13982 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
13983 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
13984 "FUNCTION", aggsig, NULL,
13985 agginfo->aggfn.dobj.namespace->dobj.name,
13986 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
13987 agginfo->aggfn.rproacl,
13988 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
13997 destroyPQExpBuffer(query);
13998 destroyPQExpBuffer(q);
13999 destroyPQExpBuffer(delq);
14000 destroyPQExpBuffer(details);
14005 * write out a single text search parser
14008 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14010 DumpOptions *dopt = fout->dopt;
14015 /* Skip if not to be dumped */
14016 if (!prsinfo->dobj.dump || dopt->dataOnly)
14019 q = createPQExpBuffer();
14020 delq = createPQExpBuffer();
14022 qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14024 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14025 fmtQualifiedDumpable(prsinfo));
14027 appendPQExpBuffer(q, " START = %s,\n",
14028 convertTSFunction(fout, prsinfo->prsstart));
14029 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14030 convertTSFunction(fout, prsinfo->prstoken));
14031 appendPQExpBuffer(q, " END = %s,\n",
14032 convertTSFunction(fout, prsinfo->prsend));
14033 if (prsinfo->prsheadline != InvalidOid)
14034 appendPQExpBuffer(q, " HEADLINE = %s,\n",
14035 convertTSFunction(fout, prsinfo->prsheadline));
14036 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14037 convertTSFunction(fout, prsinfo->prslextype));
14039 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14040 fmtQualifiedDumpable(prsinfo));
14042 if (dopt->binary_upgrade)
14043 binary_upgrade_extension_member(q, &prsinfo->dobj,
14044 "TEXT SEARCH PARSER", qprsname,
14045 prsinfo->dobj.namespace->dobj.name);
14047 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14048 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14049 prsinfo->dobj.name,
14050 prsinfo->dobj.namespace->dobj.name,
14053 "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14054 q->data, delq->data, NULL,
14058 /* Dump Parser Comments */
14059 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14060 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14061 prsinfo->dobj.namespace->dobj.name, "",
14062 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14064 destroyPQExpBuffer(q);
14065 destroyPQExpBuffer(delq);
14071 * write out a single text search dictionary
14074 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14076 DumpOptions *dopt = fout->dopt;
14085 /* Skip if not to be dumped */
14086 if (!dictinfo->dobj.dump || dopt->dataOnly)
14089 q = createPQExpBuffer();
14090 delq = createPQExpBuffer();
14091 query = createPQExpBuffer();
14093 qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14095 /* Fetch name and namespace of the dictionary's template */
14096 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14097 "FROM pg_ts_template p, pg_namespace n "
14098 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14099 dictinfo->dicttemplate);
14100 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14101 nspname = PQgetvalue(res, 0, 0);
14102 tmplname = PQgetvalue(res, 0, 1);
14104 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14105 fmtQualifiedDumpable(dictinfo));
14107 appendPQExpBufferStr(q, " TEMPLATE = ");
14108 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14109 appendPQExpBufferStr(q, fmtId(tmplname));
14113 /* the dictinitoption can be dumped straight into the command */
14114 if (dictinfo->dictinitoption)
14115 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14117 appendPQExpBufferStr(q, " );\n");
14119 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14120 fmtQualifiedDumpable(dictinfo));
14122 if (dopt->binary_upgrade)
14123 binary_upgrade_extension_member(q, &dictinfo->dobj,
14124 "TEXT SEARCH DICTIONARY", qdictname,
14125 dictinfo->dobj.namespace->dobj.name);
14127 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14128 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14129 dictinfo->dobj.name,
14130 dictinfo->dobj.namespace->dobj.name,
14133 "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14134 q->data, delq->data, NULL,
14138 /* Dump Dictionary Comments */
14139 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14140 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14141 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14142 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14144 destroyPQExpBuffer(q);
14145 destroyPQExpBuffer(delq);
14146 destroyPQExpBuffer(query);
14152 * write out a single text search template
14155 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14157 DumpOptions *dopt = fout->dopt;
14162 /* Skip if not to be dumped */
14163 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14166 q = createPQExpBuffer();
14167 delq = createPQExpBuffer();
14169 qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14171 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14172 fmtQualifiedDumpable(tmplinfo));
14174 if (tmplinfo->tmplinit != InvalidOid)
14175 appendPQExpBuffer(q, " INIT = %s,\n",
14176 convertTSFunction(fout, tmplinfo->tmplinit));
14177 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14178 convertTSFunction(fout, tmplinfo->tmpllexize));
14180 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14181 fmtQualifiedDumpable(tmplinfo));
14183 if (dopt->binary_upgrade)
14184 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14185 "TEXT SEARCH TEMPLATE", qtmplname,
14186 tmplinfo->dobj.namespace->dobj.name);
14188 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14189 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14190 tmplinfo->dobj.name,
14191 tmplinfo->dobj.namespace->dobj.name,
14194 "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14195 q->data, delq->data, NULL,
14199 /* Dump Template Comments */
14200 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14201 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14202 tmplinfo->dobj.namespace->dobj.name, "",
14203 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14205 destroyPQExpBuffer(q);
14206 destroyPQExpBuffer(delq);
14212 * write out a single text search configuration
14215 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14217 DumpOptions *dopt = fout->dopt;
14230 /* Skip if not to be dumped */
14231 if (!cfginfo->dobj.dump || dopt->dataOnly)
14234 q = createPQExpBuffer();
14235 delq = createPQExpBuffer();
14236 query = createPQExpBuffer();
14238 qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14240 /* Fetch name and namespace of the config's parser */
14241 appendPQExpBuffer(query, "SELECT nspname, prsname "
14242 "FROM pg_ts_parser p, pg_namespace n "
14243 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14244 cfginfo->cfgparser);
14245 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14246 nspname = PQgetvalue(res, 0, 0);
14247 prsname = PQgetvalue(res, 0, 1);
14249 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14250 fmtQualifiedDumpable(cfginfo));
14252 appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14253 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14257 resetPQExpBuffer(query);
14258 appendPQExpBuffer(query,
14260 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14261 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14262 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14263 "FROM pg_catalog.pg_ts_config_map AS m\n"
14264 "WHERE m.mapcfg = '%u'\n"
14265 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14266 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14268 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14269 ntups = PQntuples(res);
14271 i_tokenname = PQfnumber(res, "tokenname");
14272 i_dictname = PQfnumber(res, "dictname");
14274 for (i = 0; i < ntups; i++)
14276 char *tokenname = PQgetvalue(res, i, i_tokenname);
14277 char *dictname = PQgetvalue(res, i, i_dictname);
14280 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14282 /* starting a new token type, so start a new command */
14284 appendPQExpBufferStr(q, ";\n");
14285 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14286 fmtQualifiedDumpable(cfginfo));
14287 /* tokenname needs quoting, dictname does NOT */
14288 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14289 fmtId(tokenname), dictname);
14292 appendPQExpBuffer(q, ", %s", dictname);
14296 appendPQExpBufferStr(q, ";\n");
14300 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14301 fmtQualifiedDumpable(cfginfo));
14303 if (dopt->binary_upgrade)
14304 binary_upgrade_extension_member(q, &cfginfo->dobj,
14305 "TEXT SEARCH CONFIGURATION", qcfgname,
14306 cfginfo->dobj.namespace->dobj.name);
14308 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14309 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14310 cfginfo->dobj.name,
14311 cfginfo->dobj.namespace->dobj.name,
14314 "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14315 q->data, delq->data, NULL,
14319 /* Dump Configuration Comments */
14320 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14321 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14322 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14323 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14325 destroyPQExpBuffer(q);
14326 destroyPQExpBuffer(delq);
14327 destroyPQExpBuffer(query);
14332 * dumpForeignDataWrapper
14333 * write out a single foreign-data wrapper definition
14336 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14338 DumpOptions *dopt = fout->dopt;
14343 /* Skip if not to be dumped */
14344 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14347 q = createPQExpBuffer();
14348 delq = createPQExpBuffer();
14350 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14352 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14355 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14356 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14358 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14359 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14361 if (strlen(fdwinfo->fdwoptions) > 0)
14362 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14364 appendPQExpBufferStr(q, ";\n");
14366 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14369 if (dopt->binary_upgrade)
14370 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14371 "FOREIGN DATA WRAPPER", qfdwname,
14374 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14375 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14376 fdwinfo->dobj.name,
14380 "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14381 q->data, delq->data, NULL,
14385 /* Dump Foreign Data Wrapper Comments */
14386 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14387 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14388 NULL, fdwinfo->rolname,
14389 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14391 /* Handle the ACL */
14392 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14393 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14394 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14395 NULL, fdwinfo->rolname,
14396 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14397 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14401 destroyPQExpBuffer(q);
14402 destroyPQExpBuffer(delq);
14406 * dumpForeignServer
14407 * write out a foreign server definition
14410 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14412 DumpOptions *dopt = fout->dopt;
14420 /* Skip if not to be dumped */
14421 if (!srvinfo->dobj.dump || dopt->dataOnly)
14424 q = createPQExpBuffer();
14425 delq = createPQExpBuffer();
14426 query = createPQExpBuffer();
14428 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14430 /* look up the foreign-data wrapper */
14431 appendPQExpBuffer(query, "SELECT fdwname "
14432 "FROM pg_foreign_data_wrapper w "
14433 "WHERE w.oid = '%u'",
14435 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14436 fdwname = PQgetvalue(res, 0, 0);
14438 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14439 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14441 appendPQExpBufferStr(q, " TYPE ");
14442 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14444 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14446 appendPQExpBufferStr(q, " VERSION ");
14447 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14450 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14451 appendPQExpBufferStr(q, fmtId(fdwname));
14453 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14454 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14456 appendPQExpBufferStr(q, ";\n");
14458 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14461 if (dopt->binary_upgrade)
14462 binary_upgrade_extension_member(q, &srvinfo->dobj,
14463 "SERVER", qsrvname, NULL);
14465 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14466 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14467 srvinfo->dobj.name,
14471 "SERVER", SECTION_PRE_DATA,
14472 q->data, delq->data, NULL,
14476 /* Dump Foreign Server Comments */
14477 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14478 dumpComment(fout, "SERVER", qsrvname,
14479 NULL, srvinfo->rolname,
14480 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14482 /* Handle the ACL */
14483 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14484 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14485 "FOREIGN SERVER", qsrvname, NULL,
14486 NULL, srvinfo->rolname,
14487 srvinfo->srvacl, srvinfo->rsrvacl,
14488 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14490 /* Dump user mappings */
14491 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14492 dumpUserMappings(fout,
14493 srvinfo->dobj.name, NULL,
14495 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14499 destroyPQExpBuffer(q);
14500 destroyPQExpBuffer(delq);
14501 destroyPQExpBuffer(query);
14507 * This routine is used to dump any user mappings associated with the
14508 * server handed to this routine. Should be called after ArchiveEntry()
14512 dumpUserMappings(Archive *fout,
14513 const char *servername, const char *namespace,
14515 CatalogId catalogId, DumpId dumpId)
14527 q = createPQExpBuffer();
14528 tag = createPQExpBuffer();
14529 delq = createPQExpBuffer();
14530 query = createPQExpBuffer();
14533 * We read from the publicly accessible view pg_user_mappings, so as not
14534 * to fail if run by a non-superuser. Note that the view will show
14535 * umoptions as null if the user hasn't got privileges for the associated
14536 * server; this means that pg_dump will dump such a mapping, but with no
14537 * OPTIONS clause. A possible alternative is to skip such mappings
14538 * altogether, but it's not clear that that's an improvement.
14540 appendPQExpBuffer(query,
14542 "array_to_string(ARRAY("
14543 "SELECT quote_ident(option_name) || ' ' || "
14544 "quote_literal(option_value) "
14545 "FROM pg_options_to_table(umoptions) "
14546 "ORDER BY option_name"
14547 "), E',\n ') AS umoptions "
14548 "FROM pg_user_mappings "
14549 "WHERE srvid = '%u' "
14550 "ORDER BY usename",
14553 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14555 ntups = PQntuples(res);
14556 i_usename = PQfnumber(res, "usename");
14557 i_umoptions = PQfnumber(res, "umoptions");
14559 for (i = 0; i < ntups; i++)
14564 usename = PQgetvalue(res, i, i_usename);
14565 umoptions = PQgetvalue(res, i, i_umoptions);
14567 resetPQExpBuffer(q);
14568 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14569 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14571 if (umoptions && strlen(umoptions) > 0)
14572 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14574 appendPQExpBufferStr(q, ";\n");
14576 resetPQExpBuffer(delq);
14577 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14578 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14580 resetPQExpBuffer(tag);
14581 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14582 usename, servername);
14584 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14589 "USER MAPPING", SECTION_PRE_DATA,
14590 q->data, delq->data, NULL,
14597 destroyPQExpBuffer(query);
14598 destroyPQExpBuffer(delq);
14599 destroyPQExpBuffer(tag);
14600 destroyPQExpBuffer(q);
14604 * Write out default privileges information
14607 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14609 DumpOptions *dopt = fout->dopt;
14614 /* Skip if not to be dumped */
14615 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14618 q = createPQExpBuffer();
14619 tag = createPQExpBuffer();
14621 switch (daclinfo->defaclobjtype)
14623 case DEFACLOBJ_RELATION:
14626 case DEFACLOBJ_SEQUENCE:
14627 type = "SEQUENCES";
14629 case DEFACLOBJ_FUNCTION:
14630 type = "FUNCTIONS";
14632 case DEFACLOBJ_TYPE:
14635 case DEFACLOBJ_NAMESPACE:
14639 /* shouldn't get here */
14640 exit_horribly(NULL,
14641 "unrecognized object type in default privileges: %d\n",
14642 (int) daclinfo->defaclobjtype);
14643 type = ""; /* keep compiler quiet */
14646 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14648 /* build the actual command(s) for this tuple */
14649 if (!buildDefaultACLCommands(type,
14650 daclinfo->dobj.namespace != NULL ?
14651 daclinfo->dobj.namespace->dobj.name : NULL,
14652 daclinfo->defaclacl,
14653 daclinfo->rdefaclacl,
14654 daclinfo->initdefaclacl,
14655 daclinfo->initrdefaclacl,
14656 daclinfo->defaclrole,
14657 fout->remoteVersion,
14659 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14660 daclinfo->defaclacl);
14662 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14663 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14665 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14667 daclinfo->defaclrole,
14668 "DEFAULT ACL", SECTION_POST_DATA,
14673 destroyPQExpBuffer(tag);
14674 destroyPQExpBuffer(q);
14678 * Write out grant/revoke information
14680 * 'objCatId' is the catalog ID of the underlying object.
14681 * 'objDumpId' is the dump ID of the underlying object.
14682 * 'type' must be one of
14683 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14684 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14685 * 'name' is the formatted name of the object. Must be quoted etc. already.
14686 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14687 * (Currently we assume that subname is only provided for table columns.)
14688 * 'nspname' is the namespace the object is in (NULL if none).
14689 * 'owner' is the owner, NULL if there is no owner (for languages).
14690 * 'acls' contains the ACL string of the object from the appropriate system
14691 * catalog field; it will be passed to buildACLCommands for building the
14692 * appropriate GRANT commands.
14693 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14694 * object; it will be passed to buildACLCommands for building the
14695 * appropriate REVOKE commands.
14696 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14697 * privileges, to be recorded into pg_init_privs
14698 * 'initracls' In binary-upgrade mode, ACL string of the object's
14699 * revoked-from-default privileges, to be recorded into pg_init_privs
14701 * NB: initacls/initracls are needed because extensions can set privileges on
14702 * an object during the extension's script file and we record those into
14703 * pg_init_privs as that object's initial privileges.
14707 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14708 const char *type, const char *name, const char *subname,
14709 const char *nspname, const char *owner,
14710 const char *acls, const char *racls,
14711 const char *initacls, const char *initracls)
14713 DumpOptions *dopt = fout->dopt;
14716 /* Do nothing if ACL dump is not enabled */
14717 if (dopt->aclsSkip)
14720 /* --data-only skips ACLs *except* BLOB ACLs */
14721 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14724 sql = createPQExpBuffer();
14727 * Check to see if this object has had any initial ACLs included for it.
14728 * If so, we are in binary upgrade mode and these are the ACLs to turn
14729 * into GRANT and REVOKE statements to set and record the initial
14730 * privileges for an extension object. Let the backend know that these
14731 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14732 * before and after.
14734 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14736 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14737 if (!buildACLCommands(name, subname, nspname, type,
14738 initacls, initracls, owner,
14739 "", fout->remoteVersion, sql))
14740 exit_horribly(NULL,
14741 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14742 initacls, initracls, name, type);
14743 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14746 if (!buildACLCommands(name, subname, nspname, type,
14747 acls, racls, owner,
14748 "", fout->remoteVersion, sql))
14749 exit_horribly(NULL,
14750 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14751 acls, racls, name, type);
14755 PQExpBuffer tag = createPQExpBuffer();
14758 appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14760 appendPQExpBuffer(tag, "%s %s", type, name);
14762 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14763 tag->data, nspname,
14765 owner ? owner : "",
14766 "ACL", SECTION_NONE,
14767 sql->data, "", NULL,
14770 destroyPQExpBuffer(tag);
14773 destroyPQExpBuffer(sql);
14779 * This routine is used to dump any security labels associated with the
14780 * object handed to this routine. The routine takes the object type
14781 * and object name (ready to print, except for schema decoration), plus
14782 * the namespace and owner of the object (for labeling the ArchiveEntry),
14783 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14784 * plus the dump ID for the object (for setting a dependency).
14785 * If a matching pg_seclabel entry is found, it is dumped.
14787 * Note: although this routine takes a dumpId for dependency purposes,
14788 * that purpose is just to mark the dependency in the emitted dump file
14789 * for possible future use by pg_restore. We do NOT use it for determining
14790 * ordering of the label in the dump file, because this routine is called
14791 * after dependency sorting occurs. This routine should be called just after
14792 * calling ArchiveEntry() for the specified object.
14795 dumpSecLabel(Archive *fout, const char *type, const char *name,
14796 const char *namespace, const char *owner,
14797 CatalogId catalogId, int subid, DumpId dumpId)
14799 DumpOptions *dopt = fout->dopt;
14800 SecLabelItem *labels;
14805 /* do nothing, if --no-security-labels is supplied */
14806 if (dopt->no_security_labels)
14809 /* Security labels are schema not data ... except blob labels are data */
14810 if (strcmp(type, "LARGE OBJECT") != 0)
14812 if (dopt->dataOnly)
14817 /* We do dump blob security labels in binary-upgrade mode */
14818 if (dopt->schemaOnly && !dopt->binary_upgrade)
14822 /* Search for security labels associated with catalogId, using table */
14823 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14825 query = createPQExpBuffer();
14827 for (i = 0; i < nlabels; i++)
14830 * Ignore label entries for which the subid doesn't match.
14832 if (labels[i].objsubid != subid)
14835 appendPQExpBuffer(query,
14836 "SECURITY LABEL FOR %s ON %s ",
14837 fmtId(labels[i].provider), type);
14838 if (namespace && *namespace)
14839 appendPQExpBuffer(query, "%s.", fmtId(namespace));
14840 appendPQExpBuffer(query, "%s IS ", name);
14841 appendStringLiteralAH(query, labels[i].label, fout);
14842 appendPQExpBufferStr(query, ";\n");
14845 if (query->len > 0)
14847 PQExpBuffer tag = createPQExpBuffer();
14849 appendPQExpBuffer(tag, "%s %s", type, name);
14850 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14851 tag->data, namespace, NULL, owner,
14852 "SECURITY LABEL", SECTION_NONE,
14853 query->data, "", NULL,
14856 destroyPQExpBuffer(tag);
14859 destroyPQExpBuffer(query);
14863 * dumpTableSecLabel
14865 * As above, but dump security label for both the specified table (or view)
14869 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14871 DumpOptions *dopt = fout->dopt;
14872 SecLabelItem *labels;
14876 PQExpBuffer target;
14878 /* do nothing, if --no-security-labels is supplied */
14879 if (dopt->no_security_labels)
14882 /* SecLabel are SCHEMA not data */
14883 if (dopt->dataOnly)
14886 /* Search for comments associated with relation, using table */
14887 nlabels = findSecLabels(fout,
14888 tbinfo->dobj.catId.tableoid,
14889 tbinfo->dobj.catId.oid,
14892 /* If security labels exist, build SECURITY LABEL statements */
14896 query = createPQExpBuffer();
14897 target = createPQExpBuffer();
14899 for (i = 0; i < nlabels; i++)
14901 const char *colname;
14902 const char *provider = labels[i].provider;
14903 const char *label = labels[i].label;
14904 int objsubid = labels[i].objsubid;
14906 resetPQExpBuffer(target);
14909 appendPQExpBuffer(target, "%s %s", reltypename,
14910 fmtQualifiedDumpable(tbinfo));
14914 colname = getAttrName(objsubid, tbinfo);
14915 /* first fmtXXX result must be consumed before calling again */
14916 appendPQExpBuffer(target, "COLUMN %s",
14917 fmtQualifiedDumpable(tbinfo));
14918 appendPQExpBuffer(target, ".%s", fmtId(colname));
14920 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14921 fmtId(provider), target->data);
14922 appendStringLiteralAH(query, label, fout);
14923 appendPQExpBufferStr(query, ";\n");
14925 if (query->len > 0)
14927 resetPQExpBuffer(target);
14928 appendPQExpBuffer(target, "%s %s", reltypename,
14929 fmtId(tbinfo->dobj.name));
14930 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14932 tbinfo->dobj.namespace->dobj.name,
14933 NULL, tbinfo->rolname,
14934 "SECURITY LABEL", SECTION_NONE,
14935 query->data, "", NULL,
14936 &(tbinfo->dobj.dumpId), 1,
14939 destroyPQExpBuffer(query);
14940 destroyPQExpBuffer(target);
14946 * Find the security label(s), if any, associated with the given object.
14947 * All the objsubid values associated with the given classoid/objoid are
14948 * found with one search.
14951 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
14953 /* static storage for table of security labels */
14954 static SecLabelItem *labels = NULL;
14955 static int nlabels = -1;
14957 SecLabelItem *middle = NULL;
14959 SecLabelItem *high;
14962 /* Get security labels if we didn't already */
14964 nlabels = collectSecLabels(fout, &labels);
14966 if (nlabels <= 0) /* no labels, so no match is possible */
14973 * Do binary search to find some item matching the object.
14976 high = &labels[nlabels - 1];
14977 while (low <= high)
14979 middle = low + (high - low) / 2;
14981 if (classoid < middle->classoid)
14983 else if (classoid > middle->classoid)
14985 else if (objoid < middle->objoid)
14987 else if (objoid > middle->objoid)
14990 break; /* found a match */
14993 if (low > high) /* no matches */
15000 * Now determine how many items match the object. The search loop
15001 * invariant still holds: only items between low and high inclusive could
15005 while (middle > low)
15007 if (classoid != middle[-1].classoid ||
15008 objoid != middle[-1].objoid)
15017 while (middle <= high)
15019 if (classoid != middle->classoid ||
15020 objoid != middle->objoid)
15032 * Construct a table of all security labels available for database objects.
15033 * It's much faster to pull them all at once.
15035 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15038 collectSecLabels(Archive *fout, SecLabelItem **items)
15049 SecLabelItem *labels;
15051 query = createPQExpBuffer();
15053 appendPQExpBufferStr(query,
15054 "SELECT label, provider, classoid, objoid, objsubid "
15055 "FROM pg_catalog.pg_seclabel "
15056 "ORDER BY classoid, objoid, objsubid");
15058 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15060 /* Construct lookup table containing OIDs in numeric form */
15061 i_label = PQfnumber(res, "label");
15062 i_provider = PQfnumber(res, "provider");
15063 i_classoid = PQfnumber(res, "classoid");
15064 i_objoid = PQfnumber(res, "objoid");
15065 i_objsubid = PQfnumber(res, "objsubid");
15067 ntups = PQntuples(res);
15069 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15071 for (i = 0; i < ntups; i++)
15073 labels[i].label = PQgetvalue(res, i, i_label);
15074 labels[i].provider = PQgetvalue(res, i, i_provider);
15075 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15076 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15077 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15080 /* Do NOT free the PGresult since we are keeping pointers into it */
15081 destroyPQExpBuffer(query);
15089 * write out to fout the declarations (not data) of a user-defined table
15092 dumpTable(Archive *fout, TableInfo *tbinfo)
15094 DumpOptions *dopt = fout->dopt;
15098 * noop if we are not dumping anything about this table, or if we are
15099 * doing a data-only dump
15101 if (!tbinfo->dobj.dump || dopt->dataOnly)
15104 if (tbinfo->relkind == RELKIND_SEQUENCE)
15105 dumpSequence(fout, tbinfo);
15107 dumpTableSchema(fout, tbinfo);
15109 /* Handle the ACL here */
15110 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15111 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15113 const char *objtype =
15114 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15116 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15117 objtype, namecopy, NULL,
15118 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15119 tbinfo->relacl, tbinfo->rrelacl,
15120 tbinfo->initrelacl, tbinfo->initrrelacl);
15124 * Handle column ACLs, if any. Note: we pull these with a separate query
15125 * rather than trying to fetch them during getTableAttrs, so that we won't
15126 * miss ACLs on system columns.
15128 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15130 PQExpBuffer query = createPQExpBuffer();
15134 if (fout->remoteVersion >= 90600)
15136 PQExpBuffer acl_subquery = createPQExpBuffer();
15137 PQExpBuffer racl_subquery = createPQExpBuffer();
15138 PQExpBuffer initacl_subquery = createPQExpBuffer();
15139 PQExpBuffer initracl_subquery = createPQExpBuffer();
15141 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15142 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15143 dopt->binary_upgrade);
15145 appendPQExpBuffer(query,
15146 "SELECT at.attname, "
15149 "%s AS initattacl, "
15150 "%s AS initrattacl "
15151 "FROM pg_catalog.pg_attribute at "
15152 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15153 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15154 "(at.attrelid = pip.objoid "
15155 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15156 "AND at.attnum = pip.objsubid) "
15157 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15158 "NOT at.attisdropped "
15160 "%s IS NOT NULL OR "
15161 "%s IS NOT NULL OR "
15162 "%s IS NOT NULL OR "
15164 "ORDER BY at.attnum",
15165 acl_subquery->data,
15166 racl_subquery->data,
15167 initacl_subquery->data,
15168 initracl_subquery->data,
15169 tbinfo->dobj.catId.oid,
15170 acl_subquery->data,
15171 racl_subquery->data,
15172 initacl_subquery->data,
15173 initracl_subquery->data);
15175 destroyPQExpBuffer(acl_subquery);
15176 destroyPQExpBuffer(racl_subquery);
15177 destroyPQExpBuffer(initacl_subquery);
15178 destroyPQExpBuffer(initracl_subquery);
15182 appendPQExpBuffer(query,
15183 "SELECT attname, attacl, NULL as rattacl, "
15184 "NULL AS initattacl, NULL AS initrattacl "
15185 "FROM pg_catalog.pg_attribute "
15186 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15187 "AND attacl IS NOT NULL "
15189 tbinfo->dobj.catId.oid);
15192 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15194 for (i = 0; i < PQntuples(res); i++)
15196 char *attname = PQgetvalue(res, i, 0);
15197 char *attacl = PQgetvalue(res, i, 1);
15198 char *rattacl = PQgetvalue(res, i, 2);
15199 char *initattacl = PQgetvalue(res, i, 3);
15200 char *initrattacl = PQgetvalue(res, i, 4);
15203 attnamecopy = pg_strdup(fmtId(attname));
15204 /* Column's GRANT type is always TABLE */
15205 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15206 "TABLE", namecopy, attnamecopy,
15207 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15208 attacl, rattacl, initattacl, initrattacl);
15212 destroyPQExpBuffer(query);
15221 * Create the AS clause for a view or materialized view. The semicolon is
15222 * stripped because a materialized view must add a WITH NO DATA clause.
15224 * This returns a new buffer which must be freed by the caller.
15227 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15229 PQExpBuffer query = createPQExpBuffer();
15230 PQExpBuffer result = createPQExpBuffer();
15234 /* Fetch the view definition */
15235 appendPQExpBuffer(query,
15236 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15237 tbinfo->dobj.catId.oid);
15239 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15241 if (PQntuples(res) != 1)
15243 if (PQntuples(res) < 1)
15244 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15245 tbinfo->dobj.name);
15247 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15248 tbinfo->dobj.name);
15251 len = PQgetlength(res, 0, 0);
15254 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15255 tbinfo->dobj.name);
15257 /* Strip off the trailing semicolon so that other things may follow. */
15258 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15259 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15262 destroyPQExpBuffer(query);
15268 * Create a dummy AS clause for a view. This is used when the real view
15269 * definition has to be postponed because of circular dependencies.
15270 * We must duplicate the view's external properties -- column names and types
15271 * (including collation) -- so that it works for subsequent references.
15273 * This returns a new buffer which must be freed by the caller.
15276 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15278 PQExpBuffer result = createPQExpBuffer();
15281 appendPQExpBufferStr(result, "SELECT");
15283 for (j = 0; j < tbinfo->numatts; j++)
15286 appendPQExpBufferChar(result, ',');
15287 appendPQExpBufferStr(result, "\n ");
15289 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15292 * Must add collation if not default for the type, because CREATE OR
15293 * REPLACE VIEW won't change it
15295 if (OidIsValid(tbinfo->attcollation[j]))
15299 coll = findCollationByOid(tbinfo->attcollation[j]);
15301 appendPQExpBuffer(result, " COLLATE %s",
15302 fmtQualifiedDumpable(coll));
15305 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15313 * write the declaration (not data) of one user-defined table or view
15316 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15318 DumpOptions *dopt = fout->dopt;
15319 PQExpBuffer q = createPQExpBuffer();
15320 PQExpBuffer delq = createPQExpBuffer();
15324 TableInfo **parents;
15325 int actual_atts; /* number of attrs in this CREATE statement */
15326 const char *reltypename;
15331 qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15332 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15335 if (tbinfo->hasoids)
15337 "WARNING: WITH OIDS is not supported anymore (table \"%s\")\n",
15340 if (dopt->binary_upgrade)
15341 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15342 tbinfo->dobj.catId.oid);
15344 /* Is it a table or a view? */
15345 if (tbinfo->relkind == RELKIND_VIEW)
15347 PQExpBuffer result;
15350 * Note: keep this code in sync with the is_view case in dumpRule()
15353 reltypename = "VIEW";
15355 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15357 if (dopt->binary_upgrade)
15358 binary_upgrade_set_pg_class_oids(fout, q,
15359 tbinfo->dobj.catId.oid, false);
15361 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15363 if (tbinfo->dummy_view)
15364 result = createDummyViewAsClause(fout, tbinfo);
15367 if (nonemptyReloptions(tbinfo->reloptions))
15369 appendPQExpBufferStr(q, " WITH (");
15370 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15371 appendPQExpBufferChar(q, ')');
15373 result = createViewAsClause(fout, tbinfo);
15375 appendPQExpBuffer(q, " AS\n%s", result->data);
15376 destroyPQExpBuffer(result);
15378 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15379 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15380 appendPQExpBufferStr(q, ";\n");
15384 char *ftoptions = NULL;
15385 char *srvname = NULL;
15387 switch (tbinfo->relkind)
15389 case RELKIND_FOREIGN_TABLE:
15391 PQExpBuffer query = createPQExpBuffer();
15396 reltypename = "FOREIGN TABLE";
15398 /* retrieve name of foreign server and generic options */
15399 appendPQExpBuffer(query,
15400 "SELECT fs.srvname, "
15401 "pg_catalog.array_to_string(ARRAY("
15402 "SELECT pg_catalog.quote_ident(option_name) || "
15403 "' ' || pg_catalog.quote_literal(option_value) "
15404 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15405 "ORDER BY option_name"
15406 "), E',\n ') AS ftoptions "
15407 "FROM pg_catalog.pg_foreign_table ft "
15408 "JOIN pg_catalog.pg_foreign_server fs "
15409 "ON (fs.oid = ft.ftserver) "
15410 "WHERE ft.ftrelid = '%u'",
15411 tbinfo->dobj.catId.oid);
15412 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15413 i_srvname = PQfnumber(res, "srvname");
15414 i_ftoptions = PQfnumber(res, "ftoptions");
15415 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15416 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15418 destroyPQExpBuffer(query);
15421 case RELKIND_MATVIEW:
15422 reltypename = "MATERIALIZED VIEW";
15425 reltypename = "TABLE";
15428 numParents = tbinfo->numParents;
15429 parents = tbinfo->parents;
15431 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15433 if (dopt->binary_upgrade)
15434 binary_upgrade_set_pg_class_oids(fout, q,
15435 tbinfo->dobj.catId.oid, false);
15437 appendPQExpBuffer(q, "CREATE %s%s %s",
15438 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15444 * Attach to type, if reloftype; except in case of a binary upgrade,
15445 * we dump the table normally and attach it to the type afterward.
15447 if (tbinfo->reloftype && !dopt->binary_upgrade)
15448 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15451 * If the table is a partition, dump it as such; except in the case of
15452 * a binary upgrade, we dump the table normally and attach it to the
15453 * parent afterward.
15455 if (tbinfo->ispartition && !dopt->binary_upgrade)
15457 TableInfo *parentRel = tbinfo->parents[0];
15460 * With partitions, unlike inheritance, there can only be one
15463 if (tbinfo->numParents != 1)
15464 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15465 tbinfo->numParents, tbinfo->dobj.name);
15467 appendPQExpBuffer(q, " PARTITION OF %s",
15468 fmtQualifiedDumpable(parentRel));
15471 if (tbinfo->relkind != RELKIND_MATVIEW)
15473 /* Dump the attributes */
15475 for (j = 0; j < tbinfo->numatts; j++)
15478 * Normally, dump if it's locally defined in this table, and
15479 * not dropped. But for binary upgrade, we'll dump all the
15480 * columns, and then fix up the dropped and nonlocal cases
15483 if (shouldPrintColumn(dopt, tbinfo, j))
15486 * Default value --- suppress if to be printed separately.
15488 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15489 !tbinfo->attrdefs[j]->separate);
15492 * Not Null constraint --- suppress if inherited, except
15493 * in binary-upgrade case where that won't work.
15495 bool has_notnull = (tbinfo->notnull[j] &&
15496 (!tbinfo->inhNotNull[j] ||
15497 dopt->binary_upgrade));
15500 * Skip column if fully defined by reloftype or the
15501 * partition parent.
15503 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15504 !has_default && !has_notnull && !dopt->binary_upgrade)
15507 /* Format properly if not first attr */
15508 if (actual_atts == 0)
15509 appendPQExpBufferStr(q, " (");
15511 appendPQExpBufferChar(q, ',');
15512 appendPQExpBufferStr(q, "\n ");
15515 /* Attribute name */
15516 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15518 if (tbinfo->attisdropped[j])
15521 * ALTER TABLE DROP COLUMN clears
15522 * pg_attribute.atttypid, so we will not have gotten a
15523 * valid type name; insert INTEGER as a stopgap. We'll
15524 * clean things up later.
15526 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15527 /* Skip all the rest, too */
15534 * In binary-upgrade mode, we always include the type. If
15535 * we aren't in binary-upgrade mode, then we skip the type
15536 * when creating a typed table ('OF type_name') or a
15537 * partition ('PARTITION OF'), since the type comes from
15538 * the parent/partitioned table.
15540 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15542 appendPQExpBuffer(q, " %s",
15543 tbinfo->atttypnames[j]);
15546 /* Add collation if not default for the type */
15547 if (OidIsValid(tbinfo->attcollation[j]))
15551 coll = findCollationByOid(tbinfo->attcollation[j]);
15553 appendPQExpBuffer(q, " COLLATE %s",
15554 fmtQualifiedDumpable(coll));
15558 appendPQExpBuffer(q, " DEFAULT %s",
15559 tbinfo->attrdefs[j]->adef_expr);
15562 appendPQExpBufferStr(q, " NOT NULL");
15567 * Add non-inherited CHECK constraints, if any.
15569 for (j = 0; j < tbinfo->ncheck; j++)
15571 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15573 if (constr->separate || !constr->conislocal)
15576 if (actual_atts == 0)
15577 appendPQExpBufferStr(q, " (\n ");
15579 appendPQExpBufferStr(q, ",\n ");
15581 appendPQExpBuffer(q, "CONSTRAINT %s ",
15582 fmtId(constr->dobj.name));
15583 appendPQExpBufferStr(q, constr->condef);
15589 appendPQExpBufferStr(q, "\n)");
15590 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15591 !dopt->binary_upgrade))
15594 * We must have a parenthesized attribute list, even though
15595 * empty, when not using the OF TYPE or PARTITION OF syntax.
15597 appendPQExpBufferStr(q, " (\n)");
15600 if (tbinfo->ispartition && !dopt->binary_upgrade)
15602 appendPQExpBufferChar(q, '\n');
15603 appendPQExpBufferStr(q, tbinfo->partbound);
15606 /* Emit the INHERITS clause, except if this is a partition. */
15607 if (numParents > 0 &&
15608 !tbinfo->ispartition &&
15609 !dopt->binary_upgrade)
15611 appendPQExpBufferStr(q, "\nINHERITS (");
15612 for (k = 0; k < numParents; k++)
15614 TableInfo *parentRel = parents[k];
15617 appendPQExpBufferStr(q, ", ");
15618 appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15620 appendPQExpBufferChar(q, ')');
15623 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15624 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15626 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15627 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15630 if (nonemptyReloptions(tbinfo->reloptions) ||
15631 nonemptyReloptions(tbinfo->toast_reloptions))
15633 bool addcomma = false;
15635 appendPQExpBufferStr(q, "\nWITH (");
15636 if (nonemptyReloptions(tbinfo->reloptions))
15639 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15641 if (nonemptyReloptions(tbinfo->toast_reloptions))
15644 appendPQExpBufferStr(q, ", ");
15645 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15648 appendPQExpBufferChar(q, ')');
15651 /* Dump generic options if any */
15652 if (ftoptions && ftoptions[0])
15653 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15656 * For materialized views, create the AS clause just like a view. At
15657 * this point, we always mark the view as not populated.
15659 if (tbinfo->relkind == RELKIND_MATVIEW)
15661 PQExpBuffer result;
15663 result = createViewAsClause(fout, tbinfo);
15664 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15666 destroyPQExpBuffer(result);
15669 appendPQExpBufferStr(q, ";\n");
15672 * in binary upgrade mode, update the catalog with any missing values
15673 * that might be present.
15675 if (dopt->binary_upgrade)
15677 for (j = 0; j < tbinfo->numatts; j++)
15679 if (tbinfo->attmissingval[j][0] != '\0')
15681 appendPQExpBufferStr(q, "\n-- set missing value.\n");
15682 appendPQExpBufferStr(q,
15683 "SELECT pg_catalog.binary_upgrade_set_missing_value(");
15684 appendStringLiteralAH(q, qualrelname, fout);
15685 appendPQExpBufferStr(q, "::pg_catalog.regclass,");
15686 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15687 appendPQExpBufferStr(q, ",");
15688 appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
15689 appendPQExpBufferStr(q, ");\n\n");
15695 * To create binary-compatible heap files, we have to ensure the same
15696 * physical column order, including dropped columns, as in the
15697 * original. Therefore, we create dropped columns above and drop them
15698 * here, also updating their attlen/attalign values so that the
15699 * dropped column can be skipped properly. (We do not bother with
15700 * restoring the original attbyval setting.) Also, inheritance
15701 * relationships are set up by doing ALTER TABLE INHERIT rather than
15702 * using an INHERITS clause --- the latter would possibly mess up the
15703 * column order. That also means we have to take care about setting
15704 * attislocal correctly, plus fix up any inherited CHECK constraints.
15705 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15707 * We process foreign and partitioned tables here, even though they
15708 * lack heap storage, because they can participate in inheritance
15709 * relationships and we want this stuff to be consistent across the
15710 * inheritance tree. We can exclude indexes, toast tables, sequences
15711 * and matviews, even though they have storage, because we don't
15712 * support altering or dropping columns in them, nor can they be part
15713 * of inheritance trees.
15715 if (dopt->binary_upgrade &&
15716 (tbinfo->relkind == RELKIND_RELATION ||
15717 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15718 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15720 for (j = 0; j < tbinfo->numatts; j++)
15722 if (tbinfo->attisdropped[j])
15724 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15725 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15726 "SET attlen = %d, "
15727 "attalign = '%c', attbyval = false\n"
15728 "WHERE attname = ",
15730 tbinfo->attalign[j]);
15731 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15732 appendPQExpBufferStr(q, "\n AND attrelid = ");
15733 appendStringLiteralAH(q, qualrelname, fout);
15734 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15736 if (tbinfo->relkind == RELKIND_RELATION ||
15737 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15738 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15741 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15743 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15744 fmtId(tbinfo->attnames[j]));
15746 else if (!tbinfo->attislocal[j])
15748 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15749 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15750 "SET attislocal = false\n"
15751 "WHERE attname = ");
15752 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15753 appendPQExpBufferStr(q, "\n AND attrelid = ");
15754 appendStringLiteralAH(q, qualrelname, fout);
15755 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15759 for (k = 0; k < tbinfo->ncheck; k++)
15761 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15763 if (constr->separate || constr->conislocal)
15766 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15767 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15769 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15770 fmtId(constr->dobj.name));
15771 appendPQExpBuffer(q, "%s;\n", constr->condef);
15772 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15773 "SET conislocal = false\n"
15774 "WHERE contype = 'c' AND conname = ");
15775 appendStringLiteralAH(q, constr->dobj.name, fout);
15776 appendPQExpBufferStr(q, "\n AND conrelid = ");
15777 appendStringLiteralAH(q, qualrelname, fout);
15778 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15781 if (numParents > 0)
15783 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15784 for (k = 0; k < numParents; k++)
15786 TableInfo *parentRel = parents[k];
15788 /* In the partitioning case, we alter the parent */
15789 if (tbinfo->ispartition)
15790 appendPQExpBuffer(q,
15791 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15792 fmtQualifiedDumpable(parentRel));
15794 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15797 /* Partition needs specifying the bounds */
15798 if (tbinfo->ispartition)
15799 appendPQExpBuffer(q, "%s %s;\n",
15801 tbinfo->partbound);
15803 appendPQExpBuffer(q, "%s;\n",
15804 fmtQualifiedDumpable(parentRel));
15808 if (tbinfo->reloftype)
15810 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15811 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15813 tbinfo->reloftype);
15818 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15819 * relminmxid of all vacuumable relations. (While vacuum.c processes
15820 * TOAST tables semi-independently, here we see them only as children
15821 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15822 * child toast table is handled below.)
15824 if (dopt->binary_upgrade &&
15825 (tbinfo->relkind == RELKIND_RELATION ||
15826 tbinfo->relkind == RELKIND_MATVIEW))
15828 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15829 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15830 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15832 tbinfo->frozenxid, tbinfo->minmxid);
15833 appendStringLiteralAH(q, qualrelname, fout);
15834 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15836 if (tbinfo->toast_oid)
15839 * The toast table will have the same OID at restore, so we
15840 * can safely target it by OID.
15842 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15843 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15844 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15845 "WHERE oid = '%u';\n",
15846 tbinfo->toast_frozenxid,
15847 tbinfo->toast_minmxid, tbinfo->toast_oid);
15852 * In binary_upgrade mode, restore matviews' populated status by
15853 * poking pg_class directly. This is pretty ugly, but we can't use
15854 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15855 * matview is not populated even though this matview is; in any case,
15856 * we want to transfer the matview's heap storage, not run REFRESH.
15858 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15859 tbinfo->relispopulated)
15861 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15862 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15863 "SET relispopulated = 't'\n"
15865 appendStringLiteralAH(q, qualrelname, fout);
15866 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15870 * Dump additional per-column properties that we can't handle in the
15871 * main CREATE TABLE command.
15873 for (j = 0; j < tbinfo->numatts; j++)
15875 /* None of this applies to dropped columns */
15876 if (tbinfo->attisdropped[j])
15880 * If we didn't dump the column definition explicitly above, and
15881 * it is NOT NULL and did not inherit that property from a parent,
15882 * we have to mark it separately.
15884 if (!shouldPrintColumn(dopt, tbinfo, j) &&
15885 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15887 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15889 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15890 fmtId(tbinfo->attnames[j]));
15894 * Dump per-column statistics information. We only issue an ALTER
15895 * TABLE statement if the attstattarget entry for this column is
15896 * non-negative (i.e. it's not the default value)
15898 if (tbinfo->attstattarget[j] >= 0)
15900 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15902 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15903 fmtId(tbinfo->attnames[j]));
15904 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15905 tbinfo->attstattarget[j]);
15909 * Dump per-column storage information. The statement is only
15910 * dumped if the storage has been changed from the type's default.
15912 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15914 switch (tbinfo->attstorage[j])
15920 storage = "EXTERNAL";
15926 storage = "EXTENDED";
15933 * Only dump the statement if it's a storage type we recognize
15935 if (storage != NULL)
15937 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15939 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15940 fmtId(tbinfo->attnames[j]));
15941 appendPQExpBuffer(q, "SET STORAGE %s;\n",
15947 * Dump per-column attributes.
15949 if (tbinfo->attoptions[j][0] != '\0')
15951 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15953 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15954 fmtId(tbinfo->attnames[j]));
15955 appendPQExpBuffer(q, "SET (%s);\n",
15956 tbinfo->attoptions[j]);
15960 * Dump per-column fdw options.
15962 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
15963 tbinfo->attfdwoptions[j][0] != '\0')
15965 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
15967 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15968 fmtId(tbinfo->attnames[j]));
15969 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
15970 tbinfo->attfdwoptions[j]);
15981 * dump properties we only have ALTER TABLE syntax for
15983 if ((tbinfo->relkind == RELKIND_RELATION ||
15984 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
15985 tbinfo->relkind == RELKIND_MATVIEW) &&
15986 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
15988 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
15990 /* nothing to do, will be set when the index is dumped */
15992 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
15994 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
15997 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
15999 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16004 if (tbinfo->forcerowsec)
16005 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16008 if (dopt->binary_upgrade)
16009 binary_upgrade_extension_member(q, &tbinfo->dobj,
16010 reltypename, qrelname,
16011 tbinfo->dobj.namespace->dobj.name);
16013 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16014 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16016 tbinfo->dobj.namespace->dobj.name,
16017 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16020 tbinfo->postponed_def ?
16021 SECTION_POST_DATA : SECTION_PRE_DATA,
16022 q->data, delq->data, NULL,
16027 /* Dump Table Comments */
16028 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16029 dumpTableComment(fout, tbinfo, reltypename);
16031 /* Dump Table Security Labels */
16032 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16033 dumpTableSecLabel(fout, tbinfo, reltypename);
16035 /* Dump comments on inlined table constraints */
16036 for (j = 0; j < tbinfo->ncheck; j++)
16038 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16040 if (constr->separate || !constr->conislocal)
16043 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16044 dumpTableConstraintComment(fout, constr);
16047 destroyPQExpBuffer(q);
16048 destroyPQExpBuffer(delq);
16054 * dumpAttrDef --- dump an attribute's default-value declaration
16057 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16059 DumpOptions *dopt = fout->dopt;
16060 TableInfo *tbinfo = adinfo->adtable;
16061 int adnum = adinfo->adnum;
16067 /* Skip if table definition not to be dumped */
16068 if (!tbinfo->dobj.dump || dopt->dataOnly)
16071 /* Skip if not "separate"; it was dumped in the table's definition */
16072 if (!adinfo->separate)
16075 q = createPQExpBuffer();
16076 delq = createPQExpBuffer();
16078 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16080 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16082 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16083 fmtId(tbinfo->attnames[adnum - 1]),
16084 adinfo->adef_expr);
16086 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16088 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16089 fmtId(tbinfo->attnames[adnum - 1]));
16091 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16093 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16094 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16096 tbinfo->dobj.namespace->dobj.name,
16099 "DEFAULT", SECTION_PRE_DATA,
16100 q->data, delq->data, NULL,
16105 destroyPQExpBuffer(q);
16106 destroyPQExpBuffer(delq);
16111 * getAttrName: extract the correct name for an attribute
16113 * The array tblInfo->attnames[] only provides names of user attributes;
16114 * if a system attribute number is supplied, we have to fake it.
16115 * We also do a little bit of bounds checking for safety's sake.
16117 static const char *
16118 getAttrName(int attrnum, TableInfo *tblInfo)
16120 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16121 return tblInfo->attnames[attrnum - 1];
16124 case SelfItemPointerAttributeNumber:
16126 case MinTransactionIdAttributeNumber:
16128 case MinCommandIdAttributeNumber:
16130 case MaxTransactionIdAttributeNumber:
16132 case MaxCommandIdAttributeNumber:
16134 case TableOidAttributeNumber:
16137 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16138 attrnum, tblInfo->dobj.name);
16139 return NULL; /* keep compiler quiet */
16144 * write out to fout a user-defined index
16147 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16149 DumpOptions *dopt = fout->dopt;
16150 TableInfo *tbinfo = indxinfo->indextable;
16151 bool is_constraint = (indxinfo->indexconstraint != 0);
16156 if (dopt->dataOnly)
16159 q = createPQExpBuffer();
16160 delq = createPQExpBuffer();
16162 qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16165 * If there's an associated constraint, don't dump the index per se, but
16166 * do dump any comment for it. (This is safe because dependency ordering
16167 * will have ensured the constraint is emitted first.) Note that the
16168 * emitted comment has to be shown as depending on the constraint, not the
16169 * index, in such cases.
16171 if (!is_constraint)
16173 char *indstatcols = indxinfo->indstatcols;
16174 char *indstatvals = indxinfo->indstatvals;
16175 char **indstatcolsarray = NULL;
16176 char **indstatvalsarray = NULL;
16180 if (dopt->binary_upgrade)
16181 binary_upgrade_set_pg_class_oids(fout, q,
16182 indxinfo->dobj.catId.oid, true);
16184 /* Plain secondary index */
16185 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16188 * Append ALTER TABLE commands as needed to set properties that we
16189 * only have ALTER TABLE syntax for. Keep this in sync with the
16190 * similar code in dumpConstraint!
16193 /* If the index is clustered, we need to record that. */
16194 if (indxinfo->indisclustered)
16196 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16197 fmtQualifiedDumpable(tbinfo));
16198 /* index name is not qualified in this syntax */
16199 appendPQExpBuffer(q, " ON %s;\n",
16204 * If the index has any statistics on some of its columns, generate
16205 * the associated ALTER INDEX queries.
16207 if (parsePGArray(indstatcols, &indstatcolsarray, &nstatcols) &&
16208 parsePGArray(indstatvals, &indstatvalsarray, &nstatvals) &&
16209 nstatcols == nstatvals)
16213 for (j = 0; j < nstatcols; j++)
16215 appendPQExpBuffer(q, "ALTER INDEX %s ",
16216 fmtQualifiedDumpable(indxinfo));
16219 * Note that this is a column number, so no quotes should be
16222 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16223 indstatcolsarray[j]);
16224 appendPQExpBuffer(q, "SET STATISTICS %s;\n",
16225 indstatvalsarray[j]);
16229 /* If the index defines identity, we need to record that. */
16230 if (indxinfo->indisreplident)
16232 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16233 fmtQualifiedDumpable(tbinfo));
16234 /* index name is not qualified in this syntax */
16235 appendPQExpBuffer(q, " INDEX %s;\n",
16239 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16240 fmtQualifiedDumpable(indxinfo));
16242 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16243 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16244 indxinfo->dobj.name,
16245 tbinfo->dobj.namespace->dobj.name,
16246 indxinfo->tablespace,
16248 "INDEX", SECTION_POST_DATA,
16249 q->data, delq->data, NULL,
16253 if (indstatcolsarray)
16254 free(indstatcolsarray);
16255 if (indstatvalsarray)
16256 free(indstatvalsarray);
16259 /* Dump Index Comments */
16260 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16261 dumpComment(fout, "INDEX", qindxname,
16262 tbinfo->dobj.namespace->dobj.name,
16264 indxinfo->dobj.catId, 0,
16265 is_constraint ? indxinfo->indexconstraint :
16266 indxinfo->dobj.dumpId);
16268 destroyPQExpBuffer(q);
16269 destroyPQExpBuffer(delq);
16275 * write out to fout a partitioned-index attachment clause
16278 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16280 if (fout->dopt->dataOnly)
16283 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16285 PQExpBuffer q = createPQExpBuffer();
16287 appendPQExpBuffer(q, "ALTER INDEX %s ",
16288 fmtQualifiedDumpable(attachinfo->parentIdx));
16289 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16290 fmtQualifiedDumpable(attachinfo->partitionIdx));
16292 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16293 attachinfo->dobj.name,
16294 attachinfo->dobj.namespace->dobj.name,
16297 "INDEX ATTACH", SECTION_POST_DATA,
16302 destroyPQExpBuffer(q);
16307 * dumpStatisticsExt
16308 * write out to fout an extended statistics object
16311 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16313 DumpOptions *dopt = fout->dopt;
16317 char *qstatsextname;
16321 /* Skip if not to be dumped */
16322 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16325 q = createPQExpBuffer();
16326 delq = createPQExpBuffer();
16327 query = createPQExpBuffer();
16329 qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16331 appendPQExpBuffer(query, "SELECT "
16332 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16333 statsextinfo->dobj.catId.oid);
16335 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16337 stxdef = PQgetvalue(res, 0, 0);
16339 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16340 appendPQExpBuffer(q, "%s;\n", stxdef);
16342 appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16343 fmtQualifiedDumpable(statsextinfo));
16345 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16346 ArchiveEntry(fout, statsextinfo->dobj.catId,
16347 statsextinfo->dobj.dumpId,
16348 statsextinfo->dobj.name,
16349 statsextinfo->dobj.namespace->dobj.name,
16351 statsextinfo->rolname,
16352 "STATISTICS", SECTION_POST_DATA,
16353 q->data, delq->data, NULL,
16357 /* Dump Statistics Comments */
16358 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16359 dumpComment(fout, "STATISTICS", qstatsextname,
16360 statsextinfo->dobj.namespace->dobj.name,
16361 statsextinfo->rolname,
16362 statsextinfo->dobj.catId, 0,
16363 statsextinfo->dobj.dumpId);
16366 destroyPQExpBuffer(q);
16367 destroyPQExpBuffer(delq);
16368 destroyPQExpBuffer(query);
16369 free(qstatsextname);
16374 * write out to fout a user-defined constraint
16377 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16379 DumpOptions *dopt = fout->dopt;
16380 TableInfo *tbinfo = coninfo->contable;
16385 /* Skip if not to be dumped */
16386 if (!coninfo->dobj.dump || dopt->dataOnly)
16389 q = createPQExpBuffer();
16390 delq = createPQExpBuffer();
16392 if (coninfo->contype == 'p' ||
16393 coninfo->contype == 'u' ||
16394 coninfo->contype == 'x')
16396 /* Index-related constraint */
16397 IndxInfo *indxinfo;
16400 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16402 if (indxinfo == NULL)
16403 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16404 coninfo->dobj.name);
16406 if (dopt->binary_upgrade)
16407 binary_upgrade_set_pg_class_oids(fout, q,
16408 indxinfo->dobj.catId.oid, true);
16410 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16411 fmtQualifiedDumpable(tbinfo));
16412 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16413 fmtId(coninfo->dobj.name));
16415 if (coninfo->condef)
16417 /* pg_get_constraintdef should have provided everything */
16418 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16422 appendPQExpBuffer(q, "%s (",
16423 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16424 for (k = 0; k < indxinfo->indnkeyattrs; k++)
16426 int indkey = (int) indxinfo->indkeys[k];
16427 const char *attname;
16429 if (indkey == InvalidAttrNumber)
16431 attname = getAttrName(indkey, tbinfo);
16433 appendPQExpBuffer(q, "%s%s",
16434 (k == 0) ? "" : ", ",
16438 if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
16439 appendPQExpBuffer(q, ") INCLUDE (");
16441 for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
16443 int indkey = (int) indxinfo->indkeys[k];
16444 const char *attname;
16446 if (indkey == InvalidAttrNumber)
16448 attname = getAttrName(indkey, tbinfo);
16450 appendPQExpBuffer(q, "%s%s",
16451 (k == indxinfo->indnkeyattrs) ? "" : ", ",
16455 appendPQExpBufferChar(q, ')');
16457 if (nonemptyReloptions(indxinfo->indreloptions))
16459 appendPQExpBufferStr(q, " WITH (");
16460 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16461 appendPQExpBufferChar(q, ')');
16464 if (coninfo->condeferrable)
16466 appendPQExpBufferStr(q, " DEFERRABLE");
16467 if (coninfo->condeferred)
16468 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16471 appendPQExpBufferStr(q, ";\n");
16475 * Append ALTER TABLE commands as needed to set properties that we
16476 * only have ALTER TABLE syntax for. Keep this in sync with the
16477 * similar code in dumpIndex!
16480 /* If the index is clustered, we need to record that. */
16481 if (indxinfo->indisclustered)
16483 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16484 fmtQualifiedDumpable(tbinfo));
16485 /* index name is not qualified in this syntax */
16486 appendPQExpBuffer(q, " ON %s;\n",
16487 fmtId(indxinfo->dobj.name));
16490 /* If the index defines identity, we need to record that. */
16491 if (indxinfo->indisreplident)
16493 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16494 fmtQualifiedDumpable(tbinfo));
16495 /* index name is not qualified in this syntax */
16496 appendPQExpBuffer(q, " INDEX %s;\n",
16497 fmtId(indxinfo->dobj.name));
16500 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16501 fmtQualifiedDumpable(tbinfo));
16502 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16503 fmtId(coninfo->dobj.name));
16505 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16507 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16508 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16510 tbinfo->dobj.namespace->dobj.name,
16511 indxinfo->tablespace,
16513 "CONSTRAINT", SECTION_POST_DATA,
16514 q->data, delq->data, NULL,
16518 else if (coninfo->contype == 'f')
16523 * Foreign keys on partitioned tables are always declared as
16524 * inheriting to partitions; for all other cases, emit them as
16525 * applying ONLY directly to the named table, because that's how they
16526 * work for regular inherited tables.
16528 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
16531 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16532 * current table data is not processed
16534 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
16535 only, fmtQualifiedDumpable(tbinfo));
16536 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16537 fmtId(coninfo->dobj.name),
16540 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
16541 only, fmtQualifiedDumpable(tbinfo));
16542 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16543 fmtId(coninfo->dobj.name));
16545 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16547 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16548 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16550 tbinfo->dobj.namespace->dobj.name,
16553 "FK CONSTRAINT", SECTION_POST_DATA,
16554 q->data, delq->data, NULL,
16558 else if (coninfo->contype == 'c' && tbinfo)
16560 /* CHECK constraint on a table */
16562 /* Ignore if not to be dumped separately, or if it was inherited */
16563 if (coninfo->separate && coninfo->conislocal)
16565 /* not ONLY since we want it to propagate to children */
16566 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16567 fmtQualifiedDumpable(tbinfo));
16568 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16569 fmtId(coninfo->dobj.name),
16572 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16573 fmtQualifiedDumpable(tbinfo));
16574 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16575 fmtId(coninfo->dobj.name));
16577 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16579 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16580 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16582 tbinfo->dobj.namespace->dobj.name,
16585 "CHECK CONSTRAINT", SECTION_POST_DATA,
16586 q->data, delq->data, NULL,
16591 else if (coninfo->contype == 'c' && tbinfo == NULL)
16593 /* CHECK constraint on a domain */
16594 TypeInfo *tyinfo = coninfo->condomain;
16596 /* Ignore if not to be dumped separately */
16597 if (coninfo->separate)
16599 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16600 fmtQualifiedDumpable(tyinfo));
16601 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16602 fmtId(coninfo->dobj.name),
16605 appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16606 fmtQualifiedDumpable(tyinfo));
16607 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16608 fmtId(coninfo->dobj.name));
16610 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16612 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16613 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16615 tyinfo->dobj.namespace->dobj.name,
16618 "CHECK CONSTRAINT", SECTION_POST_DATA,
16619 q->data, delq->data, NULL,
16626 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16630 /* Dump Constraint Comments --- only works for table constraints */
16631 if (tbinfo && coninfo->separate &&
16632 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16633 dumpTableConstraintComment(fout, coninfo);
16636 destroyPQExpBuffer(q);
16637 destroyPQExpBuffer(delq);
16641 * dumpTableConstraintComment --- dump a constraint's comment if any
16643 * This is split out because we need the function in two different places
16644 * depending on whether the constraint is dumped as part of CREATE TABLE
16645 * or as a separate ALTER command.
16648 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16650 TableInfo *tbinfo = coninfo->contable;
16651 PQExpBuffer conprefix = createPQExpBuffer();
16654 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16656 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16657 fmtId(coninfo->dobj.name));
16659 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16660 dumpComment(fout, conprefix->data, qtabname,
16661 tbinfo->dobj.namespace->dobj.name,
16663 coninfo->dobj.catId, 0,
16664 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16666 destroyPQExpBuffer(conprefix);
16671 * findLastBuiltinOid_V71 -
16673 * find the last built in oid
16675 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16676 * pg_database entry for the current database. (Note: current_database()
16677 * requires 7.3; pg_dump requires 8.0 now.)
16680 findLastBuiltinOid_V71(Archive *fout)
16685 res = ExecuteSqlQueryForSingleRow(fout,
16686 "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
16687 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16695 * write the declaration (not data) of one user-defined sequence
16698 dumpSequence(Archive *fout, TableInfo *tbinfo)
16700 DumpOptions *dopt = fout->dopt;
16710 int64 default_minv,
16714 PQExpBuffer query = createPQExpBuffer();
16715 PQExpBuffer delqry = createPQExpBuffer();
16718 qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16720 if (fout->remoteVersion >= 100000)
16722 appendPQExpBuffer(query,
16723 "SELECT format_type(seqtypid, NULL), "
16724 "seqstart, seqincrement, "
16726 "seqcache, seqcycle "
16727 "FROM pg_catalog.pg_sequence "
16728 "WHERE seqrelid = '%u'::oid",
16729 tbinfo->dobj.catId.oid);
16731 else if (fout->remoteVersion >= 80400)
16734 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16736 * Note: it might seem that 'bigint' potentially needs to be
16737 * schema-qualified, but actually that's a keyword.
16739 appendPQExpBuffer(query,
16740 "SELECT 'bigint' AS sequence_type, "
16741 "start_value, increment_by, max_value, min_value, "
16742 "cache_value, is_cycled FROM %s",
16743 fmtQualifiedDumpable(tbinfo));
16747 appendPQExpBuffer(query,
16748 "SELECT 'bigint' AS sequence_type, "
16749 "0 AS start_value, increment_by, max_value, min_value, "
16750 "cache_value, is_cycled FROM %s",
16751 fmtQualifiedDumpable(tbinfo));
16754 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16756 if (PQntuples(res) != 1)
16758 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16759 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16761 tbinfo->dobj.name, PQntuples(res));
16765 seqtype = PQgetvalue(res, 0, 0);
16766 startv = PQgetvalue(res, 0, 1);
16767 incby = PQgetvalue(res, 0, 2);
16768 maxv = PQgetvalue(res, 0, 3);
16769 minv = PQgetvalue(res, 0, 4);
16770 cache = PQgetvalue(res, 0, 5);
16771 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16773 /* Calculate default limits for a sequence of this type */
16774 is_ascending = (incby[0] != '-');
16775 if (strcmp(seqtype, "smallint") == 0)
16777 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16778 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16780 else if (strcmp(seqtype, "integer") == 0)
16782 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16783 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16785 else if (strcmp(seqtype, "bigint") == 0)
16787 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16788 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16792 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16793 default_minv = default_maxv = 0; /* keep compiler quiet */
16797 * 64-bit strtol() isn't very portable, so convert the limits to strings
16798 * and compare that way.
16800 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16801 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16803 /* Don't print minv/maxv if they match the respective default limit */
16804 if (strcmp(minv, bufm) == 0)
16806 if (strcmp(maxv, bufx) == 0)
16810 * Identity sequences are not to be dropped separately.
16812 if (!tbinfo->is_identity_sequence)
16814 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16815 fmtQualifiedDumpable(tbinfo));
16818 resetPQExpBuffer(query);
16820 if (dopt->binary_upgrade)
16822 binary_upgrade_set_pg_class_oids(fout, query,
16823 tbinfo->dobj.catId.oid, false);
16824 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16825 tbinfo->dobj.catId.oid);
16828 if (tbinfo->is_identity_sequence)
16830 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16832 appendPQExpBuffer(query,
16834 fmtQualifiedDumpable(owning_tab));
16835 appendPQExpBuffer(query,
16836 "ALTER COLUMN %s ADD GENERATED ",
16837 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16838 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16839 appendPQExpBuffer(query, "ALWAYS");
16840 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16841 appendPQExpBuffer(query, "BY DEFAULT");
16842 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16843 fmtQualifiedDumpable(tbinfo));
16847 appendPQExpBuffer(query,
16848 "CREATE SEQUENCE %s\n",
16849 fmtQualifiedDumpable(tbinfo));
16851 if (strcmp(seqtype, "bigint") != 0)
16852 appendPQExpBuffer(query, " AS %s\n", seqtype);
16855 if (fout->remoteVersion >= 80400)
16856 appendPQExpBuffer(query, " START WITH %s\n", startv);
16858 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
16861 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
16863 appendPQExpBufferStr(query, " NO MINVALUE\n");
16866 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
16868 appendPQExpBufferStr(query, " NO MAXVALUE\n");
16870 appendPQExpBuffer(query,
16872 cache, (cycled ? "\n CYCLE" : ""));
16874 if (tbinfo->is_identity_sequence)
16875 appendPQExpBufferStr(query, "\n);\n");
16877 appendPQExpBufferStr(query, ";\n");
16879 /* binary_upgrade: no need to clear TOAST table oid */
16881 if (dopt->binary_upgrade)
16882 binary_upgrade_extension_member(query, &tbinfo->dobj,
16883 "SEQUENCE", qseqname,
16884 tbinfo->dobj.namespace->dobj.name);
16886 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16887 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16889 tbinfo->dobj.namespace->dobj.name,
16892 "SEQUENCE", SECTION_PRE_DATA,
16893 query->data, delqry->data, NULL,
16898 * If the sequence is owned by a table column, emit the ALTER for it as a
16899 * separate TOC entry immediately following the sequence's own entry. It's
16900 * OK to do this rather than using full sorting logic, because the
16901 * dependency that tells us it's owned will have forced the table to be
16902 * created first. We can't just include the ALTER in the TOC entry
16903 * because it will fail if we haven't reassigned the sequence owner to
16904 * match the table's owner.
16906 * We need not schema-qualify the table reference because both sequence
16907 * and table must be in the same schema.
16909 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16911 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16913 if (owning_tab == NULL)
16914 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16915 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16917 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16919 resetPQExpBuffer(query);
16920 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16921 fmtQualifiedDumpable(tbinfo));
16922 appendPQExpBuffer(query, " OWNED BY %s",
16923 fmtQualifiedDumpable(owning_tab));
16924 appendPQExpBuffer(query, ".%s;\n",
16925 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16927 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16928 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16930 tbinfo->dobj.namespace->dobj.name,
16933 "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16934 query->data, "", NULL,
16935 &(tbinfo->dobj.dumpId), 1,
16940 /* Dump Sequence Comments and Security Labels */
16941 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16942 dumpComment(fout, "SEQUENCE", qseqname,
16943 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16944 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16946 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16947 dumpSecLabel(fout, "SEQUENCE", qseqname,
16948 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16949 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16953 destroyPQExpBuffer(query);
16954 destroyPQExpBuffer(delqry);
16960 * write the data of one user-defined sequence
16963 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16965 TableInfo *tbinfo = tdinfo->tdtable;
16969 PQExpBuffer query = createPQExpBuffer();
16971 appendPQExpBuffer(query,
16972 "SELECT last_value, is_called FROM %s",
16973 fmtQualifiedDumpable(tbinfo));
16975 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16977 if (PQntuples(res) != 1)
16979 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16980 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16982 tbinfo->dobj.name, PQntuples(res));
16986 last = PQgetvalue(res, 0, 0);
16987 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
16989 resetPQExpBuffer(query);
16990 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
16991 appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
16992 appendPQExpBuffer(query, ", %s, %s);\n",
16993 last, (called ? "true" : "false"));
16995 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
16996 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16998 tbinfo->dobj.namespace->dobj.name,
17001 "SEQUENCE SET", SECTION_DATA,
17002 query->data, "", NULL,
17003 &(tbinfo->dobj.dumpId), 1,
17008 destroyPQExpBuffer(query);
17013 * write the declaration of one user-defined table trigger
17016 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17018 DumpOptions *dopt = fout->dopt;
17019 TableInfo *tbinfo = tginfo->tgtable;
17021 PQExpBuffer delqry;
17022 PQExpBuffer trigprefix;
17031 * we needn't check dobj.dump because TriggerInfo wouldn't have been
17032 * created in the first place for non-dumpable triggers
17034 if (dopt->dataOnly)
17037 query = createPQExpBuffer();
17038 delqry = createPQExpBuffer();
17039 trigprefix = createPQExpBuffer();
17041 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17043 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17044 fmtId(tginfo->dobj.name));
17045 appendPQExpBuffer(delqry, "ON %s;\n",
17046 fmtQualifiedDumpable(tbinfo));
17050 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17054 if (tginfo->tgisconstraint)
17056 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17057 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17061 appendPQExpBufferStr(query, "CREATE TRIGGER ");
17062 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17064 appendPQExpBufferStr(query, "\n ");
17067 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17068 appendPQExpBufferStr(query, "BEFORE");
17069 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17070 appendPQExpBufferStr(query, "AFTER");
17071 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17072 appendPQExpBufferStr(query, "INSTEAD OF");
17075 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17080 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17082 appendPQExpBufferStr(query, " INSERT");
17085 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17088 appendPQExpBufferStr(query, " OR DELETE");
17090 appendPQExpBufferStr(query, " DELETE");
17093 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17096 appendPQExpBufferStr(query, " OR UPDATE");
17098 appendPQExpBufferStr(query, " UPDATE");
17101 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17104 appendPQExpBufferStr(query, " OR TRUNCATE");
17106 appendPQExpBufferStr(query, " TRUNCATE");
17109 appendPQExpBuffer(query, " ON %s\n",
17110 fmtQualifiedDumpable(tbinfo));
17112 if (tginfo->tgisconstraint)
17114 if (OidIsValid(tginfo->tgconstrrelid))
17116 /* regclass output is already quoted */
17117 appendPQExpBuffer(query, " FROM %s\n ",
17118 tginfo->tgconstrrelname);
17120 if (!tginfo->tgdeferrable)
17121 appendPQExpBufferStr(query, "NOT ");
17122 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17123 if (tginfo->tginitdeferred)
17124 appendPQExpBufferStr(query, "DEFERRED\n");
17126 appendPQExpBufferStr(query, "IMMEDIATE\n");
17129 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17130 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
17132 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
17134 /* regproc output is already sufficiently quoted */
17135 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17138 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17141 for (findx = 0; findx < tginfo->tgnargs; findx++)
17143 /* find the embedded null that terminates this trigger argument */
17144 size_t tlen = strlen(p);
17146 if (p + tlen >= tgargs + lentgargs)
17148 /* hm, not found before end of bytea value... */
17149 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17152 tbinfo->dobj.name);
17157 appendPQExpBufferStr(query, ", ");
17158 appendStringLiteralAH(query, p, fout);
17162 appendPQExpBufferStr(query, ");\n");
17165 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17167 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17168 fmtQualifiedDumpable(tbinfo));
17169 switch (tginfo->tgenabled)
17173 appendPQExpBufferStr(query, "DISABLE");
17176 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17179 appendPQExpBufferStr(query, "ENABLE REPLICA");
17182 appendPQExpBufferStr(query, "ENABLE");
17185 appendPQExpBuffer(query, " TRIGGER %s;\n",
17186 fmtId(tginfo->dobj.name));
17189 appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17190 fmtId(tginfo->dobj.name));
17192 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17194 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17195 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17197 tbinfo->dobj.namespace->dobj.name,
17200 "TRIGGER", SECTION_POST_DATA,
17201 query->data, delqry->data, NULL,
17205 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17206 dumpComment(fout, trigprefix->data, qtabname,
17207 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17208 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17211 destroyPQExpBuffer(query);
17212 destroyPQExpBuffer(delqry);
17213 destroyPQExpBuffer(trigprefix);
17219 * write the declaration of one user-defined event trigger
17222 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17224 DumpOptions *dopt = fout->dopt;
17226 PQExpBuffer delqry;
17229 /* Skip if not to be dumped */
17230 if (!evtinfo->dobj.dump || dopt->dataOnly)
17233 query = createPQExpBuffer();
17234 delqry = createPQExpBuffer();
17236 qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17238 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17239 appendPQExpBufferStr(query, qevtname);
17240 appendPQExpBufferStr(query, " ON ");
17241 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17243 if (strcmp("", evtinfo->evttags) != 0)
17245 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17246 appendPQExpBufferStr(query, evtinfo->evttags);
17247 appendPQExpBufferChar(query, ')');
17250 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
17251 appendPQExpBufferStr(query, evtinfo->evtfname);
17252 appendPQExpBufferStr(query, "();\n");
17254 if (evtinfo->evtenabled != 'O')
17256 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17258 switch (evtinfo->evtenabled)
17261 appendPQExpBufferStr(query, "DISABLE");
17264 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17267 appendPQExpBufferStr(query, "ENABLE REPLICA");
17270 appendPQExpBufferStr(query, "ENABLE");
17273 appendPQExpBufferStr(query, ";\n");
17276 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17279 if (dopt->binary_upgrade)
17280 binary_upgrade_extension_member(query, &evtinfo->dobj,
17281 "EVENT TRIGGER", qevtname, NULL);
17283 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17284 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17285 evtinfo->dobj.name, NULL, NULL,
17287 "EVENT TRIGGER", SECTION_POST_DATA,
17288 query->data, delqry->data, NULL,
17292 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17293 dumpComment(fout, "EVENT TRIGGER", qevtname,
17294 NULL, evtinfo->evtowner,
17295 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17297 destroyPQExpBuffer(query);
17298 destroyPQExpBuffer(delqry);
17307 dumpRule(Archive *fout, RuleInfo *rinfo)
17309 DumpOptions *dopt = fout->dopt;
17310 TableInfo *tbinfo = rinfo->ruletable;
17314 PQExpBuffer delcmd;
17315 PQExpBuffer ruleprefix;
17320 /* Skip if not to be dumped */
17321 if (!rinfo->dobj.dump || dopt->dataOnly)
17325 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17326 * we do not want to dump it as a separate object.
17328 if (!rinfo->separate)
17332 * If it's an ON SELECT rule, we want to print it as a view definition,
17333 * instead of a rule.
17335 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17337 query = createPQExpBuffer();
17338 cmd = createPQExpBuffer();
17339 delcmd = createPQExpBuffer();
17340 ruleprefix = createPQExpBuffer();
17342 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17346 PQExpBuffer result;
17349 * We need OR REPLACE here because we'll be replacing a dummy view.
17350 * Otherwise this should look largely like the regular view dump code.
17352 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17353 fmtQualifiedDumpable(tbinfo));
17354 if (nonemptyReloptions(tbinfo->reloptions))
17356 appendPQExpBufferStr(cmd, " WITH (");
17357 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17358 appendPQExpBufferChar(cmd, ')');
17360 result = createViewAsClause(fout, tbinfo);
17361 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17362 destroyPQExpBuffer(result);
17363 if (tbinfo->checkoption != NULL)
17364 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
17365 tbinfo->checkoption);
17366 appendPQExpBufferStr(cmd, ";\n");
17370 /* In the rule case, just print pg_get_ruledef's result verbatim */
17371 appendPQExpBuffer(query,
17372 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17373 rinfo->dobj.catId.oid);
17375 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17377 if (PQntuples(res) != 1)
17379 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17380 rinfo->dobj.name, tbinfo->dobj.name);
17384 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17390 * Add the command to alter the rules replication firing semantics if it
17391 * differs from the default.
17393 if (rinfo->ev_enabled != 'O')
17395 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17396 switch (rinfo->ev_enabled)
17399 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17400 fmtId(rinfo->dobj.name));
17403 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17404 fmtId(rinfo->dobj.name));
17407 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17408 fmtId(rinfo->dobj.name));
17416 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17417 * REPLACE VIEW to replace the rule with something with minimal
17420 PQExpBuffer result;
17422 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17423 fmtQualifiedDumpable(tbinfo));
17424 result = createDummyViewAsClause(fout, tbinfo);
17425 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17426 destroyPQExpBuffer(result);
17430 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17431 fmtId(rinfo->dobj.name));
17432 appendPQExpBuffer(delcmd, "ON %s;\n",
17433 fmtQualifiedDumpable(tbinfo));
17436 appendPQExpBuffer(ruleprefix, "RULE %s ON",
17437 fmtId(rinfo->dobj.name));
17439 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17441 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17442 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17444 tbinfo->dobj.namespace->dobj.name,
17447 "RULE", SECTION_POST_DATA,
17448 cmd->data, delcmd->data, NULL,
17452 /* Dump rule comments */
17453 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17454 dumpComment(fout, ruleprefix->data, qtabname,
17455 tbinfo->dobj.namespace->dobj.name,
17457 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17460 destroyPQExpBuffer(query);
17461 destroyPQExpBuffer(cmd);
17462 destroyPQExpBuffer(delcmd);
17463 destroyPQExpBuffer(ruleprefix);
17468 * getExtensionMembership --- obtain extension membership data
17470 * We need to identify objects that are extension members as soon as they're
17471 * loaded, so that we can correctly determine whether they need to be dumped.
17472 * Generally speaking, extension member objects will get marked as *not* to
17473 * be dumped, as they will be recreated by the single CREATE EXTENSION
17474 * command. However, in binary upgrade mode we still need to dump the members
17478 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17489 ExtensionMemberId *extmembers;
17490 ExtensionInfo *ext;
17492 /* Nothing to do if no extensions */
17493 if (numExtensions == 0)
17496 query = createPQExpBuffer();
17498 /* refclassid constraint is redundant but may speed the search */
17499 appendPQExpBufferStr(query, "SELECT "
17500 "classid, objid, refobjid "
17502 "WHERE refclassid = 'pg_extension'::regclass "
17503 "AND deptype = 'e' "
17506 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17508 ntups = PQntuples(res);
17510 i_classid = PQfnumber(res, "classid");
17511 i_objid = PQfnumber(res, "objid");
17512 i_refobjid = PQfnumber(res, "refobjid");
17514 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17518 * Accumulate data into extmembers[].
17520 * Since we ordered the SELECT by referenced ID, we can expect that
17521 * multiple entries for the same extension will appear together; this
17522 * saves on searches.
17526 for (i = 0; i < ntups; i++)
17531 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17532 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17533 extId = atooid(PQgetvalue(res, i, i_refobjid));
17536 ext->dobj.catId.oid != extId)
17537 ext = findExtensionByOid(extId);
17541 /* shouldn't happen */
17542 fprintf(stderr, "could not find referenced extension %u\n", extId);
17546 extmembers[nextmembers].catId = objId;
17547 extmembers[nextmembers].ext = ext;
17553 /* Remember the data for use later */
17554 setExtensionMembership(extmembers, nextmembers);
17556 destroyPQExpBuffer(query);
17560 * processExtensionTables --- deal with extension configuration tables
17562 * There are two parts to this process:
17564 * 1. Identify and create dump records for extension configuration tables.
17566 * Extensions can mark tables as "configuration", which means that the user
17567 * is able and expected to modify those tables after the extension has been
17568 * loaded. For these tables, we dump out only the data- the structure is
17569 * expected to be handled at CREATE EXTENSION time, including any indexes or
17570 * foreign keys, which brings us to-
17572 * 2. Record FK dependencies between configuration tables.
17574 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17575 * the data is loaded, we have to work out what the best order for reloading
17576 * the data is, to avoid FK violations when the tables are restored. This is
17577 * not perfect- we can't handle circular dependencies and if any exist they
17578 * will cause an invalid dump to be produced (though at least all of the data
17579 * is included for a user to manually restore). This is currently documented
17580 * but perhaps we can provide a better solution in the future.
17583 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17586 DumpOptions *dopt = fout->dopt;
17594 /* Nothing to do if no extensions */
17595 if (numExtensions == 0)
17599 * Identify extension configuration tables and create TableDataInfo
17600 * objects for them, ensuring their data will be dumped even though the
17601 * tables themselves won't be.
17603 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17604 * user data in a configuration table is treated like schema data. This
17605 * seems appropriate since system data in a config table would get
17606 * reloaded by CREATE EXTENSION.
17608 for (i = 0; i < numExtensions; i++)
17610 ExtensionInfo *curext = &(extinfo[i]);
17611 char *extconfig = curext->extconfig;
17612 char *extcondition = curext->extcondition;
17613 char **extconfigarray = NULL;
17614 char **extconditionarray = NULL;
17616 int nconditionitems;
17618 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17619 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17620 nconfigitems == nconditionitems)
17624 for (j = 0; j < nconfigitems; j++)
17626 TableInfo *configtbl;
17627 Oid configtbloid = atooid(extconfigarray[j]);
17629 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17631 configtbl = findTableByOid(configtbloid);
17632 if (configtbl == NULL)
17636 * Tables of not-to-be-dumped extensions shouldn't be dumped
17637 * unless the table or its schema is explicitly included
17639 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17641 /* check table explicitly requested */
17642 if (table_include_oids.head != NULL &&
17643 simple_oid_list_member(&table_include_oids,
17647 /* check table's schema explicitly requested */
17648 if (configtbl->dobj.namespace->dobj.dump &
17649 DUMP_COMPONENT_DATA)
17653 /* check table excluded by an exclusion switch */
17654 if (table_exclude_oids.head != NULL &&
17655 simple_oid_list_member(&table_exclude_oids,
17659 /* check schema excluded by an exclusion switch */
17660 if (simple_oid_list_member(&schema_exclude_oids,
17661 configtbl->dobj.namespace->dobj.catId.oid))
17666 makeTableDataInfo(dopt, configtbl);
17667 if (configtbl->dataObj != NULL)
17669 if (strlen(extconditionarray[j]) > 0)
17670 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17675 if (extconfigarray)
17676 free(extconfigarray);
17677 if (extconditionarray)
17678 free(extconditionarray);
17682 * Now that all the TableInfoData objects have been created for all the
17683 * extensions, check their FK dependencies and register them to try and
17684 * dump the data out in an order that they can be restored in.
17686 * Note that this is not a problem for user tables as their FKs are
17687 * recreated after the data has been loaded.
17690 query = createPQExpBuffer();
17692 printfPQExpBuffer(query,
17693 "SELECT conrelid, confrelid "
17694 "FROM pg_constraint "
17695 "JOIN pg_depend ON (objid = confrelid) "
17696 "WHERE contype = 'f' "
17697 "AND refclassid = 'pg_extension'::regclass "
17698 "AND classid = 'pg_class'::regclass;");
17700 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17701 ntups = PQntuples(res);
17703 i_conrelid = PQfnumber(res, "conrelid");
17704 i_confrelid = PQfnumber(res, "confrelid");
17706 /* Now get the dependencies and register them */
17707 for (i = 0; i < ntups; i++)
17711 TableInfo *reftable,
17714 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17715 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17716 contable = findTableByOid(conrelid);
17717 reftable = findTableByOid(confrelid);
17719 if (reftable == NULL ||
17720 reftable->dataObj == NULL ||
17721 contable == NULL ||
17722 contable->dataObj == NULL)
17726 * Make referencing TABLE_DATA object depend on the referenced table's
17727 * TABLE_DATA object.
17729 addObjectDependency(&contable->dataObj->dobj,
17730 reftable->dataObj->dobj.dumpId);
17733 destroyPQExpBuffer(query);
17737 * getDependencies --- obtain available dependency data
17740 getDependencies(Archive *fout)
17751 DumpableObject *dobj,
17755 write_msg(NULL, "reading dependency data\n");
17757 query = createPQExpBuffer();
17760 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17761 * already processed by getExtensionMembership.
17763 appendPQExpBufferStr(query, "SELECT "
17764 "classid, objid, refclassid, refobjid, deptype "
17766 "WHERE deptype != 'p' AND deptype != 'e' "
17769 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17771 ntups = PQntuples(res);
17773 i_classid = PQfnumber(res, "classid");
17774 i_objid = PQfnumber(res, "objid");
17775 i_refclassid = PQfnumber(res, "refclassid");
17776 i_refobjid = PQfnumber(res, "refobjid");
17777 i_deptype = PQfnumber(res, "deptype");
17780 * Since we ordered the SELECT by referencing ID, we can expect that
17781 * multiple entries for the same object will appear together; this saves
17786 for (i = 0; i < ntups; i++)
17789 CatalogId refobjId;
17792 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17793 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17794 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17795 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17796 deptype = *(PQgetvalue(res, i, i_deptype));
17798 if (dobj == NULL ||
17799 dobj->catId.tableoid != objId.tableoid ||
17800 dobj->catId.oid != objId.oid)
17801 dobj = findObjectByCatalogId(objId);
17804 * Failure to find objects mentioned in pg_depend is not unexpected,
17805 * since for example we don't collect info about TOAST tables.
17810 fprintf(stderr, "no referencing object %u %u\n",
17811 objId.tableoid, objId.oid);
17816 refdobj = findObjectByCatalogId(refobjId);
17818 if (refdobj == NULL)
17821 fprintf(stderr, "no referenced object %u %u\n",
17822 refobjId.tableoid, refobjId.oid);
17828 * Ordinarily, table rowtypes have implicit dependencies on their
17829 * tables. However, for a composite type the implicit dependency goes
17830 * the other way in pg_depend; which is the right thing for DROP but
17831 * it doesn't produce the dependency ordering we need. So in that one
17832 * case, we reverse the direction of the dependency.
17834 if (deptype == 'i' &&
17835 dobj->objType == DO_TABLE &&
17836 refdobj->objType == DO_TYPE)
17837 addObjectDependency(refdobj, dobj->dumpId);
17840 addObjectDependency(dobj, refdobj->dumpId);
17845 destroyPQExpBuffer(query);
17850 * createBoundaryObjects - create dummy DumpableObjects to represent
17851 * dump section boundaries.
17853 static DumpableObject *
17854 createBoundaryObjects(void)
17856 DumpableObject *dobjs;
17858 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17860 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17861 dobjs[0].catId = nilCatalogId;
17862 AssignDumpId(dobjs + 0);
17863 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17865 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17866 dobjs[1].catId = nilCatalogId;
17867 AssignDumpId(dobjs + 1);
17868 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17874 * addBoundaryDependencies - add dependencies as needed to enforce the dump
17875 * section boundaries.
17878 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17879 DumpableObject *boundaryObjs)
17881 DumpableObject *preDataBound = boundaryObjs + 0;
17882 DumpableObject *postDataBound = boundaryObjs + 1;
17885 for (i = 0; i < numObjs; i++)
17887 DumpableObject *dobj = dobjs[i];
17890 * The classification of object types here must match the SECTION_xxx
17891 * values assigned during subsequent ArchiveEntry calls!
17893 switch (dobj->objType)
17898 case DO_SHELL_TYPE:
17902 case DO_ACCESS_METHOD:
17906 case DO_CONVERSION:
17911 case DO_DUMMY_TYPE:
17914 case DO_TSTEMPLATE:
17917 case DO_FOREIGN_SERVER:
17920 /* Pre-data objects: must come before the pre-data boundary */
17921 addObjectDependency(preDataBound, dobj->dumpId);
17923 case DO_TABLE_DATA:
17924 case DO_SEQUENCE_SET:
17926 /* Data objects: must come between the boundaries */
17927 addObjectDependency(dobj, preDataBound->dumpId);
17928 addObjectDependency(postDataBound, dobj->dumpId);
17931 case DO_INDEX_ATTACH:
17933 case DO_REFRESH_MATVIEW:
17935 case DO_EVENT_TRIGGER:
17936 case DO_DEFAULT_ACL:
17938 case DO_PUBLICATION:
17939 case DO_PUBLICATION_REL:
17940 case DO_SUBSCRIPTION:
17941 /* Post-data objects: must come after the post-data boundary */
17942 addObjectDependency(dobj, postDataBound->dumpId);
17945 /* Rules are post-data, but only if dumped separately */
17946 if (((RuleInfo *) dobj)->separate)
17947 addObjectDependency(dobj, postDataBound->dumpId);
17949 case DO_CONSTRAINT:
17950 case DO_FK_CONSTRAINT:
17951 /* Constraints are post-data, but only if dumped separately */
17952 if (((ConstraintInfo *) dobj)->separate)
17953 addObjectDependency(dobj, postDataBound->dumpId);
17955 case DO_PRE_DATA_BOUNDARY:
17956 /* nothing to do */
17958 case DO_POST_DATA_BOUNDARY:
17959 /* must come after the pre-data boundary */
17960 addObjectDependency(dobj, preDataBound->dumpId);
17968 * BuildArchiveDependencies - create dependency data for archive TOC entries
17970 * The raw dependency data obtained by getDependencies() is not terribly
17971 * useful in an archive dump, because in many cases there are dependency
17972 * chains linking through objects that don't appear explicitly in the dump.
17973 * For example, a view will depend on its _RETURN rule while the _RETURN rule
17974 * will depend on other objects --- but the rule will not appear as a separate
17975 * object in the dump. We need to adjust the view's dependencies to include
17976 * whatever the rule depends on that is included in the dump.
17978 * Just to make things more complicated, there are also "special" dependencies
17979 * such as the dependency of a TABLE DATA item on its TABLE, which we must
17980 * not rearrange because pg_restore knows that TABLE DATA only depends on
17981 * its table. In these cases we must leave the dependencies strictly as-is
17982 * even if they refer to not-to-be-dumped objects.
17984 * To handle this, the convention is that "special" dependencies are created
17985 * during ArchiveEntry calls, and an archive TOC item that has any such
17986 * entries will not be touched here. Otherwise, we recursively search the
17987 * DumpableObject data structures to build the correct dependencies for each
17988 * archive TOC item.
17991 BuildArchiveDependencies(Archive *fout)
17993 ArchiveHandle *AH = (ArchiveHandle *) fout;
17996 /* Scan all TOC entries in the archive */
17997 for (te = AH->toc->next; te != AH->toc; te = te->next)
17999 DumpableObject *dobj;
18000 DumpId *dependencies;
18004 /* No need to process entries that will not be dumped */
18007 /* Ignore entries that already have "special" dependencies */
18010 /* Otherwise, look up the item's original DumpableObject, if any */
18011 dobj = findObjectByDumpId(te->dumpId);
18014 /* No work if it has no dependencies */
18015 if (dobj->nDeps <= 0)
18017 /* Set up work array */
18019 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18021 /* Recursively find all dumpable dependencies */
18022 findDumpableDependencies(AH, dobj,
18023 &dependencies, &nDeps, &allocDeps);
18024 /* And save 'em ... */
18027 dependencies = (DumpId *) pg_realloc(dependencies,
18028 nDeps * sizeof(DumpId));
18029 te->dependencies = dependencies;
18033 free(dependencies);
18037 /* Recursive search subroutine for BuildArchiveDependencies */
18039 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18040 DumpId **dependencies, int *nDeps, int *allocDeps)
18045 * Ignore section boundary objects: if we search through them, we'll
18046 * report lots of bogus dependencies.
18048 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18049 dobj->objType == DO_POST_DATA_BOUNDARY)
18052 for (i = 0; i < dobj->nDeps; i++)
18054 DumpId depid = dobj->dependencies[i];
18056 if (TocIDRequired(AH, depid) != 0)
18058 /* Object will be dumped, so just reference it as a dependency */
18059 if (*nDeps >= *allocDeps)
18062 *dependencies = (DumpId *) pg_realloc(*dependencies,
18063 *allocDeps * sizeof(DumpId));
18065 (*dependencies)[*nDeps] = depid;
18071 * Object will not be dumped, so recursively consider its deps. We
18072 * rely on the assumption that sortDumpableObjects already broke
18073 * any dependency loops, else we might recurse infinitely.
18075 DumpableObject *otherdobj = findObjectByDumpId(depid);
18078 findDumpableDependencies(AH, otherdobj,
18079 dependencies, nDeps, allocDeps);
18086 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18089 * This does not guarantee to schema-qualify the output, so it should not
18090 * be used to create the target object name for CREATE or ALTER commands.
18092 * TODO: there might be some value in caching the results.
18095 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18103 if ((opts & zeroAsOpaque) != 0)
18104 return pg_strdup(g_opaque_type);
18105 else if ((opts & zeroAsAny) != 0)
18106 return pg_strdup("'any'");
18107 else if ((opts & zeroAsStar) != 0)
18108 return pg_strdup("*");
18109 else if ((opts & zeroAsNone) != 0)
18110 return pg_strdup("NONE");
18113 query = createPQExpBuffer();
18114 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18117 res = ExecuteSqlQueryForSingleRow(fout, query->data);
18119 /* result of format_type is already quoted */
18120 result = pg_strdup(PQgetvalue(res, 0, 0));
18123 destroyPQExpBuffer(query);
18129 * Return a column list clause for the given relation.
18131 * Special case: if there are no undropped columns in the relation, return
18132 * "", not an invalid "()" column list.
18134 static const char *
18135 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18137 int numatts = ti->numatts;
18138 char **attnames = ti->attnames;
18139 bool *attisdropped = ti->attisdropped;
18143 appendPQExpBufferChar(buffer, '(');
18145 for (i = 0; i < numatts; i++)
18147 if (attisdropped[i])
18150 appendPQExpBufferStr(buffer, ", ");
18151 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18156 return ""; /* no undropped columns */
18158 appendPQExpBufferChar(buffer, ')');
18159 return buffer->data;
18163 * Check if a reloptions array is nonempty.
18166 nonemptyReloptions(const char *reloptions)
18168 /* Don't want to print it if it's just "{}" */
18169 return (reloptions != NULL && strlen(reloptions) > 2);
18173 * Format a reloptions array and append it to the given buffer.
18175 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18178 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18179 const char *prefix, Archive *fout)
18183 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18184 fout->std_strings);
18186 write_msg(NULL, "WARNING: could not parse reloptions array\n");