1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
14 * Note that pg_dump runs in a transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to look at
18 * the currently committed state. So it is possible to get 'cache
19 * lookup failed' error if someone performs DDL changes while a dump is
20 * happening. The window for this sort of thing is from the acquisition
21 * of the transaction snapshot to getSchemaData() (when pg_dump acquires
22 * AccessShareLock on every table it intends to dump). It isn't very large,
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
32 #include "postgres_fe.h"
40 #include "getopt_long.h"
42 #include "access/attnum.h"
43 #include "access/sysattr.h"
44 #include "access/transam.h"
45 #include "catalog/pg_aggregate.h"
46 #include "catalog/pg_am.h"
47 #include "catalog/pg_attribute.h"
48 #include "catalog/pg_cast.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_default_acl.h"
51 #include "catalog/pg_largeobject.h"
52 #include "catalog/pg_largeobject_metadata.h"
53 #include "catalog/pg_proc.h"
54 #include "catalog/pg_trigger.h"
55 #include "catalog/pg_type.h"
56 #include "libpq/libpq-fs.h"
58 #include "dumputils.h"
60 #include "pg_backup_db.h"
61 #include "pg_backup_utils.h"
63 #include "fe_utils/connect.h"
64 #include "fe_utils/string_utils.h"
69 const char *descr; /* comment for an object */
70 Oid classoid; /* object class (catalog OID) */
71 Oid objoid; /* object OID */
72 int objsubid; /* subobject (table column #) */
77 const char *provider; /* label provider of this security label */
78 const char *label; /* security label for an object */
79 Oid classoid; /* object class (catalog OID) */
80 Oid objoid; /* object OID */
81 int objsubid; /* subobject (table column #) */
84 typedef enum OidOptions
93 bool g_verbose; /* User wants verbose narration of our
95 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
101 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102 * FirstNormalObjectId - 1.
104 static Oid g_last_builtin_oid; /* value of the last builtin oid */
106 /* The specified names/patterns should to match at least one entity */
107 static int strict_names = 0;
110 * Object inclusion/exclusion lists
112 * The string lists record the patterns given by command-line switches,
113 * which we then convert to lists of OIDs of matching objects.
115 static SimpleStringList schema_include_patterns = {NULL, NULL};
116 static SimpleOidList schema_include_oids = {NULL, NULL};
117 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
118 static SimpleOidList schema_exclude_oids = {NULL, NULL};
120 static SimpleStringList table_include_patterns = {NULL, NULL};
121 static SimpleOidList table_include_oids = {NULL, NULL};
122 static SimpleStringList table_exclude_patterns = {NULL, NULL};
123 static SimpleOidList table_exclude_oids = {NULL, NULL};
124 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
125 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
128 char g_opaque_type[10]; /* name for the opaque type */
130 /* placeholders for the delimiters for comments */
131 char g_comment_start[10];
132 char g_comment_end[10];
134 static const CatalogId nilCatalogId = {0, 0};
137 * Macro for producing quoted, schema-qualified name of a dumpable object.
138 * Note implicit dependence on "fout"; we should get rid of that argument.
140 #define fmtQualifiedDumpable(obj) \
141 fmtQualifiedId(fout->remoteVersion, \
142 (obj)->dobj.namespace->dobj.name, \
145 static void help(const char *progname);
146 static void setup_connection(Archive *AH,
147 const char *dumpencoding, const char *dumpsnapshot,
149 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
150 static void expand_schema_name_patterns(Archive *fout,
151 SimpleStringList *patterns,
154 static void expand_table_name_patterns(Archive *fout,
155 SimpleStringList *patterns,
158 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
159 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
160 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
161 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
162 static void dumpComment(Archive *fout, const char *type, const char *name,
163 const char *namespace, const char *owner,
164 CatalogId catalogId, int subid, DumpId dumpId);
165 static int findComments(Archive *fout, Oid classoid, Oid objoid,
166 CommentItem **items);
167 static int collectComments(Archive *fout, CommentItem **items);
168 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
169 const char *namespace, const char *owner,
170 CatalogId catalogId, int subid, DumpId dumpId);
171 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
172 SecLabelItem **items);
173 static int collectSecLabels(Archive *fout, SecLabelItem **items);
174 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
175 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
176 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
177 static void dumpType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
182 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
183 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
184 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
185 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
186 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
187 static void dumpFunc(Archive *fout, FuncInfo *finfo);
188 static void dumpCast(Archive *fout, CastInfo *cast);
189 static void dumpTransform(Archive *fout, TransformInfo *transform);
190 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
191 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
192 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
193 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
194 static void dumpCollation(Archive *fout, CollInfo *collinfo);
195 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
196 static void dumpRule(Archive *fout, RuleInfo *rinfo);
197 static void dumpAgg(Archive *fout, AggInfo *agginfo);
198 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
199 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
200 static void dumpTable(Archive *fout, TableInfo *tbinfo);
201 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
202 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
203 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
204 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
205 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
206 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
207 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
208 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
209 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
210 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
211 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
212 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
213 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
214 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
215 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
216 static void dumpUserMappings(Archive *fout,
217 const char *servername, const char *namespace,
218 const char *owner, CatalogId catalogId, DumpId dumpId);
219 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
221 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
222 const char *type, const char *name, const char *subname,
223 const char *nspname, const char *owner,
224 const char *acls, const char *racls,
225 const char *initacls, const char *initracls);
227 static void getDependencies(Archive *fout);
228 static void BuildArchiveDependencies(Archive *fout);
229 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
230 DumpId **dependencies, int *nDeps, int *allocDeps);
232 static DumpableObject *createBoundaryObjects(void);
233 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
234 DumpableObject *boundaryObjs);
236 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
237 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
238 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
239 static void buildMatViewRefreshDependencies(Archive *fout);
240 static void getTableDataFKConstraints(void);
241 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
243 static char *format_function_arguments_old(Archive *fout,
244 FuncInfo *finfo, int nallargs,
248 static char *format_function_signature(Archive *fout,
249 FuncInfo *finfo, bool honor_quotes);
250 static char *convertRegProcReference(Archive *fout,
252 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
253 static char *convertTSFunction(Archive *fout, Oid funcOid);
254 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
255 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
256 static void getBlobs(Archive *fout);
257 static void dumpBlob(Archive *fout, BlobInfo *binfo);
258 static int dumpBlobs(Archive *fout, void *arg);
259 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
260 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
261 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
262 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
263 static void dumpDatabase(Archive *AH);
264 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
265 const char *dbname, Oid dboid);
266 static void dumpEncoding(Archive *AH);
267 static void dumpStdStrings(Archive *AH);
268 static void dumpSearchPath(Archive *AH);
269 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
270 PQExpBuffer upgrade_buffer,
272 bool force_array_type);
273 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
274 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
275 static void binary_upgrade_set_pg_class_oids(Archive *fout,
276 PQExpBuffer upgrade_buffer,
277 Oid pg_class_oid, bool is_index);
278 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
279 DumpableObject *dobj,
282 const char *objnamespace);
283 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
284 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
285 static bool nonemptyReloptions(const char *reloptions);
286 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
287 const char *prefix, Archive *fout);
288 static char *get_synchronized_snapshot(Archive *fout);
289 static void setupDumpWorker(Archive *AHX);
290 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
294 main(int argc, char **argv)
297 const char *filename = NULL;
298 const char *format = "p";
301 DumpableObject **dobjs;
303 DumpableObject *boundaryObjs;
306 RestoreOptions *ropt;
307 Archive *fout; /* the script file */
308 const char *dumpencoding = NULL;
309 const char *dumpsnapshot = NULL;
310 char *use_role = NULL;
312 trivalue prompt_password = TRI_DEFAULT;
313 int compressLevel = -1;
315 ArchiveFormat archiveFormat = archUnknown;
316 ArchiveMode archiveMode;
318 static DumpOptions dopt;
320 static struct option long_options[] = {
321 {"data-only", no_argument, NULL, 'a'},
322 {"blobs", no_argument, NULL, 'b'},
323 {"no-blobs", no_argument, NULL, 'B'},
324 {"clean", no_argument, NULL, 'c'},
325 {"create", no_argument, NULL, 'C'},
326 {"dbname", required_argument, NULL, 'd'},
327 {"file", required_argument, NULL, 'f'},
328 {"format", required_argument, NULL, 'F'},
329 {"host", required_argument, NULL, 'h'},
330 {"jobs", 1, NULL, 'j'},
331 {"no-reconnect", no_argument, NULL, 'R'},
332 {"oids", no_argument, NULL, 'o'},
333 {"no-owner", no_argument, NULL, 'O'},
334 {"port", required_argument, NULL, 'p'},
335 {"schema", required_argument, NULL, 'n'},
336 {"exclude-schema", required_argument, NULL, 'N'},
337 {"schema-only", no_argument, NULL, 's'},
338 {"superuser", required_argument, NULL, 'S'},
339 {"table", required_argument, NULL, 't'},
340 {"exclude-table", required_argument, NULL, 'T'},
341 {"no-password", no_argument, NULL, 'w'},
342 {"password", no_argument, NULL, 'W'},
343 {"username", required_argument, NULL, 'U'},
344 {"verbose", no_argument, NULL, 'v'},
345 {"no-privileges", no_argument, NULL, 'x'},
346 {"no-acl", no_argument, NULL, 'x'},
347 {"compress", required_argument, NULL, 'Z'},
348 {"encoding", required_argument, NULL, 'E'},
349 {"help", no_argument, NULL, '?'},
350 {"version", no_argument, NULL, 'V'},
353 * the following options don't have an equivalent short option letter
355 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
356 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
357 {"column-inserts", no_argument, &dopt.column_inserts, 1},
358 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
359 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
360 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
361 {"exclude-table-data", required_argument, NULL, 4},
362 {"if-exists", no_argument, &dopt.if_exists, 1},
363 {"inserts", no_argument, &dopt.dump_inserts, 1},
364 {"lock-wait-timeout", required_argument, NULL, 2},
365 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
366 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
367 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
368 {"role", required_argument, NULL, 3},
369 {"section", required_argument, NULL, 5},
370 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
371 {"snapshot", required_argument, NULL, 6},
372 {"strict-names", no_argument, &strict_names, 1},
373 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
374 {"no-comments", no_argument, &dopt.no_comments, 1},
375 {"no-publications", no_argument, &dopt.no_publications, 1},
376 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
377 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
378 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
379 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
380 {"no-sync", no_argument, NULL, 7},
385 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
388 * Initialize what we need for parallel execution, especially for thread
389 * support on Windows.
391 init_parallel_dump_utils();
395 strcpy(g_comment_start, "-- ");
396 g_comment_end[0] = '\0';
397 strcpy(g_opaque_type, "opaque");
399 progname = get_progname(argv[0]);
403 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
408 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
410 puts("pg_dump (PostgreSQL) " PG_VERSION);
415 InitDumpOptions(&dopt);
417 while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
418 long_options, &optindex)) != -1)
422 case 'a': /* Dump data only */
423 dopt.dataOnly = true;
426 case 'b': /* Dump blobs */
427 dopt.outputBlobs = true;
430 case 'B': /* Don't dump blobs */
431 dopt.dontOutputBlobs = true;
434 case 'c': /* clean (i.e., drop) schema prior to create */
435 dopt.outputClean = 1;
438 case 'C': /* Create DB */
439 dopt.outputCreateDB = 1;
442 case 'd': /* database name */
443 dopt.dbname = pg_strdup(optarg);
446 case 'E': /* Dump encoding */
447 dumpencoding = pg_strdup(optarg);
451 filename = pg_strdup(optarg);
455 format = pg_strdup(optarg);
458 case 'h': /* server host */
459 dopt.pghost = pg_strdup(optarg);
462 case 'j': /* number of dump jobs */
463 numWorkers = atoi(optarg);
466 case 'n': /* include schema(s) */
467 simple_string_list_append(&schema_include_patterns, optarg);
468 dopt.include_everything = false;
471 case 'N': /* exclude schema(s) */
472 simple_string_list_append(&schema_exclude_patterns, optarg);
475 case 'o': /* Dump oids */
479 case 'O': /* Don't reconnect to match owner */
480 dopt.outputNoOwner = 1;
483 case 'p': /* server port */
484 dopt.pgport = pg_strdup(optarg);
488 /* no-op, still accepted for backwards compatibility */
491 case 's': /* dump schema only */
492 dopt.schemaOnly = true;
495 case 'S': /* Username for superuser in plain text output */
496 dopt.outputSuperuser = pg_strdup(optarg);
499 case 't': /* include table(s) */
500 simple_string_list_append(&table_include_patterns, optarg);
501 dopt.include_everything = false;
504 case 'T': /* exclude table(s) */
505 simple_string_list_append(&table_exclude_patterns, optarg);
509 dopt.username = pg_strdup(optarg);
512 case 'v': /* verbose */
517 prompt_password = TRI_NO;
521 prompt_password = TRI_YES;
524 case 'x': /* skip ACL dump */
525 dopt.aclsSkip = true;
528 case 'Z': /* Compression Level */
529 compressLevel = atoi(optarg);
530 if (compressLevel < 0 || compressLevel > 9)
532 write_msg(NULL, "compression level must be in range 0..9\n");
538 /* This covers the long options. */
541 case 2: /* lock-wait-timeout */
542 dopt.lockWaitTimeout = pg_strdup(optarg);
545 case 3: /* SET ROLE */
546 use_role = pg_strdup(optarg);
549 case 4: /* exclude table(s) data */
550 simple_string_list_append(&tabledata_exclude_patterns, optarg);
553 case 5: /* section */
554 set_dump_section(optarg, &dopt.dumpSections);
557 case 6: /* snapshot */
558 dumpsnapshot = pg_strdup(optarg);
561 case 7: /* no-sync */
566 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
572 * Non-option argument specifies database name as long as it wasn't
573 * already specified with -d / --dbname
575 if (optind < argc && dopt.dbname == NULL)
576 dopt.dbname = argv[optind++];
578 /* Complain if any arguments remain */
581 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
582 progname, argv[optind]);
583 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
588 /* --column-inserts implies --inserts */
589 if (dopt.column_inserts)
590 dopt.dump_inserts = 1;
593 * Binary upgrade mode implies dumping sequence data even in schema-only
594 * mode. This is not exposed as a separate option, but kept separate
595 * internally for clarity.
597 if (dopt.binary_upgrade)
598 dopt.sequence_data = 1;
600 if (dopt.dataOnly && dopt.schemaOnly)
602 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
606 if (dopt.dataOnly && dopt.outputClean)
608 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
612 if (dopt.dump_inserts && dopt.oids)
614 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
615 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
619 if (dopt.if_exists && !dopt.outputClean)
620 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
622 /* Identify archive format to emit */
623 archiveFormat = parseArchiveFormat(format, &archiveMode);
625 /* archiveFormat specific setup */
626 if (archiveFormat == archNull)
629 /* Custom and directory formats are compressed by default, others not */
630 if (compressLevel == -1)
633 if (archiveFormat == archCustom || archiveFormat == archDirectory)
634 compressLevel = Z_DEFAULT_COMPRESSION;
641 if (compressLevel != 0)
642 write_msg(NULL, "WARNING: requested compression not available in this "
643 "installation -- archive will be uncompressed\n");
648 * If emitting an archive format, we always want to emit a DATABASE item,
649 * in case --create is specified at pg_restore time.
652 dopt.outputCreateDB = 1;
655 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
656 * parallel jobs because that's the maximum limit for the
657 * WaitForMultipleObjects() call.
661 || numWorkers > MAXIMUM_WAIT_OBJECTS
664 exit_horribly(NULL, "invalid number of parallel jobs\n");
666 /* Parallel backup only in the directory archive format so far */
667 if (archiveFormat != archDirectory && numWorkers > 1)
668 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
670 /* Open the output file */
671 fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
672 archiveMode, setupDumpWorker);
674 /* Make dump options accessible right away */
675 SetArchiveOptions(fout, &dopt, NULL);
677 /* Register the cleanup hook */
678 on_exit_close_archive(fout);
680 /* Let the archiver know how noisy to be */
681 fout->verbose = g_verbose;
684 * We allow the server to be back to 8.0, and up to any minor release of
685 * our own major version. (See also version check in pg_dumpall.c.)
687 fout->minRemoteVersion = 80000;
688 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
690 fout->numWorkers = numWorkers;
693 * Open the database using the Archiver, so it knows about it. Errors mean
696 ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
697 setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
700 * Disable security label support if server version < v9.1.x (prevents
701 * access to nonexistent pg_seclabel catalog)
703 if (fout->remoteVersion < 90100)
704 dopt.no_security_labels = 1;
707 * On hot standbys, never try to dump unlogged table data, since it will
708 * just throw an error.
711 dopt.no_unlogged_table_data = true;
713 /* Select the appropriate subquery to convert user IDs to names */
714 if (fout->remoteVersion >= 80100)
715 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
717 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
719 /* check the version for the synchronized snapshots feature */
720 if (numWorkers > 1 && fout->remoteVersion < 90200
721 && !dopt.no_synchronized_snapshots)
723 "Synchronized snapshots are not supported by this server version.\n"
724 "Run with --no-synchronized-snapshots instead if you do not need\n"
725 "synchronized snapshots.\n");
727 /* check the version when a snapshot is explicitly specified by user */
728 if (dumpsnapshot && fout->remoteVersion < 90200)
730 "Exported snapshots are not supported by this server version.\n");
733 * Find the last built-in OID, if needed (prior to 8.1)
735 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
737 if (fout->remoteVersion < 80100)
738 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
739 PQdb(GetConnection(fout)));
741 g_last_builtin_oid = FirstNormalObjectId - 1;
744 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
746 /* Expand schema selection patterns into OID lists */
747 if (schema_include_patterns.head != NULL)
749 expand_schema_name_patterns(fout, &schema_include_patterns,
750 &schema_include_oids,
752 if (schema_include_oids.head == NULL)
753 exit_horribly(NULL, "no matching schemas were found\n");
755 expand_schema_name_patterns(fout, &schema_exclude_patterns,
756 &schema_exclude_oids,
758 /* non-matching exclusion patterns aren't an error */
760 /* Expand table selection patterns into OID lists */
761 if (table_include_patterns.head != NULL)
763 expand_table_name_patterns(fout, &table_include_patterns,
766 if (table_include_oids.head == NULL)
767 exit_horribly(NULL, "no matching tables were found\n");
769 expand_table_name_patterns(fout, &table_exclude_patterns,
773 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
774 &tabledata_exclude_oids,
777 /* non-matching exclusion patterns aren't an error */
780 * Dumping blobs is the default for dumps where an inclusion switch is not
781 * used (an "include everything" dump). -B can be used to exclude blobs
782 * from those dumps. -b can be used to include blobs even when an
783 * inclusion switch is used.
785 * -s means "schema only" and blobs are data, not schema, so we never
786 * include blobs when -s is used.
788 if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
789 dopt.outputBlobs = true;
792 * Now scan the database and create DumpableObject structs for all the
793 * objects we intend to dump.
795 tblinfo = getSchemaData(fout, &numTables);
797 if (fout->remoteVersion < 80400)
798 guessConstraintInheritance(tblinfo, numTables);
800 if (!dopt.schemaOnly)
802 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
803 buildMatViewRefreshDependencies(fout);
805 getTableDataFKConstraints();
808 if (dopt.schemaOnly && dopt.sequence_data)
809 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
812 * In binary-upgrade mode, we do not have to worry about the actual blob
813 * data or the associated metadata that resides in the pg_largeobject and
814 * pg_largeobject_metadata tables, respectively.
816 * However, we do need to collect blob information as there may be
817 * comments or other information on blobs that we do need to dump out.
819 if (dopt.outputBlobs || dopt.binary_upgrade)
823 * Collect dependency data to assist in ordering the objects.
825 getDependencies(fout);
827 /* Lastly, create dummy objects to represent the section boundaries */
828 boundaryObjs = createBoundaryObjects();
830 /* Get pointers to all the known DumpableObjects */
831 getDumpableObjects(&dobjs, &numObjs);
834 * Add dummy dependencies to enforce the dump section ordering.
836 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
839 * Sort the objects into a safe dump order (no forward references).
841 * We rely on dependency information to help us determine a safe order, so
842 * the initial sort is mostly for cosmetic purposes: we sort by name to
843 * ensure that logically identical schemas will dump identically.
845 sortDumpableObjectsByTypeName(dobjs, numObjs);
847 /* If we do a parallel dump, we want the largest tables to go first */
848 if (archiveFormat == archDirectory && numWorkers > 1)
849 sortDataAndIndexObjectsBySize(dobjs, numObjs);
851 sortDumpableObjects(dobjs, numObjs,
852 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
855 * Create archive TOC entries for all the objects to be dumped, in a safe
859 /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
861 dumpStdStrings(fout);
862 dumpSearchPath(fout);
864 /* The database items are always next, unless we don't want them at all */
865 if (dopt.outputCreateDB)
868 /* Now the rearrangeable objects. */
869 for (i = 0; i < numObjs; i++)
870 dumpDumpableObject(fout, dobjs[i]);
873 * Set up options info to ensure we dump what we want.
875 ropt = NewRestoreOptions();
876 ropt->filename = filename;
878 /* if you change this list, see dumpOptionsFromRestoreOptions */
879 ropt->dropSchema = dopt.outputClean;
880 ropt->dataOnly = dopt.dataOnly;
881 ropt->schemaOnly = dopt.schemaOnly;
882 ropt->if_exists = dopt.if_exists;
883 ropt->column_inserts = dopt.column_inserts;
884 ropt->dumpSections = dopt.dumpSections;
885 ropt->aclsSkip = dopt.aclsSkip;
886 ropt->superuser = dopt.outputSuperuser;
887 ropt->createDB = dopt.outputCreateDB;
888 ropt->noOwner = dopt.outputNoOwner;
889 ropt->noTablespace = dopt.outputNoTablespaces;
890 ropt->disable_triggers = dopt.disable_triggers;
891 ropt->use_setsessauth = dopt.use_setsessauth;
892 ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
893 ropt->dump_inserts = dopt.dump_inserts;
894 ropt->no_comments = dopt.no_comments;
895 ropt->no_publications = dopt.no_publications;
896 ropt->no_security_labels = dopt.no_security_labels;
897 ropt->no_subscriptions = dopt.no_subscriptions;
898 ropt->lockWaitTimeout = dopt.lockWaitTimeout;
899 ropt->include_everything = dopt.include_everything;
900 ropt->enable_row_security = dopt.enable_row_security;
901 ropt->sequence_data = dopt.sequence_data;
902 ropt->binary_upgrade = dopt.binary_upgrade;
904 if (compressLevel == -1)
905 ropt->compression = 0;
907 ropt->compression = compressLevel;
909 ropt->suppressDumpWarnings = true; /* We've already shown them */
911 SetArchiveOptions(fout, &dopt, ropt);
913 /* Mark which entries should be output */
914 ProcessArchiveRestoreOptions(fout);
917 * The archive's TOC entries are now marked as to which ones will actually
918 * be output, so we can set up their dependency lists properly. This isn't
919 * necessary for plain-text output, though.
922 BuildArchiveDependencies(fout);
925 * And finally we can do the actual output.
927 * Note: for non-plain-text output formats, the output file is written
928 * inside CloseArchive(). This is, um, bizarre; but not worth changing
932 RestoreArchive(fout);
941 help(const char *progname)
943 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
944 printf(_("Usage:\n"));
945 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
947 printf(_("\nGeneral options:\n"));
948 printf(_(" -f, --file=FILENAME output file or directory name\n"));
949 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
950 " plain text (default))\n"));
951 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
952 printf(_(" -v, --verbose verbose mode\n"));
953 printf(_(" -V, --version output version information, then exit\n"));
954 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
955 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
956 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
957 printf(_(" -?, --help show this help, then exit\n"));
959 printf(_("\nOptions controlling the output content:\n"));
960 printf(_(" -a, --data-only dump only the data, not the schema\n"));
961 printf(_(" -b, --blobs include large objects in dump\n"));
962 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
963 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
964 printf(_(" -C, --create include commands to create database in dump\n"));
965 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
966 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
967 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
968 printf(_(" -o, --oids include OIDs in dump\n"));
969 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
970 " plain-text format\n"));
971 printf(_(" -s, --schema-only dump only the schema, no data\n"));
972 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
973 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
974 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
975 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
976 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
977 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
978 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
979 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
980 printf(_(" --enable-row-security enable row security (dump only content user has\n"
982 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
983 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
984 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
985 printf(_(" --no-comments do not dump comments\n"));
986 printf(_(" --no-publications do not dump publications\n"));
987 printf(_(" --no-security-labels do not dump security label assignments\n"));
988 printf(_(" --no-subscriptions do not dump subscriptions\n"));
989 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
990 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
991 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
992 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
993 printf(_(" --load-via-partition-root load partitions via the root table\n"));
994 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
995 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
996 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
997 printf(_(" --strict-names require table and/or schema include patterns to\n"
998 " match at least one entity each\n"));
999 printf(_(" --use-set-session-authorization\n"
1000 " use SET SESSION AUTHORIZATION commands instead of\n"
1001 " ALTER OWNER commands to set ownership\n"));
1003 printf(_("\nConnection options:\n"));
1004 printf(_(" -d, --dbname=DBNAME database to dump\n"));
1005 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1006 printf(_(" -p, --port=PORT database server port number\n"));
1007 printf(_(" -U, --username=NAME connect as specified database user\n"));
1008 printf(_(" -w, --no-password never prompt for password\n"));
1009 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1010 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1012 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1013 "variable value is used.\n\n"));
1014 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1018 setup_connection(Archive *AH, const char *dumpencoding,
1019 const char *dumpsnapshot, char *use_role)
1021 DumpOptions *dopt = AH->dopt;
1022 PGconn *conn = GetConnection(AH);
1023 const char *std_strings;
1025 PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1028 * Set the client encoding if requested.
1032 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1033 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1038 * Get the active encoding and the standard_conforming_strings setting, so
1039 * we know how to escape strings.
1041 AH->encoding = PQclientEncoding(conn);
1043 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1044 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1047 * Set the role if requested. In a parallel dump worker, we'll be passed
1048 * use_role == NULL, but AH->use_role is already set (if user specified it
1049 * originally) and we should use that.
1051 if (!use_role && AH->use_role)
1052 use_role = AH->use_role;
1054 /* Set the role if requested */
1055 if (use_role && AH->remoteVersion >= 80100)
1057 PQExpBuffer query = createPQExpBuffer();
1059 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1060 ExecuteSqlStatement(AH, query->data);
1061 destroyPQExpBuffer(query);
1063 /* save it for possible later use by parallel workers */
1065 AH->use_role = pg_strdup(use_role);
1068 /* Set the datestyle to ISO to ensure the dump's portability */
1069 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1071 /* Likewise, avoid using sql_standard intervalstyle */
1072 if (AH->remoteVersion >= 80400)
1073 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1076 * Set extra_float_digits so that we can dump float data exactly (given
1077 * correctly implemented float I/O code, anyway)
1079 if (AH->remoteVersion >= 90000)
1080 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1082 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1085 * If synchronized scanning is supported, disable it, to prevent
1086 * unpredictable changes in row ordering across a dump and reload.
1088 if (AH->remoteVersion >= 80300)
1089 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1092 * Disable timeouts if supported.
1094 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1095 if (AH->remoteVersion >= 90300)
1096 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1097 if (AH->remoteVersion >= 90600)
1098 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1101 * Quote all identifiers, if requested.
1103 if (quote_all_identifiers && AH->remoteVersion >= 90100)
1104 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1107 * Adjust row-security mode, if supported.
1109 if (AH->remoteVersion >= 90500)
1111 if (dopt->enable_row_security)
1112 ExecuteSqlStatement(AH, "SET row_security = on");
1114 ExecuteSqlStatement(AH, "SET row_security = off");
1118 * Start transaction-snapshot mode transaction to dump consistent data.
1120 ExecuteSqlStatement(AH, "BEGIN");
1121 if (AH->remoteVersion >= 90100)
1124 * To support the combination of serializable_deferrable with the jobs
1125 * option we use REPEATABLE READ for the worker connections that are
1126 * passed a snapshot. As long as the snapshot is acquired in a
1127 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1128 * REPEATABLE READ transaction provides the appropriate integrity
1129 * guarantees. This is a kluge, but safe for back-patching.
1131 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1132 ExecuteSqlStatement(AH,
1133 "SET TRANSACTION ISOLATION LEVEL "
1134 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1136 ExecuteSqlStatement(AH,
1137 "SET TRANSACTION ISOLATION LEVEL "
1138 "REPEATABLE READ, READ ONLY");
1142 ExecuteSqlStatement(AH,
1143 "SET TRANSACTION ISOLATION LEVEL "
1144 "SERIALIZABLE, READ ONLY");
1148 * If user specified a snapshot to use, select that. In a parallel dump
1149 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1150 * is already set (if the server can handle it) and we should use that.
1153 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1155 if (AH->sync_snapshot_id)
1157 PQExpBuffer query = createPQExpBuffer();
1159 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1160 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1161 ExecuteSqlStatement(AH, query->data);
1162 destroyPQExpBuffer(query);
1164 else if (AH->numWorkers > 1 &&
1165 AH->remoteVersion >= 90200 &&
1166 !dopt->no_synchronized_snapshots)
1168 if (AH->isStandby && AH->remoteVersion < 100000)
1170 "Synchronized snapshots on standby servers are not supported by this server version.\n"
1171 "Run with --no-synchronized-snapshots instead if you do not need\n"
1172 "synchronized snapshots.\n");
1175 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1179 /* Set up connection for a parallel worker process */
1181 setupDumpWorker(Archive *AH)
1184 * We want to re-select all the same values the master connection is
1185 * using. We'll have inherited directly-usable values in
1186 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1187 * inherited encoding value back to a string to pass to setup_connection.
1189 setup_connection(AH,
1190 pg_encoding_to_char(AH->encoding),
1196 get_synchronized_snapshot(Archive *fout)
1198 char *query = "SELECT pg_catalog.pg_export_snapshot()";
1202 res = ExecuteSqlQueryForSingleRow(fout, query);
1203 result = pg_strdup(PQgetvalue(res, 0, 0));
1209 static ArchiveFormat
1210 parseArchiveFormat(const char *format, ArchiveMode *mode)
1212 ArchiveFormat archiveFormat;
1214 *mode = archModeWrite;
1216 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1218 /* This is used by pg_dumpall, and is not documented */
1219 archiveFormat = archNull;
1220 *mode = archModeAppend;
1222 else if (pg_strcasecmp(format, "c") == 0)
1223 archiveFormat = archCustom;
1224 else if (pg_strcasecmp(format, "custom") == 0)
1225 archiveFormat = archCustom;
1226 else if (pg_strcasecmp(format, "d") == 0)
1227 archiveFormat = archDirectory;
1228 else if (pg_strcasecmp(format, "directory") == 0)
1229 archiveFormat = archDirectory;
1230 else if (pg_strcasecmp(format, "p") == 0)
1231 archiveFormat = archNull;
1232 else if (pg_strcasecmp(format, "plain") == 0)
1233 archiveFormat = archNull;
1234 else if (pg_strcasecmp(format, "t") == 0)
1235 archiveFormat = archTar;
1236 else if (pg_strcasecmp(format, "tar") == 0)
1237 archiveFormat = archTar;
1239 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1240 return archiveFormat;
1244 * Find the OIDs of all schemas matching the given list of patterns,
1245 * and append them to the given OID list.
1248 expand_schema_name_patterns(Archive *fout,
1249 SimpleStringList *patterns,
1250 SimpleOidList *oids,
1255 SimpleStringListCell *cell;
1258 if (patterns->head == NULL)
1259 return; /* nothing to do */
1261 query = createPQExpBuffer();
1264 * The loop below runs multiple SELECTs might sometimes result in
1265 * duplicate entries in the OID list, but we don't care.
1268 for (cell = patterns->head; cell; cell = cell->next)
1270 appendPQExpBuffer(query,
1271 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1272 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1273 false, NULL, "n.nspname", NULL, NULL);
1275 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1276 if (strict_names && PQntuples(res) == 0)
1277 exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1279 for (i = 0; i < PQntuples(res); i++)
1281 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1285 resetPQExpBuffer(query);
1288 destroyPQExpBuffer(query);
1292 * Find the OIDs of all tables matching the given list of patterns,
1293 * and append them to the given OID list.
1296 expand_table_name_patterns(Archive *fout,
1297 SimpleStringList *patterns, SimpleOidList *oids,
1302 SimpleStringListCell *cell;
1305 if (patterns->head == NULL)
1306 return; /* nothing to do */
1308 query = createPQExpBuffer();
1311 * this might sometimes result in duplicate entries in the OID list, but
1315 for (cell = patterns->head; cell; cell = cell->next)
1318 * Query must remain ABSOLUTELY devoid of unqualified names. This
1319 * would be unnecessary given a pg_table_is_visible() variant taking a
1320 * search_path argument.
1322 appendPQExpBuffer(query,
1324 "\nFROM pg_catalog.pg_class c"
1325 "\n LEFT JOIN pg_catalog.pg_namespace n"
1326 "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1327 "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1328 "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1329 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1330 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1331 RELKIND_PARTITIONED_TABLE);
1332 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1333 false, "n.nspname", "c.relname", NULL,
1334 "pg_catalog.pg_table_is_visible(c.oid)");
1336 ExecuteSqlStatement(fout, "RESET search_path");
1337 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1338 PQclear(ExecuteSqlQueryForSingleRow(fout,
1339 ALWAYS_SECURE_SEARCH_PATH_SQL));
1340 if (strict_names && PQntuples(res) == 0)
1341 exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1343 for (i = 0; i < PQntuples(res); i++)
1345 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1349 resetPQExpBuffer(query);
1352 destroyPQExpBuffer(query);
1356 * checkExtensionMembership
1357 * Determine whether object is an extension member, and if so,
1358 * record an appropriate dependency and set the object's dump flag.
1360 * It's important to call this for each object that could be an extension
1361 * member. Generally, we integrate this with determining the object's
1362 * to-be-dumped-ness, since extension membership overrides other rules for that.
1364 * Returns true if object is an extension member, else false.
1367 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1369 ExtensionInfo *ext = findOwningExtension(dobj->catId);
1374 dobj->ext_member = true;
1376 /* Record dependency so that getDependencies needn't deal with that */
1377 addObjectDependency(dobj, ext->dobj.dumpId);
1380 * In 9.6 and above, mark the member object to have any non-initial ACL,
1381 * policies, and security labels dumped.
1383 * Note that any initial ACLs (see pg_init_privs) will be removed when we
1384 * extract the information about the object. We don't provide support for
1385 * initial policies and security labels and it seems unlikely for those to
1386 * ever exist, but we may have to revisit this later.
1388 * Prior to 9.6, we do not include any extension member components.
1390 * In binary upgrades, we still dump all components of the members
1391 * individually, since the idea is to exactly reproduce the database
1392 * contents rather than replace the extension contents with something
1395 if (fout->dopt->binary_upgrade)
1396 dobj->dump = ext->dobj.dump;
1399 if (fout->remoteVersion < 90600)
1400 dobj->dump = DUMP_COMPONENT_NONE;
1402 dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1403 DUMP_COMPONENT_SECLABEL |
1404 DUMP_COMPONENT_POLICY);
1411 * selectDumpableNamespace: policy-setting subroutine
1412 * Mark a namespace as to be dumped or not
1415 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1418 * If specific tables are being dumped, do not dump any complete
1419 * namespaces. If specific namespaces are being dumped, dump just those
1420 * namespaces. Otherwise, dump all non-system namespaces.
1422 if (table_include_oids.head != NULL)
1423 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1424 else if (schema_include_oids.head != NULL)
1425 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1426 simple_oid_list_member(&schema_include_oids,
1427 nsinfo->dobj.catId.oid) ?
1428 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1429 else if (fout->remoteVersion >= 90600 &&
1430 strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1433 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1434 * they are interesting (and not the original ACLs which were set at
1435 * initdb time, see pg_init_privs).
1437 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1439 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1440 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1442 /* Other system schemas don't get dumped */
1443 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1445 else if (strcmp(nsinfo->dobj.name, "public") == 0)
1448 * The public schema is a strange beast that sits in a sort of
1449 * no-mans-land between being a system object and a user object. We
1450 * don't want to dump creation or comment commands for it, because
1451 * that complicates matters for non-superuser use of pg_dump. But we
1452 * should dump any ACL changes that have occurred for it, and of
1453 * course we should dump contained objects.
1455 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1456 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1459 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1462 * In any case, a namespace can be excluded by an exclusion switch
1464 if (nsinfo->dobj.dump_contains &&
1465 simple_oid_list_member(&schema_exclude_oids,
1466 nsinfo->dobj.catId.oid))
1467 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1470 * If the schema belongs to an extension, allow extension membership to
1471 * override the dump decision for the schema itself. However, this does
1472 * not change dump_contains, so this won't change what we do with objects
1473 * within the schema. (If they belong to the extension, they'll get
1474 * suppressed by it, otherwise not.)
1476 (void) checkExtensionMembership(&nsinfo->dobj, fout);
1480 * selectDumpableTable: policy-setting subroutine
1481 * Mark a table as to be dumped or not
1484 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1486 if (checkExtensionMembership(&tbinfo->dobj, fout))
1487 return; /* extension membership overrides all else */
1490 * If specific tables are being dumped, dump just those tables; else, dump
1491 * according to the parent namespace's dump flag.
1493 if (table_include_oids.head != NULL)
1494 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1495 tbinfo->dobj.catId.oid) ?
1496 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1498 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1501 * In any case, a table can be excluded by an exclusion switch
1503 if (tbinfo->dobj.dump &&
1504 simple_oid_list_member(&table_exclude_oids,
1505 tbinfo->dobj.catId.oid))
1506 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1510 * selectDumpableType: policy-setting subroutine
1511 * Mark a type as to be dumped or not
1513 * If it's a table's rowtype or an autogenerated array type, we also apply a
1514 * special type code to facilitate sorting into the desired order. (We don't
1515 * want to consider those to be ordinary types because that would bring tables
1516 * up into the datatype part of the dump order.) We still set the object's
1517 * dump flag; that's not going to cause the dummy type to be dumped, but we
1518 * need it so that casts involving such types will be dumped correctly -- see
1519 * dumpCast. This means the flag should be set the same as for the underlying
1520 * object (the table or base type).
1523 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1525 /* skip complex types, except for standalone composite types */
1526 if (OidIsValid(tyinfo->typrelid) &&
1527 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1529 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1531 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1532 if (tytable != NULL)
1533 tyinfo->dobj.dump = tytable->dobj.dump;
1535 tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1539 /* skip auto-generated array types */
1540 if (tyinfo->isArray)
1542 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1545 * Fall through to set the dump flag; we assume that the subsequent
1546 * rules will do the same thing as they would for the array's base
1547 * type. (We cannot reliably look up the base type here, since
1548 * getTypes may not have processed it yet.)
1552 if (checkExtensionMembership(&tyinfo->dobj, fout))
1553 return; /* extension membership overrides all else */
1555 /* Dump based on if the contents of the namespace are being dumped */
1556 tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1560 * selectDumpableDefaultACL: policy-setting subroutine
1561 * Mark a default ACL as to be dumped or not
1563 * For per-schema default ACLs, dump if the schema is to be dumped.
1564 * Otherwise dump if we are dumping "everything". Note that dataOnly
1565 * and aclsSkip are checked separately.
1568 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1570 /* Default ACLs can't be extension members */
1572 if (dinfo->dobj.namespace)
1573 /* default ACLs are considered part of the namespace */
1574 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1576 dinfo->dobj.dump = dopt->include_everything ?
1577 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1581 * selectDumpableCast: policy-setting subroutine
1582 * Mark a cast as to be dumped or not
1584 * Casts do not belong to any particular namespace (since they haven't got
1585 * names), nor do they have identifiable owners. To distinguish user-defined
1586 * casts from built-in ones, we must resort to checking whether the cast's
1587 * OID is in the range reserved for initdb.
1590 selectDumpableCast(CastInfo *cast, Archive *fout)
1592 if (checkExtensionMembership(&cast->dobj, fout))
1593 return; /* extension membership overrides all else */
1596 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1597 * support ACLs currently.
1599 if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1600 cast->dobj.dump = DUMP_COMPONENT_NONE;
1602 cast->dobj.dump = fout->dopt->include_everything ?
1603 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1607 * selectDumpableProcLang: policy-setting subroutine
1608 * Mark a procedural language as to be dumped or not
1610 * Procedural languages do not belong to any particular namespace. To
1611 * identify built-in languages, we must resort to checking whether the
1612 * language's OID is in the range reserved for initdb.
1615 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1617 if (checkExtensionMembership(&plang->dobj, fout))
1618 return; /* extension membership overrides all else */
1621 * Only include procedural languages when we are dumping everything.
1623 * For from-initdb procedural languages, only include ACLs, as we do for
1624 * the pg_catalog namespace. We need this because procedural languages do
1625 * not live in any namespace.
1627 if (!fout->dopt->include_everything)
1628 plang->dobj.dump = DUMP_COMPONENT_NONE;
1631 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1632 plang->dobj.dump = fout->remoteVersion < 90600 ?
1633 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1635 plang->dobj.dump = DUMP_COMPONENT_ALL;
1640 * selectDumpableAccessMethod: policy-setting subroutine
1641 * Mark an access method as to be dumped or not
1643 * Access methods do not belong to any particular namespace. To identify
1644 * built-in access methods, we must resort to checking whether the
1645 * method's OID is in the range reserved for initdb.
1648 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1650 if (checkExtensionMembership(&method->dobj, fout))
1651 return; /* extension membership overrides all else */
1654 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1655 * they do not support ACLs currently.
1657 if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1658 method->dobj.dump = DUMP_COMPONENT_NONE;
1660 method->dobj.dump = fout->dopt->include_everything ?
1661 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1665 * selectDumpableExtension: policy-setting subroutine
1666 * Mark an extension as to be dumped or not
1668 * Built-in extensions should be skipped except for checking ACLs, since we
1669 * assume those will already be installed in the target database. We identify
1670 * such extensions by their having OIDs in the range reserved for initdb.
1671 * We dump all user-added extensions by default, or none of them if
1672 * include_everything is false (i.e., a --schema or --table switch was given).
1675 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1678 * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1679 * change permissions on their member objects, if they wish to, and have
1680 * those changes preserved.
1682 if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1683 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1685 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1686 dopt->include_everything ? DUMP_COMPONENT_ALL :
1687 DUMP_COMPONENT_NONE;
1691 * selectDumpablePublicationTable: policy-setting subroutine
1692 * Mark a publication table as to be dumped or not
1694 * Publication tables have schemas, but those are ignored in decision making,
1695 * because publications are only dumped when we are dumping everything.
1698 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1700 if (checkExtensionMembership(dobj, fout))
1701 return; /* extension membership overrides all else */
1703 dobj->dump = fout->dopt->include_everything ?
1704 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1708 * selectDumpableObject: policy-setting subroutine
1709 * Mark a generic dumpable object as to be dumped or not
1711 * Use this only for object types without a special-case routine above.
1714 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1716 if (checkExtensionMembership(dobj, fout))
1717 return; /* extension membership overrides all else */
1720 * Default policy is to dump if parent namespace is dumpable, or for
1721 * non-namespace-associated items, dump if we're dumping "everything".
1723 if (dobj->namespace)
1724 dobj->dump = dobj->namespace->dobj.dump_contains;
1726 dobj->dump = fout->dopt->include_everything ?
1727 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1731 * Dump a table's contents for loading using the COPY command
1732 * - this routine is called by the Archiver when it wants the table
1737 dumpTableData_copy(Archive *fout, void *dcontext)
1739 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1740 TableInfo *tbinfo = tdinfo->tdtable;
1741 const char *classname = tbinfo->dobj.name;
1742 const bool hasoids = tbinfo->hasoids;
1743 const bool oids = tdinfo->oids;
1744 PQExpBuffer q = createPQExpBuffer();
1747 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1748 * which uses it already.
1750 PQExpBuffer clistBuf = createPQExpBuffer();
1751 PGconn *conn = GetConnection(fout);
1755 const char *column_list;
1758 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1759 tbinfo->dobj.namespace->dobj.name, classname);
1762 * Specify the column list explicitly so that we have no possibility of
1763 * retrieving data in the wrong column order. (The default column
1764 * ordering of COPY will not be what we want in certain corner cases
1765 * involving ADD COLUMN and inheritance.)
1767 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1769 if (oids && hasoids)
1771 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1772 fmtQualifiedDumpable(tbinfo),
1775 else if (tdinfo->filtercond)
1777 /* Note: this syntax is only supported in 8.2 and up */
1778 appendPQExpBufferStr(q, "COPY (SELECT ");
1779 /* klugery to get rid of parens in column list */
1780 if (strlen(column_list) > 2)
1782 appendPQExpBufferStr(q, column_list + 1);
1783 q->data[q->len - 1] = ' ';
1786 appendPQExpBufferStr(q, "* ");
1787 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1788 fmtQualifiedDumpable(tbinfo),
1789 tdinfo->filtercond);
1793 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1794 fmtQualifiedDumpable(tbinfo),
1797 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1799 destroyPQExpBuffer(clistBuf);
1803 ret = PQgetCopyData(conn, ©buf, 0);
1806 break; /* done or error */
1810 WriteData(fout, copybuf, ret);
1817 * There was considerable discussion in late July, 2000 regarding
1818 * slowing down pg_dump when backing up large tables. Users with both
1819 * slow & fast (multi-processor) machines experienced performance
1820 * degradation when doing a backup.
1822 * Initial attempts based on sleeping for a number of ms for each ms
1823 * of work were deemed too complex, then a simple 'sleep in each loop'
1824 * implementation was suggested. The latter failed because the loop
1825 * was too tight. Finally, the following was implemented:
1827 * If throttle is non-zero, then
1828 * See how long since the last sleep.
1829 * Work out how long to sleep (based on ratio).
1830 * If sleep is more than 100ms, then
1836 * where the throttle value was the number of ms to sleep per ms of
1837 * work. The calculation was done in each loop.
1839 * Most of the hard work is done in the backend, and this solution
1840 * still did not work particularly well: on slow machines, the ratio
1841 * was 50:1, and on medium paced machines, 1:1, and on fast
1842 * multi-processor machines, it had little or no effect, for reasons
1843 * that were unclear.
1845 * Further discussion ensued, and the proposal was dropped.
1847 * For those people who want this feature, it can be implemented using
1848 * gettimeofday in each loop, calculating the time since last sleep,
1849 * multiplying that by the sleep ratio, then if the result is more
1850 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1851 * function to sleep for a subsecond period ie.
1853 * select(0, NULL, NULL, NULL, &tvi);
1855 * This will return after the interval specified in the structure tvi.
1856 * Finally, call gettimeofday again to save the 'last sleep time'.
1860 archprintf(fout, "\\.\n\n\n");
1864 /* copy data transfer failed */
1865 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1866 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1867 write_msg(NULL, "The command was: %s\n", q->data);
1871 /* Check command status and return to normal libpq state */
1872 res = PQgetResult(conn);
1873 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1875 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1876 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1877 write_msg(NULL, "The command was: %s\n", q->data);
1882 /* Do this to ensure we've pumped libpq back to idle state */
1883 if (PQgetResult(conn) != NULL)
1884 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1887 destroyPQExpBuffer(q);
1892 * Dump table data using INSERT commands.
1894 * Caution: when we restore from an archive file direct to database, the
1895 * INSERT commands emitted by this function have to be parsed by
1896 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1897 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1900 dumpTableData_insert(Archive *fout, void *dcontext)
1902 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1903 TableInfo *tbinfo = tdinfo->tdtable;
1904 DumpOptions *dopt = fout->dopt;
1905 PQExpBuffer q = createPQExpBuffer();
1906 PQExpBuffer insertStmt = NULL;
1912 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1913 "SELECT * FROM ONLY %s",
1914 fmtQualifiedDumpable(tbinfo));
1915 if (tdinfo->filtercond)
1916 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1918 ExecuteSqlStatement(fout, q->data);
1922 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1924 nfields = PQnfields(res);
1925 for (tuple = 0; tuple < PQntuples(res); tuple++)
1928 * First time through, we build as much of the INSERT statement as
1929 * possible in "insertStmt", which we can then just print for each
1930 * line. If the table happens to have zero columns then this will
1931 * be a complete statement, otherwise it will end in "VALUES(" and
1932 * be ready to have the row's column values appended.
1934 if (insertStmt == NULL)
1936 TableInfo *targettab;
1938 insertStmt = createPQExpBuffer();
1941 * When load-via-partition-root is set, get the root table
1942 * name for the partition table, so that we can reload data
1943 * through the root table.
1945 if (dopt->load_via_partition_root && tbinfo->ispartition)
1946 targettab = getRootTableInfo(tbinfo);
1950 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1951 fmtQualifiedDumpable(targettab));
1953 /* corner case for zero-column table */
1956 appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1960 /* append the list of column names if required */
1961 if (dopt->column_inserts)
1963 appendPQExpBufferChar(insertStmt, '(');
1964 for (field = 0; field < nfields; field++)
1967 appendPQExpBufferStr(insertStmt, ", ");
1968 appendPQExpBufferStr(insertStmt,
1969 fmtId(PQfname(res, field)));
1971 appendPQExpBufferStr(insertStmt, ") ");
1974 if (tbinfo->needs_override)
1975 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1977 appendPQExpBufferStr(insertStmt, "VALUES (");
1981 archputs(insertStmt->data, fout);
1983 /* if it is zero-column table then we're done */
1987 for (field = 0; field < nfields; field++)
1990 archputs(", ", fout);
1991 if (PQgetisnull(res, tuple, field))
1993 archputs("NULL", fout);
1997 /* XXX This code is partially duplicated in ruleutils.c */
1998 switch (PQftype(res, field))
2009 * These types are printed without quotes unless
2010 * they contain values that aren't accepted by the
2011 * scanner unquoted (e.g., 'NaN'). Note that
2012 * strtod() and friends might accept NaN, so we
2013 * can't use that to test.
2015 * In reality we only need to defend against
2016 * infinity and NaN, so we need not get too crazy
2017 * about pattern matching here.
2019 const char *s = PQgetvalue(res, tuple, field);
2021 if (strspn(s, "0123456789 +-eE.") == strlen(s))
2024 archprintf(fout, "'%s'", s);
2030 archprintf(fout, "B'%s'",
2031 PQgetvalue(res, tuple, field));
2035 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2036 archputs("true", fout);
2038 archputs("false", fout);
2042 /* All other types are printed as string literals. */
2043 resetPQExpBuffer(q);
2044 appendStringLiteralAH(q,
2045 PQgetvalue(res, tuple, field),
2047 archputs(q->data, fout);
2051 archputs(");\n", fout);
2054 if (PQntuples(res) <= 0)
2062 archputs("\n\n", fout);
2064 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2066 destroyPQExpBuffer(q);
2067 if (insertStmt != NULL)
2068 destroyPQExpBuffer(insertStmt);
2075 * get the root TableInfo for the given partition table.
2078 getRootTableInfo(TableInfo *tbinfo)
2080 TableInfo *parentTbinfo;
2082 Assert(tbinfo->ispartition);
2083 Assert(tbinfo->numParents == 1);
2085 parentTbinfo = tbinfo->parents[0];
2086 while (parentTbinfo->ispartition)
2088 Assert(parentTbinfo->numParents == 1);
2089 parentTbinfo = parentTbinfo->parents[0];
2092 return parentTbinfo;
2097 * dump the contents of a single table
2099 * Actually, this just makes an ArchiveEntry for the table contents.
2102 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2104 DumpOptions *dopt = fout->dopt;
2105 TableInfo *tbinfo = tdinfo->tdtable;
2106 PQExpBuffer copyBuf = createPQExpBuffer();
2107 PQExpBuffer clistBuf = createPQExpBuffer();
2108 DataDumperPtr dumpFn;
2110 const char *copyFrom;
2112 if (!dopt->dump_inserts)
2114 /* Dump/restore using COPY */
2115 dumpFn = dumpTableData_copy;
2118 * When load-via-partition-root is set, get the root table name for
2119 * the partition table, so that we can reload data through the root
2122 if (dopt->load_via_partition_root && tbinfo->ispartition)
2124 TableInfo *parentTbinfo;
2126 parentTbinfo = getRootTableInfo(tbinfo);
2127 copyFrom = fmtQualifiedDumpable(parentTbinfo);
2130 copyFrom = fmtQualifiedDumpable(tbinfo);
2132 /* must use 2 steps here 'cause fmtId is nonreentrant */
2133 appendPQExpBuffer(copyBuf, "COPY %s ",
2135 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2136 fmtCopyColumnList(tbinfo, clistBuf),
2137 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2138 copyStmt = copyBuf->data;
2142 /* Restore using INSERT */
2143 dumpFn = dumpTableData_insert;
2148 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2149 * dependency on its table as "special" and pass it to ArchiveEntry now.
2150 * See comments for BuildArchiveDependencies.
2152 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2153 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2154 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2155 NULL, tbinfo->rolname,
2156 false, "TABLE DATA", SECTION_DATA,
2158 &(tbinfo->dobj.dumpId), 1,
2161 destroyPQExpBuffer(copyBuf);
2162 destroyPQExpBuffer(clistBuf);
2166 * refreshMatViewData -
2167 * load or refresh the contents of a single materialized view
2169 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2173 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2175 TableInfo *tbinfo = tdinfo->tdtable;
2178 /* If the materialized view is not flagged as populated, skip this. */
2179 if (!tbinfo->relispopulated)
2182 q = createPQExpBuffer();
2184 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2185 fmtQualifiedDumpable(tbinfo));
2187 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2189 tdinfo->dobj.catId, /* catalog ID */
2190 tdinfo->dobj.dumpId, /* dump ID */
2191 tbinfo->dobj.name, /* Name */
2192 tbinfo->dobj.namespace->dobj.name, /* Namespace */
2193 NULL, /* Tablespace */
2194 tbinfo->rolname, /* Owner */
2195 false, /* with oids */
2196 "MATERIALIZED VIEW DATA", /* Desc */
2197 SECTION_POST_DATA, /* Section */
2198 q->data, /* Create */
2201 tdinfo->dobj.dependencies, /* Deps */
2202 tdinfo->dobj.nDeps, /* # Deps */
2204 NULL); /* Dumper Arg */
2206 destroyPQExpBuffer(q);
2211 * set up dumpable objects representing the contents of tables
2214 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2218 for (i = 0; i < numTables; i++)
2220 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2221 (!relkind || tblinfo[i].relkind == relkind))
2222 makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2227 * Make a dumpable object for the data of this specific table
2229 * Note: we make a TableDataInfo if and only if we are going to dump the
2230 * table data; the "dump" flag in such objects isn't used.
2233 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2235 TableDataInfo *tdinfo;
2238 * Nothing to do if we already decided to dump the table. This will
2239 * happen for "config" tables.
2241 if (tbinfo->dataObj != NULL)
2244 /* Skip VIEWs (no data to dump) */
2245 if (tbinfo->relkind == RELKIND_VIEW)
2247 /* Skip FOREIGN TABLEs (no data to dump) */
2248 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2250 /* Skip partitioned tables (data in partitions) */
2251 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2254 /* Don't dump data in unlogged tables, if so requested */
2255 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2256 dopt->no_unlogged_table_data)
2259 /* Check that the data is not explicitly excluded */
2260 if (simple_oid_list_member(&tabledata_exclude_oids,
2261 tbinfo->dobj.catId.oid))
2264 /* OK, let's dump it */
2265 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2267 if (tbinfo->relkind == RELKIND_MATVIEW)
2268 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2269 else if (tbinfo->relkind == RELKIND_SEQUENCE)
2270 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2272 tdinfo->dobj.objType = DO_TABLE_DATA;
2275 * Note: use tableoid 0 so that this object won't be mistaken for
2276 * something that pg_depend entries apply to.
2278 tdinfo->dobj.catId.tableoid = 0;
2279 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2280 AssignDumpId(&tdinfo->dobj);
2281 tdinfo->dobj.name = tbinfo->dobj.name;
2282 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2283 tdinfo->tdtable = tbinfo;
2284 tdinfo->oids = oids;
2285 tdinfo->filtercond = NULL; /* might get set later */
2286 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2288 tbinfo->dataObj = tdinfo;
2292 * The refresh for a materialized view must be dependent on the refresh for
2293 * any materialized view that this one is dependent on.
2295 * This must be called after all the objects are created, but before they are
2299 buildMatViewRefreshDependencies(Archive *fout)
2309 /* No Mat Views before 9.3. */
2310 if (fout->remoteVersion < 90300)
2313 query = createPQExpBuffer();
2315 appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2317 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2318 "FROM pg_depend d1 "
2319 "JOIN pg_class c1 ON c1.oid = d1.objid "
2320 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2321 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2322 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2323 "AND d2.objid = r1.oid "
2324 "AND d2.refobjid <> d1.objid "
2325 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2326 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2327 CppAsString2(RELKIND_VIEW) ") "
2328 "WHERE d1.classid = 'pg_class'::regclass "
2330 "SELECT w.objid, d3.refobjid, c3.relkind "
2332 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2333 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2334 "AND d3.objid = r3.oid "
2335 "AND d3.refobjid <> w.refobjid "
2336 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2337 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2338 CppAsString2(RELKIND_VIEW) ") "
2340 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2342 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2344 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2346 ntups = PQntuples(res);
2348 i_classid = PQfnumber(res, "classid");
2349 i_objid = PQfnumber(res, "objid");
2350 i_refobjid = PQfnumber(res, "refobjid");
2352 for (i = 0; i < ntups; i++)
2356 DumpableObject *dobj;
2357 DumpableObject *refdobj;
2359 TableInfo *reftbinfo;
2361 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2362 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2363 refobjId.tableoid = objId.tableoid;
2364 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2366 dobj = findObjectByCatalogId(objId);
2370 Assert(dobj->objType == DO_TABLE);
2371 tbinfo = (TableInfo *) dobj;
2372 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2373 dobj = (DumpableObject *) tbinfo->dataObj;
2376 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2378 refdobj = findObjectByCatalogId(refobjId);
2379 if (refdobj == NULL)
2382 Assert(refdobj->objType == DO_TABLE);
2383 reftbinfo = (TableInfo *) refdobj;
2384 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2385 refdobj = (DumpableObject *) reftbinfo->dataObj;
2386 if (refdobj == NULL)
2388 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2390 addObjectDependency(dobj, refdobj->dumpId);
2392 if (!reftbinfo->relispopulated)
2393 tbinfo->relispopulated = false;
2398 destroyPQExpBuffer(query);
2402 * getTableDataFKConstraints -
2403 * add dump-order dependencies reflecting foreign key constraints
2405 * This code is executed only in a data-only dump --- in schema+data dumps
2406 * we handle foreign key issues by not creating the FK constraints until
2407 * after the data is loaded. In a data-only dump, however, we want to
2408 * order the table data objects in such a way that a table's referenced
2409 * tables are restored first. (In the presence of circular references or
2410 * self-references this may be impossible; we'll detect and complain about
2411 * that during the dependency sorting step.)
2414 getTableDataFKConstraints(void)
2416 DumpableObject **dobjs;
2420 /* Search through all the dumpable objects for FK constraints */
2421 getDumpableObjects(&dobjs, &numObjs);
2422 for (i = 0; i < numObjs; i++)
2424 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2426 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2429 /* Not interesting unless both tables are to be dumped */
2430 if (cinfo->contable == NULL ||
2431 cinfo->contable->dataObj == NULL)
2433 ftable = findTableByOid(cinfo->confrelid);
2434 if (ftable == NULL ||
2435 ftable->dataObj == NULL)
2439 * Okay, make referencing table's TABLE_DATA object depend on the
2440 * referenced table's TABLE_DATA object.
2442 addObjectDependency(&cinfo->contable->dataObj->dobj,
2443 ftable->dataObj->dobj.dumpId);
2451 * guessConstraintInheritance:
2452 * In pre-8.4 databases, we can't tell for certain which constraints
2453 * are inherited. We assume a CHECK constraint is inherited if its name
2454 * matches the name of any constraint in the parent. Originally this code
2455 * tried to compare the expression texts, but that can fail for various
2456 * reasons --- for example, if the parent and child tables are in different
2457 * schemas, reverse-listing of function calls may produce different text
2458 * (schema-qualified or not) depending on search path.
2460 * In 8.4 and up we can rely on the conislocal field to decide which
2461 * constraints must be dumped; much safer.
2463 * This function assumes all conislocal flags were initialized to true.
2464 * It clears the flag on anything that seems to be inherited.
2467 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2473 for (i = 0; i < numTables; i++)
2475 TableInfo *tbinfo = &(tblinfo[i]);
2477 TableInfo **parents;
2480 /* Sequences and views never have parents */
2481 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2482 tbinfo->relkind == RELKIND_VIEW)
2485 /* Don't bother computing anything for non-target tables, either */
2486 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2489 numParents = tbinfo->numParents;
2490 parents = tbinfo->parents;
2492 if (numParents == 0)
2493 continue; /* nothing to see here, move along */
2495 /* scan for inherited CHECK constraints */
2496 for (j = 0; j < tbinfo->ncheck; j++)
2498 ConstraintInfo *constr;
2500 constr = &(tbinfo->checkexprs[j]);
2502 for (k = 0; k < numParents; k++)
2506 parent = parents[k];
2507 for (l = 0; l < parent->ncheck; l++)
2509 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2511 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2513 constr->conislocal = false;
2517 if (!constr->conislocal)
2527 * dump the database definition
2530 dumpDatabase(Archive *fout)
2532 DumpOptions *dopt = fout->dopt;
2533 PQExpBuffer dbQry = createPQExpBuffer();
2534 PQExpBuffer delQry = createPQExpBuffer();
2535 PQExpBuffer creaQry = createPQExpBuffer();
2536 PQExpBuffer labelq = createPQExpBuffer();
2537 PGconn *conn = GetConnection(fout);
2554 const char *datname,
2568 datname = PQdb(conn);
2569 qdatname = pg_strdup(fmtId(datname));
2572 write_msg(NULL, "saving database definition\n");
2574 /* Fetch the database-level properties for this database */
2575 if (fout->remoteVersion >= 90600)
2577 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2578 "(%s datdba) AS dba, "
2579 "pg_encoding_to_char(encoding) AS encoding, "
2580 "datcollate, datctype, datfrozenxid, datminmxid, "
2581 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2582 " SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2583 " EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2585 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2586 " SELECT unnest(acldefault('d',datdba)) AS acl "
2587 " EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2589 "datistemplate, datconnlimit, "
2590 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2591 "shobj_description(oid, 'pg_database') AS description "
2596 appendStringLiteralAH(dbQry, datname, fout);
2598 else if (fout->remoteVersion >= 90300)
2600 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2601 "(%s datdba) AS dba, "
2602 "pg_encoding_to_char(encoding) AS encoding, "
2603 "datcollate, datctype, datfrozenxid, datminmxid, "
2604 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2605 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2606 "shobj_description(oid, 'pg_database') AS description "
2611 appendStringLiteralAH(dbQry, datname, fout);
2613 else if (fout->remoteVersion >= 80400)
2615 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2616 "(%s datdba) AS dba, "
2617 "pg_encoding_to_char(encoding) AS encoding, "
2618 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2619 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2620 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2621 "shobj_description(oid, 'pg_database') AS description "
2626 appendStringLiteralAH(dbQry, datname, fout);
2628 else if (fout->remoteVersion >= 80200)
2630 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2631 "(%s datdba) AS dba, "
2632 "pg_encoding_to_char(encoding) AS encoding, "
2633 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2634 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2635 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2636 "shobj_description(oid, 'pg_database') AS description "
2641 appendStringLiteralAH(dbQry, datname, fout);
2645 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2646 "(%s datdba) AS dba, "
2647 "pg_encoding_to_char(encoding) AS encoding, "
2648 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2649 "datacl, '' as rdatacl, datistemplate, "
2650 "-1 as datconnlimit, "
2651 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2655 appendStringLiteralAH(dbQry, datname, fout);
2658 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2660 i_tableoid = PQfnumber(res, "tableoid");
2661 i_oid = PQfnumber(res, "oid");
2662 i_dba = PQfnumber(res, "dba");
2663 i_encoding = PQfnumber(res, "encoding");
2664 i_collate = PQfnumber(res, "datcollate");
2665 i_ctype = PQfnumber(res, "datctype");
2666 i_frozenxid = PQfnumber(res, "datfrozenxid");
2667 i_minmxid = PQfnumber(res, "datminmxid");
2668 i_datacl = PQfnumber(res, "datacl");
2669 i_rdatacl = PQfnumber(res, "rdatacl");
2670 i_datistemplate = PQfnumber(res, "datistemplate");
2671 i_datconnlimit = PQfnumber(res, "datconnlimit");
2672 i_tablespace = PQfnumber(res, "tablespace");
2674 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2675 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2676 dba = PQgetvalue(res, 0, i_dba);
2677 encoding = PQgetvalue(res, 0, i_encoding);
2678 collate = PQgetvalue(res, 0, i_collate);
2679 ctype = PQgetvalue(res, 0, i_ctype);
2680 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2681 minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2682 datacl = PQgetvalue(res, 0, i_datacl);
2683 rdatacl = PQgetvalue(res, 0, i_rdatacl);
2684 datistemplate = PQgetvalue(res, 0, i_datistemplate);
2685 datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2686 tablespace = PQgetvalue(res, 0, i_tablespace);
2689 * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2690 * and tablespace since those can't be altered later. Other DB properties
2691 * are left to the DATABASE PROPERTIES entry, so that they can be applied
2692 * after reconnecting to the target DB.
2694 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2696 if (strlen(encoding) > 0)
2698 appendPQExpBufferStr(creaQry, " ENCODING = ");
2699 appendStringLiteralAH(creaQry, encoding, fout);
2701 if (strlen(collate) > 0)
2703 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2704 appendStringLiteralAH(creaQry, collate, fout);
2706 if (strlen(ctype) > 0)
2708 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2709 appendStringLiteralAH(creaQry, ctype, fout);
2713 * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2714 * thing; the decision whether to specify a tablespace should be left till
2715 * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2716 * label the DATABASE entry with the tablespace and let the normal
2717 * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2718 * attention to default_tablespace, so that won't work.
2720 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2721 !dopt->outputNoTablespaces)
2722 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2724 appendPQExpBufferStr(creaQry, ";\n");
2726 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2729 dbDumpId = createDumpId();
2732 dbCatId, /* catalog ID */
2733 dbDumpId, /* dump ID */
2735 NULL, /* Namespace */
2736 NULL, /* Tablespace */
2738 false, /* with oids */
2739 "DATABASE", /* Desc */
2740 SECTION_PRE_DATA, /* Section */
2741 creaQry->data, /* Create */
2742 delQry->data, /* Del */
2747 NULL); /* Dumper Arg */
2749 /* Compute correct tag for archive entry */
2750 appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2752 /* Dump DB comment if any */
2753 if (fout->remoteVersion >= 80200)
2756 * 8.2 and up keep comments on shared objects in a shared table, so we
2757 * cannot use the dumpComment() code used for other database objects.
2758 * Be careful that the ArchiveEntry parameters match that function.
2760 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2762 if (comment && *comment && !dopt->no_comments)
2764 resetPQExpBuffer(dbQry);
2767 * Generates warning when loaded into a differently-named
2770 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2771 appendStringLiteralAH(dbQry, comment, fout);
2772 appendPQExpBufferStr(dbQry, ";\n");
2774 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2775 labelq->data, NULL, NULL, dba,
2776 false, "COMMENT", SECTION_NONE,
2777 dbQry->data, "", NULL,
2784 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2785 dbCatId, 0, dbDumpId);
2788 /* Dump DB security label, if enabled */
2789 if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2792 PQExpBuffer seclabelQry;
2794 seclabelQry = createPQExpBuffer();
2796 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2797 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2798 resetPQExpBuffer(seclabelQry);
2799 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2800 if (seclabelQry->len > 0)
2801 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2802 labelq->data, NULL, NULL, dba,
2803 false, "SECURITY LABEL", SECTION_NONE,
2804 seclabelQry->data, "", NULL,
2807 destroyPQExpBuffer(seclabelQry);
2812 * Dump ACL if any. Note that we do not support initial privileges
2813 * (pg_init_privs) on databases.
2815 dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2816 qdatname, NULL, NULL,
2817 dba, datacl, rdatacl, "", "");
2820 * Now construct a DATABASE PROPERTIES archive entry to restore any
2821 * non-default database-level properties. (The reason this must be
2822 * separate is that we cannot put any additional commands into the TOC
2823 * entry that has CREATE DATABASE. pg_restore would execute such a group
2824 * in an implicit transaction block, and the backend won't allow CREATE
2825 * DATABASE in that context.)
2827 resetPQExpBuffer(creaQry);
2828 resetPQExpBuffer(delQry);
2830 if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2831 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2832 qdatname, datconnlimit);
2834 if (strcmp(datistemplate, "t") == 0)
2836 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2840 * The backend won't accept DROP DATABASE on a template database. We
2841 * can deal with that by removing the template marking before the DROP
2842 * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
2843 * since no such command is currently supported, fake it with a direct
2844 * UPDATE on pg_database.
2846 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2847 "SET datistemplate = false WHERE datname = ");
2848 appendStringLiteralAH(delQry, datname, fout);
2849 appendPQExpBufferStr(delQry, ";\n");
2852 /* Add database-specific SET options */
2853 dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2856 * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2857 * entry, too, for lack of a better place.
2859 if (dopt->binary_upgrade)
2861 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2862 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2863 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2865 frozenxid, minmxid);
2866 appendStringLiteralAH(creaQry, datname, fout);
2867 appendPQExpBufferStr(creaQry, ";\n");
2870 if (creaQry->len > 0)
2871 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2872 datname, NULL, NULL, dba,
2873 false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2874 creaQry->data, delQry->data, NULL,
2879 * pg_largeobject and pg_largeobject_metadata come from the old system
2880 * intact, so set their relfrozenxids and relminmxids.
2882 if (dopt->binary_upgrade)
2885 PQExpBuffer loFrozenQry = createPQExpBuffer();
2886 PQExpBuffer loOutQry = createPQExpBuffer();
2893 if (fout->remoteVersion >= 90300)
2894 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2895 "FROM pg_catalog.pg_class\n"
2896 "WHERE oid = %u;\n",
2897 LargeObjectRelationId);
2899 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2900 "FROM pg_catalog.pg_class\n"
2901 "WHERE oid = %u;\n",
2902 LargeObjectRelationId);
2904 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2906 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2907 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2909 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2910 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2911 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2912 "WHERE oid = %u;\n",
2913 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2914 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2915 LargeObjectRelationId);
2916 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2917 "pg_largeobject", NULL, NULL, "",
2918 false, "pg_largeobject", SECTION_PRE_DATA,
2919 loOutQry->data, "", NULL,
2926 * pg_largeobject_metadata
2928 if (fout->remoteVersion >= 90000)
2930 resetPQExpBuffer(loFrozenQry);
2931 resetPQExpBuffer(loOutQry);
2933 if (fout->remoteVersion >= 90300)
2934 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2935 "FROM pg_catalog.pg_class\n"
2936 "WHERE oid = %u;\n",
2937 LargeObjectMetadataRelationId);
2939 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2940 "FROM pg_catalog.pg_class\n"
2941 "WHERE oid = %u;\n",
2942 LargeObjectMetadataRelationId);
2944 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2946 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2947 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2949 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2950 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2951 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2952 "WHERE oid = %u;\n",
2953 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2954 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2955 LargeObjectMetadataRelationId);
2956 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2957 "pg_largeobject_metadata", NULL, NULL, "",
2958 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2959 loOutQry->data, "", NULL,
2966 destroyPQExpBuffer(loFrozenQry);
2967 destroyPQExpBuffer(loOutQry);
2973 destroyPQExpBuffer(dbQry);
2974 destroyPQExpBuffer(delQry);
2975 destroyPQExpBuffer(creaQry);
2976 destroyPQExpBuffer(labelq);
2980 * Collect any database-specific or role-and-database-specific SET options
2981 * for this database, and append them to outbuf.
2984 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
2985 const char *dbname, Oid dboid)
2987 PGconn *conn = GetConnection(AH);
2988 PQExpBuffer buf = createPQExpBuffer();
2993 * First collect database-specific options. Pre-8.4 server versions lack
2994 * unnest(), so we do this the hard way by querying once per subscript.
2998 if (AH->remoteVersion >= 90000)
2999 printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3000 "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3003 printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3005 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3007 if (PQntuples(res) == 1 &&
3008 !PQgetisnull(res, 0, 0))
3010 makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3011 "DATABASE", dbname, NULL, NULL,
3023 /* Now look for role-and-database-specific options */
3024 if (AH->remoteVersion >= 90000)
3026 /* Here we can assume we have unnest() */
3027 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3028 "FROM pg_db_role_setting s, pg_roles r "
3029 "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3032 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3034 if (PQntuples(res) > 0)
3038 for (i = 0; i < PQntuples(res); i++)
3039 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3040 "ROLE", PQgetvalue(res, i, 0),
3048 destroyPQExpBuffer(buf);
3052 * dumpEncoding: put the correct encoding into the archive
3055 dumpEncoding(Archive *AH)
3057 const char *encname = pg_encoding_to_char(AH->encoding);
3058 PQExpBuffer qry = createPQExpBuffer();
3061 write_msg(NULL, "saving encoding = %s\n", encname);
3063 appendPQExpBufferStr(qry, "SET client_encoding = ");
3064 appendStringLiteralAH(qry, encname, AH);
3065 appendPQExpBufferStr(qry, ";\n");
3067 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3068 "ENCODING", NULL, NULL, "",
3069 false, "ENCODING", SECTION_PRE_DATA,
3070 qry->data, "", NULL,
3074 destroyPQExpBuffer(qry);
3079 * dumpStdStrings: put the correct escape string behavior into the archive
3082 dumpStdStrings(Archive *AH)
3084 const char *stdstrings = AH->std_strings ? "on" : "off";
3085 PQExpBuffer qry = createPQExpBuffer();
3088 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3091 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3094 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3095 "STDSTRINGS", NULL, NULL, "",
3096 false, "STDSTRINGS", SECTION_PRE_DATA,
3097 qry->data, "", NULL,
3101 destroyPQExpBuffer(qry);
3105 * dumpSearchPath: record the active search_path in the archive
3108 dumpSearchPath(Archive *AH)
3110 PQExpBuffer qry = createPQExpBuffer();
3111 PQExpBuffer path = createPQExpBuffer();
3113 char **schemanames = NULL;
3114 int nschemanames = 0;
3118 * We use the result of current_schemas(), not the search_path GUC,
3119 * because that might contain wildcards such as "$user", which won't
3120 * necessarily have the same value during restore. Also, this way avoids
3121 * listing schemas that may appear in search_path but not actually exist,
3122 * which seems like a prudent exclusion.
3124 res = ExecuteSqlQueryForSingleRow(AH,
3125 "SELECT pg_catalog.current_schemas(false)");
3127 if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3128 exit_horribly(NULL, "could not parse result of current_schemas()\n");
3131 * We use set_config(), not a simple "SET search_path" command, because
3132 * the latter has less-clean behavior if the search path is empty. While
3133 * that's likely to get fixed at some point, it seems like a good idea to
3134 * be as backwards-compatible as possible in what we put into archives.
3136 for (i = 0; i < nschemanames; i++)
3139 appendPQExpBufferStr(path, ", ");
3140 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3143 appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3144 appendStringLiteralAH(qry, path->data, AH);
3145 appendPQExpBufferStr(qry, ", false);\n");
3148 write_msg(NULL, "saving search_path = %s\n", path->data);
3150 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3151 "SEARCHPATH", NULL, NULL, "",
3152 false, "SEARCHPATH", SECTION_PRE_DATA,
3153 qry->data, "", NULL,
3157 /* Also save it in AH->searchpath, in case we're doing plain text dump */
3158 AH->searchpath = pg_strdup(qry->data);
3163 destroyPQExpBuffer(qry);
3164 destroyPQExpBuffer(path);
3170 * Collect schema-level data about large objects
3173 getBlobs(Archive *fout)
3175 DumpOptions *dopt = fout->dopt;
3176 PQExpBuffer blobQry = createPQExpBuffer();
3178 DumpableObject *bdata;
3189 /* Verbose message */
3191 write_msg(NULL, "reading large objects\n");
3193 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3194 if (fout->remoteVersion >= 90600)
3196 PQExpBuffer acl_subquery = createPQExpBuffer();
3197 PQExpBuffer racl_subquery = createPQExpBuffer();
3198 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3199 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3201 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3202 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3203 dopt->binary_upgrade);
3205 appendPQExpBuffer(blobQry,
3206 "SELECT l.oid, (%s l.lomowner) AS rolname, "
3209 "%s AS initlomacl, "
3210 "%s AS initrlomacl "
3211 "FROM pg_largeobject_metadata l "
3212 "LEFT JOIN pg_init_privs pip ON "
3213 "(l.oid = pip.objoid "
3214 "AND pip.classoid = 'pg_largeobject'::regclass "
3215 "AND pip.objsubid = 0) ",
3218 racl_subquery->data,
3219 init_acl_subquery->data,
3220 init_racl_subquery->data);
3222 destroyPQExpBuffer(acl_subquery);
3223 destroyPQExpBuffer(racl_subquery);
3224 destroyPQExpBuffer(init_acl_subquery);
3225 destroyPQExpBuffer(init_racl_subquery);
3227 else if (fout->remoteVersion >= 90000)
3228 appendPQExpBuffer(blobQry,
3229 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3230 "NULL AS rlomacl, NULL AS initlomacl, "
3231 "NULL AS initrlomacl "
3232 " FROM pg_largeobject_metadata",
3235 appendPQExpBufferStr(blobQry,
3236 "SELECT DISTINCT loid AS oid, "
3237 "NULL::name AS rolname, NULL::oid AS lomacl, "
3238 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3239 "NULL::oid AS initrlomacl "
3240 " FROM pg_largeobject");
3242 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3244 i_oid = PQfnumber(res, "oid");
3245 i_lomowner = PQfnumber(res, "rolname");
3246 i_lomacl = PQfnumber(res, "lomacl");
3247 i_rlomacl = PQfnumber(res, "rlomacl");
3248 i_initlomacl = PQfnumber(res, "initlomacl");
3249 i_initrlomacl = PQfnumber(res, "initrlomacl");
3251 ntups = PQntuples(res);
3254 * Each large object has its own BLOB archive entry.
3256 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3258 for (i = 0; i < ntups; i++)
3260 binfo[i].dobj.objType = DO_BLOB;
3261 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3262 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3263 AssignDumpId(&binfo[i].dobj);
3265 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3266 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3267 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3268 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3269 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3270 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3272 if (PQgetisnull(res, i, i_lomacl) &&
3273 PQgetisnull(res, i, i_rlomacl) &&
3274 PQgetisnull(res, i, i_initlomacl) &&
3275 PQgetisnull(res, i, i_initrlomacl))
3276 binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3279 * In binary-upgrade mode for blobs, we do *not* dump out the data or
3280 * the ACLs, should any exist. The data and ACL (if any) will be
3281 * copied by pg_upgrade, which simply copies the pg_largeobject and
3282 * pg_largeobject_metadata tables.
3284 * We *do* dump out the definition of the blob because we need that to
3285 * make the restoration of the comments, and anything else, work since
3286 * pg_upgrade copies the files behind pg_largeobject and
3287 * pg_largeobject_metadata after the dump is restored.
3289 if (dopt->binary_upgrade)
3290 binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3294 * If we have any large objects, a "BLOBS" archive entry is needed. This
3295 * is just a placeholder for sorting; it carries no data now.
3299 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3300 bdata->objType = DO_BLOB_DATA;
3301 bdata->catId = nilCatalogId;
3302 AssignDumpId(bdata);
3303 bdata->name = pg_strdup("BLOBS");
3307 destroyPQExpBuffer(blobQry);
3313 * dump the definition (metadata) of the given large object
3316 dumpBlob(Archive *fout, BlobInfo *binfo)
3318 PQExpBuffer cquery = createPQExpBuffer();
3319 PQExpBuffer dquery = createPQExpBuffer();
3321 appendPQExpBuffer(cquery,
3322 "SELECT pg_catalog.lo_create('%s');\n",
3325 appendPQExpBuffer(dquery,
3326 "SELECT pg_catalog.lo_unlink('%s');\n",
3329 if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3330 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3333 binfo->rolname, false,
3334 "BLOB", SECTION_PRE_DATA,
3335 cquery->data, dquery->data, NULL,
3339 /* Dump comment if any */
3340 if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3341 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3342 NULL, binfo->rolname,
3343 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3345 /* Dump security label if any */
3346 if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3347 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3348 NULL, binfo->rolname,
3349 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3351 /* Dump ACL if any */
3352 if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3353 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3354 binfo->dobj.name, NULL,
3355 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3356 binfo->initblobacl, binfo->initrblobacl);
3358 destroyPQExpBuffer(cquery);
3359 destroyPQExpBuffer(dquery);
3364 * dump the data contents of all large objects
3367 dumpBlobs(Archive *fout, void *arg)
3369 const char *blobQry;
3370 const char *blobFetchQry;
3371 PGconn *conn = GetConnection(fout);
3373 char buf[LOBBUFSIZE];
3379 write_msg(NULL, "saving large objects\n");
3382 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3383 * the already-in-memory dumpable objects instead...
3385 if (fout->remoteVersion >= 90000)
3386 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3388 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3390 ExecuteSqlStatement(fout, blobQry);
3392 /* Command to fetch from cursor */
3393 blobFetchQry = "FETCH 1000 IN bloboid";
3398 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3400 /* Process the tuples, if any */
3401 ntups = PQntuples(res);
3402 for (i = 0; i < ntups; i++)
3407 blobOid = atooid(PQgetvalue(res, i, 0));
3409 loFd = lo_open(conn, blobOid, INV_READ);
3411 exit_horribly(NULL, "could not open large object %u: %s",
3412 blobOid, PQerrorMessage(conn));
3414 StartBlob(fout, blobOid);
3416 /* Now read it in chunks, sending data to archive */
3419 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3421 exit_horribly(NULL, "error reading large object %u: %s",
3422 blobOid, PQerrorMessage(conn));
3424 WriteData(fout, buf, cnt);
3427 lo_close(conn, loFd);
3429 EndBlob(fout, blobOid);
3433 } while (ntups > 0);
3440 * get information about policies on a dumpable table.
3443 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3447 PolicyInfo *polinfo;
3452 int i_polpermissive;
3460 if (fout->remoteVersion < 90500)
3463 query = createPQExpBuffer();
3465 for (i = 0; i < numTables; i++)
3467 TableInfo *tbinfo = &tblinfo[i];
3469 /* Ignore row security on tables not to be dumped */
3470 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3474 write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3475 tbinfo->dobj.namespace->dobj.name,
3479 * Get row security enabled information for the table. We represent
3480 * RLS enabled on a table by creating PolicyInfo object with an empty
3486 * Note: use tableoid 0 so that this object won't be mistaken for
3487 * something that pg_depend entries apply to.
3489 polinfo = pg_malloc(sizeof(PolicyInfo));
3490 polinfo->dobj.objType = DO_POLICY;
3491 polinfo->dobj.catId.tableoid = 0;
3492 polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3493 AssignDumpId(&polinfo->dobj);
3494 polinfo->dobj.namespace = tbinfo->dobj.namespace;
3495 polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3496 polinfo->poltable = tbinfo;
3497 polinfo->polname = NULL;
3498 polinfo->polcmd = '\0';
3499 polinfo->polpermissive = 0;
3500 polinfo->polroles = NULL;
3501 polinfo->polqual = NULL;
3502 polinfo->polwithcheck = NULL;
3506 write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3507 tbinfo->dobj.namespace->dobj.name,
3510 resetPQExpBuffer(query);
3512 /* Get the policies for the table. */
3513 if (fout->remoteVersion >= 100000)
3514 appendPQExpBuffer(query,
3515 "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3516 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3517 " 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, "
3518 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3519 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3520 "FROM pg_catalog.pg_policy pol "
3521 "WHERE polrelid = '%u'",
3522 tbinfo->dobj.catId.oid);
3524 appendPQExpBuffer(query,
3525 "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3526 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3527 " 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, "
3528 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3529 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3530 "FROM pg_catalog.pg_policy pol "
3531 "WHERE polrelid = '%u'",
3532 tbinfo->dobj.catId.oid);
3533 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3535 ntups = PQntuples(res);
3540 * No explicit policies to handle (only the default-deny policy,
3541 * which is handled as part of the table definition). Clean up
3548 i_oid = PQfnumber(res, "oid");
3549 i_tableoid = PQfnumber(res, "tableoid");
3550 i_polname = PQfnumber(res, "polname");
3551 i_polcmd = PQfnumber(res, "polcmd");
3552 i_polpermissive = PQfnumber(res, "polpermissive");
3553 i_polroles = PQfnumber(res, "polroles");
3554 i_polqual = PQfnumber(res, "polqual");
3555 i_polwithcheck = PQfnumber(res, "polwithcheck");
3557 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3559 for (j = 0; j < ntups; j++)
3561 polinfo[j].dobj.objType = DO_POLICY;
3562 polinfo[j].dobj.catId.tableoid =
3563 atooid(PQgetvalue(res, j, i_tableoid));
3564 polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3565 AssignDumpId(&polinfo[j].dobj);
3566 polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3567 polinfo[j].poltable = tbinfo;
3568 polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3569 polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3571 polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3572 polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3574 if (PQgetisnull(res, j, i_polroles))
3575 polinfo[j].polroles = NULL;
3577 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3579 if (PQgetisnull(res, j, i_polqual))
3580 polinfo[j].polqual = NULL;
3582 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3584 if (PQgetisnull(res, j, i_polwithcheck))
3585 polinfo[j].polwithcheck = NULL;
3587 polinfo[j].polwithcheck
3588 = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3592 destroyPQExpBuffer(query);
3597 * dump the definition of the given policy
3600 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3602 DumpOptions *dopt = fout->dopt;
3603 TableInfo *tbinfo = polinfo->poltable;
3613 * If polname is NULL, then this record is just indicating that ROW LEVEL
3614 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3615 * ROW LEVEL SECURITY.
3617 if (polinfo->polname == NULL)
3619 query = createPQExpBuffer();
3621 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3622 fmtQualifiedDumpable(polinfo));
3624 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3625 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3627 polinfo->dobj.namespace->dobj.name,
3629 tbinfo->rolname, false,
3630 "ROW SECURITY", SECTION_POST_DATA,
3631 query->data, "", NULL,
3635 destroyPQExpBuffer(query);
3639 if (polinfo->polcmd == '*')
3641 else if (polinfo->polcmd == 'r')
3642 cmd = " FOR SELECT";
3643 else if (polinfo->polcmd == 'a')
3644 cmd = " FOR INSERT";
3645 else if (polinfo->polcmd == 'w')
3646 cmd = " FOR UPDATE";
3647 else if (polinfo->polcmd == 'd')
3648 cmd = " FOR DELETE";
3651 write_msg(NULL, "unexpected policy command type: %c\n",
3656 query = createPQExpBuffer();
3657 delqry = createPQExpBuffer();
3659 appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3661 appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3662 !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3664 if (polinfo->polroles != NULL)
3665 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3667 if (polinfo->polqual != NULL)
3668 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3670 if (polinfo->polwithcheck != NULL)
3671 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3673 appendPQExpBuffer(query, ";\n");
3675 appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3676 appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3678 tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3680 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3681 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3683 polinfo->dobj.namespace->dobj.name,
3685 tbinfo->rolname, false,
3686 "POLICY", SECTION_POST_DATA,
3687 query->data, delqry->data, NULL,
3692 destroyPQExpBuffer(query);
3693 destroyPQExpBuffer(delqry);
3698 * get information about publications
3701 getPublications(Archive *fout)
3703 DumpOptions *dopt = fout->dopt;
3706 PublicationInfo *pubinfo;
3718 if (dopt->no_publications || fout->remoteVersion < 100000)
3721 query = createPQExpBuffer();
3723 resetPQExpBuffer(query);
3725 /* Get the publications. */
3726 appendPQExpBuffer(query,
3727 "SELECT p.tableoid, p.oid, p.pubname, "
3728 "(%s p.pubowner) AS rolname, "
3729 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete "
3730 "FROM pg_publication p",
3733 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3735 ntups = PQntuples(res);
3737 i_tableoid = PQfnumber(res, "tableoid");
3738 i_oid = PQfnumber(res, "oid");
3739 i_pubname = PQfnumber(res, "pubname");
3740 i_rolname = PQfnumber(res, "rolname");
3741 i_puballtables = PQfnumber(res, "puballtables");
3742 i_pubinsert = PQfnumber(res, "pubinsert");
3743 i_pubupdate = PQfnumber(res, "pubupdate");
3744 i_pubdelete = PQfnumber(res, "pubdelete");
3746 pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3748 for (i = 0; i < ntups; i++)
3750 pubinfo[i].dobj.objType = DO_PUBLICATION;
3751 pubinfo[i].dobj.catId.tableoid =
3752 atooid(PQgetvalue(res, i, i_tableoid));
3753 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3754 AssignDumpId(&pubinfo[i].dobj);
3755 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3756 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3757 pubinfo[i].puballtables =
3758 (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3759 pubinfo[i].pubinsert =
3760 (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3761 pubinfo[i].pubupdate =
3762 (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3763 pubinfo[i].pubdelete =
3764 (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3766 if (strlen(pubinfo[i].rolname) == 0)
3767 write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3768 pubinfo[i].dobj.name);
3770 /* Decide whether we want to dump it */
3771 selectDumpableObject(&(pubinfo[i].dobj), fout);
3775 destroyPQExpBuffer(query);
3780 * dump the definition of the given publication
3783 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3790 if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3793 delq = createPQExpBuffer();
3794 query = createPQExpBuffer();
3796 qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3798 appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3801 appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3804 if (pubinfo->puballtables)
3805 appendPQExpBufferStr(query, " FOR ALL TABLES");
3807 appendPQExpBufferStr(query, " WITH (publish = '");
3808 if (pubinfo->pubinsert)
3810 appendPQExpBufferStr(query, "insert");
3814 if (pubinfo->pubupdate)
3817 appendPQExpBufferStr(query, ", ");
3819 appendPQExpBufferStr(query, "update");
3823 if (pubinfo->pubdelete)
3826 appendPQExpBufferStr(query, ", ");
3828 appendPQExpBufferStr(query, "delete");
3832 appendPQExpBufferStr(query, "');\n");
3834 ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3838 pubinfo->rolname, false,
3839 "PUBLICATION", SECTION_POST_DATA,
3840 query->data, delq->data, NULL,
3844 if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3845 dumpComment(fout, "PUBLICATION", qpubname,
3846 NULL, pubinfo->rolname,
3847 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3849 if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3850 dumpSecLabel(fout, "PUBLICATION", qpubname,
3851 NULL, pubinfo->rolname,
3852 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3854 destroyPQExpBuffer(delq);
3855 destroyPQExpBuffer(query);
3860 * getPublicationTables
3861 * get information about publication membership for dumpable tables.
3864 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3868 PublicationRelInfo *pubrinfo;
3876 if (fout->remoteVersion < 100000)
3879 query = createPQExpBuffer();
3881 for (i = 0; i < numTables; i++)
3883 TableInfo *tbinfo = &tblinfo[i];
3885 /* Only plain tables can be aded to publications. */
3886 if (tbinfo->relkind != RELKIND_RELATION)
3890 * Ignore publication membership of tables whose definitions are not
3893 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3897 write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3898 tbinfo->dobj.namespace->dobj.name,
3901 resetPQExpBuffer(query);
3903 /* Get the publication membership for the table. */
3904 appendPQExpBuffer(query,
3905 "SELECT pr.tableoid, pr.oid, p.pubname "
3906 "FROM pg_publication_rel pr, pg_publication p "
3907 "WHERE pr.prrelid = '%u'"
3908 " AND p.oid = pr.prpubid",
3909 tbinfo->dobj.catId.oid);
3910 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3912 ntups = PQntuples(res);
3917 * Table is not member of any publications. Clean up and return.
3923 i_tableoid = PQfnumber(res, "tableoid");
3924 i_oid = PQfnumber(res, "oid");
3925 i_pubname = PQfnumber(res, "pubname");
3927 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3929 for (j = 0; j < ntups; j++)
3931 pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3932 pubrinfo[j].dobj.catId.tableoid =
3933 atooid(PQgetvalue(res, j, i_tableoid));
3934 pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3935 AssignDumpId(&pubrinfo[j].dobj);
3936 pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3937 pubrinfo[j].dobj.name = tbinfo->dobj.name;
3938 pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3939 pubrinfo[j].pubtable = tbinfo;
3941 /* Decide whether we want to dump it */
3942 selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3946 destroyPQExpBuffer(query);
3950 * dumpPublicationTable
3951 * dump the definition of the given publication table mapping
3954 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3956 TableInfo *tbinfo = pubrinfo->pubtable;
3960 if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3963 tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3965 query = createPQExpBuffer();
3967 appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3968 fmtId(pubrinfo->pubname));
3969 appendPQExpBuffer(query, " %s;\n",
3970 fmtQualifiedDumpable(tbinfo));
3973 * There is no point in creating drop query as drop query as the drop is
3974 * done by table drop.
3976 ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3978 tbinfo->dobj.namespace->dobj.name,
3981 "PUBLICATION TABLE", SECTION_POST_DATA,
3982 query->data, "", NULL,
3987 destroyPQExpBuffer(query);
3991 * Is the currently connected user a superuser?
3994 is_superuser(Archive *fout)
3996 ArchiveHandle *AH = (ArchiveHandle *) fout;
3999 val = PQparameterStatus(AH->connection, "is_superuser");
4001 if (val && strcmp(val, "on") == 0)
4009 * get information about subscriptions
4012 getSubscriptions(Archive *fout)
4014 DumpOptions *dopt = fout->dopt;
4017 SubscriptionInfo *subinfo;
4024 int i_subsynccommit;
4025 int i_subpublications;
4029 if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4032 if (!is_superuser(fout))
4036 res = ExecuteSqlQuery(fout,
4037 "SELECT count(*) FROM pg_subscription "
4038 "WHERE subdbid = (SELECT oid FROM pg_database"
4039 " WHERE datname = current_database())",
4041 n = atoi(PQgetvalue(res, 0, 0));
4043 write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4048 query = createPQExpBuffer();
4050 resetPQExpBuffer(query);
4052 /* Get the subscriptions in current database. */
4053 appendPQExpBuffer(query,
4054 "SELECT s.tableoid, s.oid, s.subname,"
4055 "(%s s.subowner) AS rolname, "
4056 " s.subconninfo, s.subslotname, s.subsynccommit, "
4057 " s.subpublications "
4058 "FROM pg_subscription s "
4059 "WHERE s.subdbid = (SELECT oid FROM pg_database"
4060 " WHERE datname = current_database())",
4062 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4064 ntups = PQntuples(res);
4066 i_tableoid = PQfnumber(res, "tableoid");
4067 i_oid = PQfnumber(res, "oid");
4068 i_subname = PQfnumber(res, "subname");
4069 i_rolname = PQfnumber(res, "rolname");
4070 i_subconninfo = PQfnumber(res, "subconninfo");
4071 i_subslotname = PQfnumber(res, "subslotname");
4072 i_subsynccommit = PQfnumber(res, "subsynccommit");
4073 i_subpublications = PQfnumber(res, "subpublications");
4075 subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4077 for (i = 0; i < ntups; i++)
4079 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4080 subinfo[i].dobj.catId.tableoid =
4081 atooid(PQgetvalue(res, i, i_tableoid));
4082 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4083 AssignDumpId(&subinfo[i].dobj);
4084 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4085 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4086 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4087 if (PQgetisnull(res, i, i_subslotname))
4088 subinfo[i].subslotname = NULL;
4090 subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4091 subinfo[i].subsynccommit =
4092 pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4093 subinfo[i].subpublications =
4094 pg_strdup(PQgetvalue(res, i, i_subpublications));
4096 if (strlen(subinfo[i].rolname) == 0)
4097 write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4098 subinfo[i].dobj.name);
4100 /* Decide whether we want to dump it */
4101 selectDumpableObject(&(subinfo[i].dobj), fout);
4105 destroyPQExpBuffer(query);
4110 * dump the definition of the given subscription
4113 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4117 PQExpBuffer publications;
4119 char **pubnames = NULL;
4123 if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4126 delq = createPQExpBuffer();
4127 query = createPQExpBuffer();
4129 qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4131 appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4134 appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4136 appendStringLiteralAH(query, subinfo->subconninfo, fout);
4138 /* Build list of quoted publications and append them to query. */
4139 if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4142 "WARNING: could not parse subpublications array\n");
4149 publications = createPQExpBuffer();
4150 for (i = 0; i < npubnames; i++)
4153 appendPQExpBufferStr(publications, ", ");
4155 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4158 appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4159 if (subinfo->subslotname)
4160 appendStringLiteralAH(query, subinfo->subslotname, fout);
4162 appendPQExpBufferStr(query, "NONE");
4164 if (strcmp(subinfo->subsynccommit, "off") != 0)
4165 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4167 appendPQExpBufferStr(query, ");\n");
4169 ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4173 subinfo->rolname, false,
4174 "SUBSCRIPTION", SECTION_POST_DATA,
4175 query->data, delq->data, NULL,
4179 if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4180 dumpComment(fout, "SUBSCRIPTION", qsubname,
4181 NULL, subinfo->rolname,
4182 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4184 if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4185 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4186 NULL, subinfo->rolname,
4187 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4189 destroyPQExpBuffer(publications);
4193 destroyPQExpBuffer(delq);
4194 destroyPQExpBuffer(query);
4199 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4200 PQExpBuffer upgrade_buffer,
4202 bool force_array_type)
4204 PQExpBuffer upgrade_query = createPQExpBuffer();
4206 Oid pg_type_array_oid;
4208 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4209 appendPQExpBuffer(upgrade_buffer,
4210 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4213 /* we only support old >= 8.3 for binary upgrades */
4214 appendPQExpBuffer(upgrade_query,
4216 "FROM pg_catalog.pg_type "
4217 "WHERE oid = '%u'::pg_catalog.oid;",
4220 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4222 pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4226 if (!OidIsValid(pg_type_array_oid) && force_array_type)
4229 * If the old version didn't assign an array type, but the new version
4230 * does, we must select an unused type OID to assign. This currently
4231 * only happens for domains, when upgrading pre-v11 to v11 and up.
4233 * Note: local state here is kind of ugly, but we must have some,
4234 * since we mustn't choose the same unused OID more than once.
4236 static Oid next_possible_free_oid = FirstNormalObjectId;
4241 ++next_possible_free_oid;
4242 printfPQExpBuffer(upgrade_query,
4243 "SELECT EXISTS(SELECT 1 "
4244 "FROM pg_catalog.pg_type "
4245 "WHERE oid = '%u'::pg_catalog.oid);",
4246 next_possible_free_oid);
4247 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4248 is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4252 pg_type_array_oid = next_possible_free_oid;
4255 if (OidIsValid(pg_type_array_oid))
4257 appendPQExpBufferStr(upgrade_buffer,
4258 "\n-- For binary upgrade, must preserve pg_type array oid\n");
4259 appendPQExpBuffer(upgrade_buffer,
4260 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4264 destroyPQExpBuffer(upgrade_query);
4268 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4269 PQExpBuffer upgrade_buffer,
4272 PQExpBuffer upgrade_query = createPQExpBuffer();
4273 PGresult *upgrade_res;
4275 bool toast_set = false;
4277 /* we only support old >= 8.3 for binary upgrades */
4278 appendPQExpBuffer(upgrade_query,
4279 "SELECT c.reltype AS crel, t.reltype AS trel "
4280 "FROM pg_catalog.pg_class c "
4281 "LEFT JOIN pg_catalog.pg_class t ON "
4282 " (c.reltoastrelid = t.oid) "
4283 "WHERE c.oid = '%u'::pg_catalog.oid;",
4286 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4288 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4290 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4291 pg_type_oid, false);
4293 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4295 /* Toast tables do not have pg_type array rows */
4296 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4297 PQfnumber(upgrade_res, "trel")));
4299 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4300 appendPQExpBuffer(upgrade_buffer,
4301 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4307 PQclear(upgrade_res);
4308 destroyPQExpBuffer(upgrade_query);
4314 binary_upgrade_set_pg_class_oids(Archive *fout,
4315 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4318 PQExpBuffer upgrade_query = createPQExpBuffer();
4319 PGresult *upgrade_res;
4320 Oid pg_class_reltoastrelid;
4321 Oid pg_index_indexrelid;
4323 appendPQExpBuffer(upgrade_query,
4324 "SELECT c.reltoastrelid, i.indexrelid "
4325 "FROM pg_catalog.pg_class c LEFT JOIN "
4326 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4327 "WHERE c.oid = '%u'::pg_catalog.oid;",
4330 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4332 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4333 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4335 appendPQExpBufferStr(upgrade_buffer,
4336 "\n-- For binary upgrade, must preserve pg_class oids\n");
4340 appendPQExpBuffer(upgrade_buffer,
4341 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4343 /* only tables have toast tables, not indexes */
4344 if (OidIsValid(pg_class_reltoastrelid))
4347 * One complexity is that the table definition might not require
4348 * the creation of a TOAST table, and the TOAST table might have
4349 * been created long after table creation, when the table was
4350 * loaded with wide data. By setting the TOAST oid we force
4351 * creation of the TOAST heap and TOAST index by the backend so we
4352 * can cleanly copy the files during binary upgrade.
4355 appendPQExpBuffer(upgrade_buffer,
4356 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4357 pg_class_reltoastrelid);
4359 /* every toast table has an index */
4360 appendPQExpBuffer(upgrade_buffer,
4361 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4362 pg_index_indexrelid);
4366 appendPQExpBuffer(upgrade_buffer,
4367 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4370 appendPQExpBufferChar(upgrade_buffer, '\n');
4372 PQclear(upgrade_res);
4373 destroyPQExpBuffer(upgrade_query);
4377 * If the DumpableObject is a member of an extension, add a suitable
4378 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4380 * For somewhat historical reasons, objname should already be quoted,
4381 * but not objnamespace (if any).
4384 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4385 DumpableObject *dobj,
4386 const char *objtype,
4387 const char *objname,
4388 const char *objnamespace)
4390 DumpableObject *extobj = NULL;
4393 if (!dobj->ext_member)
4397 * Find the parent extension. We could avoid this search if we wanted to
4398 * add a link field to DumpableObject, but the space costs of that would
4399 * be considerable. We assume that member objects could only have a
4400 * direct dependency on their own extension, not any others.
4402 for (i = 0; i < dobj->nDeps; i++)
4404 extobj = findObjectByDumpId(dobj->dependencies[i]);
4405 if (extobj && extobj->objType == DO_EXTENSION)
4410 exit_horribly(NULL, "could not find parent extension for %s %s\n",
4413 appendPQExpBufferStr(upgrade_buffer,
4414 "\n-- For binary upgrade, handle extension membership the hard way\n");
4415 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4416 fmtId(extobj->name),
4418 if (objnamespace && *objnamespace)
4419 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4420 appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4425 * read all namespaces in the system catalogs and return them in the
4426 * NamespaceInfo* structure
4428 * numNamespaces is set to the number of namespaces read in
4431 getNamespaces(Archive *fout, int *numNamespaces)
4433 DumpOptions *dopt = fout->dopt;
4438 NamespaceInfo *nsinfo;
4448 query = createPQExpBuffer();
4451 * we fetch all namespaces including system ones, so that every object we
4452 * read in can be linked to a containing namespace.
4454 if (fout->remoteVersion >= 90600)
4456 PQExpBuffer acl_subquery = createPQExpBuffer();
4457 PQExpBuffer racl_subquery = createPQExpBuffer();
4458 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4459 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4461 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4462 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4463 dopt->binary_upgrade);
4465 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4466 "(%s nspowner) AS rolname, "
4469 "%s as initnspacl, "
4470 "%s as initrnspacl "
4471 "FROM pg_namespace n "
4472 "LEFT JOIN pg_init_privs pip "
4473 "ON (n.oid = pip.objoid "
4474 "AND pip.classoid = 'pg_namespace'::regclass "
4475 "AND pip.objsubid = 0",
4478 racl_subquery->data,
4479 init_acl_subquery->data,
4480 init_racl_subquery->data);
4482 appendPQExpBuffer(query, ") ");
4484 destroyPQExpBuffer(acl_subquery);
4485 destroyPQExpBuffer(racl_subquery);
4486 destroyPQExpBuffer(init_acl_subquery);
4487 destroyPQExpBuffer(init_racl_subquery);
4490 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4491 "(%s nspowner) AS rolname, "
4492 "nspacl, NULL as rnspacl, "
4493 "NULL AS initnspacl, NULL as initrnspacl "
4494 "FROM pg_namespace",
4497 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4499 ntups = PQntuples(res);
4501 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4503 i_tableoid = PQfnumber(res, "tableoid");
4504 i_oid = PQfnumber(res, "oid");
4505 i_nspname = PQfnumber(res, "nspname");
4506 i_rolname = PQfnumber(res, "rolname");
4507 i_nspacl = PQfnumber(res, "nspacl");
4508 i_rnspacl = PQfnumber(res, "rnspacl");
4509 i_initnspacl = PQfnumber(res, "initnspacl");
4510 i_initrnspacl = PQfnumber(res, "initrnspacl");
4512 for (i = 0; i < ntups; i++)
4514 nsinfo[i].dobj.objType = DO_NAMESPACE;
4515 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4516 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4517 AssignDumpId(&nsinfo[i].dobj);
4518 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4519 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4520 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4521 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4522 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4523 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4525 /* Decide whether to dump this namespace */
4526 selectDumpableNamespace(&nsinfo[i], fout);
4529 * Do not try to dump ACL if the ACL is empty or the default.
4531 * This is useful because, for some schemas/objects, the only
4532 * component we are going to try and dump is the ACL and if we can
4533 * remove that then 'dump' goes to zero/false and we don't consider
4534 * this object for dumping at all later on.
4536 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4537 PQgetisnull(res, i, i_initnspacl) &&
4538 PQgetisnull(res, i, i_initrnspacl))
4539 nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4541 if (strlen(nsinfo[i].rolname) == 0)
4542 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4543 nsinfo[i].dobj.name);
4547 destroyPQExpBuffer(query);
4549 *numNamespaces = ntups;
4556 * given a namespace OID, look up the info read by getNamespaces
4558 static NamespaceInfo *
4559 findNamespace(Archive *fout, Oid nsoid)
4561 NamespaceInfo *nsinfo;
4563 nsinfo = findNamespaceByOid(nsoid);
4565 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4571 * read all extensions in the system catalogs and return them in the
4572 * ExtensionInfo* structure
4574 * numExtensions is set to the number of extensions read in
4577 getExtensions(Archive *fout, int *numExtensions)
4579 DumpOptions *dopt = fout->dopt;
4584 ExtensionInfo *extinfo;
4589 int i_extrelocatable;
4595 * Before 9.1, there are no extensions.
4597 if (fout->remoteVersion < 90100)
4603 query = createPQExpBuffer();
4605 appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4606 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4607 "FROM pg_extension x "
4608 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4610 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4612 ntups = PQntuples(res);
4614 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4616 i_tableoid = PQfnumber(res, "tableoid");
4617 i_oid = PQfnumber(res, "oid");
4618 i_extname = PQfnumber(res, "extname");
4619 i_nspname = PQfnumber(res, "nspname");
4620 i_extrelocatable = PQfnumber(res, "extrelocatable");
4621 i_extversion = PQfnumber(res, "extversion");
4622 i_extconfig = PQfnumber(res, "extconfig");
4623 i_extcondition = PQfnumber(res, "extcondition");
4625 for (i = 0; i < ntups; i++)
4627 extinfo[i].dobj.objType = DO_EXTENSION;
4628 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4629 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4630 AssignDumpId(&extinfo[i].dobj);
4631 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4632 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4633 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4634 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4635 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4636 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4638 /* Decide whether we want to dump it */
4639 selectDumpableExtension(&(extinfo[i]), dopt);
4643 destroyPQExpBuffer(query);
4645 *numExtensions = ntups;
4652 * read all types in the system catalogs and return them in the
4653 * TypeInfo* structure
4655 * numTypes is set to the number of types read in
4657 * NB: this must run after getFuncs() because we assume we can do
4661 getTypes(Archive *fout, int *numTypes)
4663 DumpOptions *dopt = fout->dopt;
4667 PQExpBuffer query = createPQExpBuffer();
4669 ShellTypeInfo *stinfo;
4687 * we include even the built-in types because those may be used as array
4688 * elements by user-defined types
4690 * we filter out the built-in types when we dump out the types
4692 * same approach for undefined (shell) types and array types
4694 * Note: as of 8.3 we can reliably detect whether a type is an
4695 * auto-generated array type by checking the element type's typarray.
4696 * (Before that the test is capable of generating false positives.) We
4697 * still check for name beginning with '_', though, so as to avoid the
4698 * cost of the subselect probe for all standard types. This would have to
4699 * be revisited if the backend ever allows renaming of array types.
4702 if (fout->remoteVersion >= 90600)
4704 PQExpBuffer acl_subquery = createPQExpBuffer();
4705 PQExpBuffer racl_subquery = createPQExpBuffer();
4706 PQExpBuffer initacl_subquery = createPQExpBuffer();
4707 PQExpBuffer initracl_subquery = createPQExpBuffer();
4709 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4710 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4711 dopt->binary_upgrade);
4713 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4717 "%s AS inittypacl, "
4718 "%s AS initrtypacl, "
4719 "(%s t.typowner) AS rolname, "
4720 "t.typelem, t.typrelid, "
4721 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4722 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4723 "t.typtype, t.typisdefined, "
4724 "t.typname[0] = '_' AND t.typelem != 0 AND "
4725 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4727 "LEFT JOIN pg_init_privs pip ON "
4728 "(t.oid = pip.objoid "
4729 "AND pip.classoid = 'pg_type'::regclass "
4730 "AND pip.objsubid = 0) ",
4732 racl_subquery->data,
4733 initacl_subquery->data,
4734 initracl_subquery->data,
4737 destroyPQExpBuffer(acl_subquery);
4738 destroyPQExpBuffer(racl_subquery);
4739 destroyPQExpBuffer(initacl_subquery);
4740 destroyPQExpBuffer(initracl_subquery);
4742 else if (fout->remoteVersion >= 90200)
4744 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4745 "typnamespace, typacl, NULL as rtypacl, "
4746 "NULL AS inittypacl, NULL AS initrtypacl, "
4747 "(%s typowner) AS rolname, "
4748 "typelem, typrelid, "
4749 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4750 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4751 "typtype, typisdefined, "
4752 "typname[0] = '_' AND typelem != 0 AND "
4753 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4757 else if (fout->remoteVersion >= 80300)
4759 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4760 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4761 "NULL AS inittypacl, NULL AS initrtypacl, "
4762 "(%s typowner) AS rolname, "
4763 "typelem, typrelid, "
4764 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4765 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4766 "typtype, typisdefined, "
4767 "typname[0] = '_' AND typelem != 0 AND "
4768 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4774 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4775 "typnamespace, NULL AS typacl, NULL as rtypacl, "
4776 "NULL AS inittypacl, NULL AS initrtypacl, "
4777 "(%s typowner) AS rolname, "
4778 "typelem, typrelid, "
4779 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4780 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4781 "typtype, typisdefined, "
4782 "typname[0] = '_' AND typelem != 0 AS isarray "
4787 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4789 ntups = PQntuples(res);
4791 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4793 i_tableoid = PQfnumber(res, "tableoid");
4794 i_oid = PQfnumber(res, "oid");
4795 i_typname = PQfnumber(res, "typname");
4796 i_typnamespace = PQfnumber(res, "typnamespace");
4797 i_typacl = PQfnumber(res, "typacl");
4798 i_rtypacl = PQfnumber(res, "rtypacl");
4799 i_inittypacl = PQfnumber(res, "inittypacl");
4800 i_initrtypacl = PQfnumber(res, "initrtypacl");
4801 i_rolname = PQfnumber(res, "rolname");
4802 i_typelem = PQfnumber(res, "typelem");
4803 i_typrelid = PQfnumber(res, "typrelid");
4804 i_typrelkind = PQfnumber(res, "typrelkind");
4805 i_typtype = PQfnumber(res, "typtype");
4806 i_typisdefined = PQfnumber(res, "typisdefined");
4807 i_isarray = PQfnumber(res, "isarray");
4809 for (i = 0; i < ntups; i++)
4811 tyinfo[i].dobj.objType = DO_TYPE;
4812 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4813 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4814 AssignDumpId(&tyinfo[i].dobj);
4815 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4816 tyinfo[i].dobj.namespace =
4818 atooid(PQgetvalue(res, i, i_typnamespace)));
4819 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4820 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4821 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4822 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4823 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4824 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4825 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4826 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4827 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4828 tyinfo[i].shellType = NULL;
4830 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4831 tyinfo[i].isDefined = true;
4833 tyinfo[i].isDefined = false;
4835 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4836 tyinfo[i].isArray = true;
4838 tyinfo[i].isArray = false;
4840 /* Decide whether we want to dump it */
4841 selectDumpableType(&tyinfo[i], fout);
4843 /* Do not try to dump ACL if no ACL exists. */
4844 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4845 PQgetisnull(res, i, i_inittypacl) &&
4846 PQgetisnull(res, i, i_initrtypacl))
4847 tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4850 * If it's a domain, fetch info about its constraints, if any
4852 tyinfo[i].nDomChecks = 0;
4853 tyinfo[i].domChecks = NULL;
4854 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4855 tyinfo[i].typtype == TYPTYPE_DOMAIN)
4856 getDomainConstraints(fout, &(tyinfo[i]));
4859 * If it's a base type, make a DumpableObject representing a shell
4860 * definition of the type. We will need to dump that ahead of the I/O
4861 * functions for the type. Similarly, range types need a shell
4862 * definition in case they have a canonicalize function.
4864 * Note: the shell type doesn't have a catId. You might think it
4865 * should copy the base type's catId, but then it might capture the
4866 * pg_depend entries for the type, which we don't want.
4868 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4869 (tyinfo[i].typtype == TYPTYPE_BASE ||
4870 tyinfo[i].typtype == TYPTYPE_RANGE))
4872 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4873 stinfo->dobj.objType = DO_SHELL_TYPE;
4874 stinfo->dobj.catId = nilCatalogId;
4875 AssignDumpId(&stinfo->dobj);
4876 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4877 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4878 stinfo->baseType = &(tyinfo[i]);
4879 tyinfo[i].shellType = stinfo;
4882 * Initially mark the shell type as not to be dumped. We'll only
4883 * dump it if the I/O or canonicalize functions need to be dumped;
4884 * this is taken care of while sorting dependencies.
4886 stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4889 if (strlen(tyinfo[i].rolname) == 0)
4890 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4891 tyinfo[i].dobj.name);
4898 destroyPQExpBuffer(query);
4905 * read all operators in the system catalogs and return them in the
4906 * OprInfo* structure
4908 * numOprs is set to the number of operators read in
4911 getOperators(Archive *fout, int *numOprs)
4916 PQExpBuffer query = createPQExpBuffer();
4927 * find all operators, including builtin operators; we filter out
4928 * system-defined operators at dump-out time.
4931 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4933 "(%s oprowner) AS rolname, "
4935 "oprcode::oid AS oprcode "
4939 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4941 ntups = PQntuples(res);
4944 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4946 i_tableoid = PQfnumber(res, "tableoid");
4947 i_oid = PQfnumber(res, "oid");
4948 i_oprname = PQfnumber(res, "oprname");
4949 i_oprnamespace = PQfnumber(res, "oprnamespace");
4950 i_rolname = PQfnumber(res, "rolname");
4951 i_oprkind = PQfnumber(res, "oprkind");
4952 i_oprcode = PQfnumber(res, "oprcode");
4954 for (i = 0; i < ntups; i++)
4956 oprinfo[i].dobj.objType = DO_OPERATOR;
4957 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4958 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4959 AssignDumpId(&oprinfo[i].dobj);
4960 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4961 oprinfo[i].dobj.namespace =
4963 atooid(PQgetvalue(res, i, i_oprnamespace)));
4964 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4965 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4966 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4968 /* Decide whether we want to dump it */
4969 selectDumpableObject(&(oprinfo[i].dobj), fout);
4971 /* Operators do not currently have ACLs. */
4972 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4974 if (strlen(oprinfo[i].rolname) == 0)
4975 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4976 oprinfo[i].dobj.name);
4981 destroyPQExpBuffer(query);
4988 * read all collations in the system catalogs and return them in the
4989 * CollInfo* structure
4991 * numCollations is set to the number of collations read in
4994 getCollations(Archive *fout, int *numCollations)
5004 int i_collnamespace;
5007 /* Collations didn't exist pre-9.1 */
5008 if (fout->remoteVersion < 90100)
5014 query = createPQExpBuffer();
5017 * find all collations, including builtin collations; we filter out
5018 * system-defined collations at dump-out time.
5021 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5023 "(%s collowner) AS rolname "
5024 "FROM pg_collation",
5027 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5029 ntups = PQntuples(res);
5030 *numCollations = ntups;
5032 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5034 i_tableoid = PQfnumber(res, "tableoid");
5035 i_oid = PQfnumber(res, "oid");
5036 i_collname = PQfnumber(res, "collname");
5037 i_collnamespace = PQfnumber(res, "collnamespace");
5038 i_rolname = PQfnumber(res, "rolname");
5040 for (i = 0; i < ntups; i++)
5042 collinfo[i].dobj.objType = DO_COLLATION;
5043 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5044 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5045 AssignDumpId(&collinfo[i].dobj);
5046 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5047 collinfo[i].dobj.namespace =
5049 atooid(PQgetvalue(res, i, i_collnamespace)));
5050 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5052 /* Decide whether we want to dump it */
5053 selectDumpableObject(&(collinfo[i].dobj), fout);
5055 /* Collations do not currently have ACLs. */
5056 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5061 destroyPQExpBuffer(query);
5068 * read all conversions in the system catalogs and return them in the
5069 * ConvInfo* structure
5071 * numConversions is set to the number of conversions read in
5074 getConversions(Archive *fout, int *numConversions)
5087 query = createPQExpBuffer();
5090 * find all conversions, including builtin conversions; we filter out
5091 * system-defined conversions at dump-out time.
5094 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5096 "(%s conowner) AS rolname "
5097 "FROM pg_conversion",
5100 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5102 ntups = PQntuples(res);
5103 *numConversions = ntups;
5105 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5107 i_tableoid = PQfnumber(res, "tableoid");
5108 i_oid = PQfnumber(res, "oid");
5109 i_conname = PQfnumber(res, "conname");
5110 i_connamespace = PQfnumber(res, "connamespace");
5111 i_rolname = PQfnumber(res, "rolname");
5113 for (i = 0; i < ntups; i++)
5115 convinfo[i].dobj.objType = DO_CONVERSION;
5116 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5117 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5118 AssignDumpId(&convinfo[i].dobj);
5119 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5120 convinfo[i].dobj.namespace =
5122 atooid(PQgetvalue(res, i, i_connamespace)));
5123 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5125 /* Decide whether we want to dump it */
5126 selectDumpableObject(&(convinfo[i].dobj), fout);
5128 /* Conversions do not currently have ACLs. */
5129 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5134 destroyPQExpBuffer(query);
5141 * read all user-defined access methods in the system catalogs and return
5142 * them in the AccessMethodInfo* structure
5144 * numAccessMethods is set to the number of access methods read in
5147 getAccessMethods(Archive *fout, int *numAccessMethods)
5153 AccessMethodInfo *aminfo;
5160 /* Before 9.6, there are no user-defined access methods */
5161 if (fout->remoteVersion < 90600)
5163 *numAccessMethods = 0;
5167 query = createPQExpBuffer();
5169 /* Select all access methods from pg_am table */
5170 appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5171 "amhandler::pg_catalog.regproc AS amhandler "
5174 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5176 ntups = PQntuples(res);
5177 *numAccessMethods = ntups;
5179 aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5181 i_tableoid = PQfnumber(res, "tableoid");
5182 i_oid = PQfnumber(res, "oid");
5183 i_amname = PQfnumber(res, "amname");
5184 i_amhandler = PQfnumber(res, "amhandler");
5185 i_amtype = PQfnumber(res, "amtype");
5187 for (i = 0; i < ntups; i++)
5189 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5190 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5191 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5192 AssignDumpId(&aminfo[i].dobj);
5193 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5194 aminfo[i].dobj.namespace = NULL;
5195 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5196 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5198 /* Decide whether we want to dump it */
5199 selectDumpableAccessMethod(&(aminfo[i]), fout);
5201 /* Access methods do not currently have ACLs. */
5202 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5207 destroyPQExpBuffer(query);
5215 * read all opclasses in the system catalogs and return them in the
5216 * OpclassInfo* structure
5218 * numOpclasses is set to the number of opclasses read in
5221 getOpclasses(Archive *fout, int *numOpclasses)
5226 PQExpBuffer query = createPQExpBuffer();
5227 OpclassInfo *opcinfo;
5235 * find all opclasses, including builtin opclasses; we filter out
5236 * system-defined opclasses at dump-out time.
5239 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5241 "(%s opcowner) AS rolname "
5245 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5247 ntups = PQntuples(res);
5248 *numOpclasses = ntups;
5250 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5252 i_tableoid = PQfnumber(res, "tableoid");
5253 i_oid = PQfnumber(res, "oid");
5254 i_opcname = PQfnumber(res, "opcname");
5255 i_opcnamespace = PQfnumber(res, "opcnamespace");
5256 i_rolname = PQfnumber(res, "rolname");
5258 for (i = 0; i < ntups; i++)
5260 opcinfo[i].dobj.objType = DO_OPCLASS;
5261 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5262 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5263 AssignDumpId(&opcinfo[i].dobj);
5264 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5265 opcinfo[i].dobj.namespace =
5267 atooid(PQgetvalue(res, i, i_opcnamespace)));
5268 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5270 /* Decide whether we want to dump it */
5271 selectDumpableObject(&(opcinfo[i].dobj), fout);
5273 /* Op Classes do not currently have ACLs. */
5274 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5276 if (strlen(opcinfo[i].rolname) == 0)
5277 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5278 opcinfo[i].dobj.name);
5283 destroyPQExpBuffer(query);
5290 * read all opfamilies in the system catalogs and return them in the
5291 * OpfamilyInfo* structure
5293 * numOpfamilies is set to the number of opfamilies read in
5296 getOpfamilies(Archive *fout, int *numOpfamilies)
5302 OpfamilyInfo *opfinfo;
5309 /* Before 8.3, there is no separate concept of opfamilies */
5310 if (fout->remoteVersion < 80300)
5316 query = createPQExpBuffer();
5319 * find all opfamilies, including builtin opfamilies; we filter out
5320 * system-defined opfamilies at dump-out time.
5323 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5325 "(%s opfowner) AS rolname "
5329 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5331 ntups = PQntuples(res);
5332 *numOpfamilies = ntups;
5334 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5336 i_tableoid = PQfnumber(res, "tableoid");
5337 i_oid = PQfnumber(res, "oid");
5338 i_opfname = PQfnumber(res, "opfname");
5339 i_opfnamespace = PQfnumber(res, "opfnamespace");
5340 i_rolname = PQfnumber(res, "rolname");
5342 for (i = 0; i < ntups; i++)
5344 opfinfo[i].dobj.objType = DO_OPFAMILY;
5345 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5346 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5347 AssignDumpId(&opfinfo[i].dobj);
5348 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5349 opfinfo[i].dobj.namespace =
5351 atooid(PQgetvalue(res, i, i_opfnamespace)));
5352 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5354 /* Decide whether we want to dump it */
5355 selectDumpableObject(&(opfinfo[i].dobj), fout);
5357 /* Extensions do not currently have ACLs. */
5358 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5360 if (strlen(opfinfo[i].rolname) == 0)
5361 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5362 opfinfo[i].dobj.name);
5367 destroyPQExpBuffer(query);
5374 * read all the user-defined aggregates in the system catalogs and
5375 * return them in the AggInfo* structure
5377 * numAggs is set to the number of aggregates read in
5380 getAggregates(Archive *fout, int *numAggs)
5382 DumpOptions *dopt = fout->dopt;
5386 PQExpBuffer query = createPQExpBuffer();
5401 * Find all interesting aggregates. See comment in getFuncs() for the
5402 * rationale behind the filtering logic.
5404 if (fout->remoteVersion >= 90600)
5406 PQExpBuffer acl_subquery = createPQExpBuffer();
5407 PQExpBuffer racl_subquery = createPQExpBuffer();
5408 PQExpBuffer initacl_subquery = createPQExpBuffer();
5409 PQExpBuffer initracl_subquery = createPQExpBuffer();
5410 const char *agg_check;
5412 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5413 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5414 dopt->binary_upgrade);
5416 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5419 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5420 "p.proname AS aggname, "
5421 "p.pronamespace AS aggnamespace, "
5422 "p.pronargs, p.proargtypes, "
5423 "(%s p.proowner) AS rolname, "
5426 "%s AS initaggacl, "
5427 "%s AS initraggacl "
5429 "LEFT JOIN pg_init_privs pip ON "
5430 "(p.oid = pip.objoid "
5431 "AND pip.classoid = 'pg_proc'::regclass "
5432 "AND pip.objsubid = 0) "
5434 "p.pronamespace != "
5435 "(SELECT oid FROM pg_namespace "
5436 "WHERE nspname = 'pg_catalog') OR "
5437 "p.proacl IS DISTINCT FROM pip.initprivs",
5440 racl_subquery->data,
5441 initacl_subquery->data,
5442 initracl_subquery->data,
5444 if (dopt->binary_upgrade)
5445 appendPQExpBufferStr(query,
5446 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5447 "classid = 'pg_proc'::regclass AND "
5448 "objid = p.oid AND "
5449 "refclassid = 'pg_extension'::regclass AND "
5451 appendPQExpBufferChar(query, ')');
5453 destroyPQExpBuffer(acl_subquery);
5454 destroyPQExpBuffer(racl_subquery);
5455 destroyPQExpBuffer(initacl_subquery);
5456 destroyPQExpBuffer(initracl_subquery);
5458 else if (fout->remoteVersion >= 80200)
5460 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5461 "pronamespace AS aggnamespace, "
5462 "pronargs, proargtypes, "
5463 "(%s proowner) AS rolname, "
5464 "proacl AS aggacl, "
5466 "NULL AS initaggacl, NULL AS initraggacl "
5468 "WHERE proisagg AND ("
5470 "(SELECT oid FROM pg_namespace "
5471 "WHERE nspname = 'pg_catalog')",
5473 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5474 appendPQExpBufferStr(query,
5475 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5476 "classid = 'pg_proc'::regclass AND "
5477 "objid = p.oid AND "
5478 "refclassid = 'pg_extension'::regclass AND "
5480 appendPQExpBufferChar(query, ')');
5484 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5485 "pronamespace AS aggnamespace, "
5486 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5488 "(%s proowner) AS rolname, "
5489 "proacl AS aggacl, "
5491 "NULL AS initaggacl, NULL AS initraggacl "
5494 "AND pronamespace != "
5495 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5499 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5501 ntups = PQntuples(res);
5504 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5506 i_tableoid = PQfnumber(res, "tableoid");
5507 i_oid = PQfnumber(res, "oid");
5508 i_aggname = PQfnumber(res, "aggname");
5509 i_aggnamespace = PQfnumber(res, "aggnamespace");
5510 i_pronargs = PQfnumber(res, "pronargs");
5511 i_proargtypes = PQfnumber(res, "proargtypes");
5512 i_rolname = PQfnumber(res, "rolname");
5513 i_aggacl = PQfnumber(res, "aggacl");
5514 i_raggacl = PQfnumber(res, "raggacl");
5515 i_initaggacl = PQfnumber(res, "initaggacl");
5516 i_initraggacl = PQfnumber(res, "initraggacl");
5518 for (i = 0; i < ntups; i++)
5520 agginfo[i].aggfn.dobj.objType = DO_AGG;
5521 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5522 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5523 AssignDumpId(&agginfo[i].aggfn.dobj);
5524 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5525 agginfo[i].aggfn.dobj.namespace =
5527 atooid(PQgetvalue(res, i, i_aggnamespace)));
5528 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5529 if (strlen(agginfo[i].aggfn.rolname) == 0)
5530 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5531 agginfo[i].aggfn.dobj.name);
5532 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5533 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
5534 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5535 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5536 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5537 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5538 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5539 if (agginfo[i].aggfn.nargs == 0)
5540 agginfo[i].aggfn.argtypes = NULL;
5543 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5544 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5545 agginfo[i].aggfn.argtypes,
5546 agginfo[i].aggfn.nargs);
5549 /* Decide whether we want to dump it */
5550 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5552 /* Do not try to dump ACL if no ACL exists. */
5553 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5554 PQgetisnull(res, i, i_initaggacl) &&
5555 PQgetisnull(res, i, i_initraggacl))
5556 agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5561 destroyPQExpBuffer(query);
5568 * read all the user-defined functions in the system catalogs and
5569 * return them in the FuncInfo* structure
5571 * numFuncs is set to the number of functions read in
5574 getFuncs(Archive *fout, int *numFuncs)
5576 DumpOptions *dopt = fout->dopt;
5580 PQExpBuffer query = createPQExpBuffer();
5597 * Find all interesting functions. This is a bit complicated:
5599 * 1. Always exclude aggregates; those are handled elsewhere.
5601 * 2. Always exclude functions that are internally dependent on something
5602 * else, since presumably those will be created as a result of creating
5603 * the something else. This currently acts only to suppress constructor
5604 * functions for range types (so we only need it in 9.2 and up). Note
5605 * this is OK only because the constructors don't have any dependencies
5606 * the range type doesn't have; otherwise we might not get creation
5609 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5610 * they're members of extensions and we are in binary-upgrade mode then
5611 * include them, since we want to dump extension members individually in
5612 * that mode. Also, if they are used by casts or transforms then we need
5613 * to gather the information about them, though they won't be dumped if
5614 * they are built-in. Also, in 9.6 and up, include functions in
5615 * pg_catalog if they have an ACL different from what's shown in
5618 if (fout->remoteVersion >= 90600)
5620 PQExpBuffer acl_subquery = createPQExpBuffer();
5621 PQExpBuffer racl_subquery = createPQExpBuffer();
5622 PQExpBuffer initacl_subquery = createPQExpBuffer();
5623 PQExpBuffer initracl_subquery = createPQExpBuffer();
5624 const char *not_agg_check;
5626 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5627 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5628 dopt->binary_upgrade);
5630 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5631 : "NOT p.proisagg");
5633 appendPQExpBuffer(query,
5634 "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5635 "p.pronargs, p.proargtypes, p.prorettype, "
5638 "%s AS initproacl, "
5639 "%s AS initrproacl, "
5641 "(%s p.proowner) AS rolname "
5643 "LEFT JOIN pg_init_privs pip ON "
5644 "(p.oid = pip.objoid "
5645 "AND pip.classoid = 'pg_proc'::regclass "
5646 "AND pip.objsubid = 0) "
5648 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5649 "WHERE classid = 'pg_proc'::regclass AND "
5650 "objid = p.oid AND deptype = 'i')"
5652 "\n pronamespace != "
5653 "(SELECT oid FROM pg_namespace "
5654 "WHERE nspname = 'pg_catalog')"
5655 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5656 "\n WHERE pg_cast.oid > %u "
5657 "\n AND p.oid = pg_cast.castfunc)"
5658 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5659 "\n WHERE pg_transform.oid > %u AND "
5660 "\n (p.oid = pg_transform.trffromsql"
5661 "\n OR p.oid = pg_transform.trftosql))",
5663 racl_subquery->data,
5664 initacl_subquery->data,
5665 initracl_subquery->data,
5669 g_last_builtin_oid);
5670 if (dopt->binary_upgrade)
5671 appendPQExpBufferStr(query,
5672 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5673 "classid = 'pg_proc'::regclass AND "
5674 "objid = p.oid AND "
5675 "refclassid = 'pg_extension'::regclass AND "
5677 appendPQExpBufferStr(query,
5678 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5679 appendPQExpBufferChar(query, ')');
5681 destroyPQExpBuffer(acl_subquery);
5682 destroyPQExpBuffer(racl_subquery);
5683 destroyPQExpBuffer(initacl_subquery);
5684 destroyPQExpBuffer(initracl_subquery);
5688 appendPQExpBuffer(query,
5689 "SELECT tableoid, oid, proname, prolang, "
5690 "pronargs, proargtypes, prorettype, proacl, "
5692 "NULL as initproacl, NULL AS initrproacl, "
5694 "(%s proowner) AS rolname "
5696 "WHERE NOT proisagg",
5698 if (fout->remoteVersion >= 90200)
5699 appendPQExpBufferStr(query,
5700 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5701 "WHERE classid = 'pg_proc'::regclass AND "
5702 "objid = p.oid AND deptype = 'i')");
5703 appendPQExpBuffer(query,
5705 "\n pronamespace != "
5706 "(SELECT oid FROM pg_namespace "
5707 "WHERE nspname = 'pg_catalog')"
5708 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5709 "\n WHERE pg_cast.oid > '%u'::oid"
5710 "\n AND p.oid = pg_cast.castfunc)",
5711 g_last_builtin_oid);
5713 if (fout->remoteVersion >= 90500)
5714 appendPQExpBuffer(query,
5715 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5716 "\n WHERE pg_transform.oid > '%u'::oid"
5717 "\n AND (p.oid = pg_transform.trffromsql"
5718 "\n OR p.oid = pg_transform.trftosql))",
5719 g_last_builtin_oid);
5721 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5722 appendPQExpBufferStr(query,
5723 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5724 "classid = 'pg_proc'::regclass AND "
5725 "objid = p.oid AND "
5726 "refclassid = 'pg_extension'::regclass AND "
5728 appendPQExpBufferChar(query, ')');
5731 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5733 ntups = PQntuples(res);
5737 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5739 i_tableoid = PQfnumber(res, "tableoid");
5740 i_oid = PQfnumber(res, "oid");
5741 i_proname = PQfnumber(res, "proname");
5742 i_pronamespace = PQfnumber(res, "pronamespace");
5743 i_rolname = PQfnumber(res, "rolname");
5744 i_prolang = PQfnumber(res, "prolang");
5745 i_pronargs = PQfnumber(res, "pronargs");
5746 i_proargtypes = PQfnumber(res, "proargtypes");
5747 i_prorettype = PQfnumber(res, "prorettype");
5748 i_proacl = PQfnumber(res, "proacl");
5749 i_rproacl = PQfnumber(res, "rproacl");
5750 i_initproacl = PQfnumber(res, "initproacl");
5751 i_initrproacl = PQfnumber(res, "initrproacl");
5753 for (i = 0; i < ntups; i++)
5755 finfo[i].dobj.objType = DO_FUNC;
5756 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5757 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5758 AssignDumpId(&finfo[i].dobj);
5759 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5760 finfo[i].dobj.namespace =
5762 atooid(PQgetvalue(res, i, i_pronamespace)));
5763 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5764 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5765 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5766 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5767 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5768 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5769 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5770 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5771 if (finfo[i].nargs == 0)
5772 finfo[i].argtypes = NULL;
5775 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5776 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5777 finfo[i].argtypes, finfo[i].nargs);
5780 /* Decide whether we want to dump it */
5781 selectDumpableObject(&(finfo[i].dobj), fout);
5783 /* Do not try to dump ACL if no ACL exists. */
5784 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5785 PQgetisnull(res, i, i_initproacl) &&
5786 PQgetisnull(res, i, i_initrproacl))
5787 finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5789 if (strlen(finfo[i].rolname) == 0)
5791 "WARNING: owner of function \"%s\" appears to be invalid\n",
5792 finfo[i].dobj.name);
5797 destroyPQExpBuffer(query);
5804 * read all the tables (no indexes)
5805 * in the system catalogs return them in the TableInfo* structure
5807 * numTables is set to the number of tables read in
5810 getTables(Archive *fout, int *numTables)
5812 DumpOptions *dopt = fout->dopt;
5816 PQExpBuffer query = createPQExpBuffer();
5829 int i_relhastriggers;
5833 int i_relforcerowsec;
5838 int i_toastfrozenxid;
5840 int i_relpersistence;
5841 int i_relispopulated;
5845 int i_reltablespace;
5848 int i_toastreloptions;
5851 int i_is_identity_sequence;
5858 * Find all the tables and table-like objects.
5860 * We include system catalogs, so that we can work if a user table is
5861 * defined to inherit from a system catalog (pretty weird, but...)
5863 * We ignore relations that are not ordinary tables, sequences, views,
5864 * materialized views, composite types, or foreign tables.
5866 * Composite-type table entries won't be dumped as such, but we have to
5867 * make a DumpableObject for them so that we can track dependencies of the
5868 * composite type (pg_depend entries for columns of the composite type
5869 * link to the pg_class entry not the pg_type entry).
5871 * Note: in this phase we should collect only a minimal amount of
5872 * information about each table, basically just enough to decide if it is
5873 * interesting. We must fetch all tables in this phase because otherwise
5874 * we cannot correctly identify inherited columns, owned sequences, etc.
5877 if (fout->remoteVersion >= 90600)
5879 char *partkeydef = "NULL";
5880 char *ispartition = "false";
5881 char *partbound = "NULL";
5883 PQExpBuffer acl_subquery = createPQExpBuffer();
5884 PQExpBuffer racl_subquery = createPQExpBuffer();
5885 PQExpBuffer initacl_subquery = createPQExpBuffer();
5886 PQExpBuffer initracl_subquery = createPQExpBuffer();
5888 PQExpBuffer attacl_subquery = createPQExpBuffer();
5889 PQExpBuffer attracl_subquery = createPQExpBuffer();
5890 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5891 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5894 * Collect the information about any partitioned tables, which were
5898 if (fout->remoteVersion >= 100000)
5900 partkeydef = "pg_get_partkeydef(c.oid)";
5901 ispartition = "c.relispartition";
5902 partbound = "pg_get_expr(c.relpartbound, c.oid)";
5906 * Left join to pick up dependency info linking sequences to their
5907 * owning column, if any (note this dependency is AUTO as of 8.2)
5909 * Left join to detect if any privileges are still as-set-at-init, in
5910 * which case we won't dump out ACL commands for those.
5913 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5914 initracl_subquery, "c.relacl", "c.relowner",
5915 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5916 " THEN 's' ELSE 'r' END::\"char\"",
5917 dopt->binary_upgrade);
5919 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5920 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5921 dopt->binary_upgrade);
5923 appendPQExpBuffer(query,
5924 "SELECT c.tableoid, c.oid, c.relname, "
5925 "%s AS relacl, %s as rrelacl, "
5926 "%s AS initrelacl, %s as initrrelacl, "
5927 "c.relkind, c.relnamespace, "
5928 "(%s c.relowner) AS rolname, "
5929 "c.relchecks, c.relhastriggers, "
5930 "c.relhasindex, c.relhasrules, c.relhasoids, "
5931 "c.relrowsecurity, c.relforcerowsecurity, "
5932 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5933 "tc.relfrozenxid AS tfrozenxid, "
5934 "tc.relminmxid AS tminmxid, "
5935 "c.relpersistence, c.relispopulated, "
5936 "c.relreplident, c.relpages, "
5937 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5938 "d.refobjid AS owning_tab, "
5939 "d.refobjsubid AS owning_col, "
5940 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5941 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5942 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5943 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5944 "tc.reloptions AS toast_reloptions, "
5945 "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, "
5946 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5947 "(c.oid = pip.objoid "
5948 "AND pip.classoid = 'pg_class'::regclass "
5949 "AND pip.objsubid = at.attnum)"
5950 "WHERE at.attrelid = c.oid AND ("
5952 "OR %s IS NOT NULL "
5953 "OR %s IS NOT NULL "
5957 "%s AS partkeydef, "
5958 "%s AS ispartition, "
5961 "LEFT JOIN pg_depend d ON "
5962 "(c.relkind = '%c' AND "
5963 "d.classid = c.tableoid AND d.objid = c.oid AND "
5964 "d.objsubid = 0 AND "
5965 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5966 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5967 "LEFT JOIN pg_init_privs pip ON "
5968 "(c.oid = pip.objoid "
5969 "AND pip.classoid = 'pg_class'::regclass "
5970 "AND pip.objsubid = 0) "
5971 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5974 racl_subquery->data,
5975 initacl_subquery->data,
5976 initracl_subquery->data,
5979 attacl_subquery->data,
5980 attracl_subquery->data,
5981 attinitacl_subquery->data,
5982 attinitracl_subquery->data,
5987 RELKIND_RELATION, RELKIND_SEQUENCE,
5988 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5989 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5990 RELKIND_PARTITIONED_TABLE);
5992 destroyPQExpBuffer(acl_subquery);
5993 destroyPQExpBuffer(racl_subquery);
5994 destroyPQExpBuffer(initacl_subquery);
5995 destroyPQExpBuffer(initracl_subquery);
5997 destroyPQExpBuffer(attacl_subquery);
5998 destroyPQExpBuffer(attracl_subquery);
5999 destroyPQExpBuffer(attinitacl_subquery);
6000 destroyPQExpBuffer(attinitracl_subquery);
6002 else if (fout->remoteVersion >= 90500)
6005 * Left join to pick up dependency info linking sequences to their
6006 * owning column, if any (note this dependency is AUTO as of 8.2)
6008 appendPQExpBuffer(query,
6009 "SELECT c.tableoid, c.oid, c.relname, "
6010 "c.relacl, NULL as rrelacl, "
6011 "NULL AS initrelacl, NULL AS initrrelacl, "
6014 "(%s c.relowner) AS rolname, "
6015 "c.relchecks, c.relhastriggers, "
6016 "c.relhasindex, c.relhasrules, c.relhasoids, "
6017 "c.relrowsecurity, c.relforcerowsecurity, "
6018 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6019 "tc.relfrozenxid AS tfrozenxid, "
6020 "tc.relminmxid AS tminmxid, "
6021 "c.relpersistence, c.relispopulated, "
6022 "c.relreplident, c.relpages, "
6023 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6024 "d.refobjid AS owning_tab, "
6025 "d.refobjsubid AS owning_col, "
6026 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6027 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6028 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6029 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6030 "tc.reloptions AS toast_reloptions, "
6031 "NULL AS changed_acl, "
6032 "NULL AS partkeydef, "
6033 "false AS ispartition, "
6034 "NULL AS partbound "
6036 "LEFT JOIN pg_depend d ON "
6037 "(c.relkind = '%c' AND "
6038 "d.classid = c.tableoid AND d.objid = c.oid AND "
6039 "d.objsubid = 0 AND "
6040 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6041 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6042 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6046 RELKIND_RELATION, RELKIND_SEQUENCE,
6047 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6048 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6050 else if (fout->remoteVersion >= 90400)
6053 * Left join to pick up dependency info linking sequences to their
6054 * owning column, if any (note this dependency is AUTO as of 8.2)
6056 appendPQExpBuffer(query,
6057 "SELECT c.tableoid, c.oid, c.relname, "
6058 "c.relacl, NULL as rrelacl, "
6059 "NULL AS initrelacl, NULL AS initrrelacl, "
6062 "(%s c.relowner) AS rolname, "
6063 "c.relchecks, c.relhastriggers, "
6064 "c.relhasindex, c.relhasrules, c.relhasoids, "
6065 "'f'::bool AS relrowsecurity, "
6066 "'f'::bool AS relforcerowsecurity, "
6067 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6068 "tc.relfrozenxid AS tfrozenxid, "
6069 "tc.relminmxid AS tminmxid, "
6070 "c.relpersistence, c.relispopulated, "
6071 "c.relreplident, c.relpages, "
6072 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6073 "d.refobjid AS owning_tab, "
6074 "d.refobjsubid AS owning_col, "
6075 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6076 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6077 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6078 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6079 "tc.reloptions AS toast_reloptions, "
6080 "NULL AS changed_acl, "
6081 "NULL AS partkeydef, "
6082 "false AS ispartition, "
6083 "NULL AS partbound "
6085 "LEFT JOIN pg_depend d ON "
6086 "(c.relkind = '%c' AND "
6087 "d.classid = c.tableoid AND d.objid = c.oid AND "
6088 "d.objsubid = 0 AND "
6089 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6090 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6091 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6095 RELKIND_RELATION, RELKIND_SEQUENCE,
6096 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6097 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6099 else if (fout->remoteVersion >= 90300)
6102 * Left join to pick up dependency info linking sequences to their
6103 * owning column, if any (note this dependency is AUTO as of 8.2)
6105 appendPQExpBuffer(query,
6106 "SELECT c.tableoid, c.oid, c.relname, "
6107 "c.relacl, NULL as rrelacl, "
6108 "NULL AS initrelacl, NULL AS initrrelacl, "
6111 "(%s c.relowner) AS rolname, "
6112 "c.relchecks, c.relhastriggers, "
6113 "c.relhasindex, c.relhasrules, c.relhasoids, "
6114 "'f'::bool AS relrowsecurity, "
6115 "'f'::bool AS relforcerowsecurity, "
6116 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6117 "tc.relfrozenxid AS tfrozenxid, "
6118 "tc.relminmxid AS tminmxid, "
6119 "c.relpersistence, c.relispopulated, "
6120 "'d' AS relreplident, c.relpages, "
6121 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6122 "d.refobjid AS owning_tab, "
6123 "d.refobjsubid AS owning_col, "
6124 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6125 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6126 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6127 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6128 "tc.reloptions AS toast_reloptions, "
6129 "NULL AS changed_acl, "
6130 "NULL AS partkeydef, "
6131 "false AS ispartition, "
6132 "NULL AS partbound "
6134 "LEFT JOIN pg_depend d ON "
6135 "(c.relkind = '%c' AND "
6136 "d.classid = c.tableoid AND d.objid = c.oid AND "
6137 "d.objsubid = 0 AND "
6138 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6139 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6140 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6144 RELKIND_RELATION, RELKIND_SEQUENCE,
6145 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6146 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6148 else if (fout->remoteVersion >= 90100)
6151 * Left join to pick up dependency info linking sequences to their
6152 * owning column, if any (note this dependency is AUTO as of 8.2)
6154 appendPQExpBuffer(query,
6155 "SELECT c.tableoid, c.oid, c.relname, "
6156 "c.relacl, NULL as rrelacl, "
6157 "NULL AS initrelacl, NULL AS initrrelacl, "
6160 "(%s c.relowner) AS rolname, "
6161 "c.relchecks, c.relhastriggers, "
6162 "c.relhasindex, c.relhasrules, c.relhasoids, "
6163 "'f'::bool AS relrowsecurity, "
6164 "'f'::bool AS relforcerowsecurity, "
6165 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6166 "tc.relfrozenxid AS tfrozenxid, "
6168 "c.relpersistence, 't' as relispopulated, "
6169 "'d' AS relreplident, c.relpages, "
6170 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6171 "d.refobjid AS owning_tab, "
6172 "d.refobjsubid AS owning_col, "
6173 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6174 "c.reloptions AS reloptions, "
6175 "tc.reloptions AS toast_reloptions, "
6176 "NULL AS changed_acl, "
6177 "NULL AS partkeydef, "
6178 "false AS ispartition, "
6179 "NULL AS partbound "
6181 "LEFT JOIN pg_depend d ON "
6182 "(c.relkind = '%c' AND "
6183 "d.classid = c.tableoid AND d.objid = c.oid AND "
6184 "d.objsubid = 0 AND "
6185 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6186 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6187 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6191 RELKIND_RELATION, RELKIND_SEQUENCE,
6192 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6193 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6195 else if (fout->remoteVersion >= 90000)
6198 * Left join to pick up dependency info linking sequences to their
6199 * owning column, if any (note this dependency is AUTO as of 8.2)
6201 appendPQExpBuffer(query,
6202 "SELECT c.tableoid, c.oid, c.relname, "
6203 "c.relacl, NULL as rrelacl, "
6204 "NULL AS initrelacl, NULL AS initrrelacl, "
6207 "(%s c.relowner) AS rolname, "
6208 "c.relchecks, c.relhastriggers, "
6209 "c.relhasindex, c.relhasrules, c.relhasoids, "
6210 "'f'::bool AS relrowsecurity, "
6211 "'f'::bool AS relforcerowsecurity, "
6212 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6213 "tc.relfrozenxid AS tfrozenxid, "
6215 "'p' AS relpersistence, 't' as relispopulated, "
6216 "'d' AS relreplident, c.relpages, "
6217 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6218 "d.refobjid AS owning_tab, "
6219 "d.refobjsubid AS owning_col, "
6220 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6221 "c.reloptions AS reloptions, "
6222 "tc.reloptions AS toast_reloptions, "
6223 "NULL AS changed_acl, "
6224 "NULL AS partkeydef, "
6225 "false AS ispartition, "
6226 "NULL AS partbound "
6228 "LEFT JOIN pg_depend d ON "
6229 "(c.relkind = '%c' AND "
6230 "d.classid = c.tableoid AND d.objid = c.oid AND "
6231 "d.objsubid = 0 AND "
6232 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6233 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6234 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6238 RELKIND_RELATION, RELKIND_SEQUENCE,
6239 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6241 else if (fout->remoteVersion >= 80400)
6244 * Left join to pick up dependency info linking sequences to their
6245 * owning column, if any (note this dependency is AUTO as of 8.2)
6247 appendPQExpBuffer(query,
6248 "SELECT c.tableoid, c.oid, c.relname, "
6249 "c.relacl, NULL as rrelacl, "
6250 "NULL AS initrelacl, NULL AS initrrelacl, "
6253 "(%s c.relowner) AS rolname, "
6254 "c.relchecks, c.relhastriggers, "
6255 "c.relhasindex, c.relhasrules, c.relhasoids, "
6256 "'f'::bool AS relrowsecurity, "
6257 "'f'::bool AS relforcerowsecurity, "
6258 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6259 "tc.relfrozenxid AS tfrozenxid, "
6261 "'p' AS relpersistence, 't' as relispopulated, "
6262 "'d' AS relreplident, c.relpages, "
6263 "NULL AS reloftype, "
6264 "d.refobjid AS owning_tab, "
6265 "d.refobjsubid AS owning_col, "
6266 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6267 "c.reloptions AS reloptions, "
6268 "tc.reloptions AS toast_reloptions, "
6269 "NULL AS changed_acl, "
6270 "NULL AS partkeydef, "
6271 "false AS ispartition, "
6272 "NULL AS partbound "
6274 "LEFT JOIN pg_depend d ON "
6275 "(c.relkind = '%c' AND "
6276 "d.classid = c.tableoid AND d.objid = c.oid AND "
6277 "d.objsubid = 0 AND "
6278 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6279 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6280 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6284 RELKIND_RELATION, RELKIND_SEQUENCE,
6285 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6287 else if (fout->remoteVersion >= 80200)
6290 * Left join to pick up dependency info linking sequences to their
6291 * owning column, if any (note this dependency is AUTO as of 8.2)
6293 appendPQExpBuffer(query,
6294 "SELECT c.tableoid, c.oid, c.relname, "
6295 "c.relacl, NULL as rrelacl, "
6296 "NULL AS initrelacl, NULL AS initrrelacl, "
6299 "(%s c.relowner) AS rolname, "
6300 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6301 "c.relhasindex, c.relhasrules, c.relhasoids, "
6302 "'f'::bool AS relrowsecurity, "
6303 "'f'::bool AS relforcerowsecurity, "
6304 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6305 "tc.relfrozenxid AS tfrozenxid, "
6307 "'p' AS relpersistence, 't' as relispopulated, "
6308 "'d' AS relreplident, c.relpages, "
6309 "NULL AS reloftype, "
6310 "d.refobjid AS owning_tab, "
6311 "d.refobjsubid AS owning_col, "
6312 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6313 "c.reloptions AS reloptions, "
6314 "NULL AS toast_reloptions, "
6315 "NULL AS changed_acl, "
6316 "NULL AS partkeydef, "
6317 "false AS ispartition, "
6318 "NULL AS partbound "
6320 "LEFT JOIN pg_depend d ON "
6321 "(c.relkind = '%c' AND "
6322 "d.classid = c.tableoid AND d.objid = c.oid AND "
6323 "d.objsubid = 0 AND "
6324 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6325 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6326 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6330 RELKIND_RELATION, RELKIND_SEQUENCE,
6331 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6336 * Left join to pick up dependency info linking sequences to their
6337 * owning column, if any
6339 appendPQExpBuffer(query,
6340 "SELECT c.tableoid, c.oid, relname, "
6341 "relacl, NULL as rrelacl, "
6342 "NULL AS initrelacl, NULL AS initrrelacl, "
6343 "relkind, relnamespace, "
6344 "(%s relowner) AS rolname, "
6345 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6346 "relhasindex, relhasrules, relhasoids, "
6347 "'f'::bool AS relrowsecurity, "
6348 "'f'::bool AS relforcerowsecurity, "
6349 "0 AS relfrozenxid, 0 AS relminmxid,"
6351 "0 AS tfrozenxid, 0 AS tminmxid,"
6352 "'p' AS relpersistence, 't' as relispopulated, "
6353 "'d' AS relreplident, relpages, "
6354 "NULL AS reloftype, "
6355 "d.refobjid AS owning_tab, "
6356 "d.refobjsubid AS owning_col, "
6357 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6358 "NULL AS reloptions, "
6359 "NULL AS toast_reloptions, "
6360 "NULL AS changed_acl, "
6361 "NULL AS partkeydef, "
6362 "false AS ispartition, "
6363 "NULL AS partbound "
6365 "LEFT JOIN pg_depend d ON "
6366 "(c.relkind = '%c' AND "
6367 "d.classid = c.tableoid AND d.objid = c.oid AND "
6368 "d.objsubid = 0 AND "
6369 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6370 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6374 RELKIND_RELATION, RELKIND_SEQUENCE,
6375 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6378 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6380 ntups = PQntuples(res);
6385 * Extract data from result and lock dumpable tables. We do the locking
6386 * before anything else, to minimize the window wherein a table could
6387 * disappear under us.
6389 * Note that we have to save info about all tables here, even when dumping
6390 * only one, because we don't yet know which tables might be inheritance
6391 * ancestors of the target table.
6393 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6395 i_reltableoid = PQfnumber(res, "tableoid");
6396 i_reloid = PQfnumber(res, "oid");
6397 i_relname = PQfnumber(res, "relname");
6398 i_relnamespace = PQfnumber(res, "relnamespace");
6399 i_relacl = PQfnumber(res, "relacl");
6400 i_rrelacl = PQfnumber(res, "rrelacl");
6401 i_initrelacl = PQfnumber(res, "initrelacl");
6402 i_initrrelacl = PQfnumber(res, "initrrelacl");
6403 i_relkind = PQfnumber(res, "relkind");
6404 i_rolname = PQfnumber(res, "rolname");
6405 i_relchecks = PQfnumber(res, "relchecks");
6406 i_relhastriggers = PQfnumber(res, "relhastriggers");
6407 i_relhasindex = PQfnumber(res, "relhasindex");
6408 i_relhasrules = PQfnumber(res, "relhasrules");
6409 i_relrowsec = PQfnumber(res, "relrowsecurity");
6410 i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6411 i_relhasoids = PQfnumber(res, "relhasoids");
6412 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6413 i_relminmxid = PQfnumber(res, "relminmxid");
6414 i_toastoid = PQfnumber(res, "toid");
6415 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6416 i_toastminmxid = PQfnumber(res, "tminmxid");
6417 i_relpersistence = PQfnumber(res, "relpersistence");
6418 i_relispopulated = PQfnumber(res, "relispopulated");
6419 i_relreplident = PQfnumber(res, "relreplident");
6420 i_relpages = PQfnumber(res, "relpages");
6421 i_owning_tab = PQfnumber(res, "owning_tab");
6422 i_owning_col = PQfnumber(res, "owning_col");
6423 i_reltablespace = PQfnumber(res, "reltablespace");
6424 i_reloptions = PQfnumber(res, "reloptions");
6425 i_checkoption = PQfnumber(res, "checkoption");
6426 i_toastreloptions = PQfnumber(res, "toast_reloptions");
6427 i_reloftype = PQfnumber(res, "reloftype");
6428 i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6429 i_changed_acl = PQfnumber(res, "changed_acl");
6430 i_partkeydef = PQfnumber(res, "partkeydef");
6431 i_ispartition = PQfnumber(res, "ispartition");
6432 i_partbound = PQfnumber(res, "partbound");
6434 if (dopt->lockWaitTimeout)
6437 * Arrange to fail instead of waiting forever for a table lock.
6439 * NB: this coding assumes that the only queries issued within the
6440 * following loop are LOCK TABLEs; else the timeout may be undesirably
6441 * applied to other things too.
6443 resetPQExpBuffer(query);
6444 appendPQExpBufferStr(query, "SET statement_timeout = ");
6445 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6446 ExecuteSqlStatement(fout, query->data);
6449 for (i = 0; i < ntups; i++)
6451 tblinfo[i].dobj.objType = DO_TABLE;
6452 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6453 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6454 AssignDumpId(&tblinfo[i].dobj);
6455 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6456 tblinfo[i].dobj.namespace =
6458 atooid(PQgetvalue(res, i, i_relnamespace)));
6459 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6460 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6461 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6462 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6463 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6464 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6465 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6466 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6467 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6468 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6469 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6470 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6471 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6472 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6473 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6474 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6475 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6476 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6477 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6478 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6479 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6480 if (PQgetisnull(res, i, i_reloftype))
6481 tblinfo[i].reloftype = NULL;
6483 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6484 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6485 if (PQgetisnull(res, i, i_owning_tab))
6487 tblinfo[i].owning_tab = InvalidOid;
6488 tblinfo[i].owning_col = 0;
6492 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6493 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6495 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6496 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6497 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6498 tblinfo[i].checkoption = NULL;
6500 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6501 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6503 /* other fields were zeroed above */
6506 * Decide whether we want to dump this table.
6508 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6509 tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6511 selectDumpableTable(&tblinfo[i], fout);
6514 * If the table-level and all column-level ACLs for this table are
6515 * unchanged, then we don't need to worry about including the ACLs for
6516 * this table. If any column-level ACLs have been changed, the
6517 * 'changed_acl' column from the query will indicate that.
6519 * This can result in a significant performance improvement in cases
6520 * where we are only looking to dump out the ACL (eg: pg_catalog).
6522 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6523 PQgetisnull(res, i, i_initrelacl) &&
6524 PQgetisnull(res, i, i_initrrelacl) &&
6525 strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6526 tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6528 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6529 tblinfo[i].dummy_view = false; /* might get set during sort */
6530 tblinfo[i].postponed_def = false; /* might get set during sort */
6532 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6533 strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6535 /* Partition key string or NULL */
6536 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6537 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6538 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6541 * Read-lock target tables to make sure they aren't DROPPED or altered
6542 * in schema before we get around to dumping them.
6544 * Note that we don't explicitly lock parents of the target tables; we
6545 * assume our lock on the child is enough to prevent schema
6546 * alterations to parent tables.
6548 * NOTE: it'd be kinda nice to lock other relations too, not only
6549 * plain or partitioned tables, but the backend doesn't presently
6552 * We only need to lock the table for certain components; see
6555 if (tblinfo[i].dobj.dump &&
6556 (tblinfo[i].relkind == RELKIND_RELATION ||
6557 tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6558 (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6560 resetPQExpBuffer(query);
6561 appendPQExpBuffer(query,
6562 "LOCK TABLE %s IN ACCESS SHARE MODE",
6563 fmtQualifiedDumpable(&tblinfo[i]));
6564 ExecuteSqlStatement(fout, query->data);
6567 /* Emit notice if join for owner failed */
6568 if (strlen(tblinfo[i].rolname) == 0)
6569 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6570 tblinfo[i].dobj.name);
6573 if (dopt->lockWaitTimeout)
6575 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6580 destroyPQExpBuffer(query);
6587 * identify owned sequences and mark them as dumpable if owning table is
6589 * We used to do this in getTables(), but it's better to do it after the
6590 * index used by findTableByOid() has been set up.
6593 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6598 * Force sequences that are "owned" by table columns to be dumped whenever
6599 * their owning table is being dumped.
6601 for (i = 0; i < numTables; i++)
6603 TableInfo *seqinfo = &tblinfo[i];
6604 TableInfo *owning_tab;
6606 if (!OidIsValid(seqinfo->owning_tab))
6607 continue; /* not an owned sequence */
6609 owning_tab = findTableByOid(seqinfo->owning_tab);
6610 if (owning_tab == NULL)
6611 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6612 seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6615 * We need to dump the components that are being dumped for the table
6616 * and any components which the sequence is explicitly marked with.
6618 * We can't simply use the set of components which are being dumped
6619 * for the table as the table might be in an extension (and only the
6620 * non-extension components, eg: ACLs if changed, security labels, and
6621 * policies, are being dumped) while the sequence is not (and
6622 * therefore the definition and other components should also be
6625 * If the sequence is part of the extension then it should be properly
6626 * marked by checkExtensionMembership() and this will be a no-op as
6627 * the table will be equivalently marked.
6629 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6631 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6632 seqinfo->interesting = true;
6638 * read all the inheritance information
6639 * from the system catalogs return them in the InhInfo* structure
6641 * numInherits is set to the number of pairs read in
6644 getInherits(Archive *fout, int *numInherits)
6649 PQExpBuffer query = createPQExpBuffer();
6656 * Find all the inheritance information, excluding implicit inheritance
6657 * via partitioning. We handle that case using getPartitions(), because
6658 * we want more information about partitions than just the parent-child
6661 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6663 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6665 ntups = PQntuples(res);
6667 *numInherits = ntups;
6669 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6671 i_inhrelid = PQfnumber(res, "inhrelid");
6672 i_inhparent = PQfnumber(res, "inhparent");
6674 for (i = 0; i < ntups; i++)
6676 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6677 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6682 destroyPQExpBuffer(query);
6689 * get information about every index on a dumpable table
6691 * Note: index data is not returned directly to the caller, but it
6692 * does get entered into the DumpableObject tables.
6695 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6699 PQExpBuffer query = createPQExpBuffer();
6702 ConstraintInfo *constrinfo;
6724 for (i = 0; i < numTables; i++)
6726 TableInfo *tbinfo = &tblinfo[i];
6728 if (!tbinfo->hasindex)
6732 * Ignore indexes of tables whose definitions are not to be dumped.
6734 * We also need indexes on partitioned tables which have partitions to
6735 * be dumped, in order to dump the indexes on the partitions.
6737 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6738 !tbinfo->interesting)
6742 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6743 tbinfo->dobj.namespace->dobj.name,
6747 * The point of the messy-looking outer join is to find a constraint
6748 * that is related by an internal dependency link to the index. If we
6749 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6750 * assume an index won't have more than one internal dependency.
6752 * As of 9.0 we don't need to look at pg_depend but can check for a
6753 * match to pg_constraint.conindid. The check on conrelid is
6754 * redundant but useful because that column is indexed while conindid
6757 resetPQExpBuffer(query);
6758 if (fout->remoteVersion >= 110000)
6760 appendPQExpBuffer(query,
6761 "SELECT t.tableoid, t.oid, "
6762 "t.relname AS indexname, "
6763 "inh.inhparent AS parentidx, "
6764 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6765 "t.relnatts AS indnkeys, "
6766 "i.indkey, i.indisclustered, "
6767 "i.indisreplident, t.relpages, "
6768 "c.contype, c.conname, "
6769 "c.condeferrable, c.condeferred, "
6770 "c.tableoid AS contableoid, "
6772 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6773 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6774 "t.reloptions AS indreloptions "
6775 "FROM pg_catalog.pg_index i "
6776 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6777 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6778 "LEFT JOIN pg_catalog.pg_constraint c "
6779 "ON (i.indrelid = c.conrelid AND "
6780 "i.indexrelid = c.conindid AND "
6781 "c.contype IN ('p','u','x')) "
6782 "LEFT JOIN pg_catalog.pg_inherits inh "
6783 "ON (inh.inhrelid = indexrelid) "
6784 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6785 "AND (i.indisvalid OR t2.relkind = 'p') "
6787 "ORDER BY indexname",
6788 tbinfo->dobj.catId.oid);
6790 else if (fout->remoteVersion >= 90400)
6793 * the test on indisready is necessary in 9.2, and harmless in
6794 * earlier/later versions
6796 appendPQExpBuffer(query,
6797 "SELECT t.tableoid, t.oid, "
6798 "t.relname AS indexname, "
6800 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6801 "t.relnatts AS indnkeys, "
6802 "i.indkey, i.indisclustered, "
6803 "i.indisreplident, t.relpages, "
6804 "c.contype, c.conname, "
6805 "c.condeferrable, c.condeferred, "
6806 "c.tableoid AS contableoid, "
6808 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6809 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6810 "t.reloptions AS indreloptions "
6811 "FROM pg_catalog.pg_index i "
6812 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6813 "LEFT JOIN pg_catalog.pg_constraint c "
6814 "ON (i.indrelid = c.conrelid AND "
6815 "i.indexrelid = c.conindid AND "
6816 "c.contype IN ('p','u','x')) "
6817 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6818 "AND i.indisvalid AND i.indisready "
6819 "ORDER BY indexname",
6820 tbinfo->dobj.catId.oid);
6822 else if (fout->remoteVersion >= 90000)
6825 * the test on indisready is necessary in 9.2, and harmless in
6826 * earlier/later versions
6828 appendPQExpBuffer(query,
6829 "SELECT t.tableoid, t.oid, "
6830 "t.relname AS indexname, "
6832 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6833 "t.relnatts AS indnkeys, "
6834 "i.indkey, i.indisclustered, "
6835 "false AS indisreplident, t.relpages, "
6836 "c.contype, c.conname, "
6837 "c.condeferrable, c.condeferred, "
6838 "c.tableoid AS contableoid, "
6840 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6841 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6842 "t.reloptions AS indreloptions "
6843 "FROM pg_catalog.pg_index i "
6844 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6845 "LEFT JOIN pg_catalog.pg_constraint c "
6846 "ON (i.indrelid = c.conrelid AND "
6847 "i.indexrelid = c.conindid AND "
6848 "c.contype IN ('p','u','x')) "
6849 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6850 "AND i.indisvalid AND i.indisready "
6851 "ORDER BY indexname",
6852 tbinfo->dobj.catId.oid);
6854 else if (fout->remoteVersion >= 80200)
6856 appendPQExpBuffer(query,
6857 "SELECT t.tableoid, t.oid, "
6858 "t.relname AS indexname, "
6860 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6861 "t.relnatts AS indnkeys, "
6862 "i.indkey, i.indisclustered, "
6863 "false AS indisreplident, t.relpages, "
6864 "c.contype, c.conname, "
6865 "c.condeferrable, c.condeferred, "
6866 "c.tableoid AS contableoid, "
6869 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6870 "t.reloptions AS indreloptions "
6871 "FROM pg_catalog.pg_index i "
6872 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6873 "LEFT JOIN pg_catalog.pg_depend d "
6874 "ON (d.classid = t.tableoid "
6875 "AND d.objid = t.oid "
6876 "AND d.deptype = 'i') "
6877 "LEFT JOIN pg_catalog.pg_constraint c "
6878 "ON (d.refclassid = c.tableoid "
6879 "AND d.refobjid = c.oid) "
6880 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6882 "ORDER BY indexname",
6883 tbinfo->dobj.catId.oid);
6887 appendPQExpBuffer(query,
6888 "SELECT t.tableoid, t.oid, "
6889 "t.relname AS indexname, "
6891 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6892 "t.relnatts AS indnkeys, "
6893 "i.indkey, i.indisclustered, "
6894 "false AS indisreplident, t.relpages, "
6895 "c.contype, c.conname, "
6896 "c.condeferrable, c.condeferred, "
6897 "c.tableoid AS contableoid, "
6900 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6901 "null AS indreloptions "
6902 "FROM pg_catalog.pg_index i "
6903 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6904 "LEFT JOIN pg_catalog.pg_depend d "
6905 "ON (d.classid = t.tableoid "
6906 "AND d.objid = t.oid "
6907 "AND d.deptype = 'i') "
6908 "LEFT JOIN pg_catalog.pg_constraint c "
6909 "ON (d.refclassid = c.tableoid "
6910 "AND d.refobjid = c.oid) "
6911 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6912 "ORDER BY indexname",
6913 tbinfo->dobj.catId.oid);
6916 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6918 ntups = PQntuples(res);
6920 i_tableoid = PQfnumber(res, "tableoid");
6921 i_oid = PQfnumber(res, "oid");
6922 i_indexname = PQfnumber(res, "indexname");
6923 i_parentidx = PQfnumber(res, "parentidx");
6924 i_indexdef = PQfnumber(res, "indexdef");
6925 i_indnkeys = PQfnumber(res, "indnkeys");
6926 i_indkey = PQfnumber(res, "indkey");
6927 i_indisclustered = PQfnumber(res, "indisclustered");
6928 i_indisreplident = PQfnumber(res, "indisreplident");
6929 i_relpages = PQfnumber(res, "relpages");
6930 i_contype = PQfnumber(res, "contype");
6931 i_conname = PQfnumber(res, "conname");
6932 i_condeferrable = PQfnumber(res, "condeferrable");
6933 i_condeferred = PQfnumber(res, "condeferred");
6934 i_contableoid = PQfnumber(res, "contableoid");
6935 i_conoid = PQfnumber(res, "conoid");
6936 i_condef = PQfnumber(res, "condef");
6937 i_tablespace = PQfnumber(res, "tablespace");
6938 i_indreloptions = PQfnumber(res, "indreloptions");
6940 tbinfo->indexes = indxinfo =
6941 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6942 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6943 tbinfo->numIndexes = ntups;
6945 for (j = 0; j < ntups; j++)
6949 indxinfo[j].dobj.objType = DO_INDEX;
6950 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6951 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6952 AssignDumpId(&indxinfo[j].dobj);
6953 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6954 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6955 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6956 indxinfo[j].indextable = tbinfo;
6957 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6958 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
6959 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6960 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6961 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnkeys * sizeof(Oid));
6962 parseOidArray(PQgetvalue(res, j, i_indkey),
6963 indxinfo[j].indkeys, indxinfo[j].indnkeys);
6964 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6965 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6966 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6967 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
6968 contype = *(PQgetvalue(res, j, i_contype));
6970 if (contype == 'p' || contype == 'u' || contype == 'x')
6973 * If we found a constraint matching the index, create an
6976 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6977 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6978 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6979 AssignDumpId(&constrinfo[j].dobj);
6980 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
6981 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6982 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6983 constrinfo[j].contable = tbinfo;
6984 constrinfo[j].condomain = NULL;
6985 constrinfo[j].contype = contype;
6987 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6989 constrinfo[j].condef = NULL;
6990 constrinfo[j].confrelid = InvalidOid;
6991 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
6992 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
6993 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
6994 constrinfo[j].conislocal = true;
6995 constrinfo[j].separate = true;
6997 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7001 /* Plain secondary index */
7002 indxinfo[j].indexconstraint = 0;
7009 destroyPQExpBuffer(query);
7013 * getExtendedStatistics
7014 * get information about extended-statistics objects.
7016 * Note: extended statistics data is not returned directly to the caller, but
7017 * it does get entered into the DumpableObject tables.
7020 getExtendedStatistics(Archive *fout)
7024 StatsExtInfo *statsextinfo;
7033 /* Extended statistics were new in v10 */
7034 if (fout->remoteVersion < 100000)
7037 query = createPQExpBuffer();
7039 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7040 "stxnamespace, (%s stxowner) AS rolname "
7041 "FROM pg_catalog.pg_statistic_ext",
7044 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7046 ntups = PQntuples(res);
7048 i_tableoid = PQfnumber(res, "tableoid");
7049 i_oid = PQfnumber(res, "oid");
7050 i_stxname = PQfnumber(res, "stxname");
7051 i_stxnamespace = PQfnumber(res, "stxnamespace");
7052 i_rolname = PQfnumber(res, "rolname");
7054 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7056 for (i = 0; i < ntups; i++)
7058 statsextinfo[i].dobj.objType = DO_STATSEXT;
7059 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7060 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7061 AssignDumpId(&statsextinfo[i].dobj);
7062 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7063 statsextinfo[i].dobj.namespace =
7065 atooid(PQgetvalue(res, i, i_stxnamespace)));
7066 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7068 /* Decide whether we want to dump it */
7069 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7071 /* Stats objects do not currently have ACLs. */
7072 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7076 destroyPQExpBuffer(query);
7082 * Get info about constraints on dumpable tables.
7084 * Currently handles foreign keys only.
7085 * Unique and primary key constraints are handled with indexes,
7086 * while check constraints are processed in getTableAttrs().
7089 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7093 ConstraintInfo *constrinfo;
7103 query = createPQExpBuffer();
7105 for (i = 0; i < numTables; i++)
7107 TableInfo *tbinfo = &tblinfo[i];
7109 if (!tbinfo->hastriggers ||
7110 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7114 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7115 tbinfo->dobj.namespace->dobj.name,
7118 resetPQExpBuffer(query);
7119 appendPQExpBuffer(query,
7120 "SELECT tableoid, oid, conname, confrelid, "
7121 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7122 "FROM pg_catalog.pg_constraint "
7123 "WHERE conrelid = '%u'::pg_catalog.oid "
7124 "AND contype = 'f'",
7125 tbinfo->dobj.catId.oid);
7126 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7128 ntups = PQntuples(res);
7130 i_contableoid = PQfnumber(res, "tableoid");
7131 i_conoid = PQfnumber(res, "oid");
7132 i_conname = PQfnumber(res, "conname");
7133 i_confrelid = PQfnumber(res, "confrelid");
7134 i_condef = PQfnumber(res, "condef");
7136 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7138 for (j = 0; j < ntups; j++)
7140 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7141 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7142 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7143 AssignDumpId(&constrinfo[j].dobj);
7144 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7145 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7146 constrinfo[j].contable = tbinfo;
7147 constrinfo[j].condomain = NULL;
7148 constrinfo[j].contype = 'f';
7149 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7150 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7151 constrinfo[j].conindex = 0;
7152 constrinfo[j].condeferrable = false;
7153 constrinfo[j].condeferred = false;
7154 constrinfo[j].conislocal = true;
7155 constrinfo[j].separate = true;
7161 destroyPQExpBuffer(query);
7165 * getDomainConstraints
7167 * Get info about constraints on a domain.
7170 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7173 ConstraintInfo *constrinfo;
7182 query = createPQExpBuffer();
7184 if (fout->remoteVersion >= 90100)
7185 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7186 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7188 "FROM pg_catalog.pg_constraint "
7189 "WHERE contypid = '%u'::pg_catalog.oid "
7191 tyinfo->dobj.catId.oid);
7194 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7195 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7196 "true as convalidated "
7197 "FROM pg_catalog.pg_constraint "
7198 "WHERE contypid = '%u'::pg_catalog.oid "
7200 tyinfo->dobj.catId.oid);
7202 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7204 ntups = PQntuples(res);
7206 i_tableoid = PQfnumber(res, "tableoid");
7207 i_oid = PQfnumber(res, "oid");
7208 i_conname = PQfnumber(res, "conname");
7209 i_consrc = PQfnumber(res, "consrc");
7211 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7213 tyinfo->nDomChecks = ntups;
7214 tyinfo->domChecks = constrinfo;
7216 for (i = 0; i < ntups; i++)
7218 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7220 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7221 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7222 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7223 AssignDumpId(&constrinfo[i].dobj);
7224 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7225 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7226 constrinfo[i].contable = NULL;
7227 constrinfo[i].condomain = tyinfo;
7228 constrinfo[i].contype = 'c';
7229 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7230 constrinfo[i].confrelid = InvalidOid;
7231 constrinfo[i].conindex = 0;
7232 constrinfo[i].condeferrable = false;
7233 constrinfo[i].condeferred = false;
7234 constrinfo[i].conislocal = true;
7236 constrinfo[i].separate = !validated;
7239 * Make the domain depend on the constraint, ensuring it won't be
7240 * output till any constraint dependencies are OK. If the constraint
7241 * has not been validated, it's going to be dumped after the domain
7242 * anyway, so this doesn't matter.
7245 addObjectDependency(&tyinfo->dobj,
7246 constrinfo[i].dobj.dumpId);
7251 destroyPQExpBuffer(query);
7256 * get basic information about every rule in the system
7258 * numRules is set to the number of rules read in
7261 getRules(Archive *fout, int *numRules)
7266 PQExpBuffer query = createPQExpBuffer();
7276 if (fout->remoteVersion >= 80300)
7278 appendPQExpBufferStr(query, "SELECT "
7279 "tableoid, oid, rulename, "
7280 "ev_class AS ruletable, ev_type, is_instead, "
7287 appendPQExpBufferStr(query, "SELECT "
7288 "tableoid, oid, rulename, "
7289 "ev_class AS ruletable, ev_type, is_instead, "
7290 "'O'::char AS ev_enabled "
7295 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7297 ntups = PQntuples(res);
7301 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7303 i_tableoid = PQfnumber(res, "tableoid");
7304 i_oid = PQfnumber(res, "oid");
7305 i_rulename = PQfnumber(res, "rulename");
7306 i_ruletable = PQfnumber(res, "ruletable");
7307 i_ev_type = PQfnumber(res, "ev_type");
7308 i_is_instead = PQfnumber(res, "is_instead");
7309 i_ev_enabled = PQfnumber(res, "ev_enabled");
7311 for (i = 0; i < ntups; i++)
7315 ruleinfo[i].dobj.objType = DO_RULE;
7316 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7317 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7318 AssignDumpId(&ruleinfo[i].dobj);
7319 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7320 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7321 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7322 if (ruleinfo[i].ruletable == NULL)
7323 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7324 ruletableoid, ruleinfo[i].dobj.catId.oid);
7325 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7326 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7327 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7328 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7329 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7330 if (ruleinfo[i].ruletable)
7333 * If the table is a view or materialized view, force its ON
7334 * SELECT rule to be sorted before the view itself --- this
7335 * ensures that any dependencies for the rule affect the table's
7336 * positioning. Other rules are forced to appear after their
7339 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7340 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7341 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7343 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7344 ruleinfo[i].dobj.dumpId);
7345 /* We'll merge the rule into CREATE VIEW, if possible */
7346 ruleinfo[i].separate = false;
7350 addObjectDependency(&ruleinfo[i].dobj,
7351 ruleinfo[i].ruletable->dobj.dumpId);
7352 ruleinfo[i].separate = true;
7356 ruleinfo[i].separate = true;
7361 destroyPQExpBuffer(query);
7368 * get information about every trigger on a dumpable table
7370 * Note: trigger data is not returned directly to the caller, but it
7371 * does get entered into the DumpableObject tables.
7374 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7378 PQExpBuffer query = createPQExpBuffer();
7380 TriggerInfo *tginfo;
7398 for (i = 0; i < numTables; i++)
7400 TableInfo *tbinfo = &tblinfo[i];
7402 if (!tbinfo->hastriggers ||
7403 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7407 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7408 tbinfo->dobj.namespace->dobj.name,
7411 resetPQExpBuffer(query);
7412 if (fout->remoteVersion >= 90000)
7415 * NB: think not to use pretty=true in pg_get_triggerdef. It
7416 * could result in non-forward-compatible dumps of WHEN clauses
7417 * due to under-parenthesization.
7419 appendPQExpBuffer(query,
7421 "tgfoid::pg_catalog.regproc AS tgfname, "
7422 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7423 "tgenabled, tableoid, oid "
7424 "FROM pg_catalog.pg_trigger t "
7425 "WHERE tgrelid = '%u'::pg_catalog.oid "
7426 "AND NOT tgisinternal",
7427 tbinfo->dobj.catId.oid);
7429 else if (fout->remoteVersion >= 80300)
7432 * We ignore triggers that are tied to a foreign-key constraint
7434 appendPQExpBuffer(query,
7436 "tgfoid::pg_catalog.regproc AS tgfname, "
7437 "tgtype, tgnargs, tgargs, tgenabled, "
7438 "tgisconstraint, tgconstrname, tgdeferrable, "
7439 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7440 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7441 "FROM pg_catalog.pg_trigger t "
7442 "WHERE tgrelid = '%u'::pg_catalog.oid "
7443 "AND tgconstraint = 0",
7444 tbinfo->dobj.catId.oid);
7449 * We ignore triggers that are tied to a foreign-key constraint,
7450 * but in these versions we have to grovel through pg_constraint
7453 appendPQExpBuffer(query,
7455 "tgfoid::pg_catalog.regproc AS tgfname, "
7456 "tgtype, tgnargs, tgargs, tgenabled, "
7457 "tgisconstraint, tgconstrname, tgdeferrable, "
7458 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7459 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7460 "FROM pg_catalog.pg_trigger t "
7461 "WHERE tgrelid = '%u'::pg_catalog.oid "
7462 "AND (NOT tgisconstraint "
7464 " (SELECT 1 FROM pg_catalog.pg_depend d "
7465 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7466 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7467 tbinfo->dobj.catId.oid);
7470 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7472 ntups = PQntuples(res);
7474 i_tableoid = PQfnumber(res, "tableoid");
7475 i_oid = PQfnumber(res, "oid");
7476 i_tgname = PQfnumber(res, "tgname");
7477 i_tgfname = PQfnumber(res, "tgfname");
7478 i_tgtype = PQfnumber(res, "tgtype");
7479 i_tgnargs = PQfnumber(res, "tgnargs");
7480 i_tgargs = PQfnumber(res, "tgargs");
7481 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7482 i_tgconstrname = PQfnumber(res, "tgconstrname");
7483 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7484 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7485 i_tgenabled = PQfnumber(res, "tgenabled");
7486 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7487 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7488 i_tgdef = PQfnumber(res, "tgdef");
7490 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7492 tbinfo->numTriggers = ntups;
7493 tbinfo->triggers = tginfo;
7495 for (j = 0; j < ntups; j++)
7497 tginfo[j].dobj.objType = DO_TRIGGER;
7498 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7499 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7500 AssignDumpId(&tginfo[j].dobj);
7501 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7502 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7503 tginfo[j].tgtable = tbinfo;
7504 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7507 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7509 /* remaining fields are not valid if we have tgdef */
7510 tginfo[j].tgfname = NULL;
7511 tginfo[j].tgtype = 0;
7512 tginfo[j].tgnargs = 0;
7513 tginfo[j].tgargs = NULL;
7514 tginfo[j].tgisconstraint = false;
7515 tginfo[j].tgdeferrable = false;
7516 tginfo[j].tginitdeferred = false;
7517 tginfo[j].tgconstrname = NULL;
7518 tginfo[j].tgconstrrelid = InvalidOid;
7519 tginfo[j].tgconstrrelname = NULL;
7523 tginfo[j].tgdef = NULL;
7525 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7526 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7527 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7528 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7529 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7530 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7531 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7533 if (tginfo[j].tgisconstraint)
7535 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7536 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7537 if (OidIsValid(tginfo[j].tgconstrrelid))
7539 if (PQgetisnull(res, j, i_tgconstrrelname))
7540 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7541 tginfo[j].dobj.name,
7543 tginfo[j].tgconstrrelid);
7544 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7547 tginfo[j].tgconstrrelname = NULL;
7551 tginfo[j].tgconstrname = NULL;
7552 tginfo[j].tgconstrrelid = InvalidOid;
7553 tginfo[j].tgconstrrelname = NULL;
7561 destroyPQExpBuffer(query);
7566 * get information about event triggers
7569 getEventTriggers(Archive *fout, int *numEventTriggers)
7574 EventTriggerInfo *evtinfo;
7585 /* Before 9.3, there are no event triggers */
7586 if (fout->remoteVersion < 90300)
7588 *numEventTriggers = 0;
7592 query = createPQExpBuffer();
7594 appendPQExpBuffer(query,
7595 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7596 "evtevent, (%s evtowner) AS evtowner, "
7597 "array_to_string(array("
7598 "select quote_literal(x) "
7599 " from unnest(evttags) as t(x)), ', ') as evttags, "
7600 "e.evtfoid::regproc as evtfname "
7601 "FROM pg_event_trigger e "
7605 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7607 ntups = PQntuples(res);
7609 *numEventTriggers = ntups;
7611 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7613 i_tableoid = PQfnumber(res, "tableoid");
7614 i_oid = PQfnumber(res, "oid");
7615 i_evtname = PQfnumber(res, "evtname");
7616 i_evtevent = PQfnumber(res, "evtevent");
7617 i_evtowner = PQfnumber(res, "evtowner");
7618 i_evttags = PQfnumber(res, "evttags");
7619 i_evtfname = PQfnumber(res, "evtfname");
7620 i_evtenabled = PQfnumber(res, "evtenabled");
7622 for (i = 0; i < ntups; i++)
7624 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7625 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7626 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7627 AssignDumpId(&evtinfo[i].dobj);
7628 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7629 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7630 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7631 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7632 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7633 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7634 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7636 /* Decide whether we want to dump it */
7637 selectDumpableObject(&(evtinfo[i].dobj), fout);
7639 /* Event Triggers do not currently have ACLs. */
7640 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7645 destroyPQExpBuffer(query);
7652 * get basic information about every procedural language in the system
7654 * numProcLangs is set to the number of langs read in
7656 * NB: this must run after getFuncs() because we assume we can do
7660 getProcLangs(Archive *fout, int *numProcLangs)
7662 DumpOptions *dopt = fout->dopt;
7666 PQExpBuffer query = createPQExpBuffer();
7667 ProcLangInfo *planginfo;
7672 int i_lanplcallfoid;
7681 if (fout->remoteVersion >= 90600)
7683 PQExpBuffer acl_subquery = createPQExpBuffer();
7684 PQExpBuffer racl_subquery = createPQExpBuffer();
7685 PQExpBuffer initacl_subquery = createPQExpBuffer();
7686 PQExpBuffer initracl_subquery = createPQExpBuffer();
7688 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7689 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7690 dopt->binary_upgrade);
7692 /* pg_language has a laninline column */
7693 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7694 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7695 "l.laninline, l.lanvalidator, "
7698 "%s AS initlanacl, "
7699 "%s AS initrlanacl, "
7700 "(%s l.lanowner) AS lanowner "
7701 "FROM pg_language l "
7702 "LEFT JOIN pg_init_privs pip ON "
7703 "(l.oid = pip.objoid "
7704 "AND pip.classoid = 'pg_language'::regclass "
7705 "AND pip.objsubid = 0) "
7709 racl_subquery->data,
7710 initacl_subquery->data,
7711 initracl_subquery->data,
7714 destroyPQExpBuffer(acl_subquery);
7715 destroyPQExpBuffer(racl_subquery);
7716 destroyPQExpBuffer(initacl_subquery);
7717 destroyPQExpBuffer(initracl_subquery);
7719 else if (fout->remoteVersion >= 90000)
7721 /* pg_language has a laninline column */
7722 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7723 "lanname, lanpltrusted, lanplcallfoid, "
7724 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7725 "NULL AS initlanacl, NULL AS initrlanacl, "
7726 "(%s lanowner) AS lanowner "
7732 else if (fout->remoteVersion >= 80300)
7734 /* pg_language has a lanowner column */
7735 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7736 "lanname, lanpltrusted, lanplcallfoid, "
7737 "0 AS laninline, lanvalidator, lanacl, "
7739 "NULL AS initlanacl, NULL AS initrlanacl, "
7740 "(%s lanowner) AS lanowner "
7746 else if (fout->remoteVersion >= 80100)
7748 /* Languages are owned by the bootstrap superuser, OID 10 */
7749 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7750 "lanname, lanpltrusted, lanplcallfoid, "
7751 "0 AS laninline, lanvalidator, lanacl, "
7753 "NULL AS initlanacl, NULL AS initrlanacl, "
7754 "(%s '10') AS lanowner "
7762 /* Languages are owned by the bootstrap superuser, sysid 1 */
7763 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7764 "lanname, lanpltrusted, lanplcallfoid, "
7765 "0 AS laninline, lanvalidator, lanacl, "
7767 "NULL AS initlanacl, NULL AS initrlanacl, "
7768 "(%s '1') AS lanowner "
7775 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7777 ntups = PQntuples(res);
7779 *numProcLangs = ntups;
7781 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7783 i_tableoid = PQfnumber(res, "tableoid");
7784 i_oid = PQfnumber(res, "oid");
7785 i_lanname = PQfnumber(res, "lanname");
7786 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7787 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7788 i_laninline = PQfnumber(res, "laninline");
7789 i_lanvalidator = PQfnumber(res, "lanvalidator");
7790 i_lanacl = PQfnumber(res, "lanacl");
7791 i_rlanacl = PQfnumber(res, "rlanacl");
7792 i_initlanacl = PQfnumber(res, "initlanacl");
7793 i_initrlanacl = PQfnumber(res, "initrlanacl");
7794 i_lanowner = PQfnumber(res, "lanowner");
7796 for (i = 0; i < ntups; i++)
7798 planginfo[i].dobj.objType = DO_PROCLANG;
7799 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7800 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7801 AssignDumpId(&planginfo[i].dobj);
7803 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7804 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7805 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7806 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7807 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7808 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7809 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7810 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7811 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7812 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7814 /* Decide whether we want to dump it */
7815 selectDumpableProcLang(&(planginfo[i]), fout);
7817 /* Do not try to dump ACL if no ACL exists. */
7818 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7819 PQgetisnull(res, i, i_initlanacl) &&
7820 PQgetisnull(res, i, i_initrlanacl))
7821 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7826 destroyPQExpBuffer(query);
7833 * get basic information about every cast in the system
7835 * numCasts is set to the number of casts read in
7838 getCasts(Archive *fout, int *numCasts)
7843 PQExpBuffer query = createPQExpBuffer();
7853 if (fout->remoteVersion >= 80400)
7855 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7856 "castsource, casttarget, castfunc, castcontext, "
7858 "FROM pg_cast ORDER BY 3,4");
7862 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7863 "castsource, casttarget, castfunc, castcontext, "
7864 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7865 "FROM pg_cast ORDER BY 3,4");
7868 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7870 ntups = PQntuples(res);
7874 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7876 i_tableoid = PQfnumber(res, "tableoid");
7877 i_oid = PQfnumber(res, "oid");
7878 i_castsource = PQfnumber(res, "castsource");
7879 i_casttarget = PQfnumber(res, "casttarget");
7880 i_castfunc = PQfnumber(res, "castfunc");
7881 i_castcontext = PQfnumber(res, "castcontext");
7882 i_castmethod = PQfnumber(res, "castmethod");
7884 for (i = 0; i < ntups; i++)
7886 PQExpBufferData namebuf;
7887 TypeInfo *sTypeInfo;
7888 TypeInfo *tTypeInfo;
7890 castinfo[i].dobj.objType = DO_CAST;
7891 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7892 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7893 AssignDumpId(&castinfo[i].dobj);
7894 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7895 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7896 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7897 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7898 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7901 * Try to name cast as concatenation of typnames. This is only used
7902 * for purposes of sorting. If we fail to find either type, the name
7903 * will be an empty string.
7905 initPQExpBuffer(&namebuf);
7906 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7907 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7908 if (sTypeInfo && tTypeInfo)
7909 appendPQExpBuffer(&namebuf, "%s %s",
7910 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7911 castinfo[i].dobj.name = namebuf.data;
7913 /* Decide whether we want to dump it */
7914 selectDumpableCast(&(castinfo[i]), fout);
7916 /* Casts do not currently have ACLs. */
7917 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7922 destroyPQExpBuffer(query);
7928 get_language_name(Archive *fout, Oid langid)
7934 query = createPQExpBuffer();
7935 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7936 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7937 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7938 destroyPQExpBuffer(query);
7946 * get basic information about every transform in the system
7948 * numTransforms is set to the number of transforms read in
7951 getTransforms(Archive *fout, int *numTransforms)
7957 TransformInfo *transforminfo;
7965 /* Transforms didn't exist pre-9.5 */
7966 if (fout->remoteVersion < 90500)
7972 query = createPQExpBuffer();
7974 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7975 "trftype, trflang, trffromsql::oid, trftosql::oid "
7976 "FROM pg_transform "
7979 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7981 ntups = PQntuples(res);
7983 *numTransforms = ntups;
7985 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
7987 i_tableoid = PQfnumber(res, "tableoid");
7988 i_oid = PQfnumber(res, "oid");
7989 i_trftype = PQfnumber(res, "trftype");
7990 i_trflang = PQfnumber(res, "trflang");
7991 i_trffromsql = PQfnumber(res, "trffromsql");
7992 i_trftosql = PQfnumber(res, "trftosql");
7994 for (i = 0; i < ntups; i++)
7996 PQExpBufferData namebuf;
8000 transforminfo[i].dobj.objType = DO_TRANSFORM;
8001 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8002 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8003 AssignDumpId(&transforminfo[i].dobj);
8004 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8005 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8006 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8007 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8010 * Try to name transform as concatenation of type and language name.
8011 * This is only used for purposes of sorting. If we fail to find
8012 * either, the name will be an empty string.
8014 initPQExpBuffer(&namebuf);
8015 typeInfo = findTypeByOid(transforminfo[i].trftype);
8016 lanname = get_language_name(fout, transforminfo[i].trflang);
8017 if (typeInfo && lanname)
8018 appendPQExpBuffer(&namebuf, "%s %s",
8019 typeInfo->dobj.name, lanname);
8020 transforminfo[i].dobj.name = namebuf.data;
8023 /* Decide whether we want to dump it */
8024 selectDumpableObject(&(transforminfo[i].dobj), fout);
8029 destroyPQExpBuffer(query);
8031 return transforminfo;
8036 * for each interesting table, read info about its attributes
8037 * (names, types, default values, CHECK constraints, etc)
8039 * This is implemented in a very inefficient way right now, looping
8040 * through the tblinfo and doing a join per table to find the attrs and their
8041 * types. However, because we want type names and so forth to be named
8042 * relative to the schema of each table, we couldn't do it in just one
8043 * query. (Maybe one query per schema?)
8048 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8050 DumpOptions *dopt = fout->dopt;
8053 PQExpBuffer q = createPQExpBuffer();
8058 int i_attstattarget;
8070 int i_attfdwoptions;
8075 for (i = 0; i < numTables; i++)
8077 TableInfo *tbinfo = &tblinfo[i];
8079 /* Don't bother to collect info for sequences */
8080 if (tbinfo->relkind == RELKIND_SEQUENCE)
8083 /* Don't bother with uninteresting tables, either */
8084 if (!tbinfo->interesting)
8087 /* find all the user attributes and their types */
8090 * we must read the attribute names in attribute number order! because
8091 * we will use the attnum to index into the attnames array later.
8094 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8095 tbinfo->dobj.namespace->dobj.name,
8098 resetPQExpBuffer(q);
8100 if (fout->remoteVersion >= 100000)
8103 * attidentity is new in version 10.
8105 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8106 "a.attstattarget, a.attstorage, t.typstorage, "
8107 "a.attnotnull, a.atthasdef, a.attisdropped, "
8108 "a.attlen, a.attalign, a.attislocal, "
8109 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8110 "array_to_string(a.attoptions, ', ') AS attoptions, "
8111 "CASE WHEN a.attcollation <> t.typcollation "
8112 "THEN a.attcollation ELSE 0 END AS attcollation, "
8114 "pg_catalog.array_to_string(ARRAY("
8115 "SELECT pg_catalog.quote_ident(option_name) || "
8116 "' ' || pg_catalog.quote_literal(option_value) "
8117 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8118 "ORDER BY option_name"
8119 "), E',\n ') AS attfdwoptions "
8120 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8121 "ON a.atttypid = t.oid "
8122 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8123 "AND a.attnum > 0::pg_catalog.int2 "
8124 "ORDER BY a.attnum",
8125 tbinfo->dobj.catId.oid);
8127 else if (fout->remoteVersion >= 90200)
8130 * attfdwoptions is new in 9.2.
8132 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8133 "a.attstattarget, a.attstorage, t.typstorage, "
8134 "a.attnotnull, a.atthasdef, a.attisdropped, "
8135 "a.attlen, a.attalign, a.attislocal, "
8136 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8137 "array_to_string(a.attoptions, ', ') AS attoptions, "
8138 "CASE WHEN a.attcollation <> t.typcollation "
8139 "THEN a.attcollation ELSE 0 END AS attcollation, "
8140 "pg_catalog.array_to_string(ARRAY("
8141 "SELECT pg_catalog.quote_ident(option_name) || "
8142 "' ' || pg_catalog.quote_literal(option_value) "
8143 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8144 "ORDER BY option_name"
8145 "), E',\n ') AS attfdwoptions "
8146 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8147 "ON a.atttypid = t.oid "
8148 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8149 "AND a.attnum > 0::pg_catalog.int2 "
8150 "ORDER BY a.attnum",
8151 tbinfo->dobj.catId.oid);
8153 else if (fout->remoteVersion >= 90100)
8156 * attcollation is new in 9.1. Since we only want to dump COLLATE
8157 * clauses for attributes whose collation is different from their
8158 * type's default, we use a CASE here to suppress uninteresting
8159 * attcollations cheaply.
8161 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8162 "a.attstattarget, a.attstorage, t.typstorage, "
8163 "a.attnotnull, a.atthasdef, a.attisdropped, "
8164 "a.attlen, a.attalign, a.attislocal, "
8165 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8166 "array_to_string(a.attoptions, ', ') AS attoptions, "
8167 "CASE WHEN a.attcollation <> t.typcollation "
8168 "THEN a.attcollation ELSE 0 END AS attcollation, "
8169 "NULL AS attfdwoptions "
8170 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8171 "ON a.atttypid = t.oid "
8172 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8173 "AND a.attnum > 0::pg_catalog.int2 "
8174 "ORDER BY a.attnum",
8175 tbinfo->dobj.catId.oid);
8177 else if (fout->remoteVersion >= 90000)
8179 /* attoptions is new in 9.0 */
8180 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8181 "a.attstattarget, a.attstorage, t.typstorage, "
8182 "a.attnotnull, a.atthasdef, a.attisdropped, "
8183 "a.attlen, a.attalign, a.attislocal, "
8184 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8185 "array_to_string(a.attoptions, ', ') AS attoptions, "
8186 "0 AS attcollation, "
8187 "NULL AS attfdwoptions "
8188 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8189 "ON a.atttypid = t.oid "
8190 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8191 "AND a.attnum > 0::pg_catalog.int2 "
8192 "ORDER BY a.attnum",
8193 tbinfo->dobj.catId.oid);
8197 /* need left join here to not fail on dropped columns ... */
8198 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8199 "a.attstattarget, a.attstorage, t.typstorage, "
8200 "a.attnotnull, a.atthasdef, a.attisdropped, "
8201 "a.attlen, a.attalign, a.attislocal, "
8202 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8203 "'' AS attoptions, 0 AS attcollation, "
8204 "NULL AS attfdwoptions "
8205 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8206 "ON a.atttypid = t.oid "
8207 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8208 "AND a.attnum > 0::pg_catalog.int2 "
8209 "ORDER BY a.attnum",
8210 tbinfo->dobj.catId.oid);
8213 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8215 ntups = PQntuples(res);
8217 i_attnum = PQfnumber(res, "attnum");
8218 i_attname = PQfnumber(res, "attname");
8219 i_atttypname = PQfnumber(res, "atttypname");
8220 i_atttypmod = PQfnumber(res, "atttypmod");
8221 i_attstattarget = PQfnumber(res, "attstattarget");
8222 i_attstorage = PQfnumber(res, "attstorage");
8223 i_typstorage = PQfnumber(res, "typstorage");
8224 i_attnotnull = PQfnumber(res, "attnotnull");
8225 i_atthasdef = PQfnumber(res, "atthasdef");
8226 i_attidentity = PQfnumber(res, "attidentity");
8227 i_attisdropped = PQfnumber(res, "attisdropped");
8228 i_attlen = PQfnumber(res, "attlen");
8229 i_attalign = PQfnumber(res, "attalign");
8230 i_attislocal = PQfnumber(res, "attislocal");
8231 i_attoptions = PQfnumber(res, "attoptions");
8232 i_attcollation = PQfnumber(res, "attcollation");
8233 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8235 tbinfo->numatts = ntups;
8236 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8237 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8238 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8239 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8240 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8241 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8242 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8243 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8244 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8245 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8246 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8247 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8248 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8249 tbinfo->attfdwoptions = (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] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
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->attrdefs[j] = NULL; /* fix below */
8278 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8280 /* these flags will be set in flagInhAttrs() */
8281 tbinfo->inhNotNull[j] = false;
8287 * Get info about column defaults
8291 AttrDefInfo *attrdefs;
8295 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8296 tbinfo->dobj.namespace->dobj.name,
8299 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8300 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8301 "FROM pg_catalog.pg_attrdef "
8302 "WHERE adrelid = '%u'::pg_catalog.oid",
8303 tbinfo->dobj.catId.oid);
8305 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8307 numDefaults = PQntuples(res);
8308 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8310 for (j = 0; j < numDefaults; j++)
8314 adnum = atoi(PQgetvalue(res, j, 2));
8316 if (adnum <= 0 || adnum > ntups)
8318 "invalid adnum value %d for table \"%s\"\n",
8319 adnum, tbinfo->dobj.name);
8322 * dropped columns shouldn't have defaults, but just in case,
8325 if (tbinfo->attisdropped[adnum - 1])
8328 attrdefs[j].dobj.objType = DO_ATTRDEF;
8329 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8330 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8331 AssignDumpId(&attrdefs[j].dobj);
8332 attrdefs[j].adtable = tbinfo;
8333 attrdefs[j].adnum = adnum;
8334 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8336 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8337 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8339 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8342 * Defaults on a VIEW must always be dumped as separate ALTER
8343 * TABLE commands. Defaults on regular tables are dumped as
8344 * part of the CREATE TABLE if possible, which it won't be if
8345 * the column is not going to be emitted explicitly.
8347 if (tbinfo->relkind == RELKIND_VIEW)
8349 attrdefs[j].separate = true;
8351 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8353 /* column will be suppressed, print default separately */
8354 attrdefs[j].separate = true;
8358 attrdefs[j].separate = false;
8361 * Mark the default as needing to appear before the table,
8362 * so that any dependencies it has must be emitted before
8363 * the CREATE TABLE. If this is not possible, we'll
8364 * change to "separate" mode while sorting dependencies.
8366 addObjectDependency(&tbinfo->dobj,
8367 attrdefs[j].dobj.dumpId);
8370 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8376 * Get info about table CHECK constraints
8378 if (tbinfo->ncheck > 0)
8380 ConstraintInfo *constrs;
8384 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8385 tbinfo->dobj.namespace->dobj.name,
8388 resetPQExpBuffer(q);
8389 if (fout->remoteVersion >= 90200)
8392 * convalidated is new in 9.2 (actually, it is there in 9.1,
8393 * but it wasn't ever false for check constraints until 9.2).
8395 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8396 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8397 "conislocal, convalidated "
8398 "FROM pg_catalog.pg_constraint "
8399 "WHERE conrelid = '%u'::pg_catalog.oid "
8400 " AND contype = 'c' "
8402 tbinfo->dobj.catId.oid);
8404 else if (fout->remoteVersion >= 80400)
8406 /* conislocal is new in 8.4 */
8407 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8408 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8409 "conislocal, true AS convalidated "
8410 "FROM pg_catalog.pg_constraint "
8411 "WHERE conrelid = '%u'::pg_catalog.oid "
8412 " AND contype = 'c' "
8414 tbinfo->dobj.catId.oid);
8418 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8419 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8420 "true AS conislocal, true AS convalidated "
8421 "FROM pg_catalog.pg_constraint "
8422 "WHERE conrelid = '%u'::pg_catalog.oid "
8423 " AND contype = 'c' "
8425 tbinfo->dobj.catId.oid);
8428 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8430 numConstrs = PQntuples(res);
8431 if (numConstrs != tbinfo->ncheck)
8433 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8434 "expected %d check constraints on table \"%s\" but found %d\n",
8436 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8437 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8441 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8442 tbinfo->checkexprs = constrs;
8444 for (j = 0; j < numConstrs; j++)
8446 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8448 constrs[j].dobj.objType = DO_CONSTRAINT;
8449 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8450 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8451 AssignDumpId(&constrs[j].dobj);
8452 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8453 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8454 constrs[j].contable = tbinfo;
8455 constrs[j].condomain = NULL;
8456 constrs[j].contype = 'c';
8457 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8458 constrs[j].confrelid = InvalidOid;
8459 constrs[j].conindex = 0;
8460 constrs[j].condeferrable = false;
8461 constrs[j].condeferred = false;
8462 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8465 * An unvalidated constraint needs to be dumped separately, so
8466 * that potentially-violating existing data is loaded before
8469 constrs[j].separate = !validated;
8471 constrs[j].dobj.dump = tbinfo->dobj.dump;
8474 * Mark the constraint as needing to appear before the table
8475 * --- this is so that any other dependencies of the
8476 * constraint will be emitted before we try to create the
8477 * table. If the constraint is to be dumped separately, it
8478 * will be dumped after data is loaded anyway, so don't do it.
8479 * (There's an automatic dependency in the opposite direction
8480 * anyway, so don't need to add one manually here.)
8482 if (!constrs[j].separate)
8483 addObjectDependency(&tbinfo->dobj,
8484 constrs[j].dobj.dumpId);
8487 * If the constraint is inherited, this will be detected later
8488 * (in pre-8.4 databases). We also detect later if the
8489 * constraint must be split out from the table definition.
8496 destroyPQExpBuffer(q);
8500 * Test whether a column should be printed as part of table's CREATE TABLE.
8501 * Column number is zero-based.
8503 * Normally this is always true, but it's false for dropped columns, as well
8504 * as those that were inherited without any local definition. (If we print
8505 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8506 * However, in binary_upgrade mode, we must print all such columns anyway and
8507 * fix the attislocal/attisdropped state later, so as to keep control of the
8508 * physical column order.
8510 * This function exists because there are scattered nonobvious places that
8511 * must be kept in sync with this decision.
8514 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8516 if (dopt->binary_upgrade)
8518 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8524 * read all text search parsers in the system catalogs and return them
8525 * in the TSParserInfo* structure
8527 * numTSParsers is set to the number of parsers read in
8530 getTSParsers(Archive *fout, int *numTSParsers)
8536 TSParserInfo *prsinfo;
8547 /* Before 8.3, there is no built-in text search support */
8548 if (fout->remoteVersion < 80300)
8554 query = createPQExpBuffer();
8557 * find all text search objects, including builtin ones; we filter out
8558 * system-defined objects at dump-out time.
8561 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8562 "prsstart::oid, prstoken::oid, "
8563 "prsend::oid, prsheadline::oid, prslextype::oid "
8564 "FROM pg_ts_parser");
8566 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8568 ntups = PQntuples(res);
8569 *numTSParsers = ntups;
8571 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8573 i_tableoid = PQfnumber(res, "tableoid");
8574 i_oid = PQfnumber(res, "oid");
8575 i_prsname = PQfnumber(res, "prsname");
8576 i_prsnamespace = PQfnumber(res, "prsnamespace");
8577 i_prsstart = PQfnumber(res, "prsstart");
8578 i_prstoken = PQfnumber(res, "prstoken");
8579 i_prsend = PQfnumber(res, "prsend");
8580 i_prsheadline = PQfnumber(res, "prsheadline");
8581 i_prslextype = PQfnumber(res, "prslextype");
8583 for (i = 0; i < ntups; i++)
8585 prsinfo[i].dobj.objType = DO_TSPARSER;
8586 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8587 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8588 AssignDumpId(&prsinfo[i].dobj);
8589 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8590 prsinfo[i].dobj.namespace =
8592 atooid(PQgetvalue(res, i, i_prsnamespace)));
8593 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8594 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8595 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8596 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8597 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8599 /* Decide whether we want to dump it */
8600 selectDumpableObject(&(prsinfo[i].dobj), fout);
8602 /* Text Search Parsers do not currently have ACLs. */
8603 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8608 destroyPQExpBuffer(query);
8614 * getTSDictionaries:
8615 * read all text search dictionaries in the system catalogs and return them
8616 * in the TSDictInfo* structure
8618 * numTSDicts is set to the number of dictionaries read in
8621 getTSDictionaries(Archive *fout, int *numTSDicts)
8627 TSDictInfo *dictinfo;
8631 int i_dictnamespace;
8634 int i_dictinitoption;
8636 /* Before 8.3, there is no built-in text search support */
8637 if (fout->remoteVersion < 80300)
8643 query = createPQExpBuffer();
8645 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8646 "dictnamespace, (%s dictowner) AS rolname, "
8647 "dicttemplate, dictinitoption "
8651 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8653 ntups = PQntuples(res);
8654 *numTSDicts = ntups;
8656 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8658 i_tableoid = PQfnumber(res, "tableoid");
8659 i_oid = PQfnumber(res, "oid");
8660 i_dictname = PQfnumber(res, "dictname");
8661 i_dictnamespace = PQfnumber(res, "dictnamespace");
8662 i_rolname = PQfnumber(res, "rolname");
8663 i_dictinitoption = PQfnumber(res, "dictinitoption");
8664 i_dicttemplate = PQfnumber(res, "dicttemplate");
8666 for (i = 0; i < ntups; i++)
8668 dictinfo[i].dobj.objType = DO_TSDICT;
8669 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8670 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8671 AssignDumpId(&dictinfo[i].dobj);
8672 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8673 dictinfo[i].dobj.namespace =
8675 atooid(PQgetvalue(res, i, i_dictnamespace)));
8676 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8677 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8678 if (PQgetisnull(res, i, i_dictinitoption))
8679 dictinfo[i].dictinitoption = NULL;
8681 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8683 /* Decide whether we want to dump it */
8684 selectDumpableObject(&(dictinfo[i].dobj), fout);
8686 /* Text Search Dictionaries do not currently have ACLs. */
8687 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8692 destroyPQExpBuffer(query);
8699 * read all text search templates in the system catalogs and return them
8700 * in the TSTemplateInfo* structure
8702 * numTSTemplates is set to the number of templates read in
8705 getTSTemplates(Archive *fout, int *numTSTemplates)
8711 TSTemplateInfo *tmplinfo;
8715 int i_tmplnamespace;
8719 /* Before 8.3, there is no built-in text search support */
8720 if (fout->remoteVersion < 80300)
8722 *numTSTemplates = 0;
8726 query = createPQExpBuffer();
8728 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8729 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8730 "FROM pg_ts_template");
8732 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8734 ntups = PQntuples(res);
8735 *numTSTemplates = ntups;
8737 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8739 i_tableoid = PQfnumber(res, "tableoid");
8740 i_oid = PQfnumber(res, "oid");
8741 i_tmplname = PQfnumber(res, "tmplname");
8742 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8743 i_tmplinit = PQfnumber(res, "tmplinit");
8744 i_tmpllexize = PQfnumber(res, "tmpllexize");
8746 for (i = 0; i < ntups; i++)
8748 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8749 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8750 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8751 AssignDumpId(&tmplinfo[i].dobj);
8752 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8753 tmplinfo[i].dobj.namespace =
8755 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8756 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8757 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8759 /* Decide whether we want to dump it */
8760 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8762 /* Text Search Templates do not currently have ACLs. */
8763 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8768 destroyPQExpBuffer(query);
8774 * getTSConfigurations:
8775 * read all text search configurations in the system catalogs and return
8776 * them in the TSConfigInfo* structure
8778 * numTSConfigs is set to the number of configurations read in
8781 getTSConfigurations(Archive *fout, int *numTSConfigs)
8787 TSConfigInfo *cfginfo;
8795 /* Before 8.3, there is no built-in text search support */
8796 if (fout->remoteVersion < 80300)
8802 query = createPQExpBuffer();
8804 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8805 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8806 "FROM pg_ts_config",
8809 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8811 ntups = PQntuples(res);
8812 *numTSConfigs = ntups;
8814 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8816 i_tableoid = PQfnumber(res, "tableoid");
8817 i_oid = PQfnumber(res, "oid");
8818 i_cfgname = PQfnumber(res, "cfgname");
8819 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8820 i_rolname = PQfnumber(res, "rolname");
8821 i_cfgparser = PQfnumber(res, "cfgparser");
8823 for (i = 0; i < ntups; i++)
8825 cfginfo[i].dobj.objType = DO_TSCONFIG;
8826 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8827 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8828 AssignDumpId(&cfginfo[i].dobj);
8829 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8830 cfginfo[i].dobj.namespace =
8832 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8833 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8834 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8836 /* Decide whether we want to dump it */
8837 selectDumpableObject(&(cfginfo[i].dobj), fout);
8839 /* Text Search Configurations do not currently have ACLs. */
8840 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8845 destroyPQExpBuffer(query);
8851 * getForeignDataWrappers:
8852 * read all foreign-data wrappers in the system catalogs and return
8853 * them in the FdwInfo* structure
8855 * numForeignDataWrappers is set to the number of fdws read in
8858 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8860 DumpOptions *dopt = fout->dopt;
8878 /* Before 8.4, there are no foreign-data wrappers */
8879 if (fout->remoteVersion < 80400)
8881 *numForeignDataWrappers = 0;
8885 query = createPQExpBuffer();
8887 if (fout->remoteVersion >= 90600)
8889 PQExpBuffer acl_subquery = createPQExpBuffer();
8890 PQExpBuffer racl_subquery = createPQExpBuffer();
8891 PQExpBuffer initacl_subquery = createPQExpBuffer();
8892 PQExpBuffer initracl_subquery = createPQExpBuffer();
8894 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8895 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8896 dopt->binary_upgrade);
8898 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8899 "(%s f.fdwowner) AS rolname, "
8900 "f.fdwhandler::pg_catalog.regproc, "
8901 "f.fdwvalidator::pg_catalog.regproc, "
8904 "%s AS initfdwacl, "
8905 "%s AS initrfdwacl, "
8906 "array_to_string(ARRAY("
8907 "SELECT quote_ident(option_name) || ' ' || "
8908 "quote_literal(option_value) "
8909 "FROM pg_options_to_table(f.fdwoptions) "
8910 "ORDER BY option_name"
8911 "), E',\n ') AS fdwoptions "
8912 "FROM pg_foreign_data_wrapper f "
8913 "LEFT JOIN pg_init_privs pip ON "
8914 "(f.oid = pip.objoid "
8915 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8916 "AND pip.objsubid = 0) ",
8919 racl_subquery->data,
8920 initacl_subquery->data,
8921 initracl_subquery->data);
8923 destroyPQExpBuffer(acl_subquery);
8924 destroyPQExpBuffer(racl_subquery);
8925 destroyPQExpBuffer(initacl_subquery);
8926 destroyPQExpBuffer(initracl_subquery);
8928 else if (fout->remoteVersion >= 90100)
8930 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8931 "(%s fdwowner) AS rolname, "
8932 "fdwhandler::pg_catalog.regproc, "
8933 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8935 "NULL as initfdwacl, NULL AS initrfdwacl, "
8936 "array_to_string(ARRAY("
8937 "SELECT quote_ident(option_name) || ' ' || "
8938 "quote_literal(option_value) "
8939 "FROM pg_options_to_table(fdwoptions) "
8940 "ORDER BY option_name"
8941 "), E',\n ') AS fdwoptions "
8942 "FROM pg_foreign_data_wrapper",
8947 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8948 "(%s fdwowner) AS rolname, "
8949 "'-' AS fdwhandler, "
8950 "fdwvalidator::pg_catalog.regproc, fdwacl, "
8952 "NULL as initfdwacl, NULL AS initrfdwacl, "
8953 "array_to_string(ARRAY("
8954 "SELECT quote_ident(option_name) || ' ' || "
8955 "quote_literal(option_value) "
8956 "FROM pg_options_to_table(fdwoptions) "
8957 "ORDER BY option_name"
8958 "), E',\n ') AS fdwoptions "
8959 "FROM pg_foreign_data_wrapper",
8963 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8965 ntups = PQntuples(res);
8966 *numForeignDataWrappers = ntups;
8968 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
8970 i_tableoid = PQfnumber(res, "tableoid");
8971 i_oid = PQfnumber(res, "oid");
8972 i_fdwname = PQfnumber(res, "fdwname");
8973 i_rolname = PQfnumber(res, "rolname");
8974 i_fdwhandler = PQfnumber(res, "fdwhandler");
8975 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
8976 i_fdwacl = PQfnumber(res, "fdwacl");
8977 i_rfdwacl = PQfnumber(res, "rfdwacl");
8978 i_initfdwacl = PQfnumber(res, "initfdwacl");
8979 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
8980 i_fdwoptions = PQfnumber(res, "fdwoptions");
8982 for (i = 0; i < ntups; i++)
8984 fdwinfo[i].dobj.objType = DO_FDW;
8985 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8986 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8987 AssignDumpId(&fdwinfo[i].dobj);
8988 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
8989 fdwinfo[i].dobj.namespace = NULL;
8990 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8991 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
8992 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
8993 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
8994 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
8995 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
8996 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
8997 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
8999 /* Decide whether we want to dump it */
9000 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9002 /* Do not try to dump ACL if no ACL exists. */
9003 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9004 PQgetisnull(res, i, i_initfdwacl) &&
9005 PQgetisnull(res, i, i_initrfdwacl))
9006 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9011 destroyPQExpBuffer(query);
9017 * getForeignServers:
9018 * read all foreign servers in the system catalogs and return
9019 * them in the ForeignServerInfo * structure
9021 * numForeignServers is set to the number of servers read in
9024 getForeignServers(Archive *fout, int *numForeignServers)
9026 DumpOptions *dopt = fout->dopt;
9031 ForeignServerInfo *srvinfo;
9045 /* Before 8.4, there are no foreign servers */
9046 if (fout->remoteVersion < 80400)
9048 *numForeignServers = 0;
9052 query = createPQExpBuffer();
9054 if (fout->remoteVersion >= 90600)
9056 PQExpBuffer acl_subquery = createPQExpBuffer();
9057 PQExpBuffer racl_subquery = createPQExpBuffer();
9058 PQExpBuffer initacl_subquery = createPQExpBuffer();
9059 PQExpBuffer initracl_subquery = createPQExpBuffer();
9061 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9062 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9063 dopt->binary_upgrade);
9065 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9066 "(%s f.srvowner) AS rolname, "
9067 "f.srvfdw, f.srvtype, f.srvversion, "
9070 "%s AS initsrvacl, "
9071 "%s AS initrsrvacl, "
9072 "array_to_string(ARRAY("
9073 "SELECT quote_ident(option_name) || ' ' || "
9074 "quote_literal(option_value) "
9075 "FROM pg_options_to_table(f.srvoptions) "
9076 "ORDER BY option_name"
9077 "), E',\n ') AS srvoptions "
9078 "FROM pg_foreign_server f "
9079 "LEFT JOIN pg_init_privs pip "
9080 "ON (f.oid = pip.objoid "
9081 "AND pip.classoid = 'pg_foreign_server'::regclass "
9082 "AND pip.objsubid = 0) ",
9085 racl_subquery->data,
9086 initacl_subquery->data,
9087 initracl_subquery->data);
9089 destroyPQExpBuffer(acl_subquery);
9090 destroyPQExpBuffer(racl_subquery);
9091 destroyPQExpBuffer(initacl_subquery);
9092 destroyPQExpBuffer(initracl_subquery);
9096 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9097 "(%s srvowner) AS rolname, "
9098 "srvfdw, srvtype, srvversion, srvacl, "
9100 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9101 "array_to_string(ARRAY("
9102 "SELECT quote_ident(option_name) || ' ' || "
9103 "quote_literal(option_value) "
9104 "FROM pg_options_to_table(srvoptions) "
9105 "ORDER BY option_name"
9106 "), E',\n ') AS srvoptions "
9107 "FROM pg_foreign_server",
9111 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9113 ntups = PQntuples(res);
9114 *numForeignServers = ntups;
9116 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9118 i_tableoid = PQfnumber(res, "tableoid");
9119 i_oid = PQfnumber(res, "oid");
9120 i_srvname = PQfnumber(res, "srvname");
9121 i_rolname = PQfnumber(res, "rolname");
9122 i_srvfdw = PQfnumber(res, "srvfdw");
9123 i_srvtype = PQfnumber(res, "srvtype");
9124 i_srvversion = PQfnumber(res, "srvversion");
9125 i_srvacl = PQfnumber(res, "srvacl");
9126 i_rsrvacl = PQfnumber(res, "rsrvacl");
9127 i_initsrvacl = PQfnumber(res, "initsrvacl");
9128 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9129 i_srvoptions = PQfnumber(res, "srvoptions");
9131 for (i = 0; i < ntups; i++)
9133 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9134 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9135 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9136 AssignDumpId(&srvinfo[i].dobj);
9137 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9138 srvinfo[i].dobj.namespace = NULL;
9139 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9140 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9141 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9142 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9143 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9144 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9145 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9146 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9147 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9149 /* Decide whether we want to dump it */
9150 selectDumpableObject(&(srvinfo[i].dobj), fout);
9152 /* Do not try to dump ACL if no ACL exists. */
9153 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9154 PQgetisnull(res, i, i_initsrvacl) &&
9155 PQgetisnull(res, i, i_initrsrvacl))
9156 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9161 destroyPQExpBuffer(query);
9168 * read all default ACL information in the system catalogs and return
9169 * them in the DefaultACLInfo structure
9171 * numDefaultACLs is set to the number of ACLs read in
9174 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9176 DumpOptions *dopt = fout->dopt;
9177 DefaultACLInfo *daclinfo;
9183 int i_defaclnamespace;
9184 int i_defaclobjtype;
9187 int i_initdefaclacl;
9188 int i_initrdefaclacl;
9192 if (fout->remoteVersion < 90000)
9194 *numDefaultACLs = 0;
9198 query = createPQExpBuffer();
9200 if (fout->remoteVersion >= 90600)
9202 PQExpBuffer acl_subquery = createPQExpBuffer();
9203 PQExpBuffer racl_subquery = createPQExpBuffer();
9204 PQExpBuffer initacl_subquery = createPQExpBuffer();
9205 PQExpBuffer initracl_subquery = createPQExpBuffer();
9207 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9208 initracl_subquery, "defaclacl", "defaclrole",
9209 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9210 dopt->binary_upgrade);
9212 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9213 "(%s d.defaclrole) AS defaclrole, "
9214 "d.defaclnamespace, "
9217 "%s AS rdefaclacl, "
9218 "%s AS initdefaclacl, "
9219 "%s AS initrdefaclacl "
9220 "FROM pg_default_acl d "
9221 "LEFT JOIN pg_init_privs pip ON "
9222 "(d.oid = pip.objoid "
9223 "AND pip.classoid = 'pg_default_acl'::regclass "
9224 "AND pip.objsubid = 0) ",
9227 racl_subquery->data,
9228 initacl_subquery->data,
9229 initracl_subquery->data);
9233 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9234 "(%s defaclrole) AS defaclrole, "
9238 "NULL AS rdefaclacl, "
9239 "NULL AS initdefaclacl, "
9240 "NULL AS initrdefaclacl "
9241 "FROM pg_default_acl",
9245 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9247 ntups = PQntuples(res);
9248 *numDefaultACLs = ntups;
9250 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9252 i_oid = PQfnumber(res, "oid");
9253 i_tableoid = PQfnumber(res, "tableoid");
9254 i_defaclrole = PQfnumber(res, "defaclrole");
9255 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9256 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9257 i_defaclacl = PQfnumber(res, "defaclacl");
9258 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9259 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9260 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9262 for (i = 0; i < ntups; i++)
9264 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9266 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9267 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9268 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9269 AssignDumpId(&daclinfo[i].dobj);
9270 /* cheesy ... is it worth coming up with a better object name? */
9271 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9273 if (nspid != InvalidOid)
9274 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9276 daclinfo[i].dobj.namespace = NULL;
9278 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9279 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9280 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9281 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9282 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9283 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9285 /* Decide whether we want to dump it */
9286 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9291 destroyPQExpBuffer(query);
9299 * This routine is used to dump any comments associated with the
9300 * object handed to this routine. The routine takes the object type
9301 * and object name (ready to print, except for schema decoration), plus
9302 * the namespace and owner of the object (for labeling the ArchiveEntry),
9303 * plus catalog ID and subid which are the lookup key for pg_description,
9304 * plus the dump ID for the object (for setting a dependency).
9305 * If a matching pg_description entry is found, it is dumped.
9307 * Note: in some cases, such as comments for triggers and rules, the "type"
9308 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9309 * but it doesn't seem worth complicating the API for all callers to make
9312 * Note: although this routine takes a dumpId for dependency purposes,
9313 * that purpose is just to mark the dependency in the emitted dump file
9314 * for possible future use by pg_restore. We do NOT use it for determining
9315 * ordering of the comment in the dump file, because this routine is called
9316 * after dependency sorting occurs. This routine should be called just after
9317 * calling ArchiveEntry() for the specified object.
9320 dumpComment(Archive *fout, const char *type, const char *name,
9321 const char *namespace, const char *owner,
9322 CatalogId catalogId, int subid, DumpId dumpId)
9324 DumpOptions *dopt = fout->dopt;
9325 CommentItem *comments;
9328 /* do nothing, if --no-comments is supplied */
9329 if (dopt->no_comments)
9332 /* Comments are schema not data ... except blob comments are data */
9333 if (strcmp(type, "LARGE OBJECT") != 0)
9340 /* We do dump blob comments in binary-upgrade mode */
9341 if (dopt->schemaOnly && !dopt->binary_upgrade)
9345 /* Search for comments associated with catalogId, using table */
9346 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9349 /* Is there one matching the subid? */
9350 while (ncomments > 0)
9352 if (comments->objsubid == subid)
9358 /* If a comment exists, build COMMENT ON statement */
9361 PQExpBuffer query = createPQExpBuffer();
9362 PQExpBuffer tag = createPQExpBuffer();
9364 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9365 if (namespace && *namespace)
9366 appendPQExpBuffer(query, "%s.", fmtId(namespace));
9367 appendPQExpBuffer(query, "%s IS ", name);
9368 appendStringLiteralAH(query, comments->descr, fout);
9369 appendPQExpBufferStr(query, ";\n");
9371 appendPQExpBuffer(tag, "%s %s", type, name);
9374 * We mark comments as SECTION_NONE because they really belong in the
9375 * same section as their parent, whether that is pre-data or
9378 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9379 tag->data, namespace, NULL, owner,
9380 false, "COMMENT", SECTION_NONE,
9381 query->data, "", NULL,
9385 destroyPQExpBuffer(query);
9386 destroyPQExpBuffer(tag);
9391 * dumpTableComment --
9393 * As above, but dump comments for both the specified table (or view)
9397 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9398 const char *reltypename)
9400 DumpOptions *dopt = fout->dopt;
9401 CommentItem *comments;
9406 /* do nothing, if --no-comments is supplied */
9407 if (dopt->no_comments)
9410 /* Comments are SCHEMA not data */
9414 /* Search for comments associated with relation, using table */
9415 ncomments = findComments(fout,
9416 tbinfo->dobj.catId.tableoid,
9417 tbinfo->dobj.catId.oid,
9420 /* If comments exist, build COMMENT ON statements */
9424 query = createPQExpBuffer();
9425 tag = createPQExpBuffer();
9427 while (ncomments > 0)
9429 const char *descr = comments->descr;
9430 int objsubid = comments->objsubid;
9434 resetPQExpBuffer(tag);
9435 appendPQExpBuffer(tag, "%s %s", reltypename,
9436 fmtId(tbinfo->dobj.name));
9438 resetPQExpBuffer(query);
9439 appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9440 fmtQualifiedDumpable(tbinfo));
9441 appendStringLiteralAH(query, descr, fout);
9442 appendPQExpBufferStr(query, ";\n");
9444 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9446 tbinfo->dobj.namespace->dobj.name,
9447 NULL, tbinfo->rolname,
9448 false, "COMMENT", SECTION_NONE,
9449 query->data, "", NULL,
9450 &(tbinfo->dobj.dumpId), 1,
9453 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9455 resetPQExpBuffer(tag);
9456 appendPQExpBuffer(tag, "COLUMN %s.",
9457 fmtId(tbinfo->dobj.name));
9458 appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9460 resetPQExpBuffer(query);
9461 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9462 fmtQualifiedDumpable(tbinfo));
9463 appendPQExpBuffer(query, "%s IS ",
9464 fmtId(tbinfo->attnames[objsubid - 1]));
9465 appendStringLiteralAH(query, descr, fout);
9466 appendPQExpBufferStr(query, ";\n");
9468 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9470 tbinfo->dobj.namespace->dobj.name,
9471 NULL, tbinfo->rolname,
9472 false, "COMMENT", SECTION_NONE,
9473 query->data, "", NULL,
9474 &(tbinfo->dobj.dumpId), 1,
9482 destroyPQExpBuffer(query);
9483 destroyPQExpBuffer(tag);
9489 * Find the comment(s), if any, associated with the given object. All the
9490 * objsubid values associated with the given classoid/objoid are found with
9494 findComments(Archive *fout, Oid classoid, Oid objoid,
9495 CommentItem **items)
9497 /* static storage for table of comments */
9498 static CommentItem *comments = NULL;
9499 static int ncomments = -1;
9501 CommentItem *middle = NULL;
9506 /* Get comments if we didn't already */
9508 ncomments = collectComments(fout, &comments);
9511 * Do binary search to find some item matching the object.
9514 high = &comments[ncomments - 1];
9517 middle = low + (high - low) / 2;
9519 if (classoid < middle->classoid)
9521 else if (classoid > middle->classoid)
9523 else if (objoid < middle->objoid)
9525 else if (objoid > middle->objoid)
9528 break; /* found a match */
9531 if (low > high) /* no matches */
9538 * Now determine how many items match the object. The search loop
9539 * invariant still holds: only items between low and high inclusive could
9543 while (middle > low)
9545 if (classoid != middle[-1].classoid ||
9546 objoid != middle[-1].objoid)
9555 while (middle <= high)
9557 if (classoid != middle->classoid ||
9558 objoid != middle->objoid)
9568 * collectComments --
9570 * Construct a table of all comments available for database objects.
9571 * We used to do per-object queries for the comments, but it's much faster
9572 * to pull them all over at once, and on most databases the memory cost
9575 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9578 collectComments(Archive *fout, CommentItem **items)
9588 CommentItem *comments;
9590 query = createPQExpBuffer();
9592 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9593 "FROM pg_catalog.pg_description "
9594 "ORDER BY classoid, objoid, objsubid");
9596 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9598 /* Construct lookup table containing OIDs in numeric form */
9600 i_description = PQfnumber(res, "description");
9601 i_classoid = PQfnumber(res, "classoid");
9602 i_objoid = PQfnumber(res, "objoid");
9603 i_objsubid = PQfnumber(res, "objsubid");
9605 ntups = PQntuples(res);
9607 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9609 for (i = 0; i < ntups; i++)
9611 comments[i].descr = PQgetvalue(res, i, i_description);
9612 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9613 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9614 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9617 /* Do NOT free the PGresult since we are keeping pointers into it */
9618 destroyPQExpBuffer(query);
9625 * dumpDumpableObject
9627 * This routine and its subsidiaries are responsible for creating
9628 * ArchiveEntries (TOC objects) for each object to be dumped.
9631 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9633 switch (dobj->objType)
9636 dumpNamespace(fout, (NamespaceInfo *) dobj);
9639 dumpExtension(fout, (ExtensionInfo *) dobj);
9642 dumpType(fout, (TypeInfo *) dobj);
9645 dumpShellType(fout, (ShellTypeInfo *) dobj);
9648 dumpFunc(fout, (FuncInfo *) dobj);
9651 dumpAgg(fout, (AggInfo *) dobj);
9654 dumpOpr(fout, (OprInfo *) dobj);
9656 case DO_ACCESS_METHOD:
9657 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9660 dumpOpclass(fout, (OpclassInfo *) dobj);
9663 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9666 dumpCollation(fout, (CollInfo *) dobj);
9669 dumpConversion(fout, (ConvInfo *) dobj);
9672 dumpTable(fout, (TableInfo *) dobj);
9675 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9678 dumpIndex(fout, (IndxInfo *) dobj);
9680 case DO_INDEX_ATTACH:
9681 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9684 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9686 case DO_REFRESH_MATVIEW:
9687 refreshMatViewData(fout, (TableDataInfo *) dobj);
9690 dumpRule(fout, (RuleInfo *) dobj);
9693 dumpTrigger(fout, (TriggerInfo *) dobj);
9695 case DO_EVENT_TRIGGER:
9696 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9699 dumpConstraint(fout, (ConstraintInfo *) dobj);
9701 case DO_FK_CONSTRAINT:
9702 dumpConstraint(fout, (ConstraintInfo *) dobj);
9705 dumpProcLang(fout, (ProcLangInfo *) dobj);
9708 dumpCast(fout, (CastInfo *) dobj);
9711 dumpTransform(fout, (TransformInfo *) dobj);
9713 case DO_SEQUENCE_SET:
9714 dumpSequenceData(fout, (TableDataInfo *) dobj);
9717 dumpTableData(fout, (TableDataInfo *) dobj);
9720 /* table rowtypes and array types are never dumped separately */
9723 dumpTSParser(fout, (TSParserInfo *) dobj);
9726 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9729 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9732 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9735 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9737 case DO_FOREIGN_SERVER:
9738 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9740 case DO_DEFAULT_ACL:
9741 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9744 dumpBlob(fout, (BlobInfo *) dobj);
9747 if (dobj->dump & DUMP_COMPONENT_DATA)
9748 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9749 dobj->name, NULL, NULL, "",
9750 false, "BLOBS", SECTION_DATA,
9756 dumpPolicy(fout, (PolicyInfo *) dobj);
9758 case DO_PUBLICATION:
9759 dumpPublication(fout, (PublicationInfo *) dobj);
9761 case DO_PUBLICATION_REL:
9762 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9764 case DO_SUBSCRIPTION:
9765 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9767 case DO_PRE_DATA_BOUNDARY:
9768 case DO_POST_DATA_BOUNDARY:
9769 /* never dumped, nothing to do */
9776 * writes out to fout the queries to recreate a user-defined namespace
9779 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9781 DumpOptions *dopt = fout->dopt;
9786 /* Skip if not to be dumped */
9787 if (!nspinfo->dobj.dump || dopt->dataOnly)
9790 q = createPQExpBuffer();
9791 delq = createPQExpBuffer();
9793 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9795 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9797 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9799 if (dopt->binary_upgrade)
9800 binary_upgrade_extension_member(q, &nspinfo->dobj,
9801 "SCHEMA", qnspname, NULL);
9803 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9804 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9808 false, "SCHEMA", SECTION_PRE_DATA,
9809 q->data, delq->data, NULL,
9813 /* Dump Schema Comments and Security Labels */
9814 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9815 dumpComment(fout, "SCHEMA", qnspname,
9816 NULL, nspinfo->rolname,
9817 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9819 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9820 dumpSecLabel(fout, "SCHEMA", qnspname,
9821 NULL, nspinfo->rolname,
9822 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9824 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9825 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9826 qnspname, NULL, NULL,
9827 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9828 nspinfo->initnspacl, nspinfo->initrnspacl);
9832 destroyPQExpBuffer(q);
9833 destroyPQExpBuffer(delq);
9838 * writes out to fout the queries to recreate an extension
9841 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9843 DumpOptions *dopt = fout->dopt;
9848 /* Skip if not to be dumped */
9849 if (!extinfo->dobj.dump || dopt->dataOnly)
9852 q = createPQExpBuffer();
9853 delq = createPQExpBuffer();
9855 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9857 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9859 if (!dopt->binary_upgrade)
9862 * In a regular dump, we simply create the extension, intentionally
9863 * not specifying a version, so that the destination installation's
9864 * default version is used.
9866 * Use of IF NOT EXISTS here is unlike our behavior for other object
9867 * types; but there are various scenarios in which it's convenient to
9868 * manually create the desired extension before restoring, so we
9869 * prefer to allow it to exist already.
9871 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9872 qextname, fmtId(extinfo->namespace));
9877 * In binary-upgrade mode, it's critical to reproduce the state of the
9878 * database exactly, so our procedure is to create an empty extension,
9879 * restore all the contained objects normally, and add them to the
9880 * extension one by one. This function performs just the first of
9881 * those steps. binary_upgrade_extension_member() takes care of
9882 * adding member objects as they're created.
9887 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9890 * We unconditionally create the extension, so we must drop it if it
9891 * exists. This could happen if the user deleted 'plpgsql' and then
9892 * readded it, causing its oid to be greater than g_last_builtin_oid.
9894 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9896 appendPQExpBufferStr(q,
9897 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9898 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9899 appendPQExpBufferStr(q, ", ");
9900 appendStringLiteralAH(q, extinfo->namespace, fout);
9901 appendPQExpBufferStr(q, ", ");
9902 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9903 appendStringLiteralAH(q, extinfo->extversion, fout);
9904 appendPQExpBufferStr(q, ", ");
9907 * Note that we're pushing extconfig (an OID array) back into
9908 * pg_extension exactly as-is. This is OK because pg_class OIDs are
9909 * preserved in binary upgrade.
9911 if (strlen(extinfo->extconfig) > 2)
9912 appendStringLiteralAH(q, extinfo->extconfig, fout);
9914 appendPQExpBufferStr(q, "NULL");
9915 appendPQExpBufferStr(q, ", ");
9916 if (strlen(extinfo->extcondition) > 2)
9917 appendStringLiteralAH(q, extinfo->extcondition, fout);
9919 appendPQExpBufferStr(q, "NULL");
9920 appendPQExpBufferStr(q, ", ");
9921 appendPQExpBufferStr(q, "ARRAY[");
9923 for (i = 0; i < extinfo->dobj.nDeps; i++)
9925 DumpableObject *extobj;
9927 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9928 if (extobj && extobj->objType == DO_EXTENSION)
9931 appendPQExpBufferChar(q, ',');
9932 appendStringLiteralAH(q, extobj->name, fout);
9935 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
9936 appendPQExpBufferStr(q, ");\n");
9939 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9940 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
9944 false, "EXTENSION", SECTION_PRE_DATA,
9945 q->data, delq->data, NULL,
9949 /* Dump Extension Comments and Security Labels */
9950 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9951 dumpComment(fout, "EXTENSION", qextname,
9953 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9955 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9956 dumpSecLabel(fout, "EXTENSION", qextname,
9958 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9962 destroyPQExpBuffer(q);
9963 destroyPQExpBuffer(delq);
9968 * writes out to fout the queries to recreate a user-defined type
9971 dumpType(Archive *fout, TypeInfo *tyinfo)
9973 DumpOptions *dopt = fout->dopt;
9975 /* Skip if not to be dumped */
9976 if (!tyinfo->dobj.dump || dopt->dataOnly)
9979 /* Dump out in proper style */
9980 if (tyinfo->typtype == TYPTYPE_BASE)
9981 dumpBaseType(fout, tyinfo);
9982 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
9983 dumpDomain(fout, tyinfo);
9984 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
9985 dumpCompositeType(fout, tyinfo);
9986 else if (tyinfo->typtype == TYPTYPE_ENUM)
9987 dumpEnumType(fout, tyinfo);
9988 else if (tyinfo->typtype == TYPTYPE_RANGE)
9989 dumpRangeType(fout, tyinfo);
9990 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
9991 dumpUndefinedType(fout, tyinfo);
9993 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
9999 * writes out to fout the queries to recreate a user-defined enum type
10002 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10004 DumpOptions *dopt = fout->dopt;
10005 PQExpBuffer q = createPQExpBuffer();
10006 PQExpBuffer delq = createPQExpBuffer();
10007 PQExpBuffer query = createPQExpBuffer();
10016 if (fout->remoteVersion >= 90100)
10017 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10018 "FROM pg_catalog.pg_enum "
10019 "WHERE enumtypid = '%u'"
10020 "ORDER BY enumsortorder",
10021 tyinfo->dobj.catId.oid);
10023 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10024 "FROM pg_catalog.pg_enum "
10025 "WHERE enumtypid = '%u'"
10027 tyinfo->dobj.catId.oid);
10029 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10031 num = PQntuples(res);
10033 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10034 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10037 * CASCADE shouldn't be required here as for normal types since the I/O
10038 * functions are generic and do not get dropped.
10040 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10042 if (dopt->binary_upgrade)
10043 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10044 tyinfo->dobj.catId.oid,
10047 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10050 if (!dopt->binary_upgrade)
10052 /* Labels with server-assigned oids */
10053 for (i = 0; i < num; i++)
10055 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10057 appendPQExpBufferChar(q, ',');
10058 appendPQExpBufferStr(q, "\n ");
10059 appendStringLiteralAH(q, label, fout);
10063 appendPQExpBufferStr(q, "\n);\n");
10065 if (dopt->binary_upgrade)
10067 /* Labels with dump-assigned (preserved) oids */
10068 for (i = 0; i < num; i++)
10070 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10071 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10074 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10075 appendPQExpBuffer(q,
10076 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10078 appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10079 appendStringLiteralAH(q, label, fout);
10080 appendPQExpBufferStr(q, ";\n\n");
10084 if (dopt->binary_upgrade)
10085 binary_upgrade_extension_member(q, &tyinfo->dobj,
10087 tyinfo->dobj.namespace->dobj.name);
10089 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10090 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10092 tyinfo->dobj.namespace->dobj.name,
10094 tyinfo->rolname, false,
10095 "TYPE", SECTION_PRE_DATA,
10096 q->data, delq->data, NULL,
10100 /* Dump Type Comments and Security Labels */
10101 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10102 dumpComment(fout, "TYPE", qtypname,
10103 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10104 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10106 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10107 dumpSecLabel(fout, "TYPE", qtypname,
10108 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10109 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10111 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10112 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10114 tyinfo->dobj.namespace->dobj.name,
10115 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10116 tyinfo->inittypacl, tyinfo->initrtypacl);
10119 destroyPQExpBuffer(q);
10120 destroyPQExpBuffer(delq);
10121 destroyPQExpBuffer(query);
10128 * writes out to fout the queries to recreate a user-defined range type
10131 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10133 DumpOptions *dopt = fout->dopt;
10134 PQExpBuffer q = createPQExpBuffer();
10135 PQExpBuffer delq = createPQExpBuffer();
10136 PQExpBuffer query = createPQExpBuffer();
10143 appendPQExpBuffer(query,
10144 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10145 "opc.opcname AS opcname, "
10146 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10147 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10149 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10150 " ELSE rngcollation END AS collation, "
10151 "rngcanonical, rngsubdiff "
10152 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10153 " pg_catalog.pg_opclass opc "
10154 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10156 tyinfo->dobj.catId.oid);
10158 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10160 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10161 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10164 * CASCADE shouldn't be required here as for normal types since the I/O
10165 * functions are generic and do not get dropped.
10167 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10169 if (dopt->binary_upgrade)
10170 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10171 tyinfo->dobj.catId.oid,
10174 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10177 appendPQExpBuffer(q, "\n subtype = %s",
10178 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10180 /* print subtype_opclass only if not default for subtype */
10181 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10183 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10184 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10186 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10188 appendPQExpBufferStr(q, fmtId(opcname));
10191 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10192 if (OidIsValid(collationOid))
10194 CollInfo *coll = findCollationByOid(collationOid);
10197 appendPQExpBuffer(q, ",\n collation = %s",
10198 fmtQualifiedDumpable(coll));
10201 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10202 if (strcmp(procname, "-") != 0)
10203 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10205 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10206 if (strcmp(procname, "-") != 0)
10207 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10209 appendPQExpBufferStr(q, "\n);\n");
10211 if (dopt->binary_upgrade)
10212 binary_upgrade_extension_member(q, &tyinfo->dobj,
10214 tyinfo->dobj.namespace->dobj.name);
10216 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10217 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10219 tyinfo->dobj.namespace->dobj.name,
10221 tyinfo->rolname, false,
10222 "TYPE", SECTION_PRE_DATA,
10223 q->data, delq->data, NULL,
10227 /* Dump Type Comments and Security Labels */
10228 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10229 dumpComment(fout, "TYPE", qtypname,
10230 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10231 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10233 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10234 dumpSecLabel(fout, "TYPE", qtypname,
10235 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10236 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10238 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10239 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10241 tyinfo->dobj.namespace->dobj.name,
10242 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10243 tyinfo->inittypacl, tyinfo->initrtypacl);
10246 destroyPQExpBuffer(q);
10247 destroyPQExpBuffer(delq);
10248 destroyPQExpBuffer(query);
10254 * dumpUndefinedType
10255 * writes out to fout the queries to recreate a !typisdefined type
10257 * This is a shell type, but we use different terminology to distinguish
10258 * this case from where we have to emit a shell type definition to break
10259 * circular dependencies. An undefined type shouldn't ever have anything
10263 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10265 DumpOptions *dopt = fout->dopt;
10266 PQExpBuffer q = createPQExpBuffer();
10267 PQExpBuffer delq = createPQExpBuffer();
10271 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10272 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10274 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10276 if (dopt->binary_upgrade)
10277 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10278 tyinfo->dobj.catId.oid,
10281 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10284 if (dopt->binary_upgrade)
10285 binary_upgrade_extension_member(q, &tyinfo->dobj,
10287 tyinfo->dobj.namespace->dobj.name);
10289 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10290 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10292 tyinfo->dobj.namespace->dobj.name,
10294 tyinfo->rolname, false,
10295 "TYPE", SECTION_PRE_DATA,
10296 q->data, delq->data, NULL,
10300 /* Dump Type Comments and Security Labels */
10301 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10302 dumpComment(fout, "TYPE", qtypname,
10303 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10304 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10306 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10307 dumpSecLabel(fout, "TYPE", qtypname,
10308 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10309 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10311 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10312 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10314 tyinfo->dobj.namespace->dobj.name,
10315 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10316 tyinfo->inittypacl, tyinfo->initrtypacl);
10318 destroyPQExpBuffer(q);
10319 destroyPQExpBuffer(delq);
10326 * writes out to fout the queries to recreate a user-defined base type
10329 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10331 DumpOptions *dopt = fout->dopt;
10332 PQExpBuffer q = createPQExpBuffer();
10333 PQExpBuffer delq = createPQExpBuffer();
10334 PQExpBuffer query = createPQExpBuffer();
10352 char *typispreferred;
10357 char *typcollatable;
10359 bool typdefault_is_literal = false;
10361 /* Fetch type-specific details */
10362 if (fout->remoteVersion >= 90100)
10364 appendPQExpBuffer(query, "SELECT typlen, "
10365 "typinput, typoutput, typreceive, typsend, "
10366 "typmodin, typmodout, typanalyze, "
10367 "typreceive::pg_catalog.oid AS typreceiveoid, "
10368 "typsend::pg_catalog.oid AS typsendoid, "
10369 "typmodin::pg_catalog.oid AS typmodinoid, "
10370 "typmodout::pg_catalog.oid AS typmodoutoid, "
10371 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10372 "typcategory, typispreferred, "
10373 "typdelim, typbyval, typalign, typstorage, "
10374 "(typcollation <> 0) AS typcollatable, "
10375 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10376 "FROM pg_catalog.pg_type "
10377 "WHERE oid = '%u'::pg_catalog.oid",
10378 tyinfo->dobj.catId.oid);
10380 else if (fout->remoteVersion >= 80400)
10382 appendPQExpBuffer(query, "SELECT typlen, "
10383 "typinput, typoutput, typreceive, typsend, "
10384 "typmodin, typmodout, typanalyze, "
10385 "typreceive::pg_catalog.oid AS typreceiveoid, "
10386 "typsend::pg_catalog.oid AS typsendoid, "
10387 "typmodin::pg_catalog.oid AS typmodinoid, "
10388 "typmodout::pg_catalog.oid AS typmodoutoid, "
10389 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10390 "typcategory, typispreferred, "
10391 "typdelim, typbyval, typalign, typstorage, "
10392 "false AS typcollatable, "
10393 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10394 "FROM pg_catalog.pg_type "
10395 "WHERE oid = '%u'::pg_catalog.oid",
10396 tyinfo->dobj.catId.oid);
10398 else if (fout->remoteVersion >= 80300)
10400 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10401 appendPQExpBuffer(query, "SELECT typlen, "
10402 "typinput, typoutput, typreceive, typsend, "
10403 "typmodin, typmodout, typanalyze, "
10404 "typreceive::pg_catalog.oid AS typreceiveoid, "
10405 "typsend::pg_catalog.oid AS typsendoid, "
10406 "typmodin::pg_catalog.oid AS typmodinoid, "
10407 "typmodout::pg_catalog.oid AS typmodoutoid, "
10408 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10409 "'U' AS typcategory, false AS typispreferred, "
10410 "typdelim, typbyval, typalign, typstorage, "
10411 "false AS typcollatable, "
10412 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10413 "FROM pg_catalog.pg_type "
10414 "WHERE oid = '%u'::pg_catalog.oid",
10415 tyinfo->dobj.catId.oid);
10419 appendPQExpBuffer(query, "SELECT typlen, "
10420 "typinput, typoutput, typreceive, typsend, "
10421 "'-' AS typmodin, '-' AS typmodout, "
10423 "typreceive::pg_catalog.oid AS typreceiveoid, "
10424 "typsend::pg_catalog.oid AS typsendoid, "
10425 "0 AS typmodinoid, 0 AS typmodoutoid, "
10426 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10427 "'U' AS typcategory, false AS typispreferred, "
10428 "typdelim, typbyval, typalign, typstorage, "
10429 "false AS typcollatable, "
10430 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10431 "FROM pg_catalog.pg_type "
10432 "WHERE oid = '%u'::pg_catalog.oid",
10433 tyinfo->dobj.catId.oid);
10436 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10438 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10439 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10440 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10441 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10442 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10443 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10444 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10445 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10446 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10447 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10448 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10449 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10450 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10451 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10452 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10453 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10454 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10455 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10456 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10457 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10458 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10459 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10460 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10462 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10463 typdefault_is_literal = true; /* it needs quotes */
10468 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10469 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10472 * The reason we include CASCADE is that the circular dependency between
10473 * the type and its I/O functions makes it impossible to drop the type any
10476 appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10479 * We might already have a shell type, but setting pg_type_oid is
10480 * harmless, and in any case we'd better set the array type OID.
10482 if (dopt->binary_upgrade)
10483 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10484 tyinfo->dobj.catId.oid,
10487 appendPQExpBuffer(q,
10488 "CREATE TYPE %s (\n"
10489 " INTERNALLENGTH = %s",
10491 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10493 /* regproc result is sufficiently quoted already */
10494 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10495 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10496 if (OidIsValid(typreceiveoid))
10497 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10498 if (OidIsValid(typsendoid))
10499 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10500 if (OidIsValid(typmodinoid))
10501 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10502 if (OidIsValid(typmodoutoid))
10503 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10504 if (OidIsValid(typanalyzeoid))
10505 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10507 if (strcmp(typcollatable, "t") == 0)
10508 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10510 if (typdefault != NULL)
10512 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10513 if (typdefault_is_literal)
10514 appendStringLiteralAH(q, typdefault, fout);
10516 appendPQExpBufferStr(q, typdefault);
10519 if (OidIsValid(tyinfo->typelem))
10523 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10524 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10528 if (strcmp(typcategory, "U") != 0)
10530 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10531 appendStringLiteralAH(q, typcategory, fout);
10534 if (strcmp(typispreferred, "t") == 0)
10535 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10537 if (typdelim && strcmp(typdelim, ",") != 0)
10539 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10540 appendStringLiteralAH(q, typdelim, fout);
10543 if (strcmp(typalign, "c") == 0)
10544 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10545 else if (strcmp(typalign, "s") == 0)
10546 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10547 else if (strcmp(typalign, "i") == 0)
10548 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10549 else if (strcmp(typalign, "d") == 0)
10550 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10552 if (strcmp(typstorage, "p") == 0)
10553 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10554 else if (strcmp(typstorage, "e") == 0)
10555 appendPQExpBufferStr(q, ",\n STORAGE = external");
10556 else if (strcmp(typstorage, "x") == 0)
10557 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10558 else if (strcmp(typstorage, "m") == 0)
10559 appendPQExpBufferStr(q, ",\n STORAGE = main");
10561 if (strcmp(typbyval, "t") == 0)
10562 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10564 appendPQExpBufferStr(q, "\n);\n");
10566 if (dopt->binary_upgrade)
10567 binary_upgrade_extension_member(q, &tyinfo->dobj,
10569 tyinfo->dobj.namespace->dobj.name);
10571 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10572 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10574 tyinfo->dobj.namespace->dobj.name,
10576 tyinfo->rolname, false,
10577 "TYPE", SECTION_PRE_DATA,
10578 q->data, delq->data, NULL,
10582 /* Dump Type Comments and Security Labels */
10583 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10584 dumpComment(fout, "TYPE", qtypname,
10585 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10586 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10588 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10589 dumpSecLabel(fout, "TYPE", qtypname,
10590 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10591 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10593 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10594 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10596 tyinfo->dobj.namespace->dobj.name,
10597 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10598 tyinfo->inittypacl, tyinfo->initrtypacl);
10601 destroyPQExpBuffer(q);
10602 destroyPQExpBuffer(delq);
10603 destroyPQExpBuffer(query);
10610 * writes out to fout the queries to recreate a user-defined domain
10613 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10615 DumpOptions *dopt = fout->dopt;
10616 PQExpBuffer q = createPQExpBuffer();
10617 PQExpBuffer delq = createPQExpBuffer();
10618 PQExpBuffer query = createPQExpBuffer();
10627 bool typdefault_is_literal = false;
10629 /* Fetch domain specific details */
10630 if (fout->remoteVersion >= 90100)
10632 /* typcollation is new in 9.1 */
10633 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10634 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10635 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10637 "CASE WHEN t.typcollation <> u.typcollation "
10638 "THEN t.typcollation ELSE 0 END AS typcollation "
10639 "FROM pg_catalog.pg_type t "
10640 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10641 "WHERE t.oid = '%u'::pg_catalog.oid",
10642 tyinfo->dobj.catId.oid);
10646 appendPQExpBuffer(query, "SELECT typnotnull, "
10647 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10648 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10649 "typdefault, 0 AS typcollation "
10650 "FROM pg_catalog.pg_type "
10651 "WHERE oid = '%u'::pg_catalog.oid",
10652 tyinfo->dobj.catId.oid);
10655 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10657 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10658 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10659 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10660 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10661 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10663 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10664 typdefault_is_literal = true; /* it needs quotes */
10668 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10670 if (dopt->binary_upgrade)
10671 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10672 tyinfo->dobj.catId.oid,
10673 true); /* force array type */
10675 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10676 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10678 appendPQExpBuffer(q,
10679 "CREATE DOMAIN %s AS %s",
10683 /* Print collation only if different from base type's collation */
10684 if (OidIsValid(typcollation))
10688 coll = findCollationByOid(typcollation);
10690 appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10693 if (typnotnull[0] == 't')
10694 appendPQExpBufferStr(q, " NOT NULL");
10696 if (typdefault != NULL)
10698 appendPQExpBufferStr(q, " DEFAULT ");
10699 if (typdefault_is_literal)
10700 appendStringLiteralAH(q, typdefault, fout);
10702 appendPQExpBufferStr(q, typdefault);
10708 * Add any CHECK constraints for the domain
10710 for (i = 0; i < tyinfo->nDomChecks; i++)
10712 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10714 if (!domcheck->separate)
10715 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10716 fmtId(domcheck->dobj.name), domcheck->condef);
10719 appendPQExpBufferStr(q, ";\n");
10721 appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10723 if (dopt->binary_upgrade)
10724 binary_upgrade_extension_member(q, &tyinfo->dobj,
10725 "DOMAIN", qtypname,
10726 tyinfo->dobj.namespace->dobj.name);
10728 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10729 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10731 tyinfo->dobj.namespace->dobj.name,
10733 tyinfo->rolname, false,
10734 "DOMAIN", SECTION_PRE_DATA,
10735 q->data, delq->data, NULL,
10739 /* Dump Domain Comments and Security Labels */
10740 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10741 dumpComment(fout, "DOMAIN", qtypname,
10742 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10743 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10745 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10746 dumpSecLabel(fout, "DOMAIN", qtypname,
10747 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10748 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10750 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10751 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10753 tyinfo->dobj.namespace->dobj.name,
10754 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10755 tyinfo->inittypacl, tyinfo->initrtypacl);
10757 /* Dump any per-constraint comments */
10758 for (i = 0; i < tyinfo->nDomChecks; i++)
10760 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10761 PQExpBuffer conprefix = createPQExpBuffer();
10763 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10764 fmtId(domcheck->dobj.name));
10766 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10767 dumpComment(fout, conprefix->data, qtypname,
10768 tyinfo->dobj.namespace->dobj.name,
10770 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10772 destroyPQExpBuffer(conprefix);
10775 destroyPQExpBuffer(q);
10776 destroyPQExpBuffer(delq);
10777 destroyPQExpBuffer(query);
10783 * dumpCompositeType
10784 * writes out to fout the queries to recreate a user-defined stand-alone
10788 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10790 DumpOptions *dopt = fout->dopt;
10791 PQExpBuffer q = createPQExpBuffer();
10792 PQExpBuffer dropped = createPQExpBuffer();
10793 PQExpBuffer delq = createPQExpBuffer();
10794 PQExpBuffer query = createPQExpBuffer();
10803 int i_attisdropped;
10804 int i_attcollation;
10808 /* Fetch type specific details */
10809 if (fout->remoteVersion >= 90100)
10812 * attcollation is new in 9.1. Since we only want to dump COLLATE
10813 * clauses for attributes whose collation is different from their
10814 * type's default, we use a CASE here to suppress uninteresting
10815 * attcollations cheaply. atttypid will be 0 for dropped columns;
10816 * collation does not matter for those.
10818 appendPQExpBuffer(query, "SELECT a.attname, "
10819 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10820 "a.attlen, a.attalign, a.attisdropped, "
10821 "CASE WHEN a.attcollation <> at.typcollation "
10822 "THEN a.attcollation ELSE 0 END AS attcollation "
10823 "FROM pg_catalog.pg_type ct "
10824 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10825 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10826 "WHERE ct.oid = '%u'::pg_catalog.oid "
10827 "ORDER BY a.attnum ",
10828 tyinfo->dobj.catId.oid);
10833 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10834 * should always be false.
10836 appendPQExpBuffer(query, "SELECT a.attname, "
10837 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10838 "a.attlen, a.attalign, a.attisdropped, "
10839 "0 AS attcollation "
10840 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10841 "WHERE ct.oid = '%u'::pg_catalog.oid "
10842 "AND a.attrelid = ct.typrelid "
10843 "ORDER BY a.attnum ",
10844 tyinfo->dobj.catId.oid);
10847 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10849 ntups = PQntuples(res);
10851 i_attname = PQfnumber(res, "attname");
10852 i_atttypdefn = PQfnumber(res, "atttypdefn");
10853 i_attlen = PQfnumber(res, "attlen");
10854 i_attalign = PQfnumber(res, "attalign");
10855 i_attisdropped = PQfnumber(res, "attisdropped");
10856 i_attcollation = PQfnumber(res, "attcollation");
10858 if (dopt->binary_upgrade)
10860 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10861 tyinfo->dobj.catId.oid,
10863 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10866 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10867 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10869 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10873 for (i = 0; i < ntups; i++)
10882 attname = PQgetvalue(res, i, i_attname);
10883 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10884 attlen = PQgetvalue(res, i, i_attlen);
10885 attalign = PQgetvalue(res, i, i_attalign);
10886 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10887 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10889 if (attisdropped && !dopt->binary_upgrade)
10892 /* Format properly if not first attr */
10893 if (actual_atts++ > 0)
10894 appendPQExpBufferChar(q, ',');
10895 appendPQExpBufferStr(q, "\n\t");
10899 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10901 /* Add collation if not default for the column type */
10902 if (OidIsValid(attcollation))
10906 coll = findCollationByOid(attcollation);
10908 appendPQExpBuffer(q, " COLLATE %s",
10909 fmtQualifiedDumpable(coll));
10915 * This is a dropped attribute and we're in binary_upgrade mode.
10916 * Insert a placeholder for it in the CREATE TYPE command, and set
10917 * length and alignment with direct UPDATE to the catalogs
10918 * afterwards. See similar code in dumpTableSchema().
10920 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
10922 /* stash separately for insertion after the CREATE TYPE */
10923 appendPQExpBufferStr(dropped,
10924 "\n-- For binary upgrade, recreate dropped column.\n");
10925 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
10926 "SET attlen = %s, "
10927 "attalign = '%s', attbyval = false\n"
10928 "WHERE attname = ", attlen, attalign);
10929 appendStringLiteralAH(dropped, attname, fout);
10930 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
10931 appendStringLiteralAH(dropped, qualtypname, fout);
10932 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
10934 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
10936 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
10940 appendPQExpBufferStr(q, "\n);\n");
10941 appendPQExpBufferStr(q, dropped->data);
10943 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10945 if (dopt->binary_upgrade)
10946 binary_upgrade_extension_member(q, &tyinfo->dobj,
10948 tyinfo->dobj.namespace->dobj.name);
10950 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10951 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10953 tyinfo->dobj.namespace->dobj.name,
10955 tyinfo->rolname, false,
10956 "TYPE", SECTION_PRE_DATA,
10957 q->data, delq->data, NULL,
10962 /* Dump Type Comments and Security Labels */
10963 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10964 dumpComment(fout, "TYPE", qtypname,
10965 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10966 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10968 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10969 dumpSecLabel(fout, "TYPE", qtypname,
10970 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10971 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10973 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10974 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10976 tyinfo->dobj.namespace->dobj.name,
10977 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10978 tyinfo->inittypacl, tyinfo->initrtypacl);
10981 destroyPQExpBuffer(q);
10982 destroyPQExpBuffer(dropped);
10983 destroyPQExpBuffer(delq);
10984 destroyPQExpBuffer(query);
10988 /* Dump any per-column comments */
10989 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10990 dumpCompositeTypeColComments(fout, tyinfo);
10994 * dumpCompositeTypeColComments
10995 * writes out to fout the queries to recreate comments on the columns of
10996 * a user-defined stand-alone composite type
10999 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11001 CommentItem *comments;
11005 PQExpBuffer target;
11012 /* do nothing, if --no-comments is supplied */
11013 if (fout->dopt->no_comments)
11016 query = createPQExpBuffer();
11018 appendPQExpBuffer(query,
11019 "SELECT c.tableoid, a.attname, a.attnum "
11020 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11021 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11022 " AND NOT a.attisdropped "
11023 "ORDER BY a.attnum ",
11026 /* Fetch column attnames */
11027 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11029 ntups = PQntuples(res);
11033 destroyPQExpBuffer(query);
11037 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11039 /* Search for comments associated with type's pg_class OID */
11040 ncomments = findComments(fout,
11045 /* If no comments exist, we're done */
11046 if (ncomments <= 0)
11049 destroyPQExpBuffer(query);
11053 /* Build COMMENT ON statements */
11054 target = createPQExpBuffer();
11056 i_attnum = PQfnumber(res, "attnum");
11057 i_attname = PQfnumber(res, "attname");
11058 while (ncomments > 0)
11060 const char *attname;
11063 for (i = 0; i < ntups; i++)
11065 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11067 attname = PQgetvalue(res, i, i_attname);
11071 if (attname) /* just in case we don't find it */
11073 const char *descr = comments->descr;
11075 resetPQExpBuffer(target);
11076 appendPQExpBuffer(target, "COLUMN %s.",
11077 fmtId(tyinfo->dobj.name));
11078 appendPQExpBufferStr(target, fmtId(attname));
11080 resetPQExpBuffer(query);
11081 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11082 fmtQualifiedDumpable(tyinfo));
11083 appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11084 appendStringLiteralAH(query, descr, fout);
11085 appendPQExpBufferStr(query, ";\n");
11087 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11089 tyinfo->dobj.namespace->dobj.name,
11090 NULL, tyinfo->rolname,
11091 false, "COMMENT", SECTION_NONE,
11092 query->data, "", NULL,
11093 &(tyinfo->dobj.dumpId), 1,
11102 destroyPQExpBuffer(query);
11103 destroyPQExpBuffer(target);
11108 * writes out to fout the queries to create a shell type
11110 * We dump a shell definition in advance of the I/O functions for the type.
11113 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11115 DumpOptions *dopt = fout->dopt;
11118 /* Skip if not to be dumped */
11119 if (!stinfo->dobj.dump || dopt->dataOnly)
11122 q = createPQExpBuffer();
11125 * Note the lack of a DROP command for the shell type; any required DROP
11126 * is driven off the base type entry, instead. This interacts with
11127 * _printTocEntry()'s use of the presence of a DROP command to decide
11128 * whether an entry needs an ALTER OWNER command. We don't want to alter
11129 * the shell type's owner immediately on creation; that should happen only
11130 * after it's filled in, otherwise the backend complains.
11133 if (dopt->binary_upgrade)
11134 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11135 stinfo->baseType->dobj.catId.oid,
11138 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11139 fmtQualifiedDumpable(stinfo));
11141 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11142 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11144 stinfo->dobj.namespace->dobj.name,
11146 stinfo->baseType->rolname, false,
11147 "SHELL TYPE", SECTION_PRE_DATA,
11152 destroyPQExpBuffer(q);
11157 * writes out to fout the queries to recreate a user-defined
11158 * procedural language
11161 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11163 DumpOptions *dopt = fout->dopt;
11164 PQExpBuffer defqry;
11165 PQExpBuffer delqry;
11168 FuncInfo *funcInfo;
11169 FuncInfo *inlineInfo = NULL;
11170 FuncInfo *validatorInfo = NULL;
11172 /* Skip if not to be dumped */
11173 if (!plang->dobj.dump || dopt->dataOnly)
11177 * Try to find the support function(s). It is not an error if we don't
11178 * find them --- if the functions are in the pg_catalog schema, as is
11179 * standard in 8.1 and up, then we won't have loaded them. (In this case
11180 * we will emit a parameterless CREATE LANGUAGE command, which will
11181 * require PL template knowledge in the backend to reload.)
11184 funcInfo = findFuncByOid(plang->lanplcallfoid);
11185 if (funcInfo != NULL && !funcInfo->dobj.dump)
11186 funcInfo = NULL; /* treat not-dumped same as not-found */
11188 if (OidIsValid(plang->laninline))
11190 inlineInfo = findFuncByOid(plang->laninline);
11191 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11195 if (OidIsValid(plang->lanvalidator))
11197 validatorInfo = findFuncByOid(plang->lanvalidator);
11198 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11199 validatorInfo = NULL;
11203 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11204 * with parameters. Otherwise, we'll write a parameterless command, which
11205 * will rely on data from pg_pltemplate.
11207 useParams = (funcInfo != NULL &&
11208 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11209 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11211 defqry = createPQExpBuffer();
11212 delqry = createPQExpBuffer();
11214 qlanname = pg_strdup(fmtId(plang->dobj.name));
11216 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11221 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11222 plang->lanpltrusted ? "TRUSTED " : "",
11224 appendPQExpBuffer(defqry, " HANDLER %s",
11225 fmtQualifiedDumpable(funcInfo));
11226 if (OidIsValid(plang->laninline))
11227 appendPQExpBuffer(defqry, " INLINE %s",
11228 fmtQualifiedDumpable(inlineInfo));
11229 if (OidIsValid(plang->lanvalidator))
11230 appendPQExpBuffer(defqry, " VALIDATOR %s",
11231 fmtQualifiedDumpable(validatorInfo));
11236 * If not dumping parameters, then use CREATE OR REPLACE so that the
11237 * command will not fail if the language is preinstalled in the target
11238 * database. We restrict the use of REPLACE to this case so as to
11239 * eliminate the risk of replacing a language with incompatible
11240 * parameter settings: this command will only succeed at all if there
11241 * is a pg_pltemplate entry, and if there is one, the existing entry
11242 * must match it too.
11244 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11247 appendPQExpBufferStr(defqry, ";\n");
11249 if (dopt->binary_upgrade)
11250 binary_upgrade_extension_member(defqry, &plang->dobj,
11251 "LANGUAGE", qlanname, NULL);
11253 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11254 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11256 NULL, NULL, plang->lanowner,
11257 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11258 defqry->data, delqry->data, NULL,
11262 /* Dump Proc Lang Comments and Security Labels */
11263 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11264 dumpComment(fout, "LANGUAGE", qlanname,
11265 NULL, plang->lanowner,
11266 plang->dobj.catId, 0, plang->dobj.dumpId);
11268 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11269 dumpSecLabel(fout, "LANGUAGE", qlanname,
11270 NULL, plang->lanowner,
11271 plang->dobj.catId, 0, plang->dobj.dumpId);
11273 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11274 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11275 qlanname, NULL, NULL,
11276 plang->lanowner, plang->lanacl, plang->rlanacl,
11277 plang->initlanacl, plang->initrlanacl);
11281 destroyPQExpBuffer(defqry);
11282 destroyPQExpBuffer(delqry);
11286 * format_function_arguments: generate function name and argument list
11288 * This is used when we can rely on pg_get_function_arguments to format
11289 * the argument list. Note, however, that pg_get_function_arguments
11290 * does not special-case zero-argument aggregates.
11293 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11295 PQExpBufferData fn;
11297 initPQExpBuffer(&fn);
11298 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11299 if (is_agg && finfo->nargs == 0)
11300 appendPQExpBufferStr(&fn, "(*)");
11302 appendPQExpBuffer(&fn, "(%s)", funcargs);
11307 * format_function_arguments_old: generate function name and argument list
11309 * The argument type names are qualified if needed. The function name
11310 * is never qualified.
11312 * This is used only with pre-8.4 servers, so we aren't expecting to see
11313 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11315 * Any or all of allargtypes, argmodes, argnames may be NULL.
11318 format_function_arguments_old(Archive *fout,
11319 FuncInfo *finfo, int nallargs,
11320 char **allargtypes,
11324 PQExpBufferData fn;
11327 initPQExpBuffer(&fn);
11328 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11329 for (j = 0; j < nallargs; j++)
11333 const char *argmode;
11334 const char *argname;
11336 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11337 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11341 switch (argmodes[j][0])
11343 case PROARGMODE_IN:
11346 case PROARGMODE_OUT:
11349 case PROARGMODE_INOUT:
11350 argmode = "INOUT ";
11353 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11361 argname = argnames ? argnames[j] : (char *) NULL;
11362 if (argname && argname[0] == '\0')
11365 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11366 (j > 0) ? ", " : "",
11368 argname ? fmtId(argname) : "",
11369 argname ? " " : "",
11373 appendPQExpBufferChar(&fn, ')');
11378 * format_function_signature: generate function name and argument list
11380 * This is like format_function_arguments_old except that only a minimal
11381 * list of input argument types is generated; this is sufficient to
11382 * reference the function, but not to define it.
11384 * If honor_quotes is false then the function name is never quoted.
11385 * This is appropriate for use in TOC tags, but not in SQL commands.
11388 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11390 PQExpBufferData fn;
11393 initPQExpBuffer(&fn);
11395 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11397 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11398 for (j = 0; j < finfo->nargs; j++)
11403 appendPQExpBufferStr(&fn, ", ");
11405 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11407 appendPQExpBufferStr(&fn, typname);
11410 appendPQExpBufferChar(&fn, ')');
11417 * dump out one function
11420 dumpFunc(Archive *fout, FuncInfo *finfo)
11422 DumpOptions *dopt = fout->dopt;
11425 PQExpBuffer delqry;
11426 PQExpBuffer asPart;
11428 char *funcsig; /* identity signature */
11429 char *funcfullsig = NULL; /* full signature */
11437 char *proallargtypes;
11445 char *proleakproof;
11453 char **allargtypes = NULL;
11454 char **argmodes = NULL;
11455 char **argnames = NULL;
11456 char **configitems = NULL;
11457 int nconfigitems = 0;
11458 const char *keyword;
11461 /* Skip if not to be dumped */
11462 if (!finfo->dobj.dump || dopt->dataOnly)
11465 query = createPQExpBuffer();
11466 q = createPQExpBuffer();
11467 delqry = createPQExpBuffer();
11468 asPart = createPQExpBuffer();
11470 /* Fetch function-specific details */
11471 if (fout->remoteVersion >= 110000)
11474 * prokind was added in 11
11476 appendPQExpBuffer(query,
11477 "SELECT proretset, prosrc, probin, "
11478 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11479 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11480 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11481 "array_to_string(protrftypes, ' ') AS protrftypes, "
11482 "prokind, provolatile, proisstrict, prosecdef, "
11483 "proleakproof, proconfig, procost, prorows, "
11485 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11486 "FROM pg_catalog.pg_proc "
11487 "WHERE oid = '%u'::pg_catalog.oid",
11488 finfo->dobj.catId.oid);
11490 else if (fout->remoteVersion >= 90600)
11493 * proparallel was added in 9.6
11495 appendPQExpBuffer(query,
11496 "SELECT proretset, prosrc, probin, "
11497 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11498 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11499 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11500 "array_to_string(protrftypes, ' ') AS protrftypes, "
11501 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11502 "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 >= 90500)
11513 * protrftypes was added in 9.5
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, "
11524 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11525 "FROM pg_catalog.pg_proc "
11526 "WHERE oid = '%u'::pg_catalog.oid",
11527 finfo->dobj.catId.oid);
11529 else if (fout->remoteVersion >= 90200)
11532 * proleakproof was added in 9.2
11534 appendPQExpBuffer(query,
11535 "SELECT proretset, prosrc, probin, "
11536 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11537 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11538 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11539 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11540 "provolatile, proisstrict, prosecdef, "
11541 "proleakproof, proconfig, procost, prorows, "
11542 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11543 "FROM pg_catalog.pg_proc "
11544 "WHERE oid = '%u'::pg_catalog.oid",
11545 finfo->dobj.catId.oid);
11547 else if (fout->remoteVersion >= 80400)
11550 * In 8.4 and up we rely on pg_get_function_arguments and
11551 * pg_get_function_result instead of examining proallargtypes etc.
11553 appendPQExpBuffer(query,
11554 "SELECT proretset, prosrc, probin, "
11555 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11556 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11557 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11558 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11559 "provolatile, proisstrict, prosecdef, "
11560 "false AS proleakproof, "
11561 " 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 >= 80300)
11569 appendPQExpBuffer(query,
11570 "SELECT proretset, prosrc, probin, "
11571 "proallargtypes, proargmodes, proargnames, "
11573 "provolatile, proisstrict, prosecdef, "
11574 "false AS proleakproof, "
11575 "proconfig, procost, prorows, "
11576 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11577 "FROM pg_catalog.pg_proc "
11578 "WHERE oid = '%u'::pg_catalog.oid",
11579 finfo->dobj.catId.oid);
11581 else if (fout->remoteVersion >= 80100)
11583 appendPQExpBuffer(query,
11584 "SELECT proretset, prosrc, probin, "
11585 "proallargtypes, proargmodes, proargnames, "
11587 "provolatile, proisstrict, prosecdef, "
11588 "false AS proleakproof, "
11589 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11590 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11591 "FROM pg_catalog.pg_proc "
11592 "WHERE oid = '%u'::pg_catalog.oid",
11593 finfo->dobj.catId.oid);
11597 appendPQExpBuffer(query,
11598 "SELECT proretset, prosrc, probin, "
11599 "null AS proallargtypes, "
11600 "null AS proargmodes, "
11603 "provolatile, proisstrict, prosecdef, "
11604 "false AS proleakproof, "
11605 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11606 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11607 "FROM pg_catalog.pg_proc "
11608 "WHERE oid = '%u'::pg_catalog.oid",
11609 finfo->dobj.catId.oid);
11612 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11614 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11615 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11616 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11617 if (fout->remoteVersion >= 80400)
11619 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11620 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11621 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11622 proallargtypes = proargmodes = proargnames = NULL;
11626 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11627 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11628 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11629 funcargs = funciargs = funcresult = NULL;
11631 if (PQfnumber(res, "protrftypes") != -1)
11632 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11634 protrftypes = NULL;
11635 prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11636 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11637 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11638 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11639 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11640 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11641 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11642 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11644 if (PQfnumber(res, "proparallel") != -1)
11645 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11647 proparallel = NULL;
11649 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11652 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11653 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11654 * versions would set it to "-". There are no known cases in which prosrc
11655 * is unused, so the tests below for "-" are probably useless.
11657 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11659 appendPQExpBufferStr(asPart, "AS ");
11660 appendStringLiteralAH(asPart, probin, fout);
11661 if (strcmp(prosrc, "-") != 0)
11663 appendPQExpBufferStr(asPart, ", ");
11666 * where we have bin, use dollar quoting if allowed and src
11667 * contains quote or backslash; else use regular quoting.
11669 if (dopt->disable_dollar_quoting ||
11670 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11671 appendStringLiteralAH(asPart, prosrc, fout);
11673 appendStringLiteralDQ(asPart, prosrc, NULL);
11678 if (strcmp(prosrc, "-") != 0)
11680 appendPQExpBufferStr(asPart, "AS ");
11681 /* with no bin, dollar quote src unconditionally if allowed */
11682 if (dopt->disable_dollar_quoting)
11683 appendStringLiteralAH(asPart, prosrc, fout);
11685 appendStringLiteralDQ(asPart, prosrc, NULL);
11689 nallargs = finfo->nargs; /* unless we learn different from allargs */
11691 if (proallargtypes && *proallargtypes)
11695 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11696 nitems < finfo->nargs)
11698 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11701 allargtypes = NULL;
11707 if (proargmodes && *proargmodes)
11711 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11712 nitems != nallargs)
11714 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11721 if (proargnames && *proargnames)
11725 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11726 nitems != nallargs)
11728 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11735 if (proconfig && *proconfig)
11737 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11739 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11742 configitems = NULL;
11749 /* 8.4 or later; we rely on server-side code for most of the work */
11750 funcfullsig = format_function_arguments(finfo, funcargs, false);
11751 funcsig = format_function_arguments(finfo, funciargs, false);
11754 /* pre-8.4, do it ourselves */
11755 funcsig = format_function_arguments_old(fout,
11756 finfo, nallargs, allargtypes,
11757 argmodes, argnames);
11759 funcsig_tag = format_function_signature(fout, finfo, false);
11761 if (prokind[0] == PROKIND_PROCEDURE)
11762 keyword = "PROCEDURE";
11764 keyword = "FUNCTION"; /* works for window functions too */
11766 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11768 fmtId(finfo->dobj.namespace->dobj.name),
11771 appendPQExpBuffer(q, "CREATE %s %s.%s",
11773 fmtId(finfo->dobj.namespace->dobj.name),
11774 funcfullsig ? funcfullsig :
11777 if (prokind[0] == PROKIND_PROCEDURE)
11778 /* no result type to output */ ;
11779 else if (funcresult)
11780 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11783 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11785 appendPQExpBuffer(q, " RETURNS %s%s",
11786 (proretset[0] == 't') ? "SETOF " : "",
11791 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11793 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11795 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11798 appendPQExpBufferStr(q, " TRANSFORM ");
11799 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11800 for (i = 0; typeids[i]; i++)
11803 appendPQExpBufferStr(q, ", ");
11804 appendPQExpBuffer(q, "FOR TYPE %s",
11805 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11809 if (prokind[0] == PROKIND_WINDOW)
11810 appendPQExpBufferStr(q, " WINDOW");
11812 if (provolatile[0] != PROVOLATILE_VOLATILE)
11814 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11815 appendPQExpBufferStr(q, " IMMUTABLE");
11816 else if (provolatile[0] == PROVOLATILE_STABLE)
11817 appendPQExpBufferStr(q, " STABLE");
11818 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11819 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11823 if (proisstrict[0] == 't')
11824 appendPQExpBufferStr(q, " STRICT");
11826 if (prosecdef[0] == 't')
11827 appendPQExpBufferStr(q, " SECURITY DEFINER");
11829 if (proleakproof[0] == 't')
11830 appendPQExpBufferStr(q, " LEAKPROOF");
11833 * COST and ROWS are emitted only if present and not default, so as not to
11834 * break backwards-compatibility of the dump without need. Keep this code
11835 * in sync with the defaults in functioncmds.c.
11837 if (strcmp(procost, "0") != 0)
11839 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11841 /* default cost is 1 */
11842 if (strcmp(procost, "1") != 0)
11843 appendPQExpBuffer(q, " COST %s", procost);
11847 /* default cost is 100 */
11848 if (strcmp(procost, "100") != 0)
11849 appendPQExpBuffer(q, " COST %s", procost);
11852 if (proretset[0] == 't' &&
11853 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11854 appendPQExpBuffer(q, " ROWS %s", prorows);
11856 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11858 if (proparallel[0] == PROPARALLEL_SAFE)
11859 appendPQExpBufferStr(q, " PARALLEL SAFE");
11860 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11861 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11862 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11863 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11867 for (i = 0; i < nconfigitems; i++)
11869 /* we feel free to scribble on configitems[] here */
11870 char *configitem = configitems[i];
11873 pos = strchr(configitem, '=');
11877 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
11880 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11881 * by flatten_set_variable_args() before they were put into the
11882 * proconfig array; we mustn't re-quote them or we'll make a mess.
11883 * Variables that are not so marked should just be emitted as simple
11884 * string literals. If the variable is not known to
11885 * variable_is_guc_list_quote(), we'll do the latter; this makes it
11886 * unsafe to use GUC_LIST_QUOTE for extension variables.
11888 if (variable_is_guc_list_quote(configitem))
11889 appendPQExpBufferStr(q, pos);
11891 appendStringLiteralAH(q, pos, fout);
11894 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
11896 if (dopt->binary_upgrade)
11897 binary_upgrade_extension_member(q, &finfo->dobj,
11899 finfo->dobj.namespace->dobj.name);
11901 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11902 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
11904 finfo->dobj.namespace->dobj.name,
11906 finfo->rolname, false,
11907 keyword, SECTION_PRE_DATA,
11908 q->data, delqry->data, NULL,
11912 /* Dump Function Comments and Security Labels */
11913 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11914 dumpComment(fout, keyword, funcsig,
11915 finfo->dobj.namespace->dobj.name, finfo->rolname,
11916 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11918 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11919 dumpSecLabel(fout, keyword, funcsig,
11920 finfo->dobj.namespace->dobj.name, finfo->rolname,
11921 finfo->dobj.catId, 0, finfo->dobj.dumpId);
11923 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
11924 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
11926 finfo->dobj.namespace->dobj.name,
11927 finfo->rolname, finfo->proacl, finfo->rproacl,
11928 finfo->initproacl, finfo->initrproacl);
11932 destroyPQExpBuffer(query);
11933 destroyPQExpBuffer(q);
11934 destroyPQExpBuffer(delqry);
11935 destroyPQExpBuffer(asPart);
11952 * Dump a user-defined cast
11955 dumpCast(Archive *fout, CastInfo *cast)
11957 DumpOptions *dopt = fout->dopt;
11958 PQExpBuffer defqry;
11959 PQExpBuffer delqry;
11960 PQExpBuffer labelq;
11961 PQExpBuffer castargs;
11962 FuncInfo *funcInfo = NULL;
11966 /* Skip if not to be dumped */
11967 if (!cast->dobj.dump || dopt->dataOnly)
11970 /* Cannot dump if we don't have the cast function's info */
11971 if (OidIsValid(cast->castfunc))
11973 funcInfo = findFuncByOid(cast->castfunc);
11974 if (funcInfo == NULL)
11975 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11979 defqry = createPQExpBuffer();
11980 delqry = createPQExpBuffer();
11981 labelq = createPQExpBuffer();
11982 castargs = createPQExpBuffer();
11984 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
11985 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
11986 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
11987 sourceType, targetType);
11989 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
11990 sourceType, targetType);
11992 switch (cast->castmethod)
11994 case COERCION_METHOD_BINARY:
11995 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
11997 case COERCION_METHOD_INOUT:
11998 appendPQExpBufferStr(defqry, "WITH INOUT");
12000 case COERCION_METHOD_FUNCTION:
12003 char *fsig = format_function_signature(fout, funcInfo, true);
12006 * Always qualify the function name (format_function_signature
12007 * won't qualify it).
12009 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12010 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12014 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12017 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12020 if (cast->castcontext == 'a')
12021 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12022 else if (cast->castcontext == 'i')
12023 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12024 appendPQExpBufferStr(defqry, ";\n");
12026 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12027 sourceType, targetType);
12029 appendPQExpBuffer(castargs, "(%s AS %s)",
12030 sourceType, targetType);
12032 if (dopt->binary_upgrade)
12033 binary_upgrade_extension_member(defqry, &cast->dobj,
12034 "CAST", castargs->data, NULL);
12036 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12037 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12040 false, "CAST", SECTION_PRE_DATA,
12041 defqry->data, delqry->data, NULL,
12045 /* Dump Cast Comments */
12046 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12047 dumpComment(fout, "CAST", castargs->data,
12049 cast->dobj.catId, 0, cast->dobj.dumpId);
12054 destroyPQExpBuffer(defqry);
12055 destroyPQExpBuffer(delqry);
12056 destroyPQExpBuffer(labelq);
12057 destroyPQExpBuffer(castargs);
12064 dumpTransform(Archive *fout, TransformInfo *transform)
12066 DumpOptions *dopt = fout->dopt;
12067 PQExpBuffer defqry;
12068 PQExpBuffer delqry;
12069 PQExpBuffer labelq;
12070 PQExpBuffer transformargs;
12071 FuncInfo *fromsqlFuncInfo = NULL;
12072 FuncInfo *tosqlFuncInfo = NULL;
12074 char *transformType;
12076 /* Skip if not to be dumped */
12077 if (!transform->dobj.dump || dopt->dataOnly)
12080 /* Cannot dump if we don't have the transform functions' info */
12081 if (OidIsValid(transform->trffromsql))
12083 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12084 if (fromsqlFuncInfo == NULL)
12085 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12086 transform->trffromsql);
12088 if (OidIsValid(transform->trftosql))
12090 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12091 if (tosqlFuncInfo == NULL)
12092 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12093 transform->trftosql);
12096 defqry = createPQExpBuffer();
12097 delqry = createPQExpBuffer();
12098 labelq = createPQExpBuffer();
12099 transformargs = createPQExpBuffer();
12101 lanname = get_language_name(fout, transform->trflang);
12102 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12104 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12105 transformType, lanname);
12107 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12108 transformType, lanname);
12110 if (!transform->trffromsql && !transform->trftosql)
12111 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12113 if (transform->trffromsql)
12115 if (fromsqlFuncInfo)
12117 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12120 * Always qualify the function name (format_function_signature
12121 * won't qualify it).
12123 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12124 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12128 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12131 if (transform->trftosql)
12133 if (transform->trffromsql)
12134 appendPQExpBuffer(defqry, ", ");
12138 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12141 * Always qualify the function name (format_function_signature
12142 * won't qualify it).
12144 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12145 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12149 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12152 appendPQExpBuffer(defqry, ");\n");
12154 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12155 transformType, lanname);
12157 appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12158 transformType, lanname);
12160 if (dopt->binary_upgrade)
12161 binary_upgrade_extension_member(defqry, &transform->dobj,
12162 "TRANSFORM", transformargs->data, NULL);
12164 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12165 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12168 false, "TRANSFORM", SECTION_PRE_DATA,
12169 defqry->data, delqry->data, NULL,
12170 transform->dobj.dependencies, transform->dobj.nDeps,
12173 /* Dump Transform Comments */
12174 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12175 dumpComment(fout, "TRANSFORM", transformargs->data,
12177 transform->dobj.catId, 0, transform->dobj.dumpId);
12180 free(transformType);
12181 destroyPQExpBuffer(defqry);
12182 destroyPQExpBuffer(delqry);
12183 destroyPQExpBuffer(labelq);
12184 destroyPQExpBuffer(transformargs);
12190 * write out a single operator definition
12193 dumpOpr(Archive *fout, OprInfo *oprinfo)
12195 DumpOptions *dopt = fout->dopt;
12200 PQExpBuffer details;
12225 /* Skip if not to be dumped */
12226 if (!oprinfo->dobj.dump || dopt->dataOnly)
12230 * some operators are invalid because they were the result of user
12231 * defining operators before commutators exist
12233 if (!OidIsValid(oprinfo->oprcode))
12236 query = createPQExpBuffer();
12237 q = createPQExpBuffer();
12238 delq = createPQExpBuffer();
12239 oprid = createPQExpBuffer();
12240 details = createPQExpBuffer();
12242 if (fout->remoteVersion >= 80300)
12244 appendPQExpBuffer(query, "SELECT oprkind, "
12245 "oprcode::pg_catalog.regprocedure, "
12246 "oprleft::pg_catalog.regtype, "
12247 "oprright::pg_catalog.regtype, "
12250 "oprrest::pg_catalog.regprocedure, "
12251 "oprjoin::pg_catalog.regprocedure, "
12252 "oprcanmerge, oprcanhash "
12253 "FROM pg_catalog.pg_operator "
12254 "WHERE oid = '%u'::pg_catalog.oid",
12255 oprinfo->dobj.catId.oid);
12259 appendPQExpBuffer(query, "SELECT oprkind, "
12260 "oprcode::pg_catalog.regprocedure, "
12261 "oprleft::pg_catalog.regtype, "
12262 "oprright::pg_catalog.regtype, "
12265 "oprrest::pg_catalog.regprocedure, "
12266 "oprjoin::pg_catalog.regprocedure, "
12267 "(oprlsortop != 0) AS oprcanmerge, "
12269 "FROM pg_catalog.pg_operator "
12270 "WHERE oid = '%u'::pg_catalog.oid",
12271 oprinfo->dobj.catId.oid);
12274 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12276 i_oprkind = PQfnumber(res, "oprkind");
12277 i_oprcode = PQfnumber(res, "oprcode");
12278 i_oprleft = PQfnumber(res, "oprleft");
12279 i_oprright = PQfnumber(res, "oprright");
12280 i_oprcom = PQfnumber(res, "oprcom");
12281 i_oprnegate = PQfnumber(res, "oprnegate");
12282 i_oprrest = PQfnumber(res, "oprrest");
12283 i_oprjoin = PQfnumber(res, "oprjoin");
12284 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12285 i_oprcanhash = PQfnumber(res, "oprcanhash");
12287 oprkind = PQgetvalue(res, 0, i_oprkind);
12288 oprcode = PQgetvalue(res, 0, i_oprcode);
12289 oprleft = PQgetvalue(res, 0, i_oprleft);
12290 oprright = PQgetvalue(res, 0, i_oprright);
12291 oprcom = PQgetvalue(res, 0, i_oprcom);
12292 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12293 oprrest = PQgetvalue(res, 0, i_oprrest);
12294 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12295 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12296 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12298 oprregproc = convertRegProcReference(fout, oprcode);
12301 appendPQExpBuffer(details, " PROCEDURE = %s", oprregproc);
12305 appendPQExpBuffer(oprid, "%s (",
12306 oprinfo->dobj.name);
12309 * right unary means there's a left arg and left unary means there's a
12312 if (strcmp(oprkind, "r") == 0 ||
12313 strcmp(oprkind, "b") == 0)
12315 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12316 appendPQExpBufferStr(oprid, oprleft);
12319 appendPQExpBufferStr(oprid, "NONE");
12321 if (strcmp(oprkind, "l") == 0 ||
12322 strcmp(oprkind, "b") == 0)
12324 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12325 appendPQExpBuffer(oprid, ", %s)", oprright);
12328 appendPQExpBufferStr(oprid, ", NONE)");
12330 oprref = getFormattedOperatorName(fout, oprcom);
12333 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12337 oprref = getFormattedOperatorName(fout, oprnegate);
12340 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12344 if (strcmp(oprcanmerge, "t") == 0)
12345 appendPQExpBufferStr(details, ",\n MERGES");
12347 if (strcmp(oprcanhash, "t") == 0)
12348 appendPQExpBufferStr(details, ",\n HASHES");
12350 oprregproc = convertRegProcReference(fout, oprrest);
12353 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12357 oprregproc = convertRegProcReference(fout, oprjoin);
12360 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12364 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12365 fmtId(oprinfo->dobj.namespace->dobj.name),
12368 appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12369 fmtId(oprinfo->dobj.namespace->dobj.name),
12370 oprinfo->dobj.name, details->data);
12372 if (dopt->binary_upgrade)
12373 binary_upgrade_extension_member(q, &oprinfo->dobj,
12374 "OPERATOR", oprid->data,
12375 oprinfo->dobj.namespace->dobj.name);
12377 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12378 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12379 oprinfo->dobj.name,
12380 oprinfo->dobj.namespace->dobj.name,
12383 false, "OPERATOR", SECTION_PRE_DATA,
12384 q->data, delq->data, NULL,
12388 /* Dump Operator Comments */
12389 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12390 dumpComment(fout, "OPERATOR", oprid->data,
12391 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12392 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12396 destroyPQExpBuffer(query);
12397 destroyPQExpBuffer(q);
12398 destroyPQExpBuffer(delq);
12399 destroyPQExpBuffer(oprid);
12400 destroyPQExpBuffer(details);
12404 * Convert a function reference obtained from pg_operator
12406 * Returns allocated string of what to print, or NULL if function references
12407 * is InvalidOid. Returned string is expected to be free'd by the caller.
12409 * The input is a REGPROCEDURE display; we have to strip the argument-types
12413 convertRegProcReference(Archive *fout, const char *proc)
12419 /* In all cases "-" means a null reference */
12420 if (strcmp(proc, "-") == 0)
12423 name = pg_strdup(proc);
12424 /* find non-double-quoted left paren */
12426 for (paren = name; *paren; paren++)
12428 if (*paren == '(' && !inquote)
12434 inquote = !inquote;
12440 * getFormattedOperatorName - retrieve the operator name for the
12441 * given operator OID (presented in string form).
12443 * Returns an allocated string, or NULL if the given OID is invalid.
12444 * Caller is responsible for free'ing result string.
12446 * What we produce has the format "OPERATOR(schema.oprname)". This is only
12447 * useful in commands where the operator's argument types can be inferred from
12448 * context. We always schema-qualify the name, though. The predecessor to
12449 * this code tried to skip the schema qualification if possible, but that led
12450 * to wrong results in corner cases, such as if an operator and its negator
12451 * are in different schemas.
12454 getFormattedOperatorName(Archive *fout, const char *oproid)
12458 /* In all cases "0" means a null reference */
12459 if (strcmp(oproid, "0") == 0)
12462 oprInfo = findOprByOid(atooid(oproid));
12463 if (oprInfo == NULL)
12465 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12470 return psprintf("OPERATOR(%s.%s)",
12471 fmtId(oprInfo->dobj.namespace->dobj.name),
12472 oprInfo->dobj.name);
12476 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12478 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12479 * argument lists of these functions are predetermined. Note that the
12480 * caller should ensure we are in the proper schema, because the results
12481 * are search path dependent!
12484 convertTSFunction(Archive *fout, Oid funcOid)
12490 snprintf(query, sizeof(query),
12491 "SELECT '%u'::pg_catalog.regproc", funcOid);
12492 res = ExecuteSqlQueryForSingleRow(fout, query);
12494 result = pg_strdup(PQgetvalue(res, 0, 0));
12503 * write out a single access method definition
12506 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12508 DumpOptions *dopt = fout->dopt;
12513 /* Skip if not to be dumped */
12514 if (!aminfo->dobj.dump || dopt->dataOnly)
12517 q = createPQExpBuffer();
12518 delq = createPQExpBuffer();
12520 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12522 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12524 switch (aminfo->amtype)
12527 appendPQExpBuffer(q, "TYPE INDEX ");
12530 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12531 aminfo->amtype, qamname);
12532 destroyPQExpBuffer(q);
12533 destroyPQExpBuffer(delq);
12538 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12540 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12543 if (dopt->binary_upgrade)
12544 binary_upgrade_extension_member(q, &aminfo->dobj,
12545 "ACCESS METHOD", qamname, NULL);
12547 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12548 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12553 false, "ACCESS METHOD", SECTION_PRE_DATA,
12554 q->data, delq->data, NULL,
12558 /* Dump Access Method Comments */
12559 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12560 dumpComment(fout, "ACCESS METHOD", qamname,
12562 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12564 destroyPQExpBuffer(q);
12565 destroyPQExpBuffer(delq);
12571 * write out a single operator class definition
12574 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12576 DumpOptions *dopt = fout->dopt;
12580 PQExpBuffer nameusing;
12587 int i_opcfamilyname;
12588 int i_opcfamilynsp;
12590 int i_amopstrategy;
12591 int i_amopreqcheck;
12594 int i_sortfamilynsp;
12597 int i_amproclefttype;
12598 int i_amprocrighttype;
12603 char *opcfamilyname;
12604 char *opcfamilynsp;
12606 char *amopstrategy;
12607 char *amopreqcheck;
12610 char *sortfamilynsp;
12613 char *amproclefttype;
12614 char *amprocrighttype;
12618 /* Skip if not to be dumped */
12619 if (!opcinfo->dobj.dump || dopt->dataOnly)
12622 query = createPQExpBuffer();
12623 q = createPQExpBuffer();
12624 delq = createPQExpBuffer();
12625 nameusing = createPQExpBuffer();
12627 /* Get additional fields from the pg_opclass row */
12628 if (fout->remoteVersion >= 80300)
12630 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12631 "opckeytype::pg_catalog.regtype, "
12632 "opcdefault, opcfamily, "
12633 "opfname AS opcfamilyname, "
12634 "nspname AS opcfamilynsp, "
12635 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12636 "FROM pg_catalog.pg_opclass c "
12637 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12638 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12639 "WHERE c.oid = '%u'::pg_catalog.oid",
12640 opcinfo->dobj.catId.oid);
12644 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12645 "opckeytype::pg_catalog.regtype, "
12646 "opcdefault, NULL AS opcfamily, "
12647 "NULL AS opcfamilyname, "
12648 "NULL AS opcfamilynsp, "
12649 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12650 "FROM pg_catalog.pg_opclass "
12651 "WHERE oid = '%u'::pg_catalog.oid",
12652 opcinfo->dobj.catId.oid);
12655 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12657 i_opcintype = PQfnumber(res, "opcintype");
12658 i_opckeytype = PQfnumber(res, "opckeytype");
12659 i_opcdefault = PQfnumber(res, "opcdefault");
12660 i_opcfamily = PQfnumber(res, "opcfamily");
12661 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12662 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12663 i_amname = PQfnumber(res, "amname");
12665 /* opcintype may still be needed after we PQclear res */
12666 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12667 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12668 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12669 /* opcfamily will still be needed after we PQclear res */
12670 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12671 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12672 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12673 /* amname will still be needed after we PQclear res */
12674 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12676 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12677 fmtQualifiedDumpable(opcinfo));
12678 appendPQExpBuffer(delq, " USING %s;\n",
12681 /* Build the fixed portion of the CREATE command */
12682 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12683 fmtQualifiedDumpable(opcinfo));
12684 if (strcmp(opcdefault, "t") == 0)
12685 appendPQExpBufferStr(q, "DEFAULT ");
12686 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12689 if (strlen(opcfamilyname) > 0)
12691 appendPQExpBufferStr(q, " FAMILY ");
12692 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12693 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12695 appendPQExpBufferStr(q, " AS\n ");
12699 if (strcmp(opckeytype, "-") != 0)
12701 appendPQExpBuffer(q, "STORAGE %s",
12709 * Now fetch and print the OPERATOR entries (pg_amop rows).
12711 * Print only those opfamily members that are tied to the opclass by
12712 * pg_depend entries.
12714 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12715 * older server's opclass in which it is used. This is to avoid
12716 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12717 * older server and then reload into that old version. This can go away
12718 * once 8.3 is so old as to not be of interest to anyone.
12720 resetPQExpBuffer(query);
12722 if (fout->remoteVersion >= 90100)
12724 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12725 "amopopr::pg_catalog.regoperator, "
12726 "opfname AS sortfamily, "
12727 "nspname AS sortfamilynsp "
12728 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12729 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12730 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12731 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12732 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12733 "AND refobjid = '%u'::pg_catalog.oid "
12734 "AND amopfamily = '%s'::pg_catalog.oid "
12735 "ORDER BY amopstrategy",
12736 opcinfo->dobj.catId.oid,
12739 else if (fout->remoteVersion >= 80400)
12741 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12742 "amopopr::pg_catalog.regoperator, "
12743 "NULL AS sortfamily, "
12744 "NULL AS sortfamilynsp "
12745 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12746 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12747 "AND refobjid = '%u'::pg_catalog.oid "
12748 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12749 "AND objid = ao.oid "
12750 "ORDER BY amopstrategy",
12751 opcinfo->dobj.catId.oid);
12753 else if (fout->remoteVersion >= 80300)
12755 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12756 "amopopr::pg_catalog.regoperator, "
12757 "NULL AS sortfamily, "
12758 "NULL AS sortfamilynsp "
12759 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12760 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12761 "AND refobjid = '%u'::pg_catalog.oid "
12762 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12763 "AND objid = ao.oid "
12764 "ORDER BY amopstrategy",
12765 opcinfo->dobj.catId.oid);
12770 * Here, we print all entries since there are no opfamilies and hence
12771 * no loose operators to worry about.
12773 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12774 "amopopr::pg_catalog.regoperator, "
12775 "NULL AS sortfamily, "
12776 "NULL AS sortfamilynsp "
12777 "FROM pg_catalog.pg_amop "
12778 "WHERE amopclaid = '%u'::pg_catalog.oid "
12779 "ORDER BY amopstrategy",
12780 opcinfo->dobj.catId.oid);
12783 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12785 ntups = PQntuples(res);
12787 i_amopstrategy = PQfnumber(res, "amopstrategy");
12788 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12789 i_amopopr = PQfnumber(res, "amopopr");
12790 i_sortfamily = PQfnumber(res, "sortfamily");
12791 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12793 for (i = 0; i < ntups; i++)
12795 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12796 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12797 amopopr = PQgetvalue(res, i, i_amopopr);
12798 sortfamily = PQgetvalue(res, i, i_sortfamily);
12799 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12802 appendPQExpBufferStr(q, " ,\n ");
12804 appendPQExpBuffer(q, "OPERATOR %s %s",
12805 amopstrategy, amopopr);
12807 if (strlen(sortfamily) > 0)
12809 appendPQExpBufferStr(q, " FOR ORDER BY ");
12810 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12811 appendPQExpBufferStr(q, fmtId(sortfamily));
12814 if (strcmp(amopreqcheck, "t") == 0)
12815 appendPQExpBufferStr(q, " RECHECK");
12823 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12825 * Print only those opfamily members that are tied to the opclass by
12826 * pg_depend entries.
12828 * We print the amproclefttype/amprocrighttype even though in most cases
12829 * the backend could deduce the right values, because of the corner case
12830 * of a btree sort support function for a cross-type comparison. That's
12831 * only allowed in 9.2 and later, but for simplicity print them in all
12832 * versions that have the columns.
12834 resetPQExpBuffer(query);
12836 if (fout->remoteVersion >= 80300)
12838 appendPQExpBuffer(query, "SELECT amprocnum, "
12839 "amproc::pg_catalog.regprocedure, "
12840 "amproclefttype::pg_catalog.regtype, "
12841 "amprocrighttype::pg_catalog.regtype "
12842 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12843 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12844 "AND refobjid = '%u'::pg_catalog.oid "
12845 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12846 "AND objid = ap.oid "
12847 "ORDER BY amprocnum",
12848 opcinfo->dobj.catId.oid);
12852 appendPQExpBuffer(query, "SELECT amprocnum, "
12853 "amproc::pg_catalog.regprocedure, "
12854 "'' AS amproclefttype, "
12855 "'' AS amprocrighttype "
12856 "FROM pg_catalog.pg_amproc "
12857 "WHERE amopclaid = '%u'::pg_catalog.oid "
12858 "ORDER BY amprocnum",
12859 opcinfo->dobj.catId.oid);
12862 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12864 ntups = PQntuples(res);
12866 i_amprocnum = PQfnumber(res, "amprocnum");
12867 i_amproc = PQfnumber(res, "amproc");
12868 i_amproclefttype = PQfnumber(res, "amproclefttype");
12869 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12871 for (i = 0; i < ntups; i++)
12873 amprocnum = PQgetvalue(res, i, i_amprocnum);
12874 amproc = PQgetvalue(res, i, i_amproc);
12875 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12876 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12879 appendPQExpBufferStr(q, " ,\n ");
12881 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12883 if (*amproclefttype && *amprocrighttype)
12884 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12886 appendPQExpBuffer(q, " %s", amproc);
12894 * If needComma is still false it means we haven't added anything after
12895 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
12896 * clause with the same datatype. This isn't sanctioned by the
12897 * documentation, but actually DefineOpClass will treat it as a no-op.
12900 appendPQExpBuffer(q, "STORAGE %s", opcintype);
12902 appendPQExpBufferStr(q, ";\n");
12904 appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
12905 appendPQExpBuffer(nameusing, " USING %s",
12908 if (dopt->binary_upgrade)
12909 binary_upgrade_extension_member(q, &opcinfo->dobj,
12910 "OPERATOR CLASS", nameusing->data,
12911 opcinfo->dobj.namespace->dobj.name);
12913 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12914 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
12915 opcinfo->dobj.name,
12916 opcinfo->dobj.namespace->dobj.name,
12919 false, "OPERATOR CLASS", SECTION_PRE_DATA,
12920 q->data, delq->data, NULL,
12924 /* Dump Operator Class Comments */
12925 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12926 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
12927 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
12928 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
12933 destroyPQExpBuffer(query);
12934 destroyPQExpBuffer(q);
12935 destroyPQExpBuffer(delq);
12936 destroyPQExpBuffer(nameusing);
12941 * write out a single operator family definition
12943 * Note: this also dumps any "loose" operator members that aren't bound to a
12944 * specific opclass within the opfamily.
12947 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
12949 DumpOptions *dopt = fout->dopt;
12953 PQExpBuffer nameusing;
12956 PGresult *res_procs;
12959 int i_amopstrategy;
12960 int i_amopreqcheck;
12963 int i_sortfamilynsp;
12966 int i_amproclefttype;
12967 int i_amprocrighttype;
12969 char *amopstrategy;
12970 char *amopreqcheck;
12973 char *sortfamilynsp;
12976 char *amproclefttype;
12977 char *amprocrighttype;
12981 /* Skip if not to be dumped */
12982 if (!opfinfo->dobj.dump || dopt->dataOnly)
12985 query = createPQExpBuffer();
12986 q = createPQExpBuffer();
12987 delq = createPQExpBuffer();
12988 nameusing = createPQExpBuffer();
12991 * Fetch only those opfamily members that are tied directly to the
12992 * opfamily by pg_depend entries.
12994 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12995 * older server's opclass in which it is used. This is to avoid
12996 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12997 * older server and then reload into that old version. This can go away
12998 * once 8.3 is so old as to not be of interest to anyone.
13000 if (fout->remoteVersion >= 90100)
13002 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13003 "amopopr::pg_catalog.regoperator, "
13004 "opfname AS sortfamily, "
13005 "nspname AS sortfamilynsp "
13006 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13007 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13008 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13009 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13010 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13011 "AND refobjid = '%u'::pg_catalog.oid "
13012 "AND amopfamily = '%u'::pg_catalog.oid "
13013 "ORDER BY amopstrategy",
13014 opfinfo->dobj.catId.oid,
13015 opfinfo->dobj.catId.oid);
13017 else if (fout->remoteVersion >= 80400)
13019 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13020 "amopopr::pg_catalog.regoperator, "
13021 "NULL AS sortfamily, "
13022 "NULL AS sortfamilynsp "
13023 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13024 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13025 "AND refobjid = '%u'::pg_catalog.oid "
13026 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13027 "AND objid = ao.oid "
13028 "ORDER BY amopstrategy",
13029 opfinfo->dobj.catId.oid);
13033 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13034 "amopopr::pg_catalog.regoperator, "
13035 "NULL AS sortfamily, "
13036 "NULL AS sortfamilynsp "
13037 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13038 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13039 "AND refobjid = '%u'::pg_catalog.oid "
13040 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13041 "AND objid = ao.oid "
13042 "ORDER BY amopstrategy",
13043 opfinfo->dobj.catId.oid);
13046 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13048 resetPQExpBuffer(query);
13050 appendPQExpBuffer(query, "SELECT amprocnum, "
13051 "amproc::pg_catalog.regprocedure, "
13052 "amproclefttype::pg_catalog.regtype, "
13053 "amprocrighttype::pg_catalog.regtype "
13054 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13055 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13056 "AND refobjid = '%u'::pg_catalog.oid "
13057 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13058 "AND objid = ap.oid "
13059 "ORDER BY amprocnum",
13060 opfinfo->dobj.catId.oid);
13062 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13064 /* Get additional fields from the pg_opfamily row */
13065 resetPQExpBuffer(query);
13067 appendPQExpBuffer(query, "SELECT "
13068 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13069 "FROM pg_catalog.pg_opfamily "
13070 "WHERE oid = '%u'::pg_catalog.oid",
13071 opfinfo->dobj.catId.oid);
13073 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13075 i_amname = PQfnumber(res, "amname");
13077 /* amname will still be needed after we PQclear res */
13078 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13080 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13081 fmtQualifiedDumpable(opfinfo));
13082 appendPQExpBuffer(delq, " USING %s;\n",
13085 /* Build the fixed portion of the CREATE command */
13086 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13087 fmtQualifiedDumpable(opfinfo));
13088 appendPQExpBuffer(q, " USING %s;\n",
13093 /* Do we need an ALTER to add loose members? */
13094 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13096 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13097 fmtQualifiedDumpable(opfinfo));
13098 appendPQExpBuffer(q, " USING %s ADD\n ",
13104 * Now fetch and print the OPERATOR entries (pg_amop rows).
13106 ntups = PQntuples(res_ops);
13108 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13109 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13110 i_amopopr = PQfnumber(res_ops, "amopopr");
13111 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13112 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13114 for (i = 0; i < ntups; i++)
13116 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13117 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13118 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13119 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13120 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13123 appendPQExpBufferStr(q, " ,\n ");
13125 appendPQExpBuffer(q, "OPERATOR %s %s",
13126 amopstrategy, amopopr);
13128 if (strlen(sortfamily) > 0)
13130 appendPQExpBufferStr(q, " FOR ORDER BY ");
13131 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13132 appendPQExpBufferStr(q, fmtId(sortfamily));
13135 if (strcmp(amopreqcheck, "t") == 0)
13136 appendPQExpBufferStr(q, " RECHECK");
13142 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13144 ntups = PQntuples(res_procs);
13146 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13147 i_amproc = PQfnumber(res_procs, "amproc");
13148 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13149 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13151 for (i = 0; i < ntups; i++)
13153 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13154 amproc = PQgetvalue(res_procs, i, i_amproc);
13155 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13156 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13159 appendPQExpBufferStr(q, " ,\n ");
13161 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13162 amprocnum, amproclefttype, amprocrighttype,
13168 appendPQExpBufferStr(q, ";\n");
13171 appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13172 appendPQExpBuffer(nameusing, " USING %s",
13175 if (dopt->binary_upgrade)
13176 binary_upgrade_extension_member(q, &opfinfo->dobj,
13177 "OPERATOR FAMILY", nameusing->data,
13178 opfinfo->dobj.namespace->dobj.name);
13180 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13181 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13182 opfinfo->dobj.name,
13183 opfinfo->dobj.namespace->dobj.name,
13186 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13187 q->data, delq->data, NULL,
13191 /* Dump Operator Family Comments */
13192 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13193 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13194 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13195 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13199 PQclear(res_procs);
13200 destroyPQExpBuffer(query);
13201 destroyPQExpBuffer(q);
13202 destroyPQExpBuffer(delq);
13203 destroyPQExpBuffer(nameusing);
13208 * write out a single collation definition
13211 dumpCollation(Archive *fout, CollInfo *collinfo)
13213 DumpOptions *dopt = fout->dopt;
13219 int i_collprovider;
13222 const char *collprovider;
13223 const char *collcollate;
13224 const char *collctype;
13226 /* Skip if not to be dumped */
13227 if (!collinfo->dobj.dump || dopt->dataOnly)
13230 query = createPQExpBuffer();
13231 q = createPQExpBuffer();
13232 delq = createPQExpBuffer();
13234 qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13236 /* Get collation-specific details */
13237 if (fout->remoteVersion >= 100000)
13238 appendPQExpBuffer(query, "SELECT "
13243 "FROM pg_catalog.pg_collation c "
13244 "WHERE c.oid = '%u'::pg_catalog.oid",
13245 collinfo->dobj.catId.oid);
13247 appendPQExpBuffer(query, "SELECT "
13248 "'c' AS collprovider, "
13251 "NULL AS collversion "
13252 "FROM pg_catalog.pg_collation c "
13253 "WHERE c.oid = '%u'::pg_catalog.oid",
13254 collinfo->dobj.catId.oid);
13256 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13258 i_collprovider = PQfnumber(res, "collprovider");
13259 i_collcollate = PQfnumber(res, "collcollate");
13260 i_collctype = PQfnumber(res, "collctype");
13262 collprovider = PQgetvalue(res, 0, i_collprovider);
13263 collcollate = PQgetvalue(res, 0, i_collcollate);
13264 collctype = PQgetvalue(res, 0, i_collctype);
13266 appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13267 fmtQualifiedDumpable(collinfo));
13269 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13270 fmtQualifiedDumpable(collinfo));
13272 appendPQExpBufferStr(q, "provider = ");
13273 if (collprovider[0] == 'c')
13274 appendPQExpBufferStr(q, "libc");
13275 else if (collprovider[0] == 'i')
13276 appendPQExpBufferStr(q, "icu");
13277 else if (collprovider[0] == 'd')
13278 /* to allow dumping pg_catalog; not accepted on input */
13279 appendPQExpBufferStr(q, "default");
13281 exit_horribly(NULL,
13282 "unrecognized collation provider: %s\n",
13285 if (strcmp(collcollate, collctype) == 0)
13287 appendPQExpBufferStr(q, ", locale = ");
13288 appendStringLiteralAH(q, collcollate, fout);
13292 appendPQExpBufferStr(q, ", lc_collate = ");
13293 appendStringLiteralAH(q, collcollate, fout);
13294 appendPQExpBufferStr(q, ", lc_ctype = ");
13295 appendStringLiteralAH(q, collctype, fout);
13299 * For binary upgrade, carry over the collation version. For normal
13300 * dump/restore, omit the version, so that it is computed upon restore.
13302 if (dopt->binary_upgrade)
13306 i_collversion = PQfnumber(res, "collversion");
13307 if (!PQgetisnull(res, 0, i_collversion))
13309 appendPQExpBufferStr(q, ", version = ");
13310 appendStringLiteralAH(q,
13311 PQgetvalue(res, 0, i_collversion),
13316 appendPQExpBufferStr(q, ");\n");
13318 if (dopt->binary_upgrade)
13319 binary_upgrade_extension_member(q, &collinfo->dobj,
13320 "COLLATION", qcollname,
13321 collinfo->dobj.namespace->dobj.name);
13323 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13324 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13325 collinfo->dobj.name,
13326 collinfo->dobj.namespace->dobj.name,
13329 false, "COLLATION", SECTION_PRE_DATA,
13330 q->data, delq->data, NULL,
13334 /* Dump Collation Comments */
13335 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13336 dumpComment(fout, "COLLATION", qcollname,
13337 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13338 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13342 destroyPQExpBuffer(query);
13343 destroyPQExpBuffer(q);
13344 destroyPQExpBuffer(delq);
13350 * write out a single conversion definition
13353 dumpConversion(Archive *fout, ConvInfo *convinfo)
13355 DumpOptions *dopt = fout->dopt;
13361 int i_conforencoding;
13362 int i_contoencoding;
13365 const char *conforencoding;
13366 const char *contoencoding;
13367 const char *conproc;
13370 /* Skip if not to be dumped */
13371 if (!convinfo->dobj.dump || dopt->dataOnly)
13374 query = createPQExpBuffer();
13375 q = createPQExpBuffer();
13376 delq = createPQExpBuffer();
13378 qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13380 /* Get conversion-specific details */
13381 appendPQExpBuffer(query, "SELECT "
13382 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13383 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13384 "conproc, condefault "
13385 "FROM pg_catalog.pg_conversion c "
13386 "WHERE c.oid = '%u'::pg_catalog.oid",
13387 convinfo->dobj.catId.oid);
13389 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13391 i_conforencoding = PQfnumber(res, "conforencoding");
13392 i_contoencoding = PQfnumber(res, "contoencoding");
13393 i_conproc = PQfnumber(res, "conproc");
13394 i_condefault = PQfnumber(res, "condefault");
13396 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13397 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13398 conproc = PQgetvalue(res, 0, i_conproc);
13399 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13401 appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13402 fmtQualifiedDumpable(convinfo));
13404 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13405 (condefault) ? "DEFAULT " : "",
13406 fmtQualifiedDumpable(convinfo));
13407 appendStringLiteralAH(q, conforencoding, fout);
13408 appendPQExpBufferStr(q, " TO ");
13409 appendStringLiteralAH(q, contoencoding, fout);
13410 /* regproc output is already sufficiently quoted */
13411 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13413 if (dopt->binary_upgrade)
13414 binary_upgrade_extension_member(q, &convinfo->dobj,
13415 "CONVERSION", qconvname,
13416 convinfo->dobj.namespace->dobj.name);
13418 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13419 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13420 convinfo->dobj.name,
13421 convinfo->dobj.namespace->dobj.name,
13424 false, "CONVERSION", SECTION_PRE_DATA,
13425 q->data, delq->data, NULL,
13429 /* Dump Conversion Comments */
13430 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13431 dumpComment(fout, "CONVERSION", qconvname,
13432 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13433 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13437 destroyPQExpBuffer(query);
13438 destroyPQExpBuffer(q);
13439 destroyPQExpBuffer(delq);
13444 * format_aggregate_signature: generate aggregate name and argument list
13446 * The argument type names are qualified if needed. The aggregate name
13447 * is never qualified.
13450 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13452 PQExpBufferData buf;
13455 initPQExpBuffer(&buf);
13457 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13459 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13461 if (agginfo->aggfn.nargs == 0)
13462 appendPQExpBuffer(&buf, "(*)");
13465 appendPQExpBufferChar(&buf, '(');
13466 for (j = 0; j < agginfo->aggfn.nargs; j++)
13470 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13473 appendPQExpBuffer(&buf, "%s%s",
13474 (j > 0) ? ", " : "",
13478 appendPQExpBufferChar(&buf, ')');
13485 * write out a single aggregate definition
13488 dumpAgg(Archive *fout, AggInfo *agginfo)
13490 DumpOptions *dopt = fout->dopt;
13494 PQExpBuffer details;
13495 char *aggsig; /* identity signature */
13496 char *aggfullsig = NULL; /* full signature */
13501 int i_aggcombinefn;
13503 int i_aggdeserialfn;
13505 int i_aggminvtransfn;
13507 int i_aggfinalextra;
13508 int i_aggmfinalextra;
13509 int i_aggfinalmodify;
13510 int i_aggmfinalmodify;
13513 int i_aggtranstype;
13514 int i_aggtransspace;
13515 int i_aggmtranstype;
13516 int i_aggmtransspace;
13521 const char *aggtransfn;
13522 const char *aggfinalfn;
13523 const char *aggcombinefn;
13524 const char *aggserialfn;
13525 const char *aggdeserialfn;
13526 const char *aggmtransfn;
13527 const char *aggminvtransfn;
13528 const char *aggmfinalfn;
13529 bool aggfinalextra;
13530 bool aggmfinalextra;
13531 char aggfinalmodify;
13532 char aggmfinalmodify;
13533 const char *aggsortop;
13534 char *aggsortconvop;
13536 const char *aggtranstype;
13537 const char *aggtransspace;
13538 const char *aggmtranstype;
13539 const char *aggmtransspace;
13540 const char *agginitval;
13541 const char *aggminitval;
13543 const char *proparallel;
13544 char defaultfinalmodify;
13546 /* Skip if not to be dumped */
13547 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13550 query = createPQExpBuffer();
13551 q = createPQExpBuffer();
13552 delq = createPQExpBuffer();
13553 details = createPQExpBuffer();
13555 /* Get aggregate-specific details */
13556 if (fout->remoteVersion >= 110000)
13558 appendPQExpBuffer(query, "SELECT aggtransfn, "
13559 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13560 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13561 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13562 "aggfinalextra, aggmfinalextra, "
13563 "aggfinalmodify, aggmfinalmodify, "
13566 "aggtransspace, agginitval, "
13567 "aggmtransspace, aggminitval, "
13568 "true AS convertok, "
13569 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13570 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13572 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13573 "WHERE a.aggfnoid = p.oid "
13574 "AND p.oid = '%u'::pg_catalog.oid",
13575 agginfo->aggfn.dobj.catId.oid);
13577 else if (fout->remoteVersion >= 90600)
13579 appendPQExpBuffer(query, "SELECT aggtransfn, "
13580 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13581 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13582 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13583 "aggfinalextra, aggmfinalextra, "
13584 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13587 "aggtransspace, agginitval, "
13588 "aggmtransspace, aggminitval, "
13589 "true AS convertok, "
13590 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13591 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13593 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13594 "WHERE a.aggfnoid = p.oid "
13595 "AND p.oid = '%u'::pg_catalog.oid",
13596 agginfo->aggfn.dobj.catId.oid);
13598 else if (fout->remoteVersion >= 90400)
13600 appendPQExpBuffer(query, "SELECT aggtransfn, "
13601 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13602 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13603 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13604 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13605 "aggfinalextra, aggmfinalextra, "
13606 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13609 "aggtransspace, agginitval, "
13610 "aggmtransspace, aggminitval, "
13611 "true AS convertok, "
13612 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13613 "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 >= 80400)
13621 appendPQExpBuffer(query, "SELECT aggtransfn, "
13622 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13623 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13624 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13625 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13626 "0 AS aggmtranstype, false AS aggfinalextra, "
13627 "false AS aggmfinalextra, "
13628 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13631 "0 AS aggtransspace, agginitval, "
13632 "0 AS aggmtransspace, NULL AS aggminitval, "
13633 "true AS convertok, "
13634 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13635 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13636 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13637 "WHERE a.aggfnoid = p.oid "
13638 "AND p.oid = '%u'::pg_catalog.oid",
13639 agginfo->aggfn.dobj.catId.oid);
13641 else if (fout->remoteVersion >= 80100)
13643 appendPQExpBuffer(query, "SELECT aggtransfn, "
13644 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13645 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13646 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13647 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13648 "0 AS aggmtranstype, false AS aggfinalextra, "
13649 "false AS aggmfinalextra, "
13650 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13653 "0 AS aggtransspace, agginitval, "
13654 "0 AS aggmtransspace, NULL AS aggminitval, "
13655 "true AS convertok "
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);
13663 appendPQExpBuffer(query, "SELECT aggtransfn, "
13664 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13665 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13666 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13667 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13668 "0 AS aggmtranstype, false AS aggfinalextra, "
13669 "false AS aggmfinalextra, "
13670 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13673 "0 AS aggtransspace, agginitval, "
13674 "0 AS aggmtransspace, NULL AS aggminitval, "
13675 "true AS convertok "
13676 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13677 "WHERE a.aggfnoid = p.oid "
13678 "AND p.oid = '%u'::pg_catalog.oid",
13679 agginfo->aggfn.dobj.catId.oid);
13682 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13684 i_aggtransfn = PQfnumber(res, "aggtransfn");
13685 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13686 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13687 i_aggserialfn = PQfnumber(res, "aggserialfn");
13688 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13689 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13690 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13691 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13692 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13693 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13694 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13695 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13696 i_aggsortop = PQfnumber(res, "aggsortop");
13697 i_aggkind = PQfnumber(res, "aggkind");
13698 i_aggtranstype = PQfnumber(res, "aggtranstype");
13699 i_aggtransspace = PQfnumber(res, "aggtransspace");
13700 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13701 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13702 i_agginitval = PQfnumber(res, "agginitval");
13703 i_aggminitval = PQfnumber(res, "aggminitval");
13704 i_convertok = PQfnumber(res, "convertok");
13705 i_proparallel = PQfnumber(res, "proparallel");
13707 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13708 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13709 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13710 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13711 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13712 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13713 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13714 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13715 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13716 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13717 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13718 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13719 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13720 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13721 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13722 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13723 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13724 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13725 agginitval = PQgetvalue(res, 0, i_agginitval);
13726 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13727 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13729 if (fout->remoteVersion >= 80400)
13731 /* 8.4 or later; we rely on server-side code for most of the work */
13735 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13736 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13737 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13738 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13741 /* pre-8.4, do it ourselves */
13742 aggsig = format_aggregate_signature(agginfo, fout, true);
13744 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13746 if (i_proparallel != -1)
13747 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13749 proparallel = NULL;
13753 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13764 /* identify default modify flag for aggkind (must match DefineAggregate) */
13765 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13766 /* replace omitted flags for old versions */
13767 if (aggfinalmodify == '0')
13768 aggfinalmodify = defaultfinalmodify;
13769 if (aggmfinalmodify == '0')
13770 aggmfinalmodify = defaultfinalmodify;
13772 /* regproc and regtype output is already sufficiently quoted */
13773 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13774 aggtransfn, aggtranstype);
13776 if (strcmp(aggtransspace, "0") != 0)
13778 appendPQExpBuffer(details, ",\n SSPACE = %s",
13782 if (!PQgetisnull(res, 0, i_agginitval))
13784 appendPQExpBufferStr(details, ",\n INITCOND = ");
13785 appendStringLiteralAH(details, agginitval, fout);
13788 if (strcmp(aggfinalfn, "-") != 0)
13790 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13793 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13794 if (aggfinalmodify != defaultfinalmodify)
13796 switch (aggfinalmodify)
13798 case AGGMODIFY_READ_ONLY:
13799 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
13801 case AGGMODIFY_SHARABLE:
13802 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHARABLE");
13804 case AGGMODIFY_READ_WRITE:
13805 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
13808 exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13809 agginfo->aggfn.dobj.name);
13815 if (strcmp(aggcombinefn, "-") != 0)
13816 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
13818 if (strcmp(aggserialfn, "-") != 0)
13819 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
13821 if (strcmp(aggdeserialfn, "-") != 0)
13822 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
13824 if (strcmp(aggmtransfn, "-") != 0)
13826 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
13832 if (strcmp(aggmtransspace, "0") != 0)
13834 appendPQExpBuffer(details, ",\n MSSPACE = %s",
13838 if (!PQgetisnull(res, 0, i_aggminitval))
13840 appendPQExpBufferStr(details, ",\n MINITCOND = ");
13841 appendStringLiteralAH(details, aggminitval, fout);
13844 if (strcmp(aggmfinalfn, "-") != 0)
13846 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
13848 if (aggmfinalextra)
13849 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
13850 if (aggmfinalmodify != defaultfinalmodify)
13852 switch (aggmfinalmodify)
13854 case AGGMODIFY_READ_ONLY:
13855 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
13857 case AGGMODIFY_SHARABLE:
13858 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHARABLE");
13860 case AGGMODIFY_READ_WRITE:
13861 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
13864 exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13865 agginfo->aggfn.dobj.name);
13871 aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13874 appendPQExpBuffer(details, ",\n SORTOP = %s",
13876 free(aggsortconvop);
13879 if (aggkind == AGGKIND_HYPOTHETICAL)
13880 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
13882 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13884 if (proparallel[0] == PROPARALLEL_SAFE)
13885 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
13886 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13887 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
13888 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13889 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13890 agginfo->aggfn.dobj.name);
13893 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13894 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13897 appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
13898 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13899 aggfullsig ? aggfullsig : aggsig, details->data);
13901 if (dopt->binary_upgrade)
13902 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
13903 "AGGREGATE", aggsig,
13904 agginfo->aggfn.dobj.namespace->dobj.name);
13906 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
13907 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
13908 agginfo->aggfn.dobj.dumpId,
13910 agginfo->aggfn.dobj.namespace->dobj.name,
13912 agginfo->aggfn.rolname,
13913 false, "AGGREGATE", SECTION_PRE_DATA,
13914 q->data, delq->data, NULL,
13918 /* Dump Aggregate Comments */
13919 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
13920 dumpComment(fout, "AGGREGATE", aggsig,
13921 agginfo->aggfn.dobj.namespace->dobj.name,
13922 agginfo->aggfn.rolname,
13923 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13925 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
13926 dumpSecLabel(fout, "AGGREGATE", aggsig,
13927 agginfo->aggfn.dobj.namespace->dobj.name,
13928 agginfo->aggfn.rolname,
13929 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13932 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
13933 * command look like a function's GRANT; in particular this affects the
13934 * syntax for zero-argument aggregates and ordered-set aggregates.
13938 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
13940 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
13941 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
13942 "FUNCTION", aggsig, NULL,
13943 agginfo->aggfn.dobj.namespace->dobj.name,
13944 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
13945 agginfo->aggfn.rproacl,
13946 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
13955 destroyPQExpBuffer(query);
13956 destroyPQExpBuffer(q);
13957 destroyPQExpBuffer(delq);
13958 destroyPQExpBuffer(details);
13963 * write out a single text search parser
13966 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
13968 DumpOptions *dopt = fout->dopt;
13973 /* Skip if not to be dumped */
13974 if (!prsinfo->dobj.dump || dopt->dataOnly)
13977 q = createPQExpBuffer();
13978 delq = createPQExpBuffer();
13980 qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
13982 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
13983 fmtQualifiedDumpable(prsinfo));
13985 appendPQExpBuffer(q, " START = %s,\n",
13986 convertTSFunction(fout, prsinfo->prsstart));
13987 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
13988 convertTSFunction(fout, prsinfo->prstoken));
13989 appendPQExpBuffer(q, " END = %s,\n",
13990 convertTSFunction(fout, prsinfo->prsend));
13991 if (prsinfo->prsheadline != InvalidOid)
13992 appendPQExpBuffer(q, " HEADLINE = %s,\n",
13993 convertTSFunction(fout, prsinfo->prsheadline));
13994 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
13995 convertTSFunction(fout, prsinfo->prslextype));
13997 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
13998 fmtQualifiedDumpable(prsinfo));
14000 if (dopt->binary_upgrade)
14001 binary_upgrade_extension_member(q, &prsinfo->dobj,
14002 "TEXT SEARCH PARSER", qprsname,
14003 prsinfo->dobj.namespace->dobj.name);
14005 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14006 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14007 prsinfo->dobj.name,
14008 prsinfo->dobj.namespace->dobj.name,
14011 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14012 q->data, delq->data, NULL,
14016 /* Dump Parser Comments */
14017 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14018 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14019 prsinfo->dobj.namespace->dobj.name, "",
14020 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14022 destroyPQExpBuffer(q);
14023 destroyPQExpBuffer(delq);
14029 * write out a single text search dictionary
14032 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14034 DumpOptions *dopt = fout->dopt;
14043 /* Skip if not to be dumped */
14044 if (!dictinfo->dobj.dump || dopt->dataOnly)
14047 q = createPQExpBuffer();
14048 delq = createPQExpBuffer();
14049 query = createPQExpBuffer();
14051 qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14053 /* Fetch name and namespace of the dictionary's template */
14054 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14055 "FROM pg_ts_template p, pg_namespace n "
14056 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14057 dictinfo->dicttemplate);
14058 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14059 nspname = PQgetvalue(res, 0, 0);
14060 tmplname = PQgetvalue(res, 0, 1);
14062 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14063 fmtQualifiedDumpable(dictinfo));
14065 appendPQExpBufferStr(q, " TEMPLATE = ");
14066 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14067 appendPQExpBufferStr(q, fmtId(tmplname));
14071 /* the dictinitoption can be dumped straight into the command */
14072 if (dictinfo->dictinitoption)
14073 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14075 appendPQExpBufferStr(q, " );\n");
14077 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14078 fmtQualifiedDumpable(dictinfo));
14080 if (dopt->binary_upgrade)
14081 binary_upgrade_extension_member(q, &dictinfo->dobj,
14082 "TEXT SEARCH DICTIONARY", qdictname,
14083 dictinfo->dobj.namespace->dobj.name);
14085 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14086 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14087 dictinfo->dobj.name,
14088 dictinfo->dobj.namespace->dobj.name,
14091 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14092 q->data, delq->data, NULL,
14096 /* Dump Dictionary Comments */
14097 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14098 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14099 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14100 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14102 destroyPQExpBuffer(q);
14103 destroyPQExpBuffer(delq);
14104 destroyPQExpBuffer(query);
14110 * write out a single text search template
14113 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14115 DumpOptions *dopt = fout->dopt;
14120 /* Skip if not to be dumped */
14121 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14124 q = createPQExpBuffer();
14125 delq = createPQExpBuffer();
14127 qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14129 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14130 fmtQualifiedDumpable(tmplinfo));
14132 if (tmplinfo->tmplinit != InvalidOid)
14133 appendPQExpBuffer(q, " INIT = %s,\n",
14134 convertTSFunction(fout, tmplinfo->tmplinit));
14135 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14136 convertTSFunction(fout, tmplinfo->tmpllexize));
14138 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14139 fmtQualifiedDumpable(tmplinfo));
14141 if (dopt->binary_upgrade)
14142 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14143 "TEXT SEARCH TEMPLATE", qtmplname,
14144 tmplinfo->dobj.namespace->dobj.name);
14146 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14147 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14148 tmplinfo->dobj.name,
14149 tmplinfo->dobj.namespace->dobj.name,
14152 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14153 q->data, delq->data, NULL,
14157 /* Dump Template Comments */
14158 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14159 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14160 tmplinfo->dobj.namespace->dobj.name, "",
14161 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14163 destroyPQExpBuffer(q);
14164 destroyPQExpBuffer(delq);
14170 * write out a single text search configuration
14173 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14175 DumpOptions *dopt = fout->dopt;
14188 /* Skip if not to be dumped */
14189 if (!cfginfo->dobj.dump || dopt->dataOnly)
14192 q = createPQExpBuffer();
14193 delq = createPQExpBuffer();
14194 query = createPQExpBuffer();
14196 qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14198 /* Fetch name and namespace of the config's parser */
14199 appendPQExpBuffer(query, "SELECT nspname, prsname "
14200 "FROM pg_ts_parser p, pg_namespace n "
14201 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14202 cfginfo->cfgparser);
14203 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14204 nspname = PQgetvalue(res, 0, 0);
14205 prsname = PQgetvalue(res, 0, 1);
14207 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14208 fmtQualifiedDumpable(cfginfo));
14210 appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14211 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14215 resetPQExpBuffer(query);
14216 appendPQExpBuffer(query,
14218 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14219 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14220 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14221 "FROM pg_catalog.pg_ts_config_map AS m\n"
14222 "WHERE m.mapcfg = '%u'\n"
14223 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14224 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14226 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14227 ntups = PQntuples(res);
14229 i_tokenname = PQfnumber(res, "tokenname");
14230 i_dictname = PQfnumber(res, "dictname");
14232 for (i = 0; i < ntups; i++)
14234 char *tokenname = PQgetvalue(res, i, i_tokenname);
14235 char *dictname = PQgetvalue(res, i, i_dictname);
14238 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14240 /* starting a new token type, so start a new command */
14242 appendPQExpBufferStr(q, ";\n");
14243 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14244 fmtQualifiedDumpable(cfginfo));
14245 /* tokenname needs quoting, dictname does NOT */
14246 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14247 fmtId(tokenname), dictname);
14250 appendPQExpBuffer(q, ", %s", dictname);
14254 appendPQExpBufferStr(q, ";\n");
14258 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14259 fmtQualifiedDumpable(cfginfo));
14261 if (dopt->binary_upgrade)
14262 binary_upgrade_extension_member(q, &cfginfo->dobj,
14263 "TEXT SEARCH CONFIGURATION", qcfgname,
14264 cfginfo->dobj.namespace->dobj.name);
14266 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14267 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14268 cfginfo->dobj.name,
14269 cfginfo->dobj.namespace->dobj.name,
14272 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14273 q->data, delq->data, NULL,
14277 /* Dump Configuration Comments */
14278 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14279 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14280 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14281 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14283 destroyPQExpBuffer(q);
14284 destroyPQExpBuffer(delq);
14285 destroyPQExpBuffer(query);
14290 * dumpForeignDataWrapper
14291 * write out a single foreign-data wrapper definition
14294 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14296 DumpOptions *dopt = fout->dopt;
14301 /* Skip if not to be dumped */
14302 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14305 q = createPQExpBuffer();
14306 delq = createPQExpBuffer();
14308 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14310 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14313 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14314 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14316 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14317 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14319 if (strlen(fdwinfo->fdwoptions) > 0)
14320 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14322 appendPQExpBufferStr(q, ";\n");
14324 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14327 if (dopt->binary_upgrade)
14328 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14329 "FOREIGN DATA WRAPPER", qfdwname,
14332 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14333 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14334 fdwinfo->dobj.name,
14338 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14339 q->data, delq->data, NULL,
14343 /* Dump Foreign Data Wrapper Comments */
14344 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14345 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14346 NULL, fdwinfo->rolname,
14347 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14349 /* Handle the ACL */
14350 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14351 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14352 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14353 NULL, fdwinfo->rolname,
14354 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14355 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14359 destroyPQExpBuffer(q);
14360 destroyPQExpBuffer(delq);
14364 * dumpForeignServer
14365 * write out a foreign server definition
14368 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14370 DumpOptions *dopt = fout->dopt;
14378 /* Skip if not to be dumped */
14379 if (!srvinfo->dobj.dump || dopt->dataOnly)
14382 q = createPQExpBuffer();
14383 delq = createPQExpBuffer();
14384 query = createPQExpBuffer();
14386 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14388 /* look up the foreign-data wrapper */
14389 appendPQExpBuffer(query, "SELECT fdwname "
14390 "FROM pg_foreign_data_wrapper w "
14391 "WHERE w.oid = '%u'",
14393 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14394 fdwname = PQgetvalue(res, 0, 0);
14396 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14397 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14399 appendPQExpBufferStr(q, " TYPE ");
14400 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14402 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14404 appendPQExpBufferStr(q, " VERSION ");
14405 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14408 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14409 appendPQExpBufferStr(q, fmtId(fdwname));
14411 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14412 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14414 appendPQExpBufferStr(q, ";\n");
14416 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14419 if (dopt->binary_upgrade)
14420 binary_upgrade_extension_member(q, &srvinfo->dobj,
14421 "SERVER", qsrvname, NULL);
14423 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14424 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14425 srvinfo->dobj.name,
14429 false, "SERVER", SECTION_PRE_DATA,
14430 q->data, delq->data, NULL,
14434 /* Dump Foreign Server Comments */
14435 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14436 dumpComment(fout, "SERVER", qsrvname,
14437 NULL, srvinfo->rolname,
14438 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14440 /* Handle the ACL */
14441 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14442 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14443 "FOREIGN SERVER", qsrvname, NULL,
14444 NULL, srvinfo->rolname,
14445 srvinfo->srvacl, srvinfo->rsrvacl,
14446 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14448 /* Dump user mappings */
14449 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14450 dumpUserMappings(fout,
14451 srvinfo->dobj.name, NULL,
14453 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14457 destroyPQExpBuffer(q);
14458 destroyPQExpBuffer(delq);
14459 destroyPQExpBuffer(query);
14465 * This routine is used to dump any user mappings associated with the
14466 * server handed to this routine. Should be called after ArchiveEntry()
14470 dumpUserMappings(Archive *fout,
14471 const char *servername, const char *namespace,
14473 CatalogId catalogId, DumpId dumpId)
14485 q = createPQExpBuffer();
14486 tag = createPQExpBuffer();
14487 delq = createPQExpBuffer();
14488 query = createPQExpBuffer();
14491 * We read from the publicly accessible view pg_user_mappings, so as not
14492 * to fail if run by a non-superuser. Note that the view will show
14493 * umoptions as null if the user hasn't got privileges for the associated
14494 * server; this means that pg_dump will dump such a mapping, but with no
14495 * OPTIONS clause. A possible alternative is to skip such mappings
14496 * altogether, but it's not clear that that's an improvement.
14498 appendPQExpBuffer(query,
14500 "array_to_string(ARRAY("
14501 "SELECT quote_ident(option_name) || ' ' || "
14502 "quote_literal(option_value) "
14503 "FROM pg_options_to_table(umoptions) "
14504 "ORDER BY option_name"
14505 "), E',\n ') AS umoptions "
14506 "FROM pg_user_mappings "
14507 "WHERE srvid = '%u' "
14508 "ORDER BY usename",
14511 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14513 ntups = PQntuples(res);
14514 i_usename = PQfnumber(res, "usename");
14515 i_umoptions = PQfnumber(res, "umoptions");
14517 for (i = 0; i < ntups; i++)
14522 usename = PQgetvalue(res, i, i_usename);
14523 umoptions = PQgetvalue(res, i, i_umoptions);
14525 resetPQExpBuffer(q);
14526 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14527 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14529 if (umoptions && strlen(umoptions) > 0)
14530 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14532 appendPQExpBufferStr(q, ";\n");
14534 resetPQExpBuffer(delq);
14535 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14536 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14538 resetPQExpBuffer(tag);
14539 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14540 usename, servername);
14542 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14547 "USER MAPPING", SECTION_PRE_DATA,
14548 q->data, delq->data, NULL,
14555 destroyPQExpBuffer(query);
14556 destroyPQExpBuffer(delq);
14557 destroyPQExpBuffer(tag);
14558 destroyPQExpBuffer(q);
14562 * Write out default privileges information
14565 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14567 DumpOptions *dopt = fout->dopt;
14572 /* Skip if not to be dumped */
14573 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14576 q = createPQExpBuffer();
14577 tag = createPQExpBuffer();
14579 switch (daclinfo->defaclobjtype)
14581 case DEFACLOBJ_RELATION:
14584 case DEFACLOBJ_SEQUENCE:
14585 type = "SEQUENCES";
14587 case DEFACLOBJ_FUNCTION:
14588 type = "FUNCTIONS";
14590 case DEFACLOBJ_TYPE:
14593 case DEFACLOBJ_NAMESPACE:
14597 /* shouldn't get here */
14598 exit_horribly(NULL,
14599 "unrecognized object type in default privileges: %d\n",
14600 (int) daclinfo->defaclobjtype);
14601 type = ""; /* keep compiler quiet */
14604 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14606 /* build the actual command(s) for this tuple */
14607 if (!buildDefaultACLCommands(type,
14608 daclinfo->dobj.namespace != NULL ?
14609 daclinfo->dobj.namespace->dobj.name : NULL,
14610 daclinfo->defaclacl,
14611 daclinfo->rdefaclacl,
14612 daclinfo->initdefaclacl,
14613 daclinfo->initrdefaclacl,
14614 daclinfo->defaclrole,
14615 fout->remoteVersion,
14617 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14618 daclinfo->defaclacl);
14620 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14621 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14623 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14625 daclinfo->defaclrole,
14626 false, "DEFAULT ACL", SECTION_POST_DATA,
14631 destroyPQExpBuffer(tag);
14632 destroyPQExpBuffer(q);
14636 * Write out grant/revoke information
14638 * 'objCatId' is the catalog ID of the underlying object.
14639 * 'objDumpId' is the dump ID of the underlying object.
14640 * 'type' must be one of
14641 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14642 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14643 * 'name' is the formatted name of the object. Must be quoted etc. already.
14644 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14645 * (Currently we assume that subname is only provided for table columns.)
14646 * 'nspname' is the namespace the object is in (NULL if none).
14647 * 'owner' is the owner, NULL if there is no owner (for languages).
14648 * 'acls' contains the ACL string of the object from the appropriate system
14649 * catalog field; it will be passed to buildACLCommands for building the
14650 * appropriate GRANT commands.
14651 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14652 * object; it will be passed to buildACLCommands for building the
14653 * appropriate REVOKE commands.
14654 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14655 * privileges, to be recorded into pg_init_privs
14656 * 'initracls' In binary-upgrade mode, ACL string of the object's
14657 * revoked-from-default privileges, to be recorded into pg_init_privs
14659 * NB: initacls/initracls are needed because extensions can set privileges on
14660 * an object during the extension's script file and we record those into
14661 * pg_init_privs as that object's initial privileges.
14665 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14666 const char *type, const char *name, const char *subname,
14667 const char *nspname, const char *owner,
14668 const char *acls, const char *racls,
14669 const char *initacls, const char *initracls)
14671 DumpOptions *dopt = fout->dopt;
14674 /* Do nothing if ACL dump is not enabled */
14675 if (dopt->aclsSkip)
14678 /* --data-only skips ACLs *except* BLOB ACLs */
14679 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14682 sql = createPQExpBuffer();
14685 * Check to see if this object has had any initial ACLs included for it.
14686 * If so, we are in binary upgrade mode and these are the ACLs to turn
14687 * into GRANT and REVOKE statements to set and record the initial
14688 * privileges for an extension object. Let the backend know that these
14689 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14690 * before and after.
14692 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14694 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14695 if (!buildACLCommands(name, subname, nspname, type,
14696 initacls, initracls, owner,
14697 "", fout->remoteVersion, sql))
14698 exit_horribly(NULL,
14699 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14700 initacls, initracls, name, type);
14701 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14704 if (!buildACLCommands(name, subname, nspname, type,
14705 acls, racls, owner,
14706 "", fout->remoteVersion, sql))
14707 exit_horribly(NULL,
14708 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14709 acls, racls, name, type);
14713 PQExpBuffer tag = createPQExpBuffer();
14716 appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14718 appendPQExpBuffer(tag, "%s %s", type, name);
14720 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14721 tag->data, nspname,
14723 owner ? owner : "",
14724 false, "ACL", SECTION_NONE,
14725 sql->data, "", NULL,
14728 destroyPQExpBuffer(tag);
14731 destroyPQExpBuffer(sql);
14737 * This routine is used to dump any security labels associated with the
14738 * object handed to this routine. The routine takes the object type
14739 * and object name (ready to print, except for schema decoration), plus
14740 * the namespace and owner of the object (for labeling the ArchiveEntry),
14741 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14742 * plus the dump ID for the object (for setting a dependency).
14743 * If a matching pg_seclabel entry is found, it is dumped.
14745 * Note: although this routine takes a dumpId for dependency purposes,
14746 * that purpose is just to mark the dependency in the emitted dump file
14747 * for possible future use by pg_restore. We do NOT use it for determining
14748 * ordering of the label in the dump file, because this routine is called
14749 * after dependency sorting occurs. This routine should be called just after
14750 * calling ArchiveEntry() for the specified object.
14753 dumpSecLabel(Archive *fout, const char *type, const char *name,
14754 const char *namespace, const char *owner,
14755 CatalogId catalogId, int subid, DumpId dumpId)
14757 DumpOptions *dopt = fout->dopt;
14758 SecLabelItem *labels;
14763 /* do nothing, if --no-security-labels is supplied */
14764 if (dopt->no_security_labels)
14767 /* Security labels are schema not data ... except blob labels are data */
14768 if (strcmp(type, "LARGE OBJECT") != 0)
14770 if (dopt->dataOnly)
14775 /* We do dump blob security labels in binary-upgrade mode */
14776 if (dopt->schemaOnly && !dopt->binary_upgrade)
14780 /* Search for security labels associated with catalogId, using table */
14781 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14783 query = createPQExpBuffer();
14785 for (i = 0; i < nlabels; i++)
14788 * Ignore label entries for which the subid doesn't match.
14790 if (labels[i].objsubid != subid)
14793 appendPQExpBuffer(query,
14794 "SECURITY LABEL FOR %s ON %s ",
14795 fmtId(labels[i].provider), type);
14796 if (namespace && *namespace)
14797 appendPQExpBuffer(query, "%s.", fmtId(namespace));
14798 appendPQExpBuffer(query, "%s IS ", name);
14799 appendStringLiteralAH(query, labels[i].label, fout);
14800 appendPQExpBufferStr(query, ";\n");
14803 if (query->len > 0)
14805 PQExpBuffer tag = createPQExpBuffer();
14807 appendPQExpBuffer(tag, "%s %s", type, name);
14808 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14809 tag->data, namespace, NULL, owner,
14810 false, "SECURITY LABEL", SECTION_NONE,
14811 query->data, "", NULL,
14814 destroyPQExpBuffer(tag);
14817 destroyPQExpBuffer(query);
14821 * dumpTableSecLabel
14823 * As above, but dump security label for both the specified table (or view)
14827 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14829 DumpOptions *dopt = fout->dopt;
14830 SecLabelItem *labels;
14834 PQExpBuffer target;
14836 /* do nothing, if --no-security-labels is supplied */
14837 if (dopt->no_security_labels)
14840 /* SecLabel are SCHEMA not data */
14841 if (dopt->dataOnly)
14844 /* Search for comments associated with relation, using table */
14845 nlabels = findSecLabels(fout,
14846 tbinfo->dobj.catId.tableoid,
14847 tbinfo->dobj.catId.oid,
14850 /* If security labels exist, build SECURITY LABEL statements */
14854 query = createPQExpBuffer();
14855 target = createPQExpBuffer();
14857 for (i = 0; i < nlabels; i++)
14859 const char *colname;
14860 const char *provider = labels[i].provider;
14861 const char *label = labels[i].label;
14862 int objsubid = labels[i].objsubid;
14864 resetPQExpBuffer(target);
14867 appendPQExpBuffer(target, "%s %s", reltypename,
14868 fmtQualifiedDumpable(tbinfo));
14872 colname = getAttrName(objsubid, tbinfo);
14873 /* first fmtXXX result must be consumed before calling again */
14874 appendPQExpBuffer(target, "COLUMN %s",
14875 fmtQualifiedDumpable(tbinfo));
14876 appendPQExpBuffer(target, ".%s", fmtId(colname));
14878 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14879 fmtId(provider), target->data);
14880 appendStringLiteralAH(query, label, fout);
14881 appendPQExpBufferStr(query, ";\n");
14883 if (query->len > 0)
14885 resetPQExpBuffer(target);
14886 appendPQExpBuffer(target, "%s %s", reltypename,
14887 fmtId(tbinfo->dobj.name));
14888 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14890 tbinfo->dobj.namespace->dobj.name,
14891 NULL, tbinfo->rolname,
14892 false, "SECURITY LABEL", SECTION_NONE,
14893 query->data, "", NULL,
14894 &(tbinfo->dobj.dumpId), 1,
14897 destroyPQExpBuffer(query);
14898 destroyPQExpBuffer(target);
14904 * Find the security label(s), if any, associated with the given object.
14905 * All the objsubid values associated with the given classoid/objoid are
14906 * found with one search.
14909 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
14911 /* static storage for table of security labels */
14912 static SecLabelItem *labels = NULL;
14913 static int nlabels = -1;
14915 SecLabelItem *middle = NULL;
14917 SecLabelItem *high;
14920 /* Get security labels if we didn't already */
14922 nlabels = collectSecLabels(fout, &labels);
14924 if (nlabels <= 0) /* no labels, so no match is possible */
14931 * Do binary search to find some item matching the object.
14934 high = &labels[nlabels - 1];
14935 while (low <= high)
14937 middle = low + (high - low) / 2;
14939 if (classoid < middle->classoid)
14941 else if (classoid > middle->classoid)
14943 else if (objoid < middle->objoid)
14945 else if (objoid > middle->objoid)
14948 break; /* found a match */
14951 if (low > high) /* no matches */
14958 * Now determine how many items match the object. The search loop
14959 * invariant still holds: only items between low and high inclusive could
14963 while (middle > low)
14965 if (classoid != middle[-1].classoid ||
14966 objoid != middle[-1].objoid)
14975 while (middle <= high)
14977 if (classoid != middle->classoid ||
14978 objoid != middle->objoid)
14990 * Construct a table of all security labels available for database objects.
14991 * It's much faster to pull them all at once.
14993 * The table is sorted by classoid/objid/objsubid for speed in lookup.
14996 collectSecLabels(Archive *fout, SecLabelItem **items)
15007 SecLabelItem *labels;
15009 query = createPQExpBuffer();
15011 appendPQExpBufferStr(query,
15012 "SELECT label, provider, classoid, objoid, objsubid "
15013 "FROM pg_catalog.pg_seclabel "
15014 "ORDER BY classoid, objoid, objsubid");
15016 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15018 /* Construct lookup table containing OIDs in numeric form */
15019 i_label = PQfnumber(res, "label");
15020 i_provider = PQfnumber(res, "provider");
15021 i_classoid = PQfnumber(res, "classoid");
15022 i_objoid = PQfnumber(res, "objoid");
15023 i_objsubid = PQfnumber(res, "objsubid");
15025 ntups = PQntuples(res);
15027 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15029 for (i = 0; i < ntups; i++)
15031 labels[i].label = PQgetvalue(res, i, i_label);
15032 labels[i].provider = PQgetvalue(res, i, i_provider);
15033 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15034 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15035 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15038 /* Do NOT free the PGresult since we are keeping pointers into it */
15039 destroyPQExpBuffer(query);
15047 * write out to fout the declarations (not data) of a user-defined table
15050 dumpTable(Archive *fout, TableInfo *tbinfo)
15052 DumpOptions *dopt = fout->dopt;
15056 * noop if we are not dumping anything about this table, or if we are
15057 * doing a data-only dump
15059 if (!tbinfo->dobj.dump || dopt->dataOnly)
15062 if (tbinfo->relkind == RELKIND_SEQUENCE)
15063 dumpSequence(fout, tbinfo);
15065 dumpTableSchema(fout, tbinfo);
15067 /* Handle the ACL here */
15068 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15069 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15071 const char *objtype =
15072 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15074 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15075 objtype, namecopy, NULL,
15076 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15077 tbinfo->relacl, tbinfo->rrelacl,
15078 tbinfo->initrelacl, tbinfo->initrrelacl);
15082 * Handle column ACLs, if any. Note: we pull these with a separate query
15083 * rather than trying to fetch them during getTableAttrs, so that we won't
15084 * miss ACLs on system columns.
15086 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15088 PQExpBuffer query = createPQExpBuffer();
15092 if (fout->remoteVersion >= 90600)
15094 PQExpBuffer acl_subquery = createPQExpBuffer();
15095 PQExpBuffer racl_subquery = createPQExpBuffer();
15096 PQExpBuffer initacl_subquery = createPQExpBuffer();
15097 PQExpBuffer initracl_subquery = createPQExpBuffer();
15099 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15100 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15101 dopt->binary_upgrade);
15103 appendPQExpBuffer(query,
15104 "SELECT at.attname, "
15107 "%s AS initattacl, "
15108 "%s AS initrattacl "
15109 "FROM pg_catalog.pg_attribute at "
15110 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15111 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15112 "(at.attrelid = pip.objoid "
15113 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15114 "AND at.attnum = pip.objsubid) "
15115 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15116 "NOT at.attisdropped "
15118 "%s IS NOT NULL OR "
15119 "%s IS NOT NULL OR "
15120 "%s IS NOT NULL OR "
15122 "ORDER BY at.attnum",
15123 acl_subquery->data,
15124 racl_subquery->data,
15125 initacl_subquery->data,
15126 initracl_subquery->data,
15127 tbinfo->dobj.catId.oid,
15128 acl_subquery->data,
15129 racl_subquery->data,
15130 initacl_subquery->data,
15131 initracl_subquery->data);
15133 destroyPQExpBuffer(acl_subquery);
15134 destroyPQExpBuffer(racl_subquery);
15135 destroyPQExpBuffer(initacl_subquery);
15136 destroyPQExpBuffer(initracl_subquery);
15140 appendPQExpBuffer(query,
15141 "SELECT attname, attacl, NULL as rattacl, "
15142 "NULL AS initattacl, NULL AS initrattacl "
15143 "FROM pg_catalog.pg_attribute "
15144 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15145 "AND attacl IS NOT NULL "
15147 tbinfo->dobj.catId.oid);
15150 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15152 for (i = 0; i < PQntuples(res); i++)
15154 char *attname = PQgetvalue(res, i, 0);
15155 char *attacl = PQgetvalue(res, i, 1);
15156 char *rattacl = PQgetvalue(res, i, 2);
15157 char *initattacl = PQgetvalue(res, i, 3);
15158 char *initrattacl = PQgetvalue(res, i, 4);
15161 attnamecopy = pg_strdup(fmtId(attname));
15162 /* Column's GRANT type is always TABLE */
15163 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15164 "TABLE", namecopy, attnamecopy,
15165 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15166 attacl, rattacl, initattacl, initrattacl);
15170 destroyPQExpBuffer(query);
15179 * Create the AS clause for a view or materialized view. The semicolon is
15180 * stripped because a materialized view must add a WITH NO DATA clause.
15182 * This returns a new buffer which must be freed by the caller.
15185 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15187 PQExpBuffer query = createPQExpBuffer();
15188 PQExpBuffer result = createPQExpBuffer();
15192 /* Fetch the view definition */
15193 appendPQExpBuffer(query,
15194 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15195 tbinfo->dobj.catId.oid);
15197 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15199 if (PQntuples(res) != 1)
15201 if (PQntuples(res) < 1)
15202 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15203 tbinfo->dobj.name);
15205 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15206 tbinfo->dobj.name);
15209 len = PQgetlength(res, 0, 0);
15212 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15213 tbinfo->dobj.name);
15215 /* Strip off the trailing semicolon so that other things may follow. */
15216 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15217 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15220 destroyPQExpBuffer(query);
15226 * Create a dummy AS clause for a view. This is used when the real view
15227 * definition has to be postponed because of circular dependencies.
15228 * We must duplicate the view's external properties -- column names and types
15229 * (including collation) -- so that it works for subsequent references.
15231 * This returns a new buffer which must be freed by the caller.
15234 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15236 PQExpBuffer result = createPQExpBuffer();
15239 appendPQExpBufferStr(result, "SELECT");
15241 for (j = 0; j < tbinfo->numatts; j++)
15244 appendPQExpBufferChar(result, ',');
15245 appendPQExpBufferStr(result, "\n ");
15247 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15250 * Must add collation if not default for the type, because CREATE OR
15251 * REPLACE VIEW won't change it
15253 if (OidIsValid(tbinfo->attcollation[j]))
15257 coll = findCollationByOid(tbinfo->attcollation[j]);
15259 appendPQExpBuffer(result, " COLLATE %s",
15260 fmtQualifiedDumpable(coll));
15263 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15271 * write the declaration (not data) of one user-defined table or view
15274 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15276 DumpOptions *dopt = fout->dopt;
15277 PQExpBuffer q = createPQExpBuffer();
15278 PQExpBuffer delq = createPQExpBuffer();
15282 TableInfo **parents;
15283 int actual_atts; /* number of attrs in this CREATE statement */
15284 const char *reltypename;
15291 qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15292 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15294 if (dopt->binary_upgrade)
15295 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15296 tbinfo->dobj.catId.oid);
15298 /* Is it a table or a view? */
15299 if (tbinfo->relkind == RELKIND_VIEW)
15301 PQExpBuffer result;
15304 * Note: keep this code in sync with the is_view case in dumpRule()
15307 reltypename = "VIEW";
15309 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15311 if (dopt->binary_upgrade)
15312 binary_upgrade_set_pg_class_oids(fout, q,
15313 tbinfo->dobj.catId.oid, false);
15315 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15317 if (tbinfo->dummy_view)
15318 result = createDummyViewAsClause(fout, tbinfo);
15321 if (nonemptyReloptions(tbinfo->reloptions))
15323 appendPQExpBufferStr(q, " WITH (");
15324 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15325 appendPQExpBufferChar(q, ')');
15327 result = createViewAsClause(fout, tbinfo);
15329 appendPQExpBuffer(q, " AS\n%s", result->data);
15330 destroyPQExpBuffer(result);
15332 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15333 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15334 appendPQExpBufferStr(q, ";\n");
15338 switch (tbinfo->relkind)
15340 case RELKIND_FOREIGN_TABLE:
15342 PQExpBuffer query = createPQExpBuffer();
15347 reltypename = "FOREIGN TABLE";
15349 /* retrieve name of foreign server and generic options */
15350 appendPQExpBuffer(query,
15351 "SELECT fs.srvname, "
15352 "pg_catalog.array_to_string(ARRAY("
15353 "SELECT pg_catalog.quote_ident(option_name) || "
15354 "' ' || pg_catalog.quote_literal(option_value) "
15355 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15356 "ORDER BY option_name"
15357 "), E',\n ') AS ftoptions "
15358 "FROM pg_catalog.pg_foreign_table ft "
15359 "JOIN pg_catalog.pg_foreign_server fs "
15360 "ON (fs.oid = ft.ftserver) "
15361 "WHERE ft.ftrelid = '%u'",
15362 tbinfo->dobj.catId.oid);
15363 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15364 i_srvname = PQfnumber(res, "srvname");
15365 i_ftoptions = PQfnumber(res, "ftoptions");
15366 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15367 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15369 destroyPQExpBuffer(query);
15372 case RELKIND_MATVIEW:
15373 reltypename = "MATERIALIZED VIEW";
15378 reltypename = "TABLE";
15383 numParents = tbinfo->numParents;
15384 parents = tbinfo->parents;
15386 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15388 if (dopt->binary_upgrade)
15389 binary_upgrade_set_pg_class_oids(fout, q,
15390 tbinfo->dobj.catId.oid, false);
15392 appendPQExpBuffer(q, "CREATE %s%s %s",
15393 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15399 * Attach to type, if reloftype; except in case of a binary upgrade,
15400 * we dump the table normally and attach it to the type afterward.
15402 if (tbinfo->reloftype && !dopt->binary_upgrade)
15403 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15406 * If the table is a partition, dump it as such; except in the case of
15407 * a binary upgrade, we dump the table normally and attach it to the
15408 * parent afterward.
15410 if (tbinfo->ispartition && !dopt->binary_upgrade)
15412 TableInfo *parentRel = tbinfo->parents[0];
15415 * With partitions, unlike inheritance, there can only be one
15418 if (tbinfo->numParents != 1)
15419 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15420 tbinfo->numParents, tbinfo->dobj.name);
15422 appendPQExpBuffer(q, " PARTITION OF %s",
15423 fmtQualifiedDumpable(parentRel));
15426 if (tbinfo->relkind != RELKIND_MATVIEW)
15428 /* Dump the attributes */
15430 for (j = 0; j < tbinfo->numatts; j++)
15433 * Normally, dump if it's locally defined in this table, and
15434 * not dropped. But for binary upgrade, we'll dump all the
15435 * columns, and then fix up the dropped and nonlocal cases
15438 if (shouldPrintColumn(dopt, tbinfo, j))
15441 * Default value --- suppress if to be printed separately.
15443 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15444 !tbinfo->attrdefs[j]->separate);
15447 * Not Null constraint --- suppress if inherited, except
15448 * in binary-upgrade case where that won't work.
15450 bool has_notnull = (tbinfo->notnull[j] &&
15451 (!tbinfo->inhNotNull[j] ||
15452 dopt->binary_upgrade));
15455 * Skip column if fully defined by reloftype or the
15456 * partition parent.
15458 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15459 !has_default && !has_notnull && !dopt->binary_upgrade)
15462 /* Format properly if not first attr */
15463 if (actual_atts == 0)
15464 appendPQExpBufferStr(q, " (");
15466 appendPQExpBufferChar(q, ',');
15467 appendPQExpBufferStr(q, "\n ");
15470 /* Attribute name */
15471 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15473 if (tbinfo->attisdropped[j])
15476 * ALTER TABLE DROP COLUMN clears
15477 * pg_attribute.atttypid, so we will not have gotten a
15478 * valid type name; insert INTEGER as a stopgap. We'll
15479 * clean things up later.
15481 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15482 /* Skip all the rest, too */
15489 * In binary-upgrade mode, we always include the type. If
15490 * we aren't in binary-upgrade mode, then we skip the type
15491 * when creating a typed table ('OF type_name') or a
15492 * partition ('PARTITION OF'), since the type comes from
15493 * the parent/partitioned table.
15495 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15497 appendPQExpBuffer(q, " %s",
15498 tbinfo->atttypnames[j]);
15501 /* Add collation if not default for the type */
15502 if (OidIsValid(tbinfo->attcollation[j]))
15506 coll = findCollationByOid(tbinfo->attcollation[j]);
15508 appendPQExpBuffer(q, " COLLATE %s",
15509 fmtQualifiedDumpable(coll));
15513 appendPQExpBuffer(q, " DEFAULT %s",
15514 tbinfo->attrdefs[j]->adef_expr);
15517 appendPQExpBufferStr(q, " NOT NULL");
15522 * Add non-inherited CHECK constraints, if any.
15524 for (j = 0; j < tbinfo->ncheck; j++)
15526 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15528 if (constr->separate || !constr->conislocal)
15531 if (actual_atts == 0)
15532 appendPQExpBufferStr(q, " (\n ");
15534 appendPQExpBufferStr(q, ",\n ");
15536 appendPQExpBuffer(q, "CONSTRAINT %s ",
15537 fmtId(constr->dobj.name));
15538 appendPQExpBufferStr(q, constr->condef);
15544 appendPQExpBufferStr(q, "\n)");
15545 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15546 !dopt->binary_upgrade))
15549 * We must have a parenthesized attribute list, even though
15550 * empty, when not using the OF TYPE or PARTITION OF syntax.
15552 appendPQExpBufferStr(q, " (\n)");
15555 if (tbinfo->ispartition && !dopt->binary_upgrade)
15557 appendPQExpBufferChar(q, '\n');
15558 appendPQExpBufferStr(q, tbinfo->partbound);
15561 /* Emit the INHERITS clause, except if this is a partition. */
15562 if (numParents > 0 &&
15563 !tbinfo->ispartition &&
15564 !dopt->binary_upgrade)
15566 appendPQExpBufferStr(q, "\nINHERITS (");
15567 for (k = 0; k < numParents; k++)
15569 TableInfo *parentRel = parents[k];
15572 appendPQExpBufferStr(q, ", ");
15573 appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15575 appendPQExpBufferChar(q, ')');
15578 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15579 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15581 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15582 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15585 if (nonemptyReloptions(tbinfo->reloptions) ||
15586 nonemptyReloptions(tbinfo->toast_reloptions))
15588 bool addcomma = false;
15590 appendPQExpBufferStr(q, "\nWITH (");
15591 if (nonemptyReloptions(tbinfo->reloptions))
15594 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15596 if (nonemptyReloptions(tbinfo->toast_reloptions))
15599 appendPQExpBufferStr(q, ", ");
15600 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15603 appendPQExpBufferChar(q, ')');
15606 /* Dump generic options if any */
15607 if (ftoptions && ftoptions[0])
15608 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15611 * For materialized views, create the AS clause just like a view. At
15612 * this point, we always mark the view as not populated.
15614 if (tbinfo->relkind == RELKIND_MATVIEW)
15616 PQExpBuffer result;
15618 result = createViewAsClause(fout, tbinfo);
15619 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15621 destroyPQExpBuffer(result);
15624 appendPQExpBufferStr(q, ";\n");
15627 * To create binary-compatible heap files, we have to ensure the same
15628 * physical column order, including dropped columns, as in the
15629 * original. Therefore, we create dropped columns above and drop them
15630 * here, also updating their attlen/attalign values so that the
15631 * dropped column can be skipped properly. (We do not bother with
15632 * restoring the original attbyval setting.) Also, inheritance
15633 * relationships are set up by doing ALTER TABLE INHERIT rather than
15634 * using an INHERITS clause --- the latter would possibly mess up the
15635 * column order. That also means we have to take care about setting
15636 * attislocal correctly, plus fix up any inherited CHECK constraints.
15637 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15639 * We process foreign and partitioned tables here, even though they
15640 * lack heap storage, because they can participate in inheritance
15641 * relationships and we want this stuff to be consistent across the
15642 * inheritance tree. We can exclude indexes, toast tables, sequences
15643 * and matviews, even though they have storage, because we don't
15644 * support altering or dropping columns in them, nor can they be part
15645 * of inheritance trees.
15647 if (dopt->binary_upgrade &&
15648 (tbinfo->relkind == RELKIND_RELATION ||
15649 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15650 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15652 for (j = 0; j < tbinfo->numatts; j++)
15654 if (tbinfo->attisdropped[j])
15656 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15657 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15658 "SET attlen = %d, "
15659 "attalign = '%c', attbyval = false\n"
15660 "WHERE attname = ",
15662 tbinfo->attalign[j]);
15663 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15664 appendPQExpBufferStr(q, "\n AND attrelid = ");
15665 appendStringLiteralAH(q, qualrelname, fout);
15666 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15668 if (tbinfo->relkind == RELKIND_RELATION ||
15669 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15670 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15673 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15675 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15676 fmtId(tbinfo->attnames[j]));
15678 else if (!tbinfo->attislocal[j])
15680 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15681 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15682 "SET attislocal = false\n"
15683 "WHERE attname = ");
15684 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15685 appendPQExpBufferStr(q, "\n AND attrelid = ");
15686 appendStringLiteralAH(q, qualrelname, fout);
15687 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15691 for (k = 0; k < tbinfo->ncheck; k++)
15693 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15695 if (constr->separate || constr->conislocal)
15698 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15699 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15701 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15702 fmtId(constr->dobj.name));
15703 appendPQExpBuffer(q, "%s;\n", constr->condef);
15704 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15705 "SET conislocal = false\n"
15706 "WHERE contype = 'c' AND conname = ");
15707 appendStringLiteralAH(q, constr->dobj.name, fout);
15708 appendPQExpBufferStr(q, "\n AND conrelid = ");
15709 appendStringLiteralAH(q, qualrelname, fout);
15710 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15713 if (numParents > 0)
15715 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15716 for (k = 0; k < numParents; k++)
15718 TableInfo *parentRel = parents[k];
15720 /* In the partitioning case, we alter the parent */
15721 if (tbinfo->ispartition)
15722 appendPQExpBuffer(q,
15723 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15724 fmtQualifiedDumpable(parentRel));
15726 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15729 /* Partition needs specifying the bounds */
15730 if (tbinfo->ispartition)
15731 appendPQExpBuffer(q, "%s %s;\n",
15733 tbinfo->partbound);
15735 appendPQExpBuffer(q, "%s;\n",
15736 fmtQualifiedDumpable(parentRel));
15740 if (tbinfo->reloftype)
15742 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15743 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15745 tbinfo->reloftype);
15750 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15751 * relminmxid of all vacuumable relations. (While vacuum.c processes
15752 * TOAST tables semi-independently, here we see them only as children
15753 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15754 * child toast table is handled below.)
15756 if (dopt->binary_upgrade &&
15757 (tbinfo->relkind == RELKIND_RELATION ||
15758 tbinfo->relkind == RELKIND_MATVIEW))
15760 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15761 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15762 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15764 tbinfo->frozenxid, tbinfo->minmxid);
15765 appendStringLiteralAH(q, qualrelname, fout);
15766 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15768 if (tbinfo->toast_oid)
15771 * The toast table will have the same OID at restore, so we
15772 * can safely target it by OID.
15774 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15775 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15776 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15777 "WHERE oid = '%u';\n",
15778 tbinfo->toast_frozenxid,
15779 tbinfo->toast_minmxid, tbinfo->toast_oid);
15784 * In binary_upgrade mode, restore matviews' populated status by
15785 * poking pg_class directly. This is pretty ugly, but we can't use
15786 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15787 * matview is not populated even though this matview is; in any case,
15788 * we want to transfer the matview's heap storage, not run REFRESH.
15790 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15791 tbinfo->relispopulated)
15793 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15794 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15795 "SET relispopulated = 't'\n"
15797 appendStringLiteralAH(q, qualrelname, fout);
15798 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15802 * Dump additional per-column properties that we can't handle in the
15803 * main CREATE TABLE command.
15805 for (j = 0; j < tbinfo->numatts; j++)
15807 /* None of this applies to dropped columns */
15808 if (tbinfo->attisdropped[j])
15812 * If we didn't dump the column definition explicitly above, and
15813 * it is NOT NULL and did not inherit that property from a parent,
15814 * we have to mark it separately.
15816 if (!shouldPrintColumn(dopt, tbinfo, j) &&
15817 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15819 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15821 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15822 fmtId(tbinfo->attnames[j]));
15826 * Dump per-column statistics information. We only issue an ALTER
15827 * TABLE statement if the attstattarget entry for this column is
15828 * non-negative (i.e. it's not the default value)
15830 if (tbinfo->attstattarget[j] >= 0)
15832 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15834 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15835 fmtId(tbinfo->attnames[j]));
15836 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15837 tbinfo->attstattarget[j]);
15841 * Dump per-column storage information. The statement is only
15842 * dumped if the storage has been changed from the type's default.
15844 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15846 switch (tbinfo->attstorage[j])
15852 storage = "EXTERNAL";
15858 storage = "EXTENDED";
15865 * Only dump the statement if it's a storage type we recognize
15867 if (storage != NULL)
15869 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15871 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15872 fmtId(tbinfo->attnames[j]));
15873 appendPQExpBuffer(q, "SET STORAGE %s;\n",
15879 * Dump per-column attributes.
15881 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
15883 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15885 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15886 fmtId(tbinfo->attnames[j]));
15887 appendPQExpBuffer(q, "SET (%s);\n",
15888 tbinfo->attoptions[j]);
15892 * Dump per-column fdw options.
15894 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
15895 tbinfo->attfdwoptions[j] &&
15896 tbinfo->attfdwoptions[j][0] != '\0')
15898 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
15900 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15901 fmtId(tbinfo->attnames[j]));
15902 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
15903 tbinfo->attfdwoptions[j]);
15909 * dump properties we only have ALTER TABLE syntax for
15911 if ((tbinfo->relkind == RELKIND_RELATION ||
15912 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
15913 tbinfo->relkind == RELKIND_MATVIEW) &&
15914 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
15916 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
15918 /* nothing to do, will be set when the index is dumped */
15920 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
15922 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
15925 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
15927 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
15932 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
15933 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
15936 if (tbinfo->forcerowsec)
15937 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
15940 if (dopt->binary_upgrade)
15941 binary_upgrade_extension_member(q, &tbinfo->dobj,
15942 reltypename, qrelname,
15943 tbinfo->dobj.namespace->dobj.name);
15945 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15946 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15948 tbinfo->dobj.namespace->dobj.name,
15949 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
15951 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
15953 tbinfo->postponed_def ?
15954 SECTION_POST_DATA : SECTION_PRE_DATA,
15955 q->data, delq->data, NULL,
15960 /* Dump Table Comments */
15961 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15962 dumpTableComment(fout, tbinfo, reltypename);
15964 /* Dump Table Security Labels */
15965 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
15966 dumpTableSecLabel(fout, tbinfo, reltypename);
15968 /* Dump comments on inlined table constraints */
15969 for (j = 0; j < tbinfo->ncheck; j++)
15971 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15973 if (constr->separate || !constr->conislocal)
15976 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15977 dumpTableConstraintComment(fout, constr);
15980 destroyPQExpBuffer(q);
15981 destroyPQExpBuffer(delq);
15987 * dumpAttrDef --- dump an attribute's default-value declaration
15990 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
15992 DumpOptions *dopt = fout->dopt;
15993 TableInfo *tbinfo = adinfo->adtable;
15994 int adnum = adinfo->adnum;
16000 /* Skip if table definition not to be dumped */
16001 if (!tbinfo->dobj.dump || dopt->dataOnly)
16004 /* Skip if not "separate"; it was dumped in the table's definition */
16005 if (!adinfo->separate)
16008 q = createPQExpBuffer();
16009 delq = createPQExpBuffer();
16011 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16013 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16015 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16016 fmtId(tbinfo->attnames[adnum - 1]),
16017 adinfo->adef_expr);
16019 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16021 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16022 fmtId(tbinfo->attnames[adnum - 1]));
16024 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16026 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16027 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16029 tbinfo->dobj.namespace->dobj.name,
16032 false, "DEFAULT", SECTION_PRE_DATA,
16033 q->data, delq->data, NULL,
16038 destroyPQExpBuffer(q);
16039 destroyPQExpBuffer(delq);
16044 * getAttrName: extract the correct name for an attribute
16046 * The array tblInfo->attnames[] only provides names of user attributes;
16047 * if a system attribute number is supplied, we have to fake it.
16048 * We also do a little bit of bounds checking for safety's sake.
16050 static const char *
16051 getAttrName(int attrnum, TableInfo *tblInfo)
16053 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16054 return tblInfo->attnames[attrnum - 1];
16057 case SelfItemPointerAttributeNumber:
16059 case ObjectIdAttributeNumber:
16061 case MinTransactionIdAttributeNumber:
16063 case MinCommandIdAttributeNumber:
16065 case MaxTransactionIdAttributeNumber:
16067 case MaxCommandIdAttributeNumber:
16069 case TableOidAttributeNumber:
16072 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16073 attrnum, tblInfo->dobj.name);
16074 return NULL; /* keep compiler quiet */
16079 * write out to fout a user-defined index
16082 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16084 DumpOptions *dopt = fout->dopt;
16085 TableInfo *tbinfo = indxinfo->indextable;
16086 bool is_constraint = (indxinfo->indexconstraint != 0);
16091 if (dopt->dataOnly)
16094 q = createPQExpBuffer();
16095 delq = createPQExpBuffer();
16097 qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16100 * If there's an associated constraint, don't dump the index per se, but
16101 * do dump any comment for it. (This is safe because dependency ordering
16102 * will have ensured the constraint is emitted first.) Note that the
16103 * emitted comment has to be shown as depending on the constraint, not the
16104 * index, in such cases.
16106 if (!is_constraint)
16108 if (dopt->binary_upgrade)
16109 binary_upgrade_set_pg_class_oids(fout, q,
16110 indxinfo->dobj.catId.oid, true);
16112 /* Plain secondary index */
16113 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16115 /* If the index is clustered, we need to record that. */
16116 if (indxinfo->indisclustered)
16118 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16119 fmtQualifiedDumpable(tbinfo));
16120 /* index name is not qualified in this syntax */
16121 appendPQExpBuffer(q, " ON %s;\n",
16125 /* If the index defines identity, we need to record that. */
16126 if (indxinfo->indisreplident)
16128 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16129 fmtQualifiedDumpable(tbinfo));
16130 /* index name is not qualified in this syntax */
16131 appendPQExpBuffer(q, " INDEX %s;\n",
16135 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16136 fmtQualifiedDumpable(indxinfo));
16138 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16139 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16140 indxinfo->dobj.name,
16141 tbinfo->dobj.namespace->dobj.name,
16142 indxinfo->tablespace,
16143 tbinfo->rolname, false,
16144 "INDEX", SECTION_POST_DATA,
16145 q->data, delq->data, NULL,
16150 /* Dump Index Comments */
16151 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16152 dumpComment(fout, "INDEX", qindxname,
16153 tbinfo->dobj.namespace->dobj.name,
16155 indxinfo->dobj.catId, 0,
16156 is_constraint ? indxinfo->indexconstraint :
16157 indxinfo->dobj.dumpId);
16159 destroyPQExpBuffer(q);
16160 destroyPQExpBuffer(delq);
16166 * write out to fout a partitioned-index attachment clause
16169 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16171 if (fout->dopt->dataOnly)
16174 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16176 PQExpBuffer q = createPQExpBuffer();
16178 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16179 fmtQualifiedDumpable(attachinfo->parentIdx));
16180 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16181 fmtQualifiedDumpable(attachinfo->partitionIdx));
16183 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16184 attachinfo->dobj.name,
16187 false, "INDEX ATTACH", SECTION_POST_DATA,
16192 destroyPQExpBuffer(q);
16197 * dumpStatisticsExt
16198 * write out to fout an extended statistics object
16201 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16203 DumpOptions *dopt = fout->dopt;
16207 char *qstatsextname;
16211 /* Skip if not to be dumped */
16212 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16215 q = createPQExpBuffer();
16216 delq = createPQExpBuffer();
16217 query = createPQExpBuffer();
16219 qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16221 appendPQExpBuffer(query, "SELECT "
16222 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16223 statsextinfo->dobj.catId.oid);
16225 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16227 stxdef = PQgetvalue(res, 0, 0);
16229 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16230 appendPQExpBuffer(q, "%s;\n", stxdef);
16232 appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16233 fmtQualifiedDumpable(statsextinfo));
16235 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16236 ArchiveEntry(fout, statsextinfo->dobj.catId,
16237 statsextinfo->dobj.dumpId,
16238 statsextinfo->dobj.name,
16239 statsextinfo->dobj.namespace->dobj.name,
16241 statsextinfo->rolname, false,
16242 "STATISTICS", SECTION_POST_DATA,
16243 q->data, delq->data, NULL,
16247 /* Dump Statistics Comments */
16248 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16249 dumpComment(fout, "STATISTICS", qstatsextname,
16250 statsextinfo->dobj.namespace->dobj.name,
16251 statsextinfo->rolname,
16252 statsextinfo->dobj.catId, 0,
16253 statsextinfo->dobj.dumpId);
16256 destroyPQExpBuffer(q);
16257 destroyPQExpBuffer(delq);
16258 destroyPQExpBuffer(query);
16259 free(qstatsextname);
16264 * write out to fout a user-defined constraint
16267 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16269 DumpOptions *dopt = fout->dopt;
16270 TableInfo *tbinfo = coninfo->contable;
16275 /* Skip if not to be dumped */
16276 if (!coninfo->dobj.dump || dopt->dataOnly)
16279 q = createPQExpBuffer();
16280 delq = createPQExpBuffer();
16282 if (coninfo->contype == 'p' ||
16283 coninfo->contype == 'u' ||
16284 coninfo->contype == 'x')
16286 /* Index-related constraint */
16287 IndxInfo *indxinfo;
16290 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16292 if (indxinfo == NULL)
16293 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16294 coninfo->dobj.name);
16296 if (dopt->binary_upgrade)
16297 binary_upgrade_set_pg_class_oids(fout, q,
16298 indxinfo->dobj.catId.oid, true);
16300 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16301 fmtQualifiedDumpable(tbinfo));
16302 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16303 fmtId(coninfo->dobj.name));
16305 if (coninfo->condef)
16307 /* pg_get_constraintdef should have provided everything */
16308 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16312 appendPQExpBuffer(q, "%s (",
16313 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16314 for (k = 0; k < indxinfo->indnkeys; k++)
16316 int indkey = (int) indxinfo->indkeys[k];
16317 const char *attname;
16319 if (indkey == InvalidAttrNumber)
16321 attname = getAttrName(indkey, tbinfo);
16323 appendPQExpBuffer(q, "%s%s",
16324 (k == 0) ? "" : ", ",
16328 appendPQExpBufferChar(q, ')');
16330 if (nonemptyReloptions(indxinfo->indreloptions))
16332 appendPQExpBufferStr(q, " WITH (");
16333 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16334 appendPQExpBufferChar(q, ')');
16337 if (coninfo->condeferrable)
16339 appendPQExpBufferStr(q, " DEFERRABLE");
16340 if (coninfo->condeferred)
16341 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16344 appendPQExpBufferStr(q, ";\n");
16347 /* If the index is clustered, we need to record that. */
16348 if (indxinfo->indisclustered)
16350 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16351 fmtQualifiedDumpable(tbinfo));
16352 /* index name is not qualified in this syntax */
16353 appendPQExpBuffer(q, " ON %s;\n",
16354 fmtId(indxinfo->dobj.name));
16357 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16358 fmtQualifiedDumpable(tbinfo));
16359 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16360 fmtId(coninfo->dobj.name));
16362 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16364 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16365 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16367 tbinfo->dobj.namespace->dobj.name,
16368 indxinfo->tablespace,
16369 tbinfo->rolname, false,
16370 "CONSTRAINT", SECTION_POST_DATA,
16371 q->data, delq->data, NULL,
16375 else if (coninfo->contype == 'f')
16378 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16379 * current table data is not processed
16381 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16382 fmtQualifiedDumpable(tbinfo));
16383 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16384 fmtId(coninfo->dobj.name),
16387 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16388 fmtQualifiedDumpable(tbinfo));
16389 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16390 fmtId(coninfo->dobj.name));
16392 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16394 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16395 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16397 tbinfo->dobj.namespace->dobj.name,
16399 tbinfo->rolname, false,
16400 "FK CONSTRAINT", SECTION_POST_DATA,
16401 q->data, delq->data, NULL,
16405 else if (coninfo->contype == 'c' && tbinfo)
16407 /* CHECK constraint on a table */
16409 /* Ignore if not to be dumped separately, or if it was inherited */
16410 if (coninfo->separate && coninfo->conislocal)
16412 /* not ONLY since we want it to propagate to children */
16413 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16414 fmtQualifiedDumpable(tbinfo));
16415 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16416 fmtId(coninfo->dobj.name),
16419 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16420 fmtQualifiedDumpable(tbinfo));
16421 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16422 fmtId(coninfo->dobj.name));
16424 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16426 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16427 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16429 tbinfo->dobj.namespace->dobj.name,
16431 tbinfo->rolname, false,
16432 "CHECK CONSTRAINT", SECTION_POST_DATA,
16433 q->data, delq->data, NULL,
16438 else if (coninfo->contype == 'c' && tbinfo == NULL)
16440 /* CHECK constraint on a domain */
16441 TypeInfo *tyinfo = coninfo->condomain;
16443 /* Ignore if not to be dumped separately */
16444 if (coninfo->separate)
16446 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16447 fmtQualifiedDumpable(tyinfo));
16448 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16449 fmtId(coninfo->dobj.name),
16452 appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16453 fmtQualifiedDumpable(tyinfo));
16454 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16455 fmtId(coninfo->dobj.name));
16457 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16459 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16460 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16462 tyinfo->dobj.namespace->dobj.name,
16464 tyinfo->rolname, false,
16465 "CHECK CONSTRAINT", SECTION_POST_DATA,
16466 q->data, delq->data, NULL,
16473 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16477 /* Dump Constraint Comments --- only works for table constraints */
16478 if (tbinfo && coninfo->separate &&
16479 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16480 dumpTableConstraintComment(fout, coninfo);
16483 destroyPQExpBuffer(q);
16484 destroyPQExpBuffer(delq);
16488 * dumpTableConstraintComment --- dump a constraint's comment if any
16490 * This is split out because we need the function in two different places
16491 * depending on whether the constraint is dumped as part of CREATE TABLE
16492 * or as a separate ALTER command.
16495 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16497 TableInfo *tbinfo = coninfo->contable;
16498 PQExpBuffer conprefix = createPQExpBuffer();
16501 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16503 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16504 fmtId(coninfo->dobj.name));
16506 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16507 dumpComment(fout, conprefix->data, qtabname,
16508 tbinfo->dobj.namespace->dobj.name,
16510 coninfo->dobj.catId, 0,
16511 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16513 destroyPQExpBuffer(conprefix);
16518 * findLastBuiltinOid_V71 -
16520 * find the last built in oid
16522 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16523 * pg_database entry for the current database.
16526 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
16530 PQExpBuffer query = createPQExpBuffer();
16532 resetPQExpBuffer(query);
16533 appendPQExpBufferStr(query, "SELECT datlastsysoid from pg_database where datname = ");
16534 appendStringLiteralAH(query, dbname, fout);
16536 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16537 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16539 destroyPQExpBuffer(query);
16546 * write the declaration (not data) of one user-defined sequence
16549 dumpSequence(Archive *fout, TableInfo *tbinfo)
16551 DumpOptions *dopt = fout->dopt;
16561 int64 default_minv,
16565 PQExpBuffer query = createPQExpBuffer();
16566 PQExpBuffer delqry = createPQExpBuffer();
16569 qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16571 if (fout->remoteVersion >= 100000)
16573 appendPQExpBuffer(query,
16574 "SELECT format_type(seqtypid, NULL), "
16575 "seqstart, seqincrement, "
16577 "seqcache, seqcycle "
16578 "FROM pg_catalog.pg_sequence "
16579 "WHERE seqrelid = '%u'::oid",
16580 tbinfo->dobj.catId.oid);
16582 else if (fout->remoteVersion >= 80400)
16585 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16587 * Note: it might seem that 'bigint' potentially needs to be
16588 * schema-qualified, but actually that's a keyword.
16590 appendPQExpBuffer(query,
16591 "SELECT 'bigint' AS sequence_type, "
16592 "start_value, increment_by, max_value, min_value, "
16593 "cache_value, is_cycled FROM %s",
16594 fmtQualifiedDumpable(tbinfo));
16598 appendPQExpBuffer(query,
16599 "SELECT 'bigint' AS sequence_type, "
16600 "0 AS start_value, increment_by, max_value, min_value, "
16601 "cache_value, is_cycled FROM %s",
16602 fmtQualifiedDumpable(tbinfo));
16605 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16607 if (PQntuples(res) != 1)
16609 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16610 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16612 tbinfo->dobj.name, PQntuples(res));
16616 seqtype = PQgetvalue(res, 0, 0);
16617 startv = PQgetvalue(res, 0, 1);
16618 incby = PQgetvalue(res, 0, 2);
16619 maxv = PQgetvalue(res, 0, 3);
16620 minv = PQgetvalue(res, 0, 4);
16621 cache = PQgetvalue(res, 0, 5);
16622 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16624 /* Calculate default limits for a sequence of this type */
16625 is_ascending = (incby[0] != '-');
16626 if (strcmp(seqtype, "smallint") == 0)
16628 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16629 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16631 else if (strcmp(seqtype, "integer") == 0)
16633 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16634 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16636 else if (strcmp(seqtype, "bigint") == 0)
16638 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16639 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16643 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16644 default_minv = default_maxv = 0; /* keep compiler quiet */
16648 * 64-bit strtol() isn't very portable, so convert the limits to strings
16649 * and compare that way.
16651 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16652 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16654 /* Don't print minv/maxv if they match the respective default limit */
16655 if (strcmp(minv, bufm) == 0)
16657 if (strcmp(maxv, bufx) == 0)
16661 * Identity sequences are not to be dropped separately.
16663 if (!tbinfo->is_identity_sequence)
16665 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16666 fmtQualifiedDumpable(tbinfo));
16669 resetPQExpBuffer(query);
16671 if (dopt->binary_upgrade)
16673 binary_upgrade_set_pg_class_oids(fout, query,
16674 tbinfo->dobj.catId.oid, false);
16675 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16676 tbinfo->dobj.catId.oid);
16679 if (tbinfo->is_identity_sequence)
16681 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16683 appendPQExpBuffer(query,
16685 fmtQualifiedDumpable(owning_tab));
16686 appendPQExpBuffer(query,
16687 "ALTER COLUMN %s ADD GENERATED ",
16688 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16689 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16690 appendPQExpBuffer(query, "ALWAYS");
16691 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16692 appendPQExpBuffer(query, "BY DEFAULT");
16693 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16694 fmtQualifiedDumpable(tbinfo));
16698 appendPQExpBuffer(query,
16699 "CREATE SEQUENCE %s\n",
16700 fmtQualifiedDumpable(tbinfo));
16702 if (strcmp(seqtype, "bigint") != 0)
16703 appendPQExpBuffer(query, " AS %s\n", seqtype);
16706 if (fout->remoteVersion >= 80400)
16707 appendPQExpBuffer(query, " START WITH %s\n", startv);
16709 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
16712 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
16714 appendPQExpBufferStr(query, " NO MINVALUE\n");
16717 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
16719 appendPQExpBufferStr(query, " NO MAXVALUE\n");
16721 appendPQExpBuffer(query,
16723 cache, (cycled ? "\n CYCLE" : ""));
16725 if (tbinfo->is_identity_sequence)
16726 appendPQExpBufferStr(query, "\n);\n");
16728 appendPQExpBufferStr(query, ";\n");
16730 /* binary_upgrade: no need to clear TOAST table oid */
16732 if (dopt->binary_upgrade)
16733 binary_upgrade_extension_member(query, &tbinfo->dobj,
16734 "SEQUENCE", qseqname,
16735 tbinfo->dobj.namespace->dobj.name);
16737 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16738 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16740 tbinfo->dobj.namespace->dobj.name,
16743 false, "SEQUENCE", SECTION_PRE_DATA,
16744 query->data, delqry->data, NULL,
16749 * If the sequence is owned by a table column, emit the ALTER for it as a
16750 * separate TOC entry immediately following the sequence's own entry. It's
16751 * OK to do this rather than using full sorting logic, because the
16752 * dependency that tells us it's owned will have forced the table to be
16753 * created first. We can't just include the ALTER in the TOC entry
16754 * because it will fail if we haven't reassigned the sequence owner to
16755 * match the table's owner.
16757 * We need not schema-qualify the table reference because both sequence
16758 * and table must be in the same schema.
16760 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16762 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16764 if (owning_tab == NULL)
16765 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16766 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16768 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16770 resetPQExpBuffer(query);
16771 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16772 fmtQualifiedDumpable(tbinfo));
16773 appendPQExpBuffer(query, " OWNED BY %s",
16774 fmtQualifiedDumpable(owning_tab));
16775 appendPQExpBuffer(query, ".%s;\n",
16776 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16778 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16779 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16781 tbinfo->dobj.namespace->dobj.name,
16784 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16785 query->data, "", NULL,
16786 &(tbinfo->dobj.dumpId), 1,
16791 /* Dump Sequence Comments and Security Labels */
16792 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16793 dumpComment(fout, "SEQUENCE", qseqname,
16794 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16795 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16797 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16798 dumpSecLabel(fout, "SEQUENCE", qseqname,
16799 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16800 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16804 destroyPQExpBuffer(query);
16805 destroyPQExpBuffer(delqry);
16811 * write the data of one user-defined sequence
16814 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16816 TableInfo *tbinfo = tdinfo->tdtable;
16820 PQExpBuffer query = createPQExpBuffer();
16822 appendPQExpBuffer(query,
16823 "SELECT last_value, is_called FROM %s",
16824 fmtQualifiedDumpable(tbinfo));
16826 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16828 if (PQntuples(res) != 1)
16830 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16831 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16833 tbinfo->dobj.name, PQntuples(res));
16837 last = PQgetvalue(res, 0, 0);
16838 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
16840 resetPQExpBuffer(query);
16841 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
16842 appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
16843 appendPQExpBuffer(query, ", %s, %s);\n",
16844 last, (called ? "true" : "false"));
16846 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
16847 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16849 tbinfo->dobj.namespace->dobj.name,
16852 false, "SEQUENCE SET", SECTION_DATA,
16853 query->data, "", NULL,
16854 &(tbinfo->dobj.dumpId), 1,
16859 destroyPQExpBuffer(query);
16864 * write the declaration of one user-defined table trigger
16867 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
16869 DumpOptions *dopt = fout->dopt;
16870 TableInfo *tbinfo = tginfo->tgtable;
16872 PQExpBuffer delqry;
16873 PQExpBuffer trigprefix;
16882 * we needn't check dobj.dump because TriggerInfo wouldn't have been
16883 * created in the first place for non-dumpable triggers
16885 if (dopt->dataOnly)
16888 query = createPQExpBuffer();
16889 delqry = createPQExpBuffer();
16890 trigprefix = createPQExpBuffer();
16892 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16894 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
16895 fmtId(tginfo->dobj.name));
16896 appendPQExpBuffer(delqry, "ON %s;\n",
16897 fmtQualifiedDumpable(tbinfo));
16901 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
16905 if (tginfo->tgisconstraint)
16907 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
16908 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
16912 appendPQExpBufferStr(query, "CREATE TRIGGER ");
16913 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
16915 appendPQExpBufferStr(query, "\n ");
16918 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
16919 appendPQExpBufferStr(query, "BEFORE");
16920 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
16921 appendPQExpBufferStr(query, "AFTER");
16922 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
16923 appendPQExpBufferStr(query, "INSTEAD OF");
16926 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
16931 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
16933 appendPQExpBufferStr(query, " INSERT");
16936 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
16939 appendPQExpBufferStr(query, " OR DELETE");
16941 appendPQExpBufferStr(query, " DELETE");
16944 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
16947 appendPQExpBufferStr(query, " OR UPDATE");
16949 appendPQExpBufferStr(query, " UPDATE");
16952 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
16955 appendPQExpBufferStr(query, " OR TRUNCATE");
16957 appendPQExpBufferStr(query, " TRUNCATE");
16960 appendPQExpBuffer(query, " ON %s\n",
16961 fmtQualifiedDumpable(tbinfo));
16963 if (tginfo->tgisconstraint)
16965 if (OidIsValid(tginfo->tgconstrrelid))
16967 /* regclass output is already quoted */
16968 appendPQExpBuffer(query, " FROM %s\n ",
16969 tginfo->tgconstrrelname);
16971 if (!tginfo->tgdeferrable)
16972 appendPQExpBufferStr(query, "NOT ");
16973 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
16974 if (tginfo->tginitdeferred)
16975 appendPQExpBufferStr(query, "DEFERRED\n");
16977 appendPQExpBufferStr(query, "IMMEDIATE\n");
16980 if (TRIGGER_FOR_ROW(tginfo->tgtype))
16981 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
16983 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
16985 /* regproc output is already sufficiently quoted */
16986 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
16989 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
16992 for (findx = 0; findx < tginfo->tgnargs; findx++)
16994 /* find the embedded null that terminates this trigger argument */
16995 size_t tlen = strlen(p);
16997 if (p + tlen >= tgargs + lentgargs)
16999 /* hm, not found before end of bytea value... */
17000 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17003 tbinfo->dobj.name);
17008 appendPQExpBufferStr(query, ", ");
17009 appendStringLiteralAH(query, p, fout);
17013 appendPQExpBufferStr(query, ");\n");
17016 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17018 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17019 fmtQualifiedDumpable(tbinfo));
17020 switch (tginfo->tgenabled)
17024 appendPQExpBufferStr(query, "DISABLE");
17027 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17030 appendPQExpBufferStr(query, "ENABLE REPLICA");
17033 appendPQExpBufferStr(query, "ENABLE");
17036 appendPQExpBuffer(query, " TRIGGER %s;\n",
17037 fmtId(tginfo->dobj.name));
17040 appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17041 fmtId(tginfo->dobj.name));
17043 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17045 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17046 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17048 tbinfo->dobj.namespace->dobj.name,
17050 tbinfo->rolname, false,
17051 "TRIGGER", SECTION_POST_DATA,
17052 query->data, delqry->data, NULL,
17056 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17057 dumpComment(fout, trigprefix->data, qtabname,
17058 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17059 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17062 destroyPQExpBuffer(query);
17063 destroyPQExpBuffer(delqry);
17064 destroyPQExpBuffer(trigprefix);
17070 * write the declaration of one user-defined event trigger
17073 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17075 DumpOptions *dopt = fout->dopt;
17077 PQExpBuffer delqry;
17080 /* Skip if not to be dumped */
17081 if (!evtinfo->dobj.dump || dopt->dataOnly)
17084 query = createPQExpBuffer();
17085 delqry = createPQExpBuffer();
17087 qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17089 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17090 appendPQExpBufferStr(query, qevtname);
17091 appendPQExpBufferStr(query, " ON ");
17092 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17094 if (strcmp("", evtinfo->evttags) != 0)
17096 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17097 appendPQExpBufferStr(query, evtinfo->evttags);
17098 appendPQExpBufferChar(query, ')');
17101 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
17102 appendPQExpBufferStr(query, evtinfo->evtfname);
17103 appendPQExpBufferStr(query, "();\n");
17105 if (evtinfo->evtenabled != 'O')
17107 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17109 switch (evtinfo->evtenabled)
17112 appendPQExpBufferStr(query, "DISABLE");
17115 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17118 appendPQExpBufferStr(query, "ENABLE REPLICA");
17121 appendPQExpBufferStr(query, "ENABLE");
17124 appendPQExpBufferStr(query, ";\n");
17127 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17130 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17131 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17132 evtinfo->dobj.name, NULL, NULL,
17133 evtinfo->evtowner, false,
17134 "EVENT TRIGGER", SECTION_POST_DATA,
17135 query->data, delqry->data, NULL,
17139 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17140 dumpComment(fout, "EVENT TRIGGER", qevtname,
17141 NULL, evtinfo->evtowner,
17142 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17144 destroyPQExpBuffer(query);
17145 destroyPQExpBuffer(delqry);
17154 dumpRule(Archive *fout, RuleInfo *rinfo)
17156 DumpOptions *dopt = fout->dopt;
17157 TableInfo *tbinfo = rinfo->ruletable;
17161 PQExpBuffer delcmd;
17162 PQExpBuffer ruleprefix;
17167 /* Skip if not to be dumped */
17168 if (!rinfo->dobj.dump || dopt->dataOnly)
17172 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17173 * we do not want to dump it as a separate object.
17175 if (!rinfo->separate)
17179 * If it's an ON SELECT rule, we want to print it as a view definition,
17180 * instead of a rule.
17182 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17184 query = createPQExpBuffer();
17185 cmd = createPQExpBuffer();
17186 delcmd = createPQExpBuffer();
17187 ruleprefix = createPQExpBuffer();
17189 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17193 PQExpBuffer result;
17196 * We need OR REPLACE here because we'll be replacing a dummy view.
17197 * Otherwise this should look largely like the regular view dump code.
17199 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17200 fmtQualifiedDumpable(tbinfo));
17201 if (nonemptyReloptions(tbinfo->reloptions))
17203 appendPQExpBufferStr(cmd, " WITH (");
17204 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17205 appendPQExpBufferChar(cmd, ')');
17207 result = createViewAsClause(fout, tbinfo);
17208 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17209 destroyPQExpBuffer(result);
17210 if (tbinfo->checkoption != NULL)
17211 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
17212 tbinfo->checkoption);
17213 appendPQExpBufferStr(cmd, ";\n");
17217 /* In the rule case, just print pg_get_ruledef's result verbatim */
17218 appendPQExpBuffer(query,
17219 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17220 rinfo->dobj.catId.oid);
17222 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17224 if (PQntuples(res) != 1)
17226 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17227 rinfo->dobj.name, tbinfo->dobj.name);
17231 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17237 * Add the command to alter the rules replication firing semantics if it
17238 * differs from the default.
17240 if (rinfo->ev_enabled != 'O')
17242 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17243 switch (rinfo->ev_enabled)
17246 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17247 fmtId(rinfo->dobj.name));
17250 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17251 fmtId(rinfo->dobj.name));
17254 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17255 fmtId(rinfo->dobj.name));
17263 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17264 * REPLACE VIEW to replace the rule with something with minimal
17267 PQExpBuffer result;
17269 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17270 fmtQualifiedDumpable(tbinfo));
17271 result = createDummyViewAsClause(fout, tbinfo);
17272 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17273 destroyPQExpBuffer(result);
17277 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17278 fmtId(rinfo->dobj.name));
17279 appendPQExpBuffer(delcmd, "ON %s;\n",
17280 fmtQualifiedDumpable(tbinfo));
17283 appendPQExpBuffer(ruleprefix, "RULE %s ON",
17284 fmtId(rinfo->dobj.name));
17286 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17288 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17289 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17291 tbinfo->dobj.namespace->dobj.name,
17293 tbinfo->rolname, false,
17294 "RULE", SECTION_POST_DATA,
17295 cmd->data, delcmd->data, NULL,
17299 /* Dump rule comments */
17300 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17301 dumpComment(fout, ruleprefix->data, qtabname,
17302 tbinfo->dobj.namespace->dobj.name,
17304 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17307 destroyPQExpBuffer(query);
17308 destroyPQExpBuffer(cmd);
17309 destroyPQExpBuffer(delcmd);
17310 destroyPQExpBuffer(ruleprefix);
17315 * getExtensionMembership --- obtain extension membership data
17317 * We need to identify objects that are extension members as soon as they're
17318 * loaded, so that we can correctly determine whether they need to be dumped.
17319 * Generally speaking, extension member objects will get marked as *not* to
17320 * be dumped, as they will be recreated by the single CREATE EXTENSION
17321 * command. However, in binary upgrade mode we still need to dump the members
17325 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17336 ExtensionMemberId *extmembers;
17337 ExtensionInfo *ext;
17339 /* Nothing to do if no extensions */
17340 if (numExtensions == 0)
17343 query = createPQExpBuffer();
17345 /* refclassid constraint is redundant but may speed the search */
17346 appendPQExpBufferStr(query, "SELECT "
17347 "classid, objid, refobjid "
17349 "WHERE refclassid = 'pg_extension'::regclass "
17350 "AND deptype = 'e' "
17353 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17355 ntups = PQntuples(res);
17357 i_classid = PQfnumber(res, "classid");
17358 i_objid = PQfnumber(res, "objid");
17359 i_refobjid = PQfnumber(res, "refobjid");
17361 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17365 * Accumulate data into extmembers[].
17367 * Since we ordered the SELECT by referenced ID, we can expect that
17368 * multiple entries for the same extension will appear together; this
17369 * saves on searches.
17373 for (i = 0; i < ntups; i++)
17378 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17379 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17380 extId = atooid(PQgetvalue(res, i, i_refobjid));
17383 ext->dobj.catId.oid != extId)
17384 ext = findExtensionByOid(extId);
17388 /* shouldn't happen */
17389 fprintf(stderr, "could not find referenced extension %u\n", extId);
17393 extmembers[nextmembers].catId = objId;
17394 extmembers[nextmembers].ext = ext;
17400 /* Remember the data for use later */
17401 setExtensionMembership(extmembers, nextmembers);
17403 destroyPQExpBuffer(query);
17407 * processExtensionTables --- deal with extension configuration tables
17409 * There are two parts to this process:
17411 * 1. Identify and create dump records for extension configuration tables.
17413 * Extensions can mark tables as "configuration", which means that the user
17414 * is able and expected to modify those tables after the extension has been
17415 * loaded. For these tables, we dump out only the data- the structure is
17416 * expected to be handled at CREATE EXTENSION time, including any indexes or
17417 * foreign keys, which brings us to-
17419 * 2. Record FK dependencies between configuration tables.
17421 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17422 * the data is loaded, we have to work out what the best order for reloading
17423 * the data is, to avoid FK violations when the tables are restored. This is
17424 * not perfect- we can't handle circular dependencies and if any exist they
17425 * will cause an invalid dump to be produced (though at least all of the data
17426 * is included for a user to manually restore). This is currently documented
17427 * but perhaps we can provide a better solution in the future.
17430 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17433 DumpOptions *dopt = fout->dopt;
17441 /* Nothing to do if no extensions */
17442 if (numExtensions == 0)
17446 * Identify extension configuration tables and create TableDataInfo
17447 * objects for them, ensuring their data will be dumped even though the
17448 * tables themselves won't be.
17450 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17451 * user data in a configuration table is treated like schema data. This
17452 * seems appropriate since system data in a config table would get
17453 * reloaded by CREATE EXTENSION.
17455 for (i = 0; i < numExtensions; i++)
17457 ExtensionInfo *curext = &(extinfo[i]);
17458 char *extconfig = curext->extconfig;
17459 char *extcondition = curext->extcondition;
17460 char **extconfigarray = NULL;
17461 char **extconditionarray = NULL;
17463 int nconditionitems;
17465 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17466 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17467 nconfigitems == nconditionitems)
17471 for (j = 0; j < nconfigitems; j++)
17473 TableInfo *configtbl;
17474 Oid configtbloid = atooid(extconfigarray[j]);
17476 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17478 configtbl = findTableByOid(configtbloid);
17479 if (configtbl == NULL)
17483 * Tables of not-to-be-dumped extensions shouldn't be dumped
17484 * unless the table or its schema is explicitly included
17486 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17488 /* check table explicitly requested */
17489 if (table_include_oids.head != NULL &&
17490 simple_oid_list_member(&table_include_oids,
17494 /* check table's schema explicitly requested */
17495 if (configtbl->dobj.namespace->dobj.dump &
17496 DUMP_COMPONENT_DATA)
17500 /* check table excluded by an exclusion switch */
17501 if (table_exclude_oids.head != NULL &&
17502 simple_oid_list_member(&table_exclude_oids,
17506 /* check schema excluded by an exclusion switch */
17507 if (simple_oid_list_member(&schema_exclude_oids,
17508 configtbl->dobj.namespace->dobj.catId.oid))
17514 * Note: config tables are dumped without OIDs regardless
17515 * of the --oids setting. This is because row filtering
17516 * conditions aren't compatible with dumping OIDs.
17518 makeTableDataInfo(dopt, configtbl, false);
17519 if (configtbl->dataObj != NULL)
17521 if (strlen(extconditionarray[j]) > 0)
17522 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17527 if (extconfigarray)
17528 free(extconfigarray);
17529 if (extconditionarray)
17530 free(extconditionarray);
17534 * Now that all the TableInfoData objects have been created for all the
17535 * extensions, check their FK dependencies and register them to try and
17536 * dump the data out in an order that they can be restored in.
17538 * Note that this is not a problem for user tables as their FKs are
17539 * recreated after the data has been loaded.
17542 query = createPQExpBuffer();
17544 printfPQExpBuffer(query,
17545 "SELECT conrelid, confrelid "
17546 "FROM pg_constraint "
17547 "JOIN pg_depend ON (objid = confrelid) "
17548 "WHERE contype = 'f' "
17549 "AND refclassid = 'pg_extension'::regclass "
17550 "AND classid = 'pg_class'::regclass;");
17552 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17553 ntups = PQntuples(res);
17555 i_conrelid = PQfnumber(res, "conrelid");
17556 i_confrelid = PQfnumber(res, "confrelid");
17558 /* Now get the dependencies and register them */
17559 for (i = 0; i < ntups; i++)
17563 TableInfo *reftable,
17566 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17567 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17568 contable = findTableByOid(conrelid);
17569 reftable = findTableByOid(confrelid);
17571 if (reftable == NULL ||
17572 reftable->dataObj == NULL ||
17573 contable == NULL ||
17574 contable->dataObj == NULL)
17578 * Make referencing TABLE_DATA object depend on the referenced table's
17579 * TABLE_DATA object.
17581 addObjectDependency(&contable->dataObj->dobj,
17582 reftable->dataObj->dobj.dumpId);
17585 destroyPQExpBuffer(query);
17589 * getDependencies --- obtain available dependency data
17592 getDependencies(Archive *fout)
17603 DumpableObject *dobj,
17607 write_msg(NULL, "reading dependency data\n");
17609 query = createPQExpBuffer();
17612 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17613 * already processed by getExtensionMembership.
17615 appendPQExpBufferStr(query, "SELECT "
17616 "classid, objid, refclassid, refobjid, deptype "
17618 "WHERE deptype != 'p' AND deptype != 'e' "
17621 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17623 ntups = PQntuples(res);
17625 i_classid = PQfnumber(res, "classid");
17626 i_objid = PQfnumber(res, "objid");
17627 i_refclassid = PQfnumber(res, "refclassid");
17628 i_refobjid = PQfnumber(res, "refobjid");
17629 i_deptype = PQfnumber(res, "deptype");
17632 * Since we ordered the SELECT by referencing ID, we can expect that
17633 * multiple entries for the same object will appear together; this saves
17638 for (i = 0; i < ntups; i++)
17641 CatalogId refobjId;
17644 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17645 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17646 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17647 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17648 deptype = *(PQgetvalue(res, i, i_deptype));
17650 if (dobj == NULL ||
17651 dobj->catId.tableoid != objId.tableoid ||
17652 dobj->catId.oid != objId.oid)
17653 dobj = findObjectByCatalogId(objId);
17656 * Failure to find objects mentioned in pg_depend is not unexpected,
17657 * since for example we don't collect info about TOAST tables.
17662 fprintf(stderr, "no referencing object %u %u\n",
17663 objId.tableoid, objId.oid);
17668 refdobj = findObjectByCatalogId(refobjId);
17670 if (refdobj == NULL)
17673 fprintf(stderr, "no referenced object %u %u\n",
17674 refobjId.tableoid, refobjId.oid);
17680 * Ordinarily, table rowtypes have implicit dependencies on their
17681 * tables. However, for a composite type the implicit dependency goes
17682 * the other way in pg_depend; which is the right thing for DROP but
17683 * it doesn't produce the dependency ordering we need. So in that one
17684 * case, we reverse the direction of the dependency.
17686 if (deptype == 'i' &&
17687 dobj->objType == DO_TABLE &&
17688 refdobj->objType == DO_TYPE)
17689 addObjectDependency(refdobj, dobj->dumpId);
17692 addObjectDependency(dobj, refdobj->dumpId);
17697 destroyPQExpBuffer(query);
17702 * createBoundaryObjects - create dummy DumpableObjects to represent
17703 * dump section boundaries.
17705 static DumpableObject *
17706 createBoundaryObjects(void)
17708 DumpableObject *dobjs;
17710 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17712 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17713 dobjs[0].catId = nilCatalogId;
17714 AssignDumpId(dobjs + 0);
17715 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17717 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17718 dobjs[1].catId = nilCatalogId;
17719 AssignDumpId(dobjs + 1);
17720 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17726 * addBoundaryDependencies - add dependencies as needed to enforce the dump
17727 * section boundaries.
17730 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17731 DumpableObject *boundaryObjs)
17733 DumpableObject *preDataBound = boundaryObjs + 0;
17734 DumpableObject *postDataBound = boundaryObjs + 1;
17737 for (i = 0; i < numObjs; i++)
17739 DumpableObject *dobj = dobjs[i];
17742 * The classification of object types here must match the SECTION_xxx
17743 * values assigned during subsequent ArchiveEntry calls!
17745 switch (dobj->objType)
17750 case DO_SHELL_TYPE:
17754 case DO_ACCESS_METHOD:
17758 case DO_CONVERSION:
17763 case DO_DUMMY_TYPE:
17766 case DO_TSTEMPLATE:
17769 case DO_FOREIGN_SERVER:
17772 /* Pre-data objects: must come before the pre-data boundary */
17773 addObjectDependency(preDataBound, dobj->dumpId);
17775 case DO_TABLE_DATA:
17776 case DO_SEQUENCE_SET:
17778 /* Data objects: must come between the boundaries */
17779 addObjectDependency(dobj, preDataBound->dumpId);
17780 addObjectDependency(postDataBound, dobj->dumpId);
17783 case DO_INDEX_ATTACH:
17785 case DO_REFRESH_MATVIEW:
17787 case DO_EVENT_TRIGGER:
17788 case DO_DEFAULT_ACL:
17790 case DO_PUBLICATION:
17791 case DO_PUBLICATION_REL:
17792 case DO_SUBSCRIPTION:
17793 /* Post-data objects: must come after the post-data boundary */
17794 addObjectDependency(dobj, postDataBound->dumpId);
17797 /* Rules are post-data, but only if dumped separately */
17798 if (((RuleInfo *) dobj)->separate)
17799 addObjectDependency(dobj, postDataBound->dumpId);
17801 case DO_CONSTRAINT:
17802 case DO_FK_CONSTRAINT:
17803 /* Constraints are post-data, but only if dumped separately */
17804 if (((ConstraintInfo *) dobj)->separate)
17805 addObjectDependency(dobj, postDataBound->dumpId);
17807 case DO_PRE_DATA_BOUNDARY:
17808 /* nothing to do */
17810 case DO_POST_DATA_BOUNDARY:
17811 /* must come after the pre-data boundary */
17812 addObjectDependency(dobj, preDataBound->dumpId);
17820 * BuildArchiveDependencies - create dependency data for archive TOC entries
17822 * The raw dependency data obtained by getDependencies() is not terribly
17823 * useful in an archive dump, because in many cases there are dependency
17824 * chains linking through objects that don't appear explicitly in the dump.
17825 * For example, a view will depend on its _RETURN rule while the _RETURN rule
17826 * will depend on other objects --- but the rule will not appear as a separate
17827 * object in the dump. We need to adjust the view's dependencies to include
17828 * whatever the rule depends on that is included in the dump.
17830 * Just to make things more complicated, there are also "special" dependencies
17831 * such as the dependency of a TABLE DATA item on its TABLE, which we must
17832 * not rearrange because pg_restore knows that TABLE DATA only depends on
17833 * its table. In these cases we must leave the dependencies strictly as-is
17834 * even if they refer to not-to-be-dumped objects.
17836 * To handle this, the convention is that "special" dependencies are created
17837 * during ArchiveEntry calls, and an archive TOC item that has any such
17838 * entries will not be touched here. Otherwise, we recursively search the
17839 * DumpableObject data structures to build the correct dependencies for each
17840 * archive TOC item.
17843 BuildArchiveDependencies(Archive *fout)
17845 ArchiveHandle *AH = (ArchiveHandle *) fout;
17848 /* Scan all TOC entries in the archive */
17849 for (te = AH->toc->next; te != AH->toc; te = te->next)
17851 DumpableObject *dobj;
17852 DumpId *dependencies;
17856 /* No need to process entries that will not be dumped */
17859 /* Ignore entries that already have "special" dependencies */
17862 /* Otherwise, look up the item's original DumpableObject, if any */
17863 dobj = findObjectByDumpId(te->dumpId);
17866 /* No work if it has no dependencies */
17867 if (dobj->nDeps <= 0)
17869 /* Set up work array */
17871 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
17873 /* Recursively find all dumpable dependencies */
17874 findDumpableDependencies(AH, dobj,
17875 &dependencies, &nDeps, &allocDeps);
17876 /* And save 'em ... */
17879 dependencies = (DumpId *) pg_realloc(dependencies,
17880 nDeps * sizeof(DumpId));
17881 te->dependencies = dependencies;
17885 free(dependencies);
17889 /* Recursive search subroutine for BuildArchiveDependencies */
17891 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
17892 DumpId **dependencies, int *nDeps, int *allocDeps)
17897 * Ignore section boundary objects: if we search through them, we'll
17898 * report lots of bogus dependencies.
17900 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
17901 dobj->objType == DO_POST_DATA_BOUNDARY)
17904 for (i = 0; i < dobj->nDeps; i++)
17906 DumpId depid = dobj->dependencies[i];
17908 if (TocIDRequired(AH, depid) != 0)
17910 /* Object will be dumped, so just reference it as a dependency */
17911 if (*nDeps >= *allocDeps)
17914 *dependencies = (DumpId *) pg_realloc(*dependencies,
17915 *allocDeps * sizeof(DumpId));
17917 (*dependencies)[*nDeps] = depid;
17923 * Object will not be dumped, so recursively consider its deps. We
17924 * rely on the assumption that sortDumpableObjects already broke
17925 * any dependency loops, else we might recurse infinitely.
17927 DumpableObject *otherdobj = findObjectByDumpId(depid);
17930 findDumpableDependencies(AH, otherdobj,
17931 dependencies, nDeps, allocDeps);
17938 * getFormattedTypeName - retrieve a nicely-formatted type name for the
17941 * This does not guarantee to schema-qualify the output, so it should not
17942 * be used to create the target object name for CREATE or ALTER commands.
17944 * TODO: there might be some value in caching the results.
17947 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
17955 if ((opts & zeroAsOpaque) != 0)
17956 return pg_strdup(g_opaque_type);
17957 else if ((opts & zeroAsAny) != 0)
17958 return pg_strdup("'any'");
17959 else if ((opts & zeroAsStar) != 0)
17960 return pg_strdup("*");
17961 else if ((opts & zeroAsNone) != 0)
17962 return pg_strdup("NONE");
17965 query = createPQExpBuffer();
17966 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
17969 res = ExecuteSqlQueryForSingleRow(fout, query->data);
17971 /* result of format_type is already quoted */
17972 result = pg_strdup(PQgetvalue(res, 0, 0));
17975 destroyPQExpBuffer(query);
17981 * Return a column list clause for the given relation.
17983 * Special case: if there are no undropped columns in the relation, return
17984 * "", not an invalid "()" column list.
17986 static const char *
17987 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
17989 int numatts = ti->numatts;
17990 char **attnames = ti->attnames;
17991 bool *attisdropped = ti->attisdropped;
17995 appendPQExpBufferChar(buffer, '(');
17997 for (i = 0; i < numatts; i++)
17999 if (attisdropped[i])
18002 appendPQExpBufferStr(buffer, ", ");
18003 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18008 return ""; /* no undropped columns */
18010 appendPQExpBufferChar(buffer, ')');
18011 return buffer->data;
18015 * Check if a reloptions array is nonempty.
18018 nonemptyReloptions(const char *reloptions)
18020 /* Don't want to print it if it's just "{}" */
18021 return (reloptions != NULL && strlen(reloptions) > 2);
18025 * Format a reloptions array and append it to the given buffer.
18027 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18030 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18031 const char *prefix, Archive *fout)
18035 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18036 fout->std_strings);
18038 write_msg(NULL, "WARNING: could not parse reloptions array\n");