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/string_utils.h"
68 const char *descr; /* comment for an object */
69 Oid classoid; /* object class (catalog OID) */
70 Oid objoid; /* object OID */
71 int objsubid; /* subobject (table column #) */
76 const char *provider; /* label provider of this security label */
77 const char *label; /* security label for an object */
78 Oid classoid; /* object class (catalog OID) */
79 Oid objoid; /* object OID */
80 int objsubid; /* subobject (table column #) */
83 typedef enum OidOptions
92 bool g_verbose; /* User wants verbose narration of our
94 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
96 /* subquery used to convert user ID (eg, datdba) to user name */
97 static const char *username_subquery;
100 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
101 * FirstNormalObjectId - 1.
103 static Oid g_last_builtin_oid; /* value of the last builtin oid */
105 /* The specified names/patterns should to match at least one entity */
106 static int strict_names = 0;
109 * Object inclusion/exclusion lists
111 * The string lists record the patterns given by command-line switches,
112 * which we then convert to lists of OIDs of matching objects.
114 static SimpleStringList schema_include_patterns = {NULL, NULL};
115 static SimpleOidList schema_include_oids = {NULL, NULL};
116 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
117 static SimpleOidList schema_exclude_oids = {NULL, NULL};
119 static SimpleStringList table_include_patterns = {NULL, NULL};
120 static SimpleOidList table_include_oids = {NULL, NULL};
121 static SimpleStringList table_exclude_patterns = {NULL, NULL};
122 static SimpleOidList table_exclude_oids = {NULL, NULL};
123 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
124 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
127 char g_opaque_type[10]; /* name for the opaque type */
129 /* placeholders for the delimiters for comments */
130 char g_comment_start[10];
131 char g_comment_end[10];
133 static const CatalogId nilCatalogId = {0, 0};
135 static void help(const char *progname);
136 static void setup_connection(Archive *AH,
137 const char *dumpencoding, const char *dumpsnapshot,
139 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
140 static void expand_schema_name_patterns(Archive *fout,
141 SimpleStringList *patterns,
144 static void expand_table_name_patterns(Archive *fout,
145 SimpleStringList *patterns,
148 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
149 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
150 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
151 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
152 static void dumpComment(Archive *fout, const char *target,
153 const char *namespace, const char *owner,
154 CatalogId catalogId, int subid, DumpId dumpId);
155 static int findComments(Archive *fout, Oid classoid, Oid objoid,
156 CommentItem **items);
157 static int collectComments(Archive *fout, CommentItem **items);
158 static void dumpSecLabel(Archive *fout, const char *target,
159 const char *namespace, const char *owner,
160 CatalogId catalogId, int subid, DumpId dumpId);
161 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
162 SecLabelItem **items);
163 static int collectSecLabels(Archive *fout, SecLabelItem **items);
164 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
165 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
166 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
167 static void dumpType(Archive *fout, TypeInfo *tyinfo);
168 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
169 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
170 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
173 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
175 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
176 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
177 static void dumpFunc(Archive *fout, FuncInfo *finfo);
178 static void dumpCast(Archive *fout, CastInfo *cast);
179 static void dumpTransform(Archive *fout, TransformInfo *transform);
180 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
181 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *collinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
190 static void dumpTable(Archive *fout, TableInfo *tbinfo);
191 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
192 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
193 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
194 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
195 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
196 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
197 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
198 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
199 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
201 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
202 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
203 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
204 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
205 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
206 static void dumpUserMappings(Archive *fout,
207 const char *servername, const char *namespace,
208 const char *owner, CatalogId catalogId, DumpId dumpId);
209 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
211 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
212 const char *type, const char *name, const char *subname,
213 const char *tag, const char *nspname, const char *owner,
214 const char *acls, const char *racls,
215 const char *initacls, const char *initracls);
217 static void getDependencies(Archive *fout);
218 static void BuildArchiveDependencies(Archive *fout);
219 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
220 DumpId **dependencies, int *nDeps, int *allocDeps);
222 static DumpableObject *createBoundaryObjects(void);
223 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
224 DumpableObject *boundaryObjs);
226 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
227 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
228 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
229 static void buildMatViewRefreshDependencies(Archive *fout);
230 static void getTableDataFKConstraints(void);
231 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
233 static char *format_function_arguments_old(Archive *fout,
234 FuncInfo *finfo, int nallargs,
238 static char *format_function_signature(Archive *fout,
239 FuncInfo *finfo, bool honor_quotes);
240 static char *convertRegProcReference(Archive *fout,
242 static char *convertOperatorReference(Archive *fout, const char *opr);
243 static char *convertTSFunction(Archive *fout, Oid funcOid);
244 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
245 static void selectSourceSchema(Archive *fout, const char *schemaName);
246 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
247 static void getBlobs(Archive *fout);
248 static void dumpBlob(Archive *fout, BlobInfo *binfo);
249 static int dumpBlobs(Archive *fout, void *arg);
250 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
251 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
252 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
253 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
254 static void dumpDatabase(Archive *AH);
255 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
256 const char *dbname, Oid dboid);
257 static void dumpEncoding(Archive *AH);
258 static void dumpStdStrings(Archive *AH);
259 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
260 PQExpBuffer upgrade_buffer,
262 bool force_array_type);
263 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
264 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
265 static void binary_upgrade_set_pg_class_oids(Archive *fout,
266 PQExpBuffer upgrade_buffer,
267 Oid pg_class_oid, bool is_index);
268 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
269 DumpableObject *dobj,
270 const char *objlabel);
271 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
272 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
273 static bool nonemptyReloptions(const char *reloptions);
274 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
275 const char *prefix, Archive *fout);
276 static char *get_synchronized_snapshot(Archive *fout);
277 static void setupDumpWorker(Archive *AHX);
278 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
282 main(int argc, char **argv)
285 const char *filename = NULL;
286 const char *format = "p";
289 DumpableObject **dobjs;
291 DumpableObject *boundaryObjs;
294 RestoreOptions *ropt;
295 Archive *fout; /* the script file */
296 const char *dumpencoding = NULL;
297 const char *dumpsnapshot = NULL;
298 char *use_role = NULL;
300 trivalue prompt_password = TRI_DEFAULT;
301 int compressLevel = -1;
303 ArchiveFormat archiveFormat = archUnknown;
304 ArchiveMode archiveMode;
306 static DumpOptions dopt;
308 static struct option long_options[] = {
309 {"data-only", no_argument, NULL, 'a'},
310 {"blobs", no_argument, NULL, 'b'},
311 {"no-blobs", no_argument, NULL, 'B'},
312 {"clean", no_argument, NULL, 'c'},
313 {"create", no_argument, NULL, 'C'},
314 {"dbname", required_argument, NULL, 'd'},
315 {"file", required_argument, NULL, 'f'},
316 {"format", required_argument, NULL, 'F'},
317 {"host", required_argument, NULL, 'h'},
318 {"jobs", 1, NULL, 'j'},
319 {"no-reconnect", no_argument, NULL, 'R'},
320 {"oids", no_argument, NULL, 'o'},
321 {"no-owner", no_argument, NULL, 'O'},
322 {"port", required_argument, NULL, 'p'},
323 {"schema", required_argument, NULL, 'n'},
324 {"exclude-schema", required_argument, NULL, 'N'},
325 {"schema-only", no_argument, NULL, 's'},
326 {"superuser", required_argument, NULL, 'S'},
327 {"table", required_argument, NULL, 't'},
328 {"exclude-table", required_argument, NULL, 'T'},
329 {"no-password", no_argument, NULL, 'w'},
330 {"password", no_argument, NULL, 'W'},
331 {"username", required_argument, NULL, 'U'},
332 {"verbose", no_argument, NULL, 'v'},
333 {"no-privileges", no_argument, NULL, 'x'},
334 {"no-acl", no_argument, NULL, 'x'},
335 {"compress", required_argument, NULL, 'Z'},
336 {"encoding", required_argument, NULL, 'E'},
337 {"help", no_argument, NULL, '?'},
338 {"version", no_argument, NULL, 'V'},
341 * the following options don't have an equivalent short option letter
343 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
344 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
345 {"column-inserts", no_argument, &dopt.column_inserts, 1},
346 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
347 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
348 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
349 {"exclude-table-data", required_argument, NULL, 4},
350 {"if-exists", no_argument, &dopt.if_exists, 1},
351 {"inserts", no_argument, &dopt.dump_inserts, 1},
352 {"lock-wait-timeout", required_argument, NULL, 2},
353 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
354 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
355 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
356 {"role", required_argument, NULL, 3},
357 {"section", required_argument, NULL, 5},
358 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
359 {"snapshot", required_argument, NULL, 6},
360 {"strict-names", no_argument, &strict_names, 1},
361 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
362 {"no-comments", no_argument, &dopt.no_comments, 1},
363 {"no-publications", no_argument, &dopt.no_publications, 1},
364 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
365 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
366 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
367 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
368 {"no-sync", no_argument, NULL, 7},
373 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
376 * Initialize what we need for parallel execution, especially for thread
377 * support on Windows.
379 init_parallel_dump_utils();
383 strcpy(g_comment_start, "-- ");
384 g_comment_end[0] = '\0';
385 strcpy(g_opaque_type, "opaque");
387 progname = get_progname(argv[0]);
391 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
396 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
398 puts("pg_dump (PostgreSQL) " PG_VERSION);
403 InitDumpOptions(&dopt);
405 while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
406 long_options, &optindex)) != -1)
410 case 'a': /* Dump data only */
411 dopt.dataOnly = true;
414 case 'b': /* Dump blobs */
415 dopt.outputBlobs = true;
418 case 'B': /* Don't dump blobs */
419 dopt.dontOutputBlobs = true;
422 case 'c': /* clean (i.e., drop) schema prior to create */
423 dopt.outputClean = 1;
426 case 'C': /* Create DB */
427 dopt.outputCreateDB = 1;
430 case 'd': /* database name */
431 dopt.dbname = pg_strdup(optarg);
434 case 'E': /* Dump encoding */
435 dumpencoding = pg_strdup(optarg);
439 filename = pg_strdup(optarg);
443 format = pg_strdup(optarg);
446 case 'h': /* server host */
447 dopt.pghost = pg_strdup(optarg);
450 case 'j': /* number of dump jobs */
451 numWorkers = atoi(optarg);
454 case 'n': /* include schema(s) */
455 simple_string_list_append(&schema_include_patterns, optarg);
456 dopt.include_everything = false;
459 case 'N': /* exclude schema(s) */
460 simple_string_list_append(&schema_exclude_patterns, optarg);
463 case 'o': /* Dump oids */
467 case 'O': /* Don't reconnect to match owner */
468 dopt.outputNoOwner = 1;
471 case 'p': /* server port */
472 dopt.pgport = pg_strdup(optarg);
476 /* no-op, still accepted for backwards compatibility */
479 case 's': /* dump schema only */
480 dopt.schemaOnly = true;
483 case 'S': /* Username for superuser in plain text output */
484 dopt.outputSuperuser = pg_strdup(optarg);
487 case 't': /* include table(s) */
488 simple_string_list_append(&table_include_patterns, optarg);
489 dopt.include_everything = false;
492 case 'T': /* exclude table(s) */
493 simple_string_list_append(&table_exclude_patterns, optarg);
497 dopt.username = pg_strdup(optarg);
500 case 'v': /* verbose */
505 prompt_password = TRI_NO;
509 prompt_password = TRI_YES;
512 case 'x': /* skip ACL dump */
513 dopt.aclsSkip = true;
516 case 'Z': /* Compression Level */
517 compressLevel = atoi(optarg);
518 if (compressLevel < 0 || compressLevel > 9)
520 write_msg(NULL, "compression level must be in range 0..9\n");
526 /* This covers the long options. */
529 case 2: /* lock-wait-timeout */
530 dopt.lockWaitTimeout = pg_strdup(optarg);
533 case 3: /* SET ROLE */
534 use_role = pg_strdup(optarg);
537 case 4: /* exclude table(s) data */
538 simple_string_list_append(&tabledata_exclude_patterns, optarg);
541 case 5: /* section */
542 set_dump_section(optarg, &dopt.dumpSections);
545 case 6: /* snapshot */
546 dumpsnapshot = pg_strdup(optarg);
549 case 7: /* no-sync */
554 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
560 * Non-option argument specifies database name as long as it wasn't
561 * already specified with -d / --dbname
563 if (optind < argc && dopt.dbname == NULL)
564 dopt.dbname = argv[optind++];
566 /* Complain if any arguments remain */
569 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
570 progname, argv[optind]);
571 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
576 /* --column-inserts implies --inserts */
577 if (dopt.column_inserts)
578 dopt.dump_inserts = 1;
581 * Binary upgrade mode implies dumping sequence data even in schema-only
582 * mode. This is not exposed as a separate option, but kept separate
583 * internally for clarity.
585 if (dopt.binary_upgrade)
586 dopt.sequence_data = 1;
588 if (dopt.dataOnly && dopt.schemaOnly)
590 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
594 if (dopt.dataOnly && dopt.outputClean)
596 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
600 if (dopt.dump_inserts && dopt.oids)
602 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
603 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
607 if (dopt.if_exists && !dopt.outputClean)
608 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
610 /* Identify archive format to emit */
611 archiveFormat = parseArchiveFormat(format, &archiveMode);
613 /* archiveFormat specific setup */
614 if (archiveFormat == archNull)
617 /* Custom and directory formats are compressed by default, others not */
618 if (compressLevel == -1)
621 if (archiveFormat == archCustom || archiveFormat == archDirectory)
622 compressLevel = Z_DEFAULT_COMPRESSION;
629 if (compressLevel != 0)
630 write_msg(NULL, "WARNING: requested compression not available in this "
631 "installation -- archive will be uncompressed\n");
636 * If emitting an archive format, we always want to emit a DATABASE item,
637 * in case --create is specified at pg_restore time.
640 dopt.outputCreateDB = 1;
643 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
644 * parallel jobs because that's the maximum limit for the
645 * WaitForMultipleObjects() call.
649 || numWorkers > MAXIMUM_WAIT_OBJECTS
652 exit_horribly(NULL, "invalid number of parallel jobs\n");
654 /* Parallel backup only in the directory archive format so far */
655 if (archiveFormat != archDirectory && numWorkers > 1)
656 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
658 /* Open the output file */
659 fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
660 archiveMode, setupDumpWorker);
662 /* Make dump options accessible right away */
663 SetArchiveOptions(fout, &dopt, NULL);
665 /* Register the cleanup hook */
666 on_exit_close_archive(fout);
668 /* Let the archiver know how noisy to be */
669 fout->verbose = g_verbose;
672 * We allow the server to be back to 8.0, and up to any minor release of
673 * our own major version. (See also version check in pg_dumpall.c.)
675 fout->minRemoteVersion = 80000;
676 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
678 fout->numWorkers = numWorkers;
681 * Open the database using the Archiver, so it knows about it. Errors mean
684 ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
685 setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
688 * Disable security label support if server version < v9.1.x (prevents
689 * access to nonexistent pg_seclabel catalog)
691 if (fout->remoteVersion < 90100)
692 dopt.no_security_labels = 1;
695 * On hot standbys, never try to dump unlogged table data, since it will
696 * just throw an error.
699 dopt.no_unlogged_table_data = true;
701 /* Select the appropriate subquery to convert user IDs to names */
702 if (fout->remoteVersion >= 80100)
703 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
705 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
707 /* check the version for the synchronized snapshots feature */
708 if (numWorkers > 1 && fout->remoteVersion < 90200
709 && !dopt.no_synchronized_snapshots)
711 "Synchronized snapshots are not supported by this server version.\n"
712 "Run with --no-synchronized-snapshots instead if you do not need\n"
713 "synchronized snapshots.\n");
715 /* check the version when a snapshot is explicitly specified by user */
716 if (dumpsnapshot && fout->remoteVersion < 90200)
718 "Exported snapshots are not supported by this server version.\n");
721 * Find the last built-in OID, if needed (prior to 8.1)
723 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
725 if (fout->remoteVersion < 80100)
726 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
727 PQdb(GetConnection(fout)));
729 g_last_builtin_oid = FirstNormalObjectId - 1;
732 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
734 /* Expand schema selection patterns into OID lists */
735 if (schema_include_patterns.head != NULL)
737 expand_schema_name_patterns(fout, &schema_include_patterns,
738 &schema_include_oids,
740 if (schema_include_oids.head == NULL)
741 exit_horribly(NULL, "no matching schemas were found\n");
743 expand_schema_name_patterns(fout, &schema_exclude_patterns,
744 &schema_exclude_oids,
746 /* non-matching exclusion patterns aren't an error */
748 /* Expand table selection patterns into OID lists */
749 if (table_include_patterns.head != NULL)
751 expand_table_name_patterns(fout, &table_include_patterns,
754 if (table_include_oids.head == NULL)
755 exit_horribly(NULL, "no matching tables were found\n");
757 expand_table_name_patterns(fout, &table_exclude_patterns,
761 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
762 &tabledata_exclude_oids,
765 /* non-matching exclusion patterns aren't an error */
768 * Dumping blobs is the default for dumps where an inclusion switch is not
769 * used (an "include everything" dump). -B can be used to exclude blobs
770 * from those dumps. -b can be used to include blobs even when an
771 * inclusion switch is used.
773 * -s means "schema only" and blobs are data, not schema, so we never
774 * include blobs when -s is used.
776 if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
777 dopt.outputBlobs = true;
780 * Now scan the database and create DumpableObject structs for all the
781 * objects we intend to dump.
783 tblinfo = getSchemaData(fout, &numTables);
785 if (fout->remoteVersion < 80400)
786 guessConstraintInheritance(tblinfo, numTables);
788 if (!dopt.schemaOnly)
790 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
791 buildMatViewRefreshDependencies(fout);
793 getTableDataFKConstraints();
796 if (dopt.schemaOnly && dopt.sequence_data)
797 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
800 * In binary-upgrade mode, we do not have to worry about the actual blob
801 * data or the associated metadata that resides in the pg_largeobject and
802 * pg_largeobject_metadata tables, respectivly.
804 * However, we do need to collect blob information as there may be
805 * comments or other information on blobs that we do need to dump out.
807 if (dopt.outputBlobs || dopt.binary_upgrade)
811 * Collect dependency data to assist in ordering the objects.
813 getDependencies(fout);
815 /* Lastly, create dummy objects to represent the section boundaries */
816 boundaryObjs = createBoundaryObjects();
818 /* Get pointers to all the known DumpableObjects */
819 getDumpableObjects(&dobjs, &numObjs);
822 * Add dummy dependencies to enforce the dump section ordering.
824 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
827 * Sort the objects into a safe dump order (no forward references).
829 * We rely on dependency information to help us determine a safe order, so
830 * the initial sort is mostly for cosmetic purposes: we sort by name to
831 * ensure that logically identical schemas will dump identically.
833 sortDumpableObjectsByTypeName(dobjs, numObjs);
835 /* If we do a parallel dump, we want the largest tables to go first */
836 if (archiveFormat == archDirectory && numWorkers > 1)
837 sortDataAndIndexObjectsBySize(dobjs, numObjs);
839 sortDumpableObjects(dobjs, numObjs,
840 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
843 * Create archive TOC entries for all the objects to be dumped, in a safe
847 /* First the special ENCODING and STDSTRINGS entries. */
849 dumpStdStrings(fout);
851 /* The database items are always next, unless we don't want them at all */
852 if (dopt.outputCreateDB)
855 /* Now the rearrangeable objects. */
856 for (i = 0; i < numObjs; i++)
857 dumpDumpableObject(fout, dobjs[i]);
860 * Set up options info to ensure we dump what we want.
862 ropt = NewRestoreOptions();
863 ropt->filename = filename;
865 /* if you change this list, see dumpOptionsFromRestoreOptions */
866 ropt->dropSchema = dopt.outputClean;
867 ropt->dataOnly = dopt.dataOnly;
868 ropt->schemaOnly = dopt.schemaOnly;
869 ropt->if_exists = dopt.if_exists;
870 ropt->column_inserts = dopt.column_inserts;
871 ropt->dumpSections = dopt.dumpSections;
872 ropt->aclsSkip = dopt.aclsSkip;
873 ropt->superuser = dopt.outputSuperuser;
874 ropt->createDB = dopt.outputCreateDB;
875 ropt->noOwner = dopt.outputNoOwner;
876 ropt->noTablespace = dopt.outputNoTablespaces;
877 ropt->disable_triggers = dopt.disable_triggers;
878 ropt->use_setsessauth = dopt.use_setsessauth;
879 ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
880 ropt->dump_inserts = dopt.dump_inserts;
881 ropt->no_comments = dopt.no_comments;
882 ropt->no_publications = dopt.no_publications;
883 ropt->no_security_labels = dopt.no_security_labels;
884 ropt->no_subscriptions = dopt.no_subscriptions;
885 ropt->lockWaitTimeout = dopt.lockWaitTimeout;
886 ropt->include_everything = dopt.include_everything;
887 ropt->enable_row_security = dopt.enable_row_security;
888 ropt->sequence_data = dopt.sequence_data;
889 ropt->binary_upgrade = dopt.binary_upgrade;
891 if (compressLevel == -1)
892 ropt->compression = 0;
894 ropt->compression = compressLevel;
896 ropt->suppressDumpWarnings = true; /* We've already shown them */
898 SetArchiveOptions(fout, &dopt, ropt);
900 /* Mark which entries should be output */
901 ProcessArchiveRestoreOptions(fout);
904 * The archive's TOC entries are now marked as to which ones will actually
905 * be output, so we can set up their dependency lists properly. This isn't
906 * necessary for plain-text output, though.
909 BuildArchiveDependencies(fout);
912 * And finally we can do the actual output.
914 * Note: for non-plain-text output formats, the output file is written
915 * inside CloseArchive(). This is, um, bizarre; but not worth changing
919 RestoreArchive(fout);
928 help(const char *progname)
930 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
931 printf(_("Usage:\n"));
932 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
934 printf(_("\nGeneral options:\n"));
935 printf(_(" -f, --file=FILENAME output file or directory name\n"));
936 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
937 " plain text (default))\n"));
938 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
939 printf(_(" -v, --verbose verbose mode\n"));
940 printf(_(" -V, --version output version information, then exit\n"));
941 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
942 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
943 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
944 printf(_(" -?, --help show this help, then exit\n"));
946 printf(_("\nOptions controlling the output content:\n"));
947 printf(_(" -a, --data-only dump only the data, not the schema\n"));
948 printf(_(" -b, --blobs include large objects in dump\n"));
949 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
950 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
951 printf(_(" -C, --create include commands to create database in dump\n"));
952 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
953 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
954 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
955 printf(_(" -o, --oids include OIDs in dump\n"));
956 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
957 " plain-text format\n"));
958 printf(_(" -s, --schema-only dump only the schema, no data\n"));
959 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
960 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
961 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
962 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
963 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
964 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
965 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
966 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
967 printf(_(" --enable-row-security enable row security (dump only content user has\n"
969 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
970 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
971 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
972 printf(_(" --no-comments do not dump comments\n"));
973 printf(_(" --no-publications do not dump publications\n"));
974 printf(_(" --no-security-labels do not dump security label assignments\n"));
975 printf(_(" --no-subscriptions do not dump subscriptions\n"));
976 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
977 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
978 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
979 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
980 printf(_(" --load-via-partition-root load partitions via the root table\n"));
981 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
982 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
983 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
984 printf(_(" --strict-names require table and/or schema include patterns to\n"
985 " match at least one entity each\n"));
986 printf(_(" --use-set-session-authorization\n"
987 " use SET SESSION AUTHORIZATION commands instead of\n"
988 " ALTER OWNER commands to set ownership\n"));
990 printf(_("\nConnection options:\n"));
991 printf(_(" -d, --dbname=DBNAME database to dump\n"));
992 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
993 printf(_(" -p, --port=PORT database server port number\n"));
994 printf(_(" -U, --username=NAME connect as specified database user\n"));
995 printf(_(" -w, --no-password never prompt for password\n"));
996 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
997 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
999 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1000 "variable value is used.\n\n"));
1001 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1005 setup_connection(Archive *AH, const char *dumpencoding,
1006 const char *dumpsnapshot, char *use_role)
1008 DumpOptions *dopt = AH->dopt;
1009 PGconn *conn = GetConnection(AH);
1010 const char *std_strings;
1013 * Set the client encoding if requested.
1017 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1018 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1023 * Get the active encoding and the standard_conforming_strings setting, so
1024 * we know how to escape strings.
1026 AH->encoding = PQclientEncoding(conn);
1028 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1029 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1032 * Set the role if requested. In a parallel dump worker, we'll be passed
1033 * use_role == NULL, but AH->use_role is already set (if user specified it
1034 * originally) and we should use that.
1036 if (!use_role && AH->use_role)
1037 use_role = AH->use_role;
1039 /* Set the role if requested */
1040 if (use_role && AH->remoteVersion >= 80100)
1042 PQExpBuffer query = createPQExpBuffer();
1044 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1045 ExecuteSqlStatement(AH, query->data);
1046 destroyPQExpBuffer(query);
1048 /* save it for possible later use by parallel workers */
1050 AH->use_role = pg_strdup(use_role);
1053 /* Set the datestyle to ISO to ensure the dump's portability */
1054 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1056 /* Likewise, avoid using sql_standard intervalstyle */
1057 if (AH->remoteVersion >= 80400)
1058 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1061 * Set extra_float_digits so that we can dump float data exactly (given
1062 * correctly implemented float I/O code, anyway)
1064 if (AH->remoteVersion >= 90000)
1065 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1067 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1070 * If synchronized scanning is supported, disable it, to prevent
1071 * unpredictable changes in row ordering across a dump and reload.
1073 if (AH->remoteVersion >= 80300)
1074 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1077 * Disable timeouts if supported.
1079 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1080 if (AH->remoteVersion >= 90300)
1081 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1082 if (AH->remoteVersion >= 90600)
1083 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1086 * Quote all identifiers, if requested.
1088 if (quote_all_identifiers && AH->remoteVersion >= 90100)
1089 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1092 * Adjust row-security mode, if supported.
1094 if (AH->remoteVersion >= 90500)
1096 if (dopt->enable_row_security)
1097 ExecuteSqlStatement(AH, "SET row_security = on");
1099 ExecuteSqlStatement(AH, "SET row_security = off");
1103 * Start transaction-snapshot mode transaction to dump consistent data.
1105 ExecuteSqlStatement(AH, "BEGIN");
1106 if (AH->remoteVersion >= 90100)
1109 * To support the combination of serializable_deferrable with the jobs
1110 * option we use REPEATABLE READ for the worker connections that are
1111 * passed a snapshot. As long as the snapshot is acquired in a
1112 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1113 * REPEATABLE READ transaction provides the appropriate integrity
1114 * guarantees. This is a kluge, but safe for back-patching.
1116 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1117 ExecuteSqlStatement(AH,
1118 "SET TRANSACTION ISOLATION LEVEL "
1119 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1121 ExecuteSqlStatement(AH,
1122 "SET TRANSACTION ISOLATION LEVEL "
1123 "REPEATABLE READ, READ ONLY");
1127 ExecuteSqlStatement(AH,
1128 "SET TRANSACTION ISOLATION LEVEL "
1129 "SERIALIZABLE, READ ONLY");
1133 * If user specified a snapshot to use, select that. In a parallel dump
1134 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1135 * is already set (if the server can handle it) and we should use that.
1138 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1140 if (AH->sync_snapshot_id)
1142 PQExpBuffer query = createPQExpBuffer();
1144 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1145 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1146 ExecuteSqlStatement(AH, query->data);
1147 destroyPQExpBuffer(query);
1149 else if (AH->numWorkers > 1 &&
1150 AH->remoteVersion >= 90200 &&
1151 !dopt->no_synchronized_snapshots)
1153 if (AH->isStandby && AH->remoteVersion < 100000)
1155 "Synchronized snapshots on standby servers are not supported by this server version.\n"
1156 "Run with --no-synchronized-snapshots instead if you do not need\n"
1157 "synchronized snapshots.\n");
1160 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1164 /* Set up connection for a parallel worker process */
1166 setupDumpWorker(Archive *AH)
1169 * We want to re-select all the same values the master connection is
1170 * using. We'll have inherited directly-usable values in
1171 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1172 * inherited encoding value back to a string to pass to setup_connection.
1174 setup_connection(AH,
1175 pg_encoding_to_char(AH->encoding),
1181 get_synchronized_snapshot(Archive *fout)
1183 char *query = "SELECT pg_catalog.pg_export_snapshot()";
1187 res = ExecuteSqlQueryForSingleRow(fout, query);
1188 result = pg_strdup(PQgetvalue(res, 0, 0));
1194 static ArchiveFormat
1195 parseArchiveFormat(const char *format, ArchiveMode *mode)
1197 ArchiveFormat archiveFormat;
1199 *mode = archModeWrite;
1201 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1203 /* This is used by pg_dumpall, and is not documented */
1204 archiveFormat = archNull;
1205 *mode = archModeAppend;
1207 else if (pg_strcasecmp(format, "c") == 0)
1208 archiveFormat = archCustom;
1209 else if (pg_strcasecmp(format, "custom") == 0)
1210 archiveFormat = archCustom;
1211 else if (pg_strcasecmp(format, "d") == 0)
1212 archiveFormat = archDirectory;
1213 else if (pg_strcasecmp(format, "directory") == 0)
1214 archiveFormat = archDirectory;
1215 else if (pg_strcasecmp(format, "p") == 0)
1216 archiveFormat = archNull;
1217 else if (pg_strcasecmp(format, "plain") == 0)
1218 archiveFormat = archNull;
1219 else if (pg_strcasecmp(format, "t") == 0)
1220 archiveFormat = archTar;
1221 else if (pg_strcasecmp(format, "tar") == 0)
1222 archiveFormat = archTar;
1224 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1225 return archiveFormat;
1229 * Find the OIDs of all schemas matching the given list of patterns,
1230 * and append them to the given OID list.
1233 expand_schema_name_patterns(Archive *fout,
1234 SimpleStringList *patterns,
1235 SimpleOidList *oids,
1240 SimpleStringListCell *cell;
1243 if (patterns->head == NULL)
1244 return; /* nothing to do */
1246 query = createPQExpBuffer();
1249 * The loop below runs multiple SELECTs might sometimes result in
1250 * duplicate entries in the OID list, but we don't care.
1253 for (cell = patterns->head; cell; cell = cell->next)
1255 appendPQExpBuffer(query,
1256 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1257 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1258 false, NULL, "n.nspname", NULL, NULL);
1260 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1261 if (strict_names && PQntuples(res) == 0)
1262 exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1264 for (i = 0; i < PQntuples(res); i++)
1266 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1270 resetPQExpBuffer(query);
1273 destroyPQExpBuffer(query);
1277 * Find the OIDs of all tables matching the given list of patterns,
1278 * and append them to the given OID list.
1281 expand_table_name_patterns(Archive *fout,
1282 SimpleStringList *patterns, SimpleOidList *oids,
1287 SimpleStringListCell *cell;
1290 if (patterns->head == NULL)
1291 return; /* nothing to do */
1293 query = createPQExpBuffer();
1296 * this might sometimes result in duplicate entries in the OID list, but
1300 for (cell = patterns->head; cell; cell = cell->next)
1302 appendPQExpBuffer(query,
1304 "\nFROM pg_catalog.pg_class c"
1305 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1306 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c')\n",
1307 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1308 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1309 RELKIND_PARTITIONED_TABLE);
1310 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1311 false, "n.nspname", "c.relname", NULL,
1312 "pg_catalog.pg_table_is_visible(c.oid)");
1314 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1315 if (strict_names && PQntuples(res) == 0)
1316 exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1318 for (i = 0; i < PQntuples(res); i++)
1320 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1324 resetPQExpBuffer(query);
1327 destroyPQExpBuffer(query);
1331 * checkExtensionMembership
1332 * Determine whether object is an extension member, and if so,
1333 * record an appropriate dependency and set the object's dump flag.
1335 * It's important to call this for each object that could be an extension
1336 * member. Generally, we integrate this with determining the object's
1337 * to-be-dumped-ness, since extension membership overrides other rules for that.
1339 * Returns true if object is an extension member, else false.
1342 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1344 ExtensionInfo *ext = findOwningExtension(dobj->catId);
1349 dobj->ext_member = true;
1351 /* Record dependency so that getDependencies needn't deal with that */
1352 addObjectDependency(dobj, ext->dobj.dumpId);
1355 * In 9.6 and above, mark the member object to have any non-initial ACL,
1356 * policies, and security labels dumped.
1358 * Note that any initial ACLs (see pg_init_privs) will be removed when we
1359 * extract the information about the object. We don't provide support for
1360 * initial policies and security labels and it seems unlikely for those to
1361 * ever exist, but we may have to revisit this later.
1363 * Prior to 9.6, we do not include any extension member components.
1365 * In binary upgrades, we still dump all components of the members
1366 * individually, since the idea is to exactly reproduce the database
1367 * contents rather than replace the extension contents with something
1370 if (fout->dopt->binary_upgrade)
1371 dobj->dump = ext->dobj.dump;
1374 if (fout->remoteVersion < 90600)
1375 dobj->dump = DUMP_COMPONENT_NONE;
1377 dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1378 DUMP_COMPONENT_SECLABEL |
1379 DUMP_COMPONENT_POLICY);
1386 * selectDumpableNamespace: policy-setting subroutine
1387 * Mark a namespace as to be dumped or not
1390 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1393 * If specific tables are being dumped, do not dump any complete
1394 * namespaces. If specific namespaces are being dumped, dump just those
1395 * namespaces. Otherwise, dump all non-system namespaces.
1397 if (table_include_oids.head != NULL)
1398 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1399 else if (schema_include_oids.head != NULL)
1400 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1401 simple_oid_list_member(&schema_include_oids,
1402 nsinfo->dobj.catId.oid) ?
1403 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1404 else if (fout->remoteVersion >= 90600 &&
1405 strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1408 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1409 * they are interesting (and not the original ACLs which were set at
1410 * initdb time, see pg_init_privs).
1412 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1414 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1415 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1417 /* Other system schemas don't get dumped */
1418 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1420 else if (strcmp(nsinfo->dobj.name, "public") == 0)
1423 * The public schema is a strange beast that sits in a sort of
1424 * no-mans-land between being a system object and a user object. We
1425 * don't want to dump creation or comment commands for it, because
1426 * that complicates matters for non-superuser use of pg_dump. But we
1427 * should dump any ACL changes that have occurred for it, and of
1428 * course we should dump contained objects.
1430 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1431 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1434 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1437 * In any case, a namespace can be excluded by an exclusion switch
1439 if (nsinfo->dobj.dump_contains &&
1440 simple_oid_list_member(&schema_exclude_oids,
1441 nsinfo->dobj.catId.oid))
1442 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1445 * If the schema belongs to an extension, allow extension membership to
1446 * override the dump decision for the schema itself. However, this does
1447 * not change dump_contains, so this won't change what we do with objects
1448 * within the schema. (If they belong to the extension, they'll get
1449 * suppressed by it, otherwise not.)
1451 (void) checkExtensionMembership(&nsinfo->dobj, fout);
1455 * selectDumpableTable: policy-setting subroutine
1456 * Mark a table as to be dumped or not
1459 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1461 if (checkExtensionMembership(&tbinfo->dobj, fout))
1462 return; /* extension membership overrides all else */
1465 * If specific tables are being dumped, dump just those tables; else, dump
1466 * according to the parent namespace's dump flag.
1468 if (table_include_oids.head != NULL)
1469 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1470 tbinfo->dobj.catId.oid) ?
1471 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1473 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1476 * In any case, a table can be excluded by an exclusion switch
1478 if (tbinfo->dobj.dump &&
1479 simple_oid_list_member(&table_exclude_oids,
1480 tbinfo->dobj.catId.oid))
1481 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1485 * selectDumpableType: policy-setting subroutine
1486 * Mark a type as to be dumped or not
1488 * If it's a table's rowtype or an autogenerated array type, we also apply a
1489 * special type code to facilitate sorting into the desired order. (We don't
1490 * want to consider those to be ordinary types because that would bring tables
1491 * up into the datatype part of the dump order.) We still set the object's
1492 * dump flag; that's not going to cause the dummy type to be dumped, but we
1493 * need it so that casts involving such types will be dumped correctly -- see
1494 * dumpCast. This means the flag should be set the same as for the underlying
1495 * object (the table or base type).
1498 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1500 /* skip complex types, except for standalone composite types */
1501 if (OidIsValid(tyinfo->typrelid) &&
1502 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1504 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1506 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1507 if (tytable != NULL)
1508 tyinfo->dobj.dump = tytable->dobj.dump;
1510 tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1514 /* skip auto-generated array types */
1515 if (tyinfo->isArray)
1517 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1520 * Fall through to set the dump flag; we assume that the subsequent
1521 * rules will do the same thing as they would for the array's base
1522 * type. (We cannot reliably look up the base type here, since
1523 * getTypes may not have processed it yet.)
1527 if (checkExtensionMembership(&tyinfo->dobj, fout))
1528 return; /* extension membership overrides all else */
1530 /* Dump based on if the contents of the namespace are being dumped */
1531 tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1535 * selectDumpableDefaultACL: policy-setting subroutine
1536 * Mark a default ACL as to be dumped or not
1538 * For per-schema default ACLs, dump if the schema is to be dumped.
1539 * Otherwise dump if we are dumping "everything". Note that dataOnly
1540 * and aclsSkip are checked separately.
1543 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1545 /* Default ACLs can't be extension members */
1547 if (dinfo->dobj.namespace)
1548 /* default ACLs are considered part of the namespace */
1549 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1551 dinfo->dobj.dump = dopt->include_everything ?
1552 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1556 * selectDumpableCast: policy-setting subroutine
1557 * Mark a cast as to be dumped or not
1559 * Casts do not belong to any particular namespace (since they haven't got
1560 * names), nor do they have identifiable owners. To distinguish user-defined
1561 * casts from built-in ones, we must resort to checking whether the cast's
1562 * OID is in the range reserved for initdb.
1565 selectDumpableCast(CastInfo *cast, Archive *fout)
1567 if (checkExtensionMembership(&cast->dobj, fout))
1568 return; /* extension membership overrides all else */
1571 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1572 * support ACLs currently.
1574 if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1575 cast->dobj.dump = DUMP_COMPONENT_NONE;
1577 cast->dobj.dump = fout->dopt->include_everything ?
1578 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1582 * selectDumpableProcLang: policy-setting subroutine
1583 * Mark a procedural language as to be dumped or not
1585 * Procedural languages do not belong to any particular namespace. To
1586 * identify built-in languages, we must resort to checking whether the
1587 * language's OID is in the range reserved for initdb.
1590 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1592 if (checkExtensionMembership(&plang->dobj, fout))
1593 return; /* extension membership overrides all else */
1596 * Only include procedural languages when we are dumping everything.
1598 * For from-initdb procedural languages, only include ACLs, as we do for
1599 * the pg_catalog namespace. We need this because procedural languages do
1600 * not live in any namespace.
1602 if (!fout->dopt->include_everything)
1603 plang->dobj.dump = DUMP_COMPONENT_NONE;
1606 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1607 plang->dobj.dump = fout->remoteVersion < 90600 ?
1608 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1610 plang->dobj.dump = DUMP_COMPONENT_ALL;
1615 * selectDumpableAccessMethod: policy-setting subroutine
1616 * Mark an access method as to be dumped or not
1618 * Access methods do not belong to any particular namespace. To identify
1619 * built-in access methods, we must resort to checking whether the
1620 * method's OID is in the range reserved for initdb.
1623 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1625 if (checkExtensionMembership(&method->dobj, fout))
1626 return; /* extension membership overrides all else */
1629 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1630 * they do not support ACLs currently.
1632 if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1633 method->dobj.dump = DUMP_COMPONENT_NONE;
1635 method->dobj.dump = fout->dopt->include_everything ?
1636 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1640 * selectDumpableExtension: policy-setting subroutine
1641 * Mark an extension as to be dumped or not
1643 * Built-in extensions should be skipped except for checking ACLs, since we
1644 * assume those will already be installed in the target database. We identify
1645 * such extensions by their having OIDs in the range reserved for initdb.
1646 * We dump all user-added extensions by default, or none of them if
1647 * include_everything is false (i.e., a --schema or --table switch was given).
1650 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1653 * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1654 * change permissions on their member objects, if they wish to, and have
1655 * those changes preserved.
1657 if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1658 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1660 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1661 dopt->include_everything ? DUMP_COMPONENT_ALL :
1662 DUMP_COMPONENT_NONE;
1666 * selectDumpablePublicationTable: policy-setting subroutine
1667 * Mark a publication table as to be dumped or not
1669 * Publication tables have schemas, but those are ignored in decision making,
1670 * because publications are only dumped when we are dumping everything.
1673 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1675 if (checkExtensionMembership(dobj, fout))
1676 return; /* extension membership overrides all else */
1678 dobj->dump = fout->dopt->include_everything ?
1679 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1683 * selectDumpableObject: policy-setting subroutine
1684 * Mark a generic dumpable object as to be dumped or not
1686 * Use this only for object types without a special-case routine above.
1689 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1691 if (checkExtensionMembership(dobj, fout))
1692 return; /* extension membership overrides all else */
1695 * Default policy is to dump if parent namespace is dumpable, or for
1696 * non-namespace-associated items, dump if we're dumping "everything".
1698 if (dobj->namespace)
1699 dobj->dump = dobj->namespace->dobj.dump_contains;
1701 dobj->dump = fout->dopt->include_everything ?
1702 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1706 * Dump a table's contents for loading using the COPY command
1707 * - this routine is called by the Archiver when it wants the table
1712 dumpTableData_copy(Archive *fout, void *dcontext)
1714 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1715 TableInfo *tbinfo = tdinfo->tdtable;
1716 const char *classname = tbinfo->dobj.name;
1717 const bool hasoids = tbinfo->hasoids;
1718 const bool oids = tdinfo->oids;
1719 PQExpBuffer q = createPQExpBuffer();
1722 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1723 * which uses it already.
1725 PQExpBuffer clistBuf = createPQExpBuffer();
1726 PGconn *conn = GetConnection(fout);
1730 const char *column_list;
1733 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1734 tbinfo->dobj.namespace->dobj.name, classname);
1737 * Make sure we are in proper schema. We will qualify the table name
1738 * below anyway (in case its name conflicts with a pg_catalog table); but
1739 * this ensures reproducible results in case the table contains regproc,
1740 * regclass, etc columns.
1742 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1745 * Specify the column list explicitly so that we have no possibility of
1746 * retrieving data in the wrong column order. (The default column
1747 * ordering of COPY will not be what we want in certain corner cases
1748 * involving ADD COLUMN and inheritance.)
1750 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1752 if (oids && hasoids)
1754 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1755 fmtQualifiedId(fout->remoteVersion,
1756 tbinfo->dobj.namespace->dobj.name,
1760 else if (tdinfo->filtercond)
1762 /* Note: this syntax is only supported in 8.2 and up */
1763 appendPQExpBufferStr(q, "COPY (SELECT ");
1764 /* klugery to get rid of parens in column list */
1765 if (strlen(column_list) > 2)
1767 appendPQExpBufferStr(q, column_list + 1);
1768 q->data[q->len - 1] = ' ';
1771 appendPQExpBufferStr(q, "* ");
1772 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1773 fmtQualifiedId(fout->remoteVersion,
1774 tbinfo->dobj.namespace->dobj.name,
1776 tdinfo->filtercond);
1780 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1781 fmtQualifiedId(fout->remoteVersion,
1782 tbinfo->dobj.namespace->dobj.name,
1786 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1788 destroyPQExpBuffer(clistBuf);
1792 ret = PQgetCopyData(conn, ©buf, 0);
1795 break; /* done or error */
1799 WriteData(fout, copybuf, ret);
1806 * There was considerable discussion in late July, 2000 regarding
1807 * slowing down pg_dump when backing up large tables. Users with both
1808 * slow & fast (multi-processor) machines experienced performance
1809 * degradation when doing a backup.
1811 * Initial attempts based on sleeping for a number of ms for each ms
1812 * of work were deemed too complex, then a simple 'sleep in each loop'
1813 * implementation was suggested. The latter failed because the loop
1814 * was too tight. Finally, the following was implemented:
1816 * If throttle is non-zero, then
1817 * See how long since the last sleep.
1818 * Work out how long to sleep (based on ratio).
1819 * If sleep is more than 100ms, then
1825 * where the throttle value was the number of ms to sleep per ms of
1826 * work. The calculation was done in each loop.
1828 * Most of the hard work is done in the backend, and this solution
1829 * still did not work particularly well: on slow machines, the ratio
1830 * was 50:1, and on medium paced machines, 1:1, and on fast
1831 * multi-processor machines, it had little or no effect, for reasons
1832 * that were unclear.
1834 * Further discussion ensued, and the proposal was dropped.
1836 * For those people who want this feature, it can be implemented using
1837 * gettimeofday in each loop, calculating the time since last sleep,
1838 * multiplying that by the sleep ratio, then if the result is more
1839 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1840 * function to sleep for a subsecond period ie.
1842 * select(0, NULL, NULL, NULL, &tvi);
1844 * This will return after the interval specified in the structure tvi.
1845 * Finally, call gettimeofday again to save the 'last sleep time'.
1849 archprintf(fout, "\\.\n\n\n");
1853 /* copy data transfer failed */
1854 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1855 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1856 write_msg(NULL, "The command was: %s\n", q->data);
1860 /* Check command status and return to normal libpq state */
1861 res = PQgetResult(conn);
1862 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1864 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1865 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1866 write_msg(NULL, "The command was: %s\n", q->data);
1871 /* Do this to ensure we've pumped libpq back to idle state */
1872 if (PQgetResult(conn) != NULL)
1873 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1876 destroyPQExpBuffer(q);
1881 * Dump table data using INSERT commands.
1883 * Caution: when we restore from an archive file direct to database, the
1884 * INSERT commands emitted by this function have to be parsed by
1885 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1886 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1889 dumpTableData_insert(Archive *fout, void *dcontext)
1891 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1892 TableInfo *tbinfo = tdinfo->tdtable;
1893 const char *classname = tbinfo->dobj.name;
1894 DumpOptions *dopt = fout->dopt;
1895 PQExpBuffer q = createPQExpBuffer();
1896 PQExpBuffer insertStmt = NULL;
1903 * Make sure we are in proper schema. We will qualify the table name
1904 * below anyway (in case its name conflicts with a pg_catalog table); but
1905 * this ensures reproducible results in case the table contains regproc,
1906 * regclass, etc columns.
1908 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1910 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1911 "SELECT * FROM ONLY %s",
1912 fmtQualifiedId(fout->remoteVersion,
1913 tbinfo->dobj.namespace->dobj.name,
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 insertStmt = createPQExpBuffer();
1939 * When load-via-partition-root is set, get the root table
1940 * name for the partition table, so that we can reload data
1941 * through the root table.
1943 if (dopt->load_via_partition_root && tbinfo->ispartition)
1945 TableInfo *parentTbinfo;
1947 parentTbinfo = getRootTableInfo(tbinfo);
1950 * When we loading data through the root, we will qualify
1951 * the table name. This is needed because earlier
1952 * search_path will be set for the partition table.
1954 classname = (char *) fmtQualifiedId(fout->remoteVersion,
1955 parentTbinfo->dobj.namespace->dobj.name,
1956 parentTbinfo->dobj.name);
1959 classname = fmtId(tbinfo->dobj.name);
1961 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1964 /* corner case for zero-column table */
1967 appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1971 /* append the list of column names if required */
1972 if (dopt->column_inserts)
1974 appendPQExpBufferChar(insertStmt, '(');
1975 for (field = 0; field < nfields; field++)
1978 appendPQExpBufferStr(insertStmt, ", ");
1979 appendPQExpBufferStr(insertStmt,
1980 fmtId(PQfname(res, field)));
1982 appendPQExpBufferStr(insertStmt, ") ");
1985 if (tbinfo->needs_override)
1986 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1988 appendPQExpBufferStr(insertStmt, "VALUES (");
1992 archputs(insertStmt->data, fout);
1994 /* if it is zero-column table then we're done */
1998 for (field = 0; field < nfields; field++)
2001 archputs(", ", fout);
2002 if (PQgetisnull(res, tuple, field))
2004 archputs("NULL", fout);
2008 /* XXX This code is partially duplicated in ruleutils.c */
2009 switch (PQftype(res, field))
2020 * These types are printed without quotes unless
2021 * they contain values that aren't accepted by the
2022 * scanner unquoted (e.g., 'NaN'). Note that
2023 * strtod() and friends might accept NaN, so we
2024 * can't use that to test.
2026 * In reality we only need to defend against
2027 * infinity and NaN, so we need not get too crazy
2028 * about pattern matching here.
2030 const char *s = PQgetvalue(res, tuple, field);
2032 if (strspn(s, "0123456789 +-eE.") == strlen(s))
2035 archprintf(fout, "'%s'", s);
2041 archprintf(fout, "B'%s'",
2042 PQgetvalue(res, tuple, field));
2046 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2047 archputs("true", fout);
2049 archputs("false", fout);
2053 /* All other types are printed as string literals. */
2054 resetPQExpBuffer(q);
2055 appendStringLiteralAH(q,
2056 PQgetvalue(res, tuple, field),
2058 archputs(q->data, fout);
2062 archputs(");\n", fout);
2065 if (PQntuples(res) <= 0)
2073 archputs("\n\n", fout);
2075 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2077 destroyPQExpBuffer(q);
2078 if (insertStmt != NULL)
2079 destroyPQExpBuffer(insertStmt);
2086 * get the root TableInfo for the given partition table.
2089 getRootTableInfo(TableInfo *tbinfo)
2091 TableInfo *parentTbinfo;
2093 Assert(tbinfo->ispartition);
2094 Assert(tbinfo->numParents == 1);
2096 parentTbinfo = tbinfo->parents[0];
2097 while (parentTbinfo->ispartition)
2099 Assert(parentTbinfo->numParents == 1);
2100 parentTbinfo = parentTbinfo->parents[0];
2103 return parentTbinfo;
2108 * dump the contents of a single table
2110 * Actually, this just makes an ArchiveEntry for the table contents.
2113 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2115 DumpOptions *dopt = fout->dopt;
2116 TableInfo *tbinfo = tdinfo->tdtable;
2117 PQExpBuffer copyBuf = createPQExpBuffer();
2118 PQExpBuffer clistBuf = createPQExpBuffer();
2119 DataDumperPtr dumpFn;
2121 const char *copyFrom;
2123 if (!dopt->dump_inserts)
2125 /* Dump/restore using COPY */
2126 dumpFn = dumpTableData_copy;
2129 * When load-via-partition-root is set, get the root table name for
2130 * the partition table, so that we can reload data through the root
2133 if (dopt->load_via_partition_root && tbinfo->ispartition)
2135 TableInfo *parentTbinfo;
2137 parentTbinfo = getRootTableInfo(tbinfo);
2140 * When we load data through the root, we will qualify the table
2141 * name, because search_path is set for the partition.
2143 copyFrom = fmtQualifiedId(fout->remoteVersion,
2144 parentTbinfo->dobj.namespace->dobj.name,
2145 parentTbinfo->dobj.name);
2148 copyFrom = fmtId(tbinfo->dobj.name);
2150 /* must use 2 steps here 'cause fmtId is nonreentrant */
2151 appendPQExpBuffer(copyBuf, "COPY %s ",
2153 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2154 fmtCopyColumnList(tbinfo, clistBuf),
2155 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2156 copyStmt = copyBuf->data;
2160 /* Restore using INSERT */
2161 dumpFn = dumpTableData_insert;
2166 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2167 * dependency on its table as "special" and pass it to ArchiveEntry now.
2168 * See comments for BuildArchiveDependencies.
2170 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2171 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2172 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2173 NULL, tbinfo->rolname,
2174 false, "TABLE DATA", SECTION_DATA,
2176 &(tbinfo->dobj.dumpId), 1,
2179 destroyPQExpBuffer(copyBuf);
2180 destroyPQExpBuffer(clistBuf);
2184 * refreshMatViewData -
2185 * load or refresh the contents of a single materialized view
2187 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2191 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2193 TableInfo *tbinfo = tdinfo->tdtable;
2196 /* If the materialized view is not flagged as populated, skip this. */
2197 if (!tbinfo->relispopulated)
2200 q = createPQExpBuffer();
2202 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2203 fmtId(tbinfo->dobj.name));
2205 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2207 tdinfo->dobj.catId, /* catalog ID */
2208 tdinfo->dobj.dumpId, /* dump ID */
2209 tbinfo->dobj.name, /* Name */
2210 tbinfo->dobj.namespace->dobj.name, /* Namespace */
2211 NULL, /* Tablespace */
2212 tbinfo->rolname, /* Owner */
2213 false, /* with oids */
2214 "MATERIALIZED VIEW DATA", /* Desc */
2215 SECTION_POST_DATA, /* Section */
2216 q->data, /* Create */
2219 tdinfo->dobj.dependencies, /* Deps */
2220 tdinfo->dobj.nDeps, /* # Deps */
2222 NULL); /* Dumper Arg */
2224 destroyPQExpBuffer(q);
2229 * set up dumpable objects representing the contents of tables
2232 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2236 for (i = 0; i < numTables; i++)
2238 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2239 (!relkind || tblinfo[i].relkind == relkind))
2240 makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2245 * Make a dumpable object for the data of this specific table
2247 * Note: we make a TableDataInfo if and only if we are going to dump the
2248 * table data; the "dump" flag in such objects isn't used.
2251 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2253 TableDataInfo *tdinfo;
2256 * Nothing to do if we already decided to dump the table. This will
2257 * happen for "config" tables.
2259 if (tbinfo->dataObj != NULL)
2262 /* Skip VIEWs (no data to dump) */
2263 if (tbinfo->relkind == RELKIND_VIEW)
2265 /* Skip FOREIGN TABLEs (no data to dump) */
2266 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2268 /* Skip partitioned tables (data in partitions) */
2269 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2272 /* Don't dump data in unlogged tables, if so requested */
2273 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2274 dopt->no_unlogged_table_data)
2277 /* Check that the data is not explicitly excluded */
2278 if (simple_oid_list_member(&tabledata_exclude_oids,
2279 tbinfo->dobj.catId.oid))
2282 /* OK, let's dump it */
2283 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2285 if (tbinfo->relkind == RELKIND_MATVIEW)
2286 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2287 else if (tbinfo->relkind == RELKIND_SEQUENCE)
2288 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2290 tdinfo->dobj.objType = DO_TABLE_DATA;
2293 * Note: use tableoid 0 so that this object won't be mistaken for
2294 * something that pg_depend entries apply to.
2296 tdinfo->dobj.catId.tableoid = 0;
2297 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2298 AssignDumpId(&tdinfo->dobj);
2299 tdinfo->dobj.name = tbinfo->dobj.name;
2300 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2301 tdinfo->tdtable = tbinfo;
2302 tdinfo->oids = oids;
2303 tdinfo->filtercond = NULL; /* might get set later */
2304 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2306 tbinfo->dataObj = tdinfo;
2310 * The refresh for a materialized view must be dependent on the refresh for
2311 * any materialized view that this one is dependent on.
2313 * This must be called after all the objects are created, but before they are
2317 buildMatViewRefreshDependencies(Archive *fout)
2327 /* No Mat Views before 9.3. */
2328 if (fout->remoteVersion < 90300)
2331 /* Make sure we are in proper schema */
2332 selectSourceSchema(fout, "pg_catalog");
2334 query = createPQExpBuffer();
2336 appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2338 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2339 "FROM pg_depend d1 "
2340 "JOIN pg_class c1 ON c1.oid = d1.objid "
2341 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2342 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2343 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2344 "AND d2.objid = r1.oid "
2345 "AND d2.refobjid <> d1.objid "
2346 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2347 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2348 CppAsString2(RELKIND_VIEW) ") "
2349 "WHERE d1.classid = 'pg_class'::regclass "
2351 "SELECT w.objid, d3.refobjid, c3.relkind "
2353 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2354 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2355 "AND d3.objid = r3.oid "
2356 "AND d3.refobjid <> w.refobjid "
2357 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2358 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2359 CppAsString2(RELKIND_VIEW) ") "
2361 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2363 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2365 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2367 ntups = PQntuples(res);
2369 i_classid = PQfnumber(res, "classid");
2370 i_objid = PQfnumber(res, "objid");
2371 i_refobjid = PQfnumber(res, "refobjid");
2373 for (i = 0; i < ntups; i++)
2377 DumpableObject *dobj;
2378 DumpableObject *refdobj;
2380 TableInfo *reftbinfo;
2382 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2383 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2384 refobjId.tableoid = objId.tableoid;
2385 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2387 dobj = findObjectByCatalogId(objId);
2391 Assert(dobj->objType == DO_TABLE);
2392 tbinfo = (TableInfo *) dobj;
2393 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2394 dobj = (DumpableObject *) tbinfo->dataObj;
2397 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2399 refdobj = findObjectByCatalogId(refobjId);
2400 if (refdobj == NULL)
2403 Assert(refdobj->objType == DO_TABLE);
2404 reftbinfo = (TableInfo *) refdobj;
2405 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2406 refdobj = (DumpableObject *) reftbinfo->dataObj;
2407 if (refdobj == NULL)
2409 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2411 addObjectDependency(dobj, refdobj->dumpId);
2413 if (!reftbinfo->relispopulated)
2414 tbinfo->relispopulated = false;
2419 destroyPQExpBuffer(query);
2423 * getTableDataFKConstraints -
2424 * add dump-order dependencies reflecting foreign key constraints
2426 * This code is executed only in a data-only dump --- in schema+data dumps
2427 * we handle foreign key issues by not creating the FK constraints until
2428 * after the data is loaded. In a data-only dump, however, we want to
2429 * order the table data objects in such a way that a table's referenced
2430 * tables are restored first. (In the presence of circular references or
2431 * self-references this may be impossible; we'll detect and complain about
2432 * that during the dependency sorting step.)
2435 getTableDataFKConstraints(void)
2437 DumpableObject **dobjs;
2441 /* Search through all the dumpable objects for FK constraints */
2442 getDumpableObjects(&dobjs, &numObjs);
2443 for (i = 0; i < numObjs; i++)
2445 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2447 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2450 /* Not interesting unless both tables are to be dumped */
2451 if (cinfo->contable == NULL ||
2452 cinfo->contable->dataObj == NULL)
2454 ftable = findTableByOid(cinfo->confrelid);
2455 if (ftable == NULL ||
2456 ftable->dataObj == NULL)
2460 * Okay, make referencing table's TABLE_DATA object depend on the
2461 * referenced table's TABLE_DATA object.
2463 addObjectDependency(&cinfo->contable->dataObj->dobj,
2464 ftable->dataObj->dobj.dumpId);
2472 * guessConstraintInheritance:
2473 * In pre-8.4 databases, we can't tell for certain which constraints
2474 * are inherited. We assume a CHECK constraint is inherited if its name
2475 * matches the name of any constraint in the parent. Originally this code
2476 * tried to compare the expression texts, but that can fail for various
2477 * reasons --- for example, if the parent and child tables are in different
2478 * schemas, reverse-listing of function calls may produce different text
2479 * (schema-qualified or not) depending on search path.
2481 * In 8.4 and up we can rely on the conislocal field to decide which
2482 * constraints must be dumped; much safer.
2484 * This function assumes all conislocal flags were initialized to true.
2485 * It clears the flag on anything that seems to be inherited.
2488 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2494 for (i = 0; i < numTables; i++)
2496 TableInfo *tbinfo = &(tblinfo[i]);
2498 TableInfo **parents;
2501 /* Sequences and views never have parents */
2502 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2503 tbinfo->relkind == RELKIND_VIEW)
2506 /* Don't bother computing anything for non-target tables, either */
2507 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2510 numParents = tbinfo->numParents;
2511 parents = tbinfo->parents;
2513 if (numParents == 0)
2514 continue; /* nothing to see here, move along */
2516 /* scan for inherited CHECK constraints */
2517 for (j = 0; j < tbinfo->ncheck; j++)
2519 ConstraintInfo *constr;
2521 constr = &(tbinfo->checkexprs[j]);
2523 for (k = 0; k < numParents; k++)
2527 parent = parents[k];
2528 for (l = 0; l < parent->ncheck; l++)
2530 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2532 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2534 constr->conislocal = false;
2538 if (!constr->conislocal)
2548 * dump the database definition
2551 dumpDatabase(Archive *fout)
2553 DumpOptions *dopt = fout->dopt;
2554 PQExpBuffer dbQry = createPQExpBuffer();
2555 PQExpBuffer delQry = createPQExpBuffer();
2556 PQExpBuffer creaQry = createPQExpBuffer();
2557 PQExpBuffer labelq = createPQExpBuffer();
2558 PGconn *conn = GetConnection(fout);
2575 const char *datname,
2589 datname = PQdb(conn);
2590 qdatname = pg_strdup(fmtId(datname));
2593 write_msg(NULL, "saving database definition\n");
2595 /* Make sure we are in proper schema */
2596 selectSourceSchema(fout, "pg_catalog");
2598 /* Fetch the database-level properties for this database */
2599 if (fout->remoteVersion >= 90600)
2601 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2602 "(%s datdba) AS dba, "
2603 "pg_encoding_to_char(encoding) AS encoding, "
2604 "datcollate, datctype, datfrozenxid, datminmxid, "
2605 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2606 " SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2607 " EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2609 "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2610 " SELECT unnest(acldefault('d',datdba)) AS acl "
2611 " EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2613 "datistemplate, datconnlimit, "
2614 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2615 "shobj_description(oid, 'pg_database') AS description "
2620 appendStringLiteralAH(dbQry, datname, fout);
2622 else if (fout->remoteVersion >= 90300)
2624 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2625 "(%s datdba) AS dba, "
2626 "pg_encoding_to_char(encoding) AS encoding, "
2627 "datcollate, datctype, datfrozenxid, datminmxid, "
2628 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2629 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2630 "shobj_description(oid, 'pg_database') AS description "
2635 appendStringLiteralAH(dbQry, datname, fout);
2637 else if (fout->remoteVersion >= 80400)
2639 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2640 "(%s datdba) AS dba, "
2641 "pg_encoding_to_char(encoding) AS encoding, "
2642 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2643 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2644 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2645 "shobj_description(oid, 'pg_database') AS description "
2650 appendStringLiteralAH(dbQry, datname, fout);
2652 else if (fout->remoteVersion >= 80200)
2654 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2655 "(%s datdba) AS dba, "
2656 "pg_encoding_to_char(encoding) AS encoding, "
2657 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2658 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2659 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2660 "shobj_description(oid, 'pg_database') AS description "
2665 appendStringLiteralAH(dbQry, datname, fout);
2669 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2670 "(%s datdba) AS dba, "
2671 "pg_encoding_to_char(encoding) AS encoding, "
2672 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2673 "datacl, '' as rdatacl, datistemplate, "
2674 "-1 as datconnlimit, "
2675 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2679 appendStringLiteralAH(dbQry, datname, fout);
2682 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2684 i_tableoid = PQfnumber(res, "tableoid");
2685 i_oid = PQfnumber(res, "oid");
2686 i_dba = PQfnumber(res, "dba");
2687 i_encoding = PQfnumber(res, "encoding");
2688 i_collate = PQfnumber(res, "datcollate");
2689 i_ctype = PQfnumber(res, "datctype");
2690 i_frozenxid = PQfnumber(res, "datfrozenxid");
2691 i_minmxid = PQfnumber(res, "datminmxid");
2692 i_datacl = PQfnumber(res, "datacl");
2693 i_rdatacl = PQfnumber(res, "rdatacl");
2694 i_datistemplate = PQfnumber(res, "datistemplate");
2695 i_datconnlimit = PQfnumber(res, "datconnlimit");
2696 i_tablespace = PQfnumber(res, "tablespace");
2698 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2699 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2700 dba = PQgetvalue(res, 0, i_dba);
2701 encoding = PQgetvalue(res, 0, i_encoding);
2702 collate = PQgetvalue(res, 0, i_collate);
2703 ctype = PQgetvalue(res, 0, i_ctype);
2704 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2705 minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2706 datacl = PQgetvalue(res, 0, i_datacl);
2707 rdatacl = PQgetvalue(res, 0, i_rdatacl);
2708 datistemplate = PQgetvalue(res, 0, i_datistemplate);
2709 datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2710 tablespace = PQgetvalue(res, 0, i_tablespace);
2713 * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2714 * and tablespace since those can't be altered later. Other DB properties
2715 * are left to the DATABASE PROPERTIES entry, so that they can be applied
2716 * after reconnecting to the target DB.
2718 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2720 if (strlen(encoding) > 0)
2722 appendPQExpBufferStr(creaQry, " ENCODING = ");
2723 appendStringLiteralAH(creaQry, encoding, fout);
2725 if (strlen(collate) > 0)
2727 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2728 appendStringLiteralAH(creaQry, collate, fout);
2730 if (strlen(ctype) > 0)
2732 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2733 appendStringLiteralAH(creaQry, ctype, fout);
2737 * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2738 * thing; the decision whether to specify a tablespace should be left till
2739 * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2740 * label the DATABASE entry with the tablespace and let the normal
2741 * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2742 * attention to default_tablespace, so that won't work.
2744 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2745 !dopt->outputNoTablespaces)
2746 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2748 appendPQExpBufferStr(creaQry, ";\n");
2750 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2753 dbDumpId = createDumpId();
2756 dbCatId, /* catalog ID */
2757 dbDumpId, /* dump ID */
2759 NULL, /* Namespace */
2760 NULL, /* Tablespace */
2762 false, /* with oids */
2763 "DATABASE", /* Desc */
2764 SECTION_PRE_DATA, /* Section */
2765 creaQry->data, /* Create */
2766 delQry->data, /* Del */
2771 NULL); /* Dumper Arg */
2773 /* Compute correct tag for comments etc */
2774 appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2776 /* Dump DB comment if any */
2777 if (fout->remoteVersion >= 80200)
2780 * 8.2 and up keep comments on shared objects in a shared table, so we
2781 * cannot use the dumpComment() code used for other database objects.
2782 * Be careful that the ArchiveEntry parameters match that function.
2784 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2786 if (comment && *comment && !dopt->no_comments)
2788 resetPQExpBuffer(dbQry);
2791 * Generates warning when loaded into a differently-named
2794 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2795 appendStringLiteralAH(dbQry, comment, fout);
2796 appendPQExpBufferStr(dbQry, ";\n");
2798 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2799 labelq->data, NULL, NULL, dba,
2800 false, "COMMENT", SECTION_NONE,
2801 dbQry->data, "", NULL,
2808 dumpComment(fout, labelq->data, NULL, dba,
2809 dbCatId, 0, dbDumpId);
2812 /* Dump DB security label, if enabled */
2813 if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2816 PQExpBuffer seclabelQry;
2818 seclabelQry = createPQExpBuffer();
2820 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2821 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2822 resetPQExpBuffer(seclabelQry);
2823 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2824 if (seclabelQry->len > 0)
2825 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2826 labelq->data, NULL, NULL, dba,
2827 false, "SECURITY LABEL", SECTION_NONE,
2828 seclabelQry->data, "", NULL,
2831 destroyPQExpBuffer(seclabelQry);
2836 * Dump ACL if any. Note that we do not support initial privileges
2837 * (pg_init_privs) on databases.
2839 dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2840 qdatname, NULL, labelq->data, NULL,
2841 dba, datacl, rdatacl, "", "");
2844 * Now construct a DATABASE PROPERTIES archive entry to restore any
2845 * non-default database-level properties. (The reason this must be
2846 * separate is that we cannot put any additional commands into the TOC
2847 * entry that has CREATE DATABASE. pg_restore would execute such a group
2848 * in an implicit transaction block, and the backend won't allow CREATE
2849 * DATABASE in that context.)
2851 resetPQExpBuffer(creaQry);
2852 resetPQExpBuffer(delQry);
2854 if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2855 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2856 qdatname, datconnlimit);
2858 if (strcmp(datistemplate, "t") == 0)
2860 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2864 * The backend won't accept DROP DATABASE on a template database. We
2865 * can deal with that by removing the template marking before the DROP
2866 * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
2867 * since no such command is currently supported, fake it with a direct
2868 * UPDATE on pg_database.
2870 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2871 "SET datistemplate = false WHERE datname = ");
2872 appendStringLiteralAH(delQry, datname, fout);
2873 appendPQExpBufferStr(delQry, ";\n");
2876 /* Add database-specific SET options */
2877 dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2880 * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2881 * entry, too, for lack of a better place.
2883 if (dopt->binary_upgrade)
2885 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2886 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2887 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2889 frozenxid, minmxid);
2890 appendStringLiteralAH(creaQry, datname, fout);
2891 appendPQExpBufferStr(creaQry, ";\n");
2894 if (creaQry->len > 0)
2895 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2896 datname, NULL, NULL, dba,
2897 false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2898 creaQry->data, delQry->data, NULL,
2903 * pg_largeobject and pg_largeobject_metadata come from the old system
2904 * intact, so set their relfrozenxids and relminmxids.
2906 if (dopt->binary_upgrade)
2909 PQExpBuffer loFrozenQry = createPQExpBuffer();
2910 PQExpBuffer loOutQry = createPQExpBuffer();
2917 if (fout->remoteVersion >= 90300)
2918 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2919 "FROM pg_catalog.pg_class\n"
2920 "WHERE oid = %u;\n",
2921 LargeObjectRelationId);
2923 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2924 "FROM pg_catalog.pg_class\n"
2925 "WHERE oid = %u;\n",
2926 LargeObjectRelationId);
2928 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2930 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2931 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2933 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2934 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2935 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2936 "WHERE oid = %u;\n",
2937 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2938 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2939 LargeObjectRelationId);
2940 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2941 "pg_largeobject", NULL, NULL, "",
2942 false, "pg_largeobject", SECTION_PRE_DATA,
2943 loOutQry->data, "", NULL,
2950 * pg_largeobject_metadata
2952 if (fout->remoteVersion >= 90000)
2954 resetPQExpBuffer(loFrozenQry);
2955 resetPQExpBuffer(loOutQry);
2957 if (fout->remoteVersion >= 90300)
2958 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2959 "FROM pg_catalog.pg_class\n"
2960 "WHERE oid = %u;\n",
2961 LargeObjectMetadataRelationId);
2963 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2964 "FROM pg_catalog.pg_class\n"
2965 "WHERE oid = %u;\n",
2966 LargeObjectMetadataRelationId);
2968 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2970 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2971 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2973 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2974 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2975 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2976 "WHERE oid = %u;\n",
2977 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2978 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2979 LargeObjectMetadataRelationId);
2980 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2981 "pg_largeobject_metadata", NULL, NULL, "",
2982 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2983 loOutQry->data, "", NULL,
2990 destroyPQExpBuffer(loFrozenQry);
2991 destroyPQExpBuffer(loOutQry);
2997 destroyPQExpBuffer(dbQry);
2998 destroyPQExpBuffer(delQry);
2999 destroyPQExpBuffer(creaQry);
3000 destroyPQExpBuffer(labelq);
3004 * Collect any database-specific or role-and-database-specific SET options
3005 * for this database, and append them to outbuf.
3008 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
3009 const char *dbname, Oid dboid)
3011 PGconn *conn = GetConnection(AH);
3012 PQExpBuffer buf = createPQExpBuffer();
3017 * First collect database-specific options. Pre-8.4 server versions lack
3018 * unnest(), so we do this the hard way by querying once per subscript.
3022 if (AH->remoteVersion >= 90000)
3023 printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3024 "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3027 printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3029 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3031 if (PQntuples(res) == 1 &&
3032 !PQgetisnull(res, 0, 0))
3034 makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3035 "DATABASE", dbname, NULL, NULL,
3047 /* Now look for role-and-database-specific options */
3048 if (AH->remoteVersion >= 90000)
3050 /* Here we can assume we have unnest() */
3051 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3052 "FROM pg_db_role_setting s, pg_roles r "
3053 "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3056 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3058 if (PQntuples(res) > 0)
3062 for (i = 0; i < PQntuples(res); i++)
3063 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3064 "ROLE", PQgetvalue(res, i, 0),
3072 destroyPQExpBuffer(buf);
3076 * dumpEncoding: put the correct encoding into the archive
3079 dumpEncoding(Archive *AH)
3081 const char *encname = pg_encoding_to_char(AH->encoding);
3082 PQExpBuffer qry = createPQExpBuffer();
3085 write_msg(NULL, "saving encoding = %s\n", encname);
3087 appendPQExpBufferStr(qry, "SET client_encoding = ");
3088 appendStringLiteralAH(qry, encname, AH);
3089 appendPQExpBufferStr(qry, ";\n");
3091 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3092 "ENCODING", NULL, NULL, "",
3093 false, "ENCODING", SECTION_PRE_DATA,
3094 qry->data, "", NULL,
3098 destroyPQExpBuffer(qry);
3103 * dumpStdStrings: put the correct escape string behavior into the archive
3106 dumpStdStrings(Archive *AH)
3108 const char *stdstrings = AH->std_strings ? "on" : "off";
3109 PQExpBuffer qry = createPQExpBuffer();
3112 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3115 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3118 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3119 "STDSTRINGS", NULL, NULL, "",
3120 false, "STDSTRINGS", SECTION_PRE_DATA,
3121 qry->data, "", NULL,
3125 destroyPQExpBuffer(qry);
3131 * Collect schema-level data about large objects
3134 getBlobs(Archive *fout)
3136 DumpOptions *dopt = fout->dopt;
3137 PQExpBuffer blobQry = createPQExpBuffer();
3139 DumpableObject *bdata;
3150 /* Verbose message */
3152 write_msg(NULL, "reading large objects\n");
3154 /* Make sure we are in proper schema */
3155 selectSourceSchema(fout, "pg_catalog");
3157 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3158 if (fout->remoteVersion >= 90600)
3160 PQExpBuffer acl_subquery = createPQExpBuffer();
3161 PQExpBuffer racl_subquery = createPQExpBuffer();
3162 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3163 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3165 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3166 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3167 dopt->binary_upgrade);
3169 appendPQExpBuffer(blobQry,
3170 "SELECT l.oid, (%s l.lomowner) AS rolname, "
3173 "%s AS initlomacl, "
3174 "%s AS initrlomacl "
3175 "FROM pg_largeobject_metadata l "
3176 "LEFT JOIN pg_init_privs pip ON "
3177 "(l.oid = pip.objoid "
3178 "AND pip.classoid = 'pg_largeobject'::regclass "
3179 "AND pip.objsubid = 0) ",
3182 racl_subquery->data,
3183 init_acl_subquery->data,
3184 init_racl_subquery->data);
3186 destroyPQExpBuffer(acl_subquery);
3187 destroyPQExpBuffer(racl_subquery);
3188 destroyPQExpBuffer(init_acl_subquery);
3189 destroyPQExpBuffer(init_racl_subquery);
3191 else if (fout->remoteVersion >= 90000)
3192 appendPQExpBuffer(blobQry,
3193 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3194 "NULL AS rlomacl, NULL AS initlomacl, "
3195 "NULL AS initrlomacl "
3196 " FROM pg_largeobject_metadata",
3199 appendPQExpBufferStr(blobQry,
3200 "SELECT DISTINCT loid AS oid, "
3201 "NULL::name AS rolname, NULL::oid AS lomacl, "
3202 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3203 "NULL::oid AS initrlomacl "
3204 " FROM pg_largeobject");
3206 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3208 i_oid = PQfnumber(res, "oid");
3209 i_lomowner = PQfnumber(res, "rolname");
3210 i_lomacl = PQfnumber(res, "lomacl");
3211 i_rlomacl = PQfnumber(res, "rlomacl");
3212 i_initlomacl = PQfnumber(res, "initlomacl");
3213 i_initrlomacl = PQfnumber(res, "initrlomacl");
3215 ntups = PQntuples(res);
3218 * Each large object has its own BLOB archive entry.
3220 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3222 for (i = 0; i < ntups; i++)
3224 binfo[i].dobj.objType = DO_BLOB;
3225 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3226 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3227 AssignDumpId(&binfo[i].dobj);
3229 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3230 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3231 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3232 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3233 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3234 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3236 if (PQgetisnull(res, i, i_lomacl) &&
3237 PQgetisnull(res, i, i_rlomacl) &&
3238 PQgetisnull(res, i, i_initlomacl) &&
3239 PQgetisnull(res, i, i_initrlomacl))
3240 binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3243 * In binary-upgrade mode for blobs, we do *not* dump out the data or
3244 * the ACLs, should any exist. The data and ACL (if any) will be
3245 * copied by pg_upgrade, which simply copies the pg_largeobject and
3246 * pg_largeobject_metadata tables.
3248 * We *do* dump out the definition of the blob because we need that to
3249 * make the restoration of the comments, and anything else, work since
3250 * pg_upgrade copies the files behind pg_largeobject and
3251 * pg_largeobject_metadata after the dump is restored.
3253 if (dopt->binary_upgrade)
3254 binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3258 * If we have any large objects, a "BLOBS" archive entry is needed. This
3259 * is just a placeholder for sorting; it carries no data now.
3263 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3264 bdata->objType = DO_BLOB_DATA;
3265 bdata->catId = nilCatalogId;
3266 AssignDumpId(bdata);
3267 bdata->name = pg_strdup("BLOBS");
3271 destroyPQExpBuffer(blobQry);
3277 * dump the definition (metadata) of the given large object
3280 dumpBlob(Archive *fout, BlobInfo *binfo)
3282 PQExpBuffer cquery = createPQExpBuffer();
3283 PQExpBuffer dquery = createPQExpBuffer();
3285 appendPQExpBuffer(cquery,
3286 "SELECT pg_catalog.lo_create('%s');\n",
3289 appendPQExpBuffer(dquery,
3290 "SELECT pg_catalog.lo_unlink('%s');\n",
3293 if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3294 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3297 binfo->rolname, false,
3298 "BLOB", SECTION_PRE_DATA,
3299 cquery->data, dquery->data, NULL,
3303 /* set up tag for comment and/or ACL */
3304 resetPQExpBuffer(cquery);
3305 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
3307 /* Dump comment if any */
3308 if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3309 dumpComment(fout, cquery->data,
3310 NULL, binfo->rolname,
3311 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3313 /* Dump security label if any */
3314 if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3315 dumpSecLabel(fout, cquery->data,
3316 NULL, binfo->rolname,
3317 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3319 /* Dump ACL if any */
3320 if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3321 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3322 binfo->dobj.name, NULL, cquery->data,
3323 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3324 binfo->initblobacl, binfo->initrblobacl);
3326 destroyPQExpBuffer(cquery);
3327 destroyPQExpBuffer(dquery);
3332 * dump the data contents of all large objects
3335 dumpBlobs(Archive *fout, void *arg)
3337 const char *blobQry;
3338 const char *blobFetchQry;
3339 PGconn *conn = GetConnection(fout);
3341 char buf[LOBBUFSIZE];
3347 write_msg(NULL, "saving large objects\n");
3349 /* Make sure we are in proper schema */
3350 selectSourceSchema(fout, "pg_catalog");
3353 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3354 * the already-in-memory dumpable objects instead...
3356 if (fout->remoteVersion >= 90000)
3357 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3359 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3361 ExecuteSqlStatement(fout, blobQry);
3363 /* Command to fetch from cursor */
3364 blobFetchQry = "FETCH 1000 IN bloboid";
3369 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3371 /* Process the tuples, if any */
3372 ntups = PQntuples(res);
3373 for (i = 0; i < ntups; i++)
3378 blobOid = atooid(PQgetvalue(res, i, 0));
3380 loFd = lo_open(conn, blobOid, INV_READ);
3382 exit_horribly(NULL, "could not open large object %u: %s",
3383 blobOid, PQerrorMessage(conn));
3385 StartBlob(fout, blobOid);
3387 /* Now read it in chunks, sending data to archive */
3390 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3392 exit_horribly(NULL, "error reading large object %u: %s",
3393 blobOid, PQerrorMessage(conn));
3395 WriteData(fout, buf, cnt);
3398 lo_close(conn, loFd);
3400 EndBlob(fout, blobOid);
3404 } while (ntups > 0);
3411 * get information about policies on a dumpable table.
3414 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3418 PolicyInfo *polinfo;
3423 int i_polpermissive;
3431 if (fout->remoteVersion < 90500)
3434 query = createPQExpBuffer();
3436 for (i = 0; i < numTables; i++)
3438 TableInfo *tbinfo = &tblinfo[i];
3440 /* Ignore row security on tables not to be dumped */
3441 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3445 write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3446 tbinfo->dobj.namespace->dobj.name,
3450 * Get row security enabled information for the table. We represent
3451 * RLS enabled on a table by creating PolicyInfo object with an empty
3457 * Note: use tableoid 0 so that this object won't be mistaken for
3458 * something that pg_depend entries apply to.
3460 polinfo = pg_malloc(sizeof(PolicyInfo));
3461 polinfo->dobj.objType = DO_POLICY;
3462 polinfo->dobj.catId.tableoid = 0;
3463 polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3464 AssignDumpId(&polinfo->dobj);
3465 polinfo->dobj.namespace = tbinfo->dobj.namespace;
3466 polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3467 polinfo->poltable = tbinfo;
3468 polinfo->polname = NULL;
3469 polinfo->polcmd = '\0';
3470 polinfo->polpermissive = 0;
3471 polinfo->polroles = NULL;
3472 polinfo->polqual = NULL;
3473 polinfo->polwithcheck = NULL;
3477 write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3478 tbinfo->dobj.namespace->dobj.name,
3482 * select table schema to ensure regproc name is qualified if needed
3484 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
3486 resetPQExpBuffer(query);
3488 /* Get the policies for the table. */
3489 if (fout->remoteVersion >= 100000)
3490 appendPQExpBuffer(query,
3491 "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3492 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3493 " 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, "
3494 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3495 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3496 "FROM pg_catalog.pg_policy pol "
3497 "WHERE polrelid = '%u'",
3498 tbinfo->dobj.catId.oid);
3500 appendPQExpBuffer(query,
3501 "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3502 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3503 " 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, "
3504 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3505 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3506 "FROM pg_catalog.pg_policy pol "
3507 "WHERE polrelid = '%u'",
3508 tbinfo->dobj.catId.oid);
3509 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3511 ntups = PQntuples(res);
3516 * No explicit policies to handle (only the default-deny policy,
3517 * which is handled as part of the table definition). Clean up
3524 i_oid = PQfnumber(res, "oid");
3525 i_tableoid = PQfnumber(res, "tableoid");
3526 i_polname = PQfnumber(res, "polname");
3527 i_polcmd = PQfnumber(res, "polcmd");
3528 i_polpermissive = PQfnumber(res, "polpermissive");
3529 i_polroles = PQfnumber(res, "polroles");
3530 i_polqual = PQfnumber(res, "polqual");
3531 i_polwithcheck = PQfnumber(res, "polwithcheck");
3533 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3535 for (j = 0; j < ntups; j++)
3537 polinfo[j].dobj.objType = DO_POLICY;
3538 polinfo[j].dobj.catId.tableoid =
3539 atooid(PQgetvalue(res, j, i_tableoid));
3540 polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3541 AssignDumpId(&polinfo[j].dobj);
3542 polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3543 polinfo[j].poltable = tbinfo;
3544 polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3545 polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3547 polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3548 polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3550 if (PQgetisnull(res, j, i_polroles))
3551 polinfo[j].polroles = NULL;
3553 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3555 if (PQgetisnull(res, j, i_polqual))
3556 polinfo[j].polqual = NULL;
3558 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3560 if (PQgetisnull(res, j, i_polwithcheck))
3561 polinfo[j].polwithcheck = NULL;
3563 polinfo[j].polwithcheck
3564 = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3568 destroyPQExpBuffer(query);
3573 * dump the definition of the given policy
3576 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3578 DumpOptions *dopt = fout->dopt;
3579 TableInfo *tbinfo = polinfo->poltable;
3589 * If polname is NULL, then this record is just indicating that ROW LEVEL
3590 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3591 * ROW LEVEL SECURITY.
3593 if (polinfo->polname == NULL)
3595 query = createPQExpBuffer();
3597 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3598 fmtId(polinfo->dobj.name));
3600 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3601 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3603 polinfo->dobj.namespace->dobj.name,
3605 tbinfo->rolname, false,
3606 "ROW SECURITY", SECTION_POST_DATA,
3607 query->data, "", NULL,
3611 destroyPQExpBuffer(query);
3615 if (polinfo->polcmd == '*')
3617 else if (polinfo->polcmd == 'r')
3618 cmd = " FOR SELECT";
3619 else if (polinfo->polcmd == 'a')
3620 cmd = " FOR INSERT";
3621 else if (polinfo->polcmd == 'w')
3622 cmd = " FOR UPDATE";
3623 else if (polinfo->polcmd == 'd')
3624 cmd = " FOR DELETE";
3627 write_msg(NULL, "unexpected policy command type: %c\n",
3632 query = createPQExpBuffer();
3633 delqry = createPQExpBuffer();
3635 appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3637 appendPQExpBuffer(query, " ON %s%s%s", fmtId(tbinfo->dobj.name),
3638 !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3640 if (polinfo->polroles != NULL)
3641 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3643 if (polinfo->polqual != NULL)
3644 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3646 if (polinfo->polwithcheck != NULL)
3647 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3649 appendPQExpBuffer(query, ";\n");
3651 appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3652 appendPQExpBuffer(delqry, " ON %s;\n", fmtId(tbinfo->dobj.name));
3654 tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3656 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3657 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3659 polinfo->dobj.namespace->dobj.name,
3661 tbinfo->rolname, false,
3662 "POLICY", SECTION_POST_DATA,
3663 query->data, delqry->data, NULL,
3668 destroyPQExpBuffer(query);
3669 destroyPQExpBuffer(delqry);
3674 * get information about publications
3677 getPublications(Archive *fout)
3679 DumpOptions *dopt = fout->dopt;
3682 PublicationInfo *pubinfo;
3694 if (dopt->no_publications || fout->remoteVersion < 100000)
3697 query = createPQExpBuffer();
3699 resetPQExpBuffer(query);
3701 /* Make sure we are in proper schema */
3702 selectSourceSchema(fout, "pg_catalog");
3704 /* Get the publications. */
3705 appendPQExpBuffer(query,
3706 "SELECT p.tableoid, p.oid, p.pubname, "
3707 "(%s p.pubowner) AS rolname, "
3708 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete "
3709 "FROM pg_publication p",
3712 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3714 ntups = PQntuples(res);
3716 i_tableoid = PQfnumber(res, "tableoid");
3717 i_oid = PQfnumber(res, "oid");
3718 i_pubname = PQfnumber(res, "pubname");
3719 i_rolname = PQfnumber(res, "rolname");
3720 i_puballtables = PQfnumber(res, "puballtables");
3721 i_pubinsert = PQfnumber(res, "pubinsert");
3722 i_pubupdate = PQfnumber(res, "pubupdate");
3723 i_pubdelete = PQfnumber(res, "pubdelete");
3725 pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3727 for (i = 0; i < ntups; i++)
3729 pubinfo[i].dobj.objType = DO_PUBLICATION;
3730 pubinfo[i].dobj.catId.tableoid =
3731 atooid(PQgetvalue(res, i, i_tableoid));
3732 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3733 AssignDumpId(&pubinfo[i].dobj);
3734 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3735 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3736 pubinfo[i].puballtables =
3737 (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3738 pubinfo[i].pubinsert =
3739 (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3740 pubinfo[i].pubupdate =
3741 (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3742 pubinfo[i].pubdelete =
3743 (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3745 if (strlen(pubinfo[i].rolname) == 0)
3746 write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3747 pubinfo[i].dobj.name);
3749 /* Decide whether we want to dump it */
3750 selectDumpableObject(&(pubinfo[i].dobj), fout);
3754 destroyPQExpBuffer(query);
3759 * dump the definition of the given publication
3762 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3769 if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3772 delq = createPQExpBuffer();
3773 query = createPQExpBuffer();
3774 labelq = createPQExpBuffer();
3776 appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3777 fmtId(pubinfo->dobj.name));
3779 appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3780 fmtId(pubinfo->dobj.name));
3782 appendPQExpBuffer(labelq, "PUBLICATION %s", fmtId(pubinfo->dobj.name));
3784 if (pubinfo->puballtables)
3785 appendPQExpBufferStr(query, " FOR ALL TABLES");
3787 appendPQExpBufferStr(query, " WITH (publish = '");
3788 if (pubinfo->pubinsert)
3790 appendPQExpBufferStr(query, "insert");
3794 if (pubinfo->pubupdate)
3797 appendPQExpBufferStr(query, ", ");
3799 appendPQExpBufferStr(query, "update");
3803 if (pubinfo->pubdelete)
3806 appendPQExpBufferStr(query, ", ");
3808 appendPQExpBufferStr(query, "delete");
3812 appendPQExpBufferStr(query, "');\n");
3814 ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3818 pubinfo->rolname, false,
3819 "PUBLICATION", SECTION_POST_DATA,
3820 query->data, delq->data, NULL,
3824 if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3825 dumpComment(fout, labelq->data,
3826 NULL, pubinfo->rolname,
3827 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3829 if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3830 dumpSecLabel(fout, labelq->data,
3831 NULL, pubinfo->rolname,
3832 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3834 destroyPQExpBuffer(delq);
3835 destroyPQExpBuffer(query);
3839 * getPublicationTables
3840 * get information about publication membership for dumpable tables.
3843 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3847 PublicationRelInfo *pubrinfo;
3855 if (fout->remoteVersion < 100000)
3858 query = createPQExpBuffer();
3860 /* Make sure we are in proper schema */
3861 selectSourceSchema(fout, "pg_catalog");
3863 for (i = 0; i < numTables; i++)
3865 TableInfo *tbinfo = &tblinfo[i];
3867 /* Only plain tables can be aded to publications. */
3868 if (tbinfo->relkind != RELKIND_RELATION)
3872 * Ignore publication membership of tables whose definitions are not
3875 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3879 write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3880 tbinfo->dobj.namespace->dobj.name,
3883 resetPQExpBuffer(query);
3885 /* Get the publication membership for the table. */
3886 appendPQExpBuffer(query,
3887 "SELECT pr.tableoid, pr.oid, p.pubname "
3888 "FROM pg_publication_rel pr, pg_publication p "
3889 "WHERE pr.prrelid = '%u'"
3890 " AND p.oid = pr.prpubid",
3891 tbinfo->dobj.catId.oid);
3892 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3894 ntups = PQntuples(res);
3899 * Table is not member of any publications. Clean up and return.
3905 i_tableoid = PQfnumber(res, "tableoid");
3906 i_oid = PQfnumber(res, "oid");
3907 i_pubname = PQfnumber(res, "pubname");
3909 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3911 for (j = 0; j < ntups; j++)
3913 pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3914 pubrinfo[j].dobj.catId.tableoid =
3915 atooid(PQgetvalue(res, j, i_tableoid));
3916 pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3917 AssignDumpId(&pubrinfo[j].dobj);
3918 pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3919 pubrinfo[j].dobj.name = tbinfo->dobj.name;
3920 pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3921 pubrinfo[j].pubtable = tbinfo;
3923 /* Decide whether we want to dump it */
3924 selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3928 destroyPQExpBuffer(query);
3932 * dumpPublicationTable
3933 * dump the definition of the given publication table mapping
3936 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3938 TableInfo *tbinfo = pubrinfo->pubtable;
3942 if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3945 tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3947 query = createPQExpBuffer();
3949 appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3950 fmtId(pubrinfo->pubname));
3951 appendPQExpBuffer(query, " %s;",
3952 fmtId(tbinfo->dobj.name));
3955 * There is no point in creating drop query as drop query as the drop is
3956 * done by table drop.
3958 ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3960 tbinfo->dobj.namespace->dobj.name,
3963 "PUBLICATION TABLE", SECTION_POST_DATA,
3964 query->data, "", NULL,
3969 destroyPQExpBuffer(query);
3973 * Is the currently connected user a superuser?
3976 is_superuser(Archive *fout)
3978 ArchiveHandle *AH = (ArchiveHandle *) fout;
3981 val = PQparameterStatus(AH->connection, "is_superuser");
3983 if (val && strcmp(val, "on") == 0)
3991 * get information about subscriptions
3994 getSubscriptions(Archive *fout)
3996 DumpOptions *dopt = fout->dopt;
3999 SubscriptionInfo *subinfo;
4006 int i_subsynccommit;
4007 int i_subpublications;
4011 if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4014 /* Make sure we are in proper schema */
4015 selectSourceSchema(fout, "pg_catalog");
4017 if (!is_superuser(fout))
4021 res = ExecuteSqlQuery(fout,
4022 "SELECT count(*) FROM pg_subscription "
4023 "WHERE subdbid = (SELECT oid FROM pg_database"
4024 " WHERE datname = current_database())",
4026 n = atoi(PQgetvalue(res, 0, 0));
4028 write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4033 query = createPQExpBuffer();
4035 resetPQExpBuffer(query);
4037 /* Get the subscriptions in current database. */
4038 appendPQExpBuffer(query,
4039 "SELECT s.tableoid, s.oid, s.subname,"
4040 "(%s s.subowner) AS rolname, "
4041 " s.subconninfo, s.subslotname, s.subsynccommit, "
4042 " s.subpublications "
4043 "FROM pg_subscription s "
4044 "WHERE s.subdbid = (SELECT oid FROM pg_database"
4045 " WHERE datname = current_database())",
4047 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4049 ntups = PQntuples(res);
4051 i_tableoid = PQfnumber(res, "tableoid");
4052 i_oid = PQfnumber(res, "oid");
4053 i_subname = PQfnumber(res, "subname");
4054 i_rolname = PQfnumber(res, "rolname");
4055 i_subconninfo = PQfnumber(res, "subconninfo");
4056 i_subslotname = PQfnumber(res, "subslotname");
4057 i_subsynccommit = PQfnumber(res, "subsynccommit");
4058 i_subpublications = PQfnumber(res, "subpublications");
4060 subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4062 for (i = 0; i < ntups; i++)
4064 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4065 subinfo[i].dobj.catId.tableoid =
4066 atooid(PQgetvalue(res, i, i_tableoid));
4067 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4068 AssignDumpId(&subinfo[i].dobj);
4069 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4070 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4071 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4072 if (PQgetisnull(res, i, i_subslotname))
4073 subinfo[i].subslotname = NULL;
4075 subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4076 subinfo[i].subsynccommit =
4077 pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4078 subinfo[i].subpublications =
4079 pg_strdup(PQgetvalue(res, i, i_subpublications));
4081 if (strlen(subinfo[i].rolname) == 0)
4082 write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4083 subinfo[i].dobj.name);
4085 /* Decide whether we want to dump it */
4086 selectDumpableObject(&(subinfo[i].dobj), fout);
4090 destroyPQExpBuffer(query);
4095 * dump the definition of the given subscription
4098 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4103 PQExpBuffer publications;
4104 char **pubnames = NULL;
4108 if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4111 delq = createPQExpBuffer();
4112 query = createPQExpBuffer();
4113 labelq = createPQExpBuffer();
4115 appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4116 fmtId(subinfo->dobj.name));
4118 appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4119 fmtId(subinfo->dobj.name));
4120 appendStringLiteralAH(query, subinfo->subconninfo, fout);
4122 /* Build list of quoted publications and append them to query. */
4123 if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4126 "WARNING: could not parse subpublications array\n");
4133 publications = createPQExpBuffer();
4134 for (i = 0; i < npubnames; i++)
4137 appendPQExpBufferStr(publications, ", ");
4139 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4142 appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4143 if (subinfo->subslotname)
4144 appendStringLiteralAH(query, subinfo->subslotname, fout);
4146 appendPQExpBufferStr(query, "NONE");
4148 if (strcmp(subinfo->subsynccommit, "off") != 0)
4149 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4151 appendPQExpBufferStr(query, ");\n");
4153 appendPQExpBuffer(labelq, "SUBSCRIPTION %s", fmtId(subinfo->dobj.name));
4155 ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4159 subinfo->rolname, false,
4160 "SUBSCRIPTION", SECTION_POST_DATA,
4161 query->data, delq->data, NULL,
4165 if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4166 dumpComment(fout, labelq->data,
4167 NULL, subinfo->rolname,
4168 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4170 if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4171 dumpSecLabel(fout, labelq->data,
4172 NULL, subinfo->rolname,
4173 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4175 destroyPQExpBuffer(publications);
4179 destroyPQExpBuffer(delq);
4180 destroyPQExpBuffer(query);
4184 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4185 PQExpBuffer upgrade_buffer,
4187 bool force_array_type)
4189 PQExpBuffer upgrade_query = createPQExpBuffer();
4191 Oid pg_type_array_oid;
4193 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4194 appendPQExpBuffer(upgrade_buffer,
4195 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4198 /* we only support old >= 8.3 for binary upgrades */
4199 appendPQExpBuffer(upgrade_query,
4201 "FROM pg_catalog.pg_type "
4202 "WHERE oid = '%u'::pg_catalog.oid;",
4205 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4207 pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4211 if (!OidIsValid(pg_type_array_oid) && force_array_type)
4214 * If the old version didn't assign an array type, but the new version
4215 * does, we must select an unused type OID to assign. This currently
4216 * only happens for domains, when upgrading pre-v11 to v11 and up.
4218 * Note: local state here is kind of ugly, but we must have some,
4219 * since we mustn't choose the same unused OID more than once.
4221 static Oid next_possible_free_oid = FirstNormalObjectId;
4226 ++next_possible_free_oid;
4227 printfPQExpBuffer(upgrade_query,
4228 "SELECT EXISTS(SELECT 1 "
4229 "FROM pg_catalog.pg_type "
4230 "WHERE oid = '%u'::pg_catalog.oid);",
4231 next_possible_free_oid);
4232 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4233 is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4237 pg_type_array_oid = next_possible_free_oid;
4240 if (OidIsValid(pg_type_array_oid))
4242 appendPQExpBufferStr(upgrade_buffer,
4243 "\n-- For binary upgrade, must preserve pg_type array oid\n");
4244 appendPQExpBuffer(upgrade_buffer,
4245 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4249 destroyPQExpBuffer(upgrade_query);
4253 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4254 PQExpBuffer upgrade_buffer,
4257 PQExpBuffer upgrade_query = createPQExpBuffer();
4258 PGresult *upgrade_res;
4260 bool toast_set = false;
4262 /* we only support old >= 8.3 for binary upgrades */
4263 appendPQExpBuffer(upgrade_query,
4264 "SELECT c.reltype AS crel, t.reltype AS trel "
4265 "FROM pg_catalog.pg_class c "
4266 "LEFT JOIN pg_catalog.pg_class t ON "
4267 " (c.reltoastrelid = t.oid) "
4268 "WHERE c.oid = '%u'::pg_catalog.oid;",
4271 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4273 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4275 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4276 pg_type_oid, false);
4278 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4280 /* Toast tables do not have pg_type array rows */
4281 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4282 PQfnumber(upgrade_res, "trel")));
4284 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4285 appendPQExpBuffer(upgrade_buffer,
4286 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4292 PQclear(upgrade_res);
4293 destroyPQExpBuffer(upgrade_query);
4299 binary_upgrade_set_pg_class_oids(Archive *fout,
4300 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4303 PQExpBuffer upgrade_query = createPQExpBuffer();
4304 PGresult *upgrade_res;
4305 Oid pg_class_reltoastrelid;
4306 Oid pg_index_indexrelid;
4308 appendPQExpBuffer(upgrade_query,
4309 "SELECT c.reltoastrelid, i.indexrelid "
4310 "FROM pg_catalog.pg_class c LEFT JOIN "
4311 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4312 "WHERE c.oid = '%u'::pg_catalog.oid;",
4315 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4317 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4318 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4320 appendPQExpBufferStr(upgrade_buffer,
4321 "\n-- For binary upgrade, must preserve pg_class oids\n");
4325 appendPQExpBuffer(upgrade_buffer,
4326 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4328 /* only tables have toast tables, not indexes */
4329 if (OidIsValid(pg_class_reltoastrelid))
4332 * One complexity is that the table definition might not require
4333 * the creation of a TOAST table, and the TOAST table might have
4334 * been created long after table creation, when the table was
4335 * loaded with wide data. By setting the TOAST oid we force
4336 * creation of the TOAST heap and TOAST index by the backend so we
4337 * can cleanly copy the files during binary upgrade.
4340 appendPQExpBuffer(upgrade_buffer,
4341 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4342 pg_class_reltoastrelid);
4344 /* every toast table has an index */
4345 appendPQExpBuffer(upgrade_buffer,
4346 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4347 pg_index_indexrelid);
4351 appendPQExpBuffer(upgrade_buffer,
4352 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4355 appendPQExpBufferChar(upgrade_buffer, '\n');
4357 PQclear(upgrade_res);
4358 destroyPQExpBuffer(upgrade_query);
4362 * If the DumpableObject is a member of an extension, add a suitable
4363 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4366 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4367 DumpableObject *dobj,
4368 const char *objlabel)
4370 DumpableObject *extobj = NULL;
4373 if (!dobj->ext_member)
4377 * Find the parent extension. We could avoid this search if we wanted to
4378 * add a link field to DumpableObject, but the space costs of that would
4379 * be considerable. We assume that member objects could only have a
4380 * direct dependency on their own extension, not any others.
4382 for (i = 0; i < dobj->nDeps; i++)
4384 extobj = findObjectByDumpId(dobj->dependencies[i]);
4385 if (extobj && extobj->objType == DO_EXTENSION)
4390 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
4392 appendPQExpBufferStr(upgrade_buffer,
4393 "\n-- For binary upgrade, handle extension membership the hard way\n");
4394 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
4395 fmtId(extobj->name),
4401 * read all namespaces in the system catalogs and return them in the
4402 * NamespaceInfo* structure
4404 * numNamespaces is set to the number of namespaces read in
4407 getNamespaces(Archive *fout, int *numNamespaces)
4409 DumpOptions *dopt = fout->dopt;
4414 NamespaceInfo *nsinfo;
4424 query = createPQExpBuffer();
4426 /* Make sure we are in proper schema */
4427 selectSourceSchema(fout, "pg_catalog");
4430 * we fetch all namespaces including system ones, so that every object we
4431 * read in can be linked to a containing namespace.
4433 if (fout->remoteVersion >= 90600)
4435 PQExpBuffer acl_subquery = createPQExpBuffer();
4436 PQExpBuffer racl_subquery = createPQExpBuffer();
4437 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4438 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4440 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4441 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4442 dopt->binary_upgrade);
4444 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4445 "(%s nspowner) AS rolname, "
4448 "%s as initnspacl, "
4449 "%s as initrnspacl "
4450 "FROM pg_namespace n "
4451 "LEFT JOIN pg_init_privs pip "
4452 "ON (n.oid = pip.objoid "
4453 "AND pip.classoid = 'pg_namespace'::regclass "
4454 "AND pip.objsubid = 0",
4457 racl_subquery->data,
4458 init_acl_subquery->data,
4459 init_racl_subquery->data);
4461 appendPQExpBuffer(query, ") ");
4463 destroyPQExpBuffer(acl_subquery);
4464 destroyPQExpBuffer(racl_subquery);
4465 destroyPQExpBuffer(init_acl_subquery);
4466 destroyPQExpBuffer(init_racl_subquery);
4469 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4470 "(%s nspowner) AS rolname, "
4471 "nspacl, NULL as rnspacl, "
4472 "NULL AS initnspacl, NULL as initrnspacl "
4473 "FROM pg_namespace",
4476 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4478 ntups = PQntuples(res);
4480 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4482 i_tableoid = PQfnumber(res, "tableoid");
4483 i_oid = PQfnumber(res, "oid");
4484 i_nspname = PQfnumber(res, "nspname");
4485 i_rolname = PQfnumber(res, "rolname");
4486 i_nspacl = PQfnumber(res, "nspacl");
4487 i_rnspacl = PQfnumber(res, "rnspacl");
4488 i_initnspacl = PQfnumber(res, "initnspacl");
4489 i_initrnspacl = PQfnumber(res, "initrnspacl");
4491 for (i = 0; i < ntups; i++)
4493 nsinfo[i].dobj.objType = DO_NAMESPACE;
4494 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4495 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4496 AssignDumpId(&nsinfo[i].dobj);
4497 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4498 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4499 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4500 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4501 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4502 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4504 /* Decide whether to dump this namespace */
4505 selectDumpableNamespace(&nsinfo[i], fout);
4508 * Do not try to dump ACL if the ACL is empty or the default.
4510 * This is useful because, for some schemas/objects, the only
4511 * component we are going to try and dump is the ACL and if we can
4512 * remove that then 'dump' goes to zero/false and we don't consider
4513 * this object for dumping at all later on.
4515 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4516 PQgetisnull(res, i, i_initnspacl) &&
4517 PQgetisnull(res, i, i_initrnspacl))
4518 nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4520 if (strlen(nsinfo[i].rolname) == 0)
4521 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4522 nsinfo[i].dobj.name);
4526 destroyPQExpBuffer(query);
4528 *numNamespaces = ntups;
4535 * given a namespace OID, look up the info read by getNamespaces
4537 static NamespaceInfo *
4538 findNamespace(Archive *fout, Oid nsoid)
4540 NamespaceInfo *nsinfo;
4542 nsinfo = findNamespaceByOid(nsoid);
4544 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4550 * read all extensions in the system catalogs and return them in the
4551 * ExtensionInfo* structure
4553 * numExtensions is set to the number of extensions read in
4556 getExtensions(Archive *fout, int *numExtensions)
4558 DumpOptions *dopt = fout->dopt;
4563 ExtensionInfo *extinfo;
4568 int i_extrelocatable;
4574 * Before 9.1, there are no extensions.
4576 if (fout->remoteVersion < 90100)
4582 query = createPQExpBuffer();
4584 /* Make sure we are in proper schema */
4585 selectSourceSchema(fout, "pg_catalog");
4587 appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4588 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4589 "FROM pg_extension x "
4590 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4592 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4594 ntups = PQntuples(res);
4596 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4598 i_tableoid = PQfnumber(res, "tableoid");
4599 i_oid = PQfnumber(res, "oid");
4600 i_extname = PQfnumber(res, "extname");
4601 i_nspname = PQfnumber(res, "nspname");
4602 i_extrelocatable = PQfnumber(res, "extrelocatable");
4603 i_extversion = PQfnumber(res, "extversion");
4604 i_extconfig = PQfnumber(res, "extconfig");
4605 i_extcondition = PQfnumber(res, "extcondition");
4607 for (i = 0; i < ntups; i++)
4609 extinfo[i].dobj.objType = DO_EXTENSION;
4610 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4611 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4612 AssignDumpId(&extinfo[i].dobj);
4613 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4614 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4615 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4616 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4617 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4618 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4620 /* Decide whether we want to dump it */
4621 selectDumpableExtension(&(extinfo[i]), dopt);
4625 destroyPQExpBuffer(query);
4627 *numExtensions = ntups;
4634 * read all types in the system catalogs and return them in the
4635 * TypeInfo* structure
4637 * numTypes is set to the number of types read in
4639 * NB: this must run after getFuncs() because we assume we can do
4643 getTypes(Archive *fout, int *numTypes)
4645 DumpOptions *dopt = fout->dopt;
4649 PQExpBuffer query = createPQExpBuffer();
4651 ShellTypeInfo *stinfo;
4669 * we include even the built-in types because those may be used as array
4670 * elements by user-defined types
4672 * we filter out the built-in types when we dump out the types
4674 * same approach for undefined (shell) types and array types
4676 * Note: as of 8.3 we can reliably detect whether a type is an
4677 * auto-generated array type by checking the element type's typarray.
4678 * (Before that the test is capable of generating false positives.) We
4679 * still check for name beginning with '_', though, so as to avoid the
4680 * cost of the subselect probe for all standard types. This would have to
4681 * be revisited if the backend ever allows renaming of array types.
4684 /* Make sure we are in proper schema */
4685 selectSourceSchema(fout, "pg_catalog");
4687 if (fout->remoteVersion >= 90600)
4689 PQExpBuffer acl_subquery = createPQExpBuffer();
4690 PQExpBuffer racl_subquery = createPQExpBuffer();
4691 PQExpBuffer initacl_subquery = createPQExpBuffer();
4692 PQExpBuffer initracl_subquery = createPQExpBuffer();
4694 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4695 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4696 dopt->binary_upgrade);
4698 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4702 "%s AS inittypacl, "
4703 "%s AS initrtypacl, "
4704 "(%s t.typowner) AS rolname, "
4705 "t.typelem, t.typrelid, "
4706 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4707 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4708 "t.typtype, t.typisdefined, "
4709 "t.typname[0] = '_' AND t.typelem != 0 AND "
4710 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4712 "LEFT JOIN pg_init_privs pip ON "
4713 "(t.oid = pip.objoid "
4714 "AND pip.classoid = 'pg_type'::regclass "
4715 "AND pip.objsubid = 0) ",
4717 racl_subquery->data,
4718 initacl_subquery->data,
4719 initracl_subquery->data,
4722 destroyPQExpBuffer(acl_subquery);
4723 destroyPQExpBuffer(racl_subquery);
4724 destroyPQExpBuffer(initacl_subquery);
4725 destroyPQExpBuffer(initracl_subquery);
4727 else if (fout->remoteVersion >= 90200)
4729 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4730 "typnamespace, typacl, NULL as rtypacl, "
4731 "NULL AS inittypacl, NULL AS initrtypacl, "
4732 "(%s typowner) AS rolname, "
4733 "typelem, typrelid, "
4734 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4735 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4736 "typtype, typisdefined, "
4737 "typname[0] = '_' AND typelem != 0 AND "
4738 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4742 else if (fout->remoteVersion >= 80300)
4744 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4745 "typnamespace, NULL AS 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 "
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 AS isarray "
4772 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4774 ntups = PQntuples(res);
4776 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4778 i_tableoid = PQfnumber(res, "tableoid");
4779 i_oid = PQfnumber(res, "oid");
4780 i_typname = PQfnumber(res, "typname");
4781 i_typnamespace = PQfnumber(res, "typnamespace");
4782 i_typacl = PQfnumber(res, "typacl");
4783 i_rtypacl = PQfnumber(res, "rtypacl");
4784 i_inittypacl = PQfnumber(res, "inittypacl");
4785 i_initrtypacl = PQfnumber(res, "initrtypacl");
4786 i_rolname = PQfnumber(res, "rolname");
4787 i_typelem = PQfnumber(res, "typelem");
4788 i_typrelid = PQfnumber(res, "typrelid");
4789 i_typrelkind = PQfnumber(res, "typrelkind");
4790 i_typtype = PQfnumber(res, "typtype");
4791 i_typisdefined = PQfnumber(res, "typisdefined");
4792 i_isarray = PQfnumber(res, "isarray");
4794 for (i = 0; i < ntups; i++)
4796 tyinfo[i].dobj.objType = DO_TYPE;
4797 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4798 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4799 AssignDumpId(&tyinfo[i].dobj);
4800 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4801 tyinfo[i].dobj.namespace =
4803 atooid(PQgetvalue(res, i, i_typnamespace)));
4804 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4805 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4806 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4807 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4808 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4809 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4810 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4811 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4812 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4813 tyinfo[i].shellType = NULL;
4815 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4816 tyinfo[i].isDefined = true;
4818 tyinfo[i].isDefined = false;
4820 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4821 tyinfo[i].isArray = true;
4823 tyinfo[i].isArray = false;
4825 /* Decide whether we want to dump it */
4826 selectDumpableType(&tyinfo[i], fout);
4828 /* Do not try to dump ACL if no ACL exists. */
4829 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4830 PQgetisnull(res, i, i_inittypacl) &&
4831 PQgetisnull(res, i, i_initrtypacl))
4832 tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4835 * If it's a domain, fetch info about its constraints, if any
4837 tyinfo[i].nDomChecks = 0;
4838 tyinfo[i].domChecks = NULL;
4839 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4840 tyinfo[i].typtype == TYPTYPE_DOMAIN)
4841 getDomainConstraints(fout, &(tyinfo[i]));
4844 * If it's a base type, make a DumpableObject representing a shell
4845 * definition of the type. We will need to dump that ahead of the I/O
4846 * functions for the type. Similarly, range types need a shell
4847 * definition in case they have a canonicalize function.
4849 * Note: the shell type doesn't have a catId. You might think it
4850 * should copy the base type's catId, but then it might capture the
4851 * pg_depend entries for the type, which we don't want.
4853 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4854 (tyinfo[i].typtype == TYPTYPE_BASE ||
4855 tyinfo[i].typtype == TYPTYPE_RANGE))
4857 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4858 stinfo->dobj.objType = DO_SHELL_TYPE;
4859 stinfo->dobj.catId = nilCatalogId;
4860 AssignDumpId(&stinfo->dobj);
4861 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4862 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4863 stinfo->baseType = &(tyinfo[i]);
4864 tyinfo[i].shellType = stinfo;
4867 * Initially mark the shell type as not to be dumped. We'll only
4868 * dump it if the I/O or canonicalize functions need to be dumped;
4869 * this is taken care of while sorting dependencies.
4871 stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4874 if (strlen(tyinfo[i].rolname) == 0)
4875 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4876 tyinfo[i].dobj.name);
4883 destroyPQExpBuffer(query);
4890 * read all operators in the system catalogs and return them in the
4891 * OprInfo* structure
4893 * numOprs is set to the number of operators read in
4896 getOperators(Archive *fout, int *numOprs)
4901 PQExpBuffer query = createPQExpBuffer();
4912 * find all operators, including builtin operators; we filter out
4913 * system-defined operators at dump-out time.
4916 /* Make sure we are in proper schema */
4917 selectSourceSchema(fout, "pg_catalog");
4919 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4921 "(%s oprowner) AS rolname, "
4923 "oprcode::oid AS oprcode "
4927 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4929 ntups = PQntuples(res);
4932 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4934 i_tableoid = PQfnumber(res, "tableoid");
4935 i_oid = PQfnumber(res, "oid");
4936 i_oprname = PQfnumber(res, "oprname");
4937 i_oprnamespace = PQfnumber(res, "oprnamespace");
4938 i_rolname = PQfnumber(res, "rolname");
4939 i_oprkind = PQfnumber(res, "oprkind");
4940 i_oprcode = PQfnumber(res, "oprcode");
4942 for (i = 0; i < ntups; i++)
4944 oprinfo[i].dobj.objType = DO_OPERATOR;
4945 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4946 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4947 AssignDumpId(&oprinfo[i].dobj);
4948 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4949 oprinfo[i].dobj.namespace =
4951 atooid(PQgetvalue(res, i, i_oprnamespace)));
4952 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4953 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4954 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4956 /* Decide whether we want to dump it */
4957 selectDumpableObject(&(oprinfo[i].dobj), fout);
4959 /* Operators do not currently have ACLs. */
4960 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4962 if (strlen(oprinfo[i].rolname) == 0)
4963 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4964 oprinfo[i].dobj.name);
4969 destroyPQExpBuffer(query);
4976 * read all collations in the system catalogs and return them in the
4977 * CollInfo* structure
4979 * numCollations is set to the number of collations read in
4982 getCollations(Archive *fout, int *numCollations)
4992 int i_collnamespace;
4995 /* Collations didn't exist pre-9.1 */
4996 if (fout->remoteVersion < 90100)
5002 query = createPQExpBuffer();
5005 * find all collations, including builtin collations; we filter out
5006 * system-defined collations at dump-out time.
5009 /* Make sure we are in proper schema */
5010 selectSourceSchema(fout, "pg_catalog");
5012 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5014 "(%s collowner) AS rolname "
5015 "FROM pg_collation",
5018 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5020 ntups = PQntuples(res);
5021 *numCollations = ntups;
5023 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5025 i_tableoid = PQfnumber(res, "tableoid");
5026 i_oid = PQfnumber(res, "oid");
5027 i_collname = PQfnumber(res, "collname");
5028 i_collnamespace = PQfnumber(res, "collnamespace");
5029 i_rolname = PQfnumber(res, "rolname");
5031 for (i = 0; i < ntups; i++)
5033 collinfo[i].dobj.objType = DO_COLLATION;
5034 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5035 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5036 AssignDumpId(&collinfo[i].dobj);
5037 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5038 collinfo[i].dobj.namespace =
5040 atooid(PQgetvalue(res, i, i_collnamespace)));
5041 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5043 /* Decide whether we want to dump it */
5044 selectDumpableObject(&(collinfo[i].dobj), fout);
5046 /* Collations do not currently have ACLs. */
5047 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5052 destroyPQExpBuffer(query);
5059 * read all conversions in the system catalogs and return them in the
5060 * ConvInfo* structure
5062 * numConversions is set to the number of conversions read in
5065 getConversions(Archive *fout, int *numConversions)
5078 query = createPQExpBuffer();
5081 * find all conversions, including builtin conversions; we filter out
5082 * system-defined conversions at dump-out time.
5085 /* Make sure we are in proper schema */
5086 selectSourceSchema(fout, "pg_catalog");
5088 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5090 "(%s conowner) AS rolname "
5091 "FROM pg_conversion",
5094 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5096 ntups = PQntuples(res);
5097 *numConversions = ntups;
5099 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5101 i_tableoid = PQfnumber(res, "tableoid");
5102 i_oid = PQfnumber(res, "oid");
5103 i_conname = PQfnumber(res, "conname");
5104 i_connamespace = PQfnumber(res, "connamespace");
5105 i_rolname = PQfnumber(res, "rolname");
5107 for (i = 0; i < ntups; i++)
5109 convinfo[i].dobj.objType = DO_CONVERSION;
5110 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5111 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5112 AssignDumpId(&convinfo[i].dobj);
5113 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5114 convinfo[i].dobj.namespace =
5116 atooid(PQgetvalue(res, i, i_connamespace)));
5117 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5119 /* Decide whether we want to dump it */
5120 selectDumpableObject(&(convinfo[i].dobj), fout);
5122 /* Conversions do not currently have ACLs. */
5123 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5128 destroyPQExpBuffer(query);
5135 * read all user-defined access methods in the system catalogs and return
5136 * them in the AccessMethodInfo* structure
5138 * numAccessMethods is set to the number of access methods read in
5141 getAccessMethods(Archive *fout, int *numAccessMethods)
5147 AccessMethodInfo *aminfo;
5154 /* Before 9.6, there are no user-defined access methods */
5155 if (fout->remoteVersion < 90600)
5157 *numAccessMethods = 0;
5161 query = createPQExpBuffer();
5163 /* Make sure we are in proper schema */
5164 selectSourceSchema(fout, "pg_catalog");
5166 /* Select all access methods from pg_am table */
5167 appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5168 "amhandler::pg_catalog.regproc AS amhandler "
5171 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5173 ntups = PQntuples(res);
5174 *numAccessMethods = ntups;
5176 aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5178 i_tableoid = PQfnumber(res, "tableoid");
5179 i_oid = PQfnumber(res, "oid");
5180 i_amname = PQfnumber(res, "amname");
5181 i_amhandler = PQfnumber(res, "amhandler");
5182 i_amtype = PQfnumber(res, "amtype");
5184 for (i = 0; i < ntups; i++)
5186 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5187 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5188 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5189 AssignDumpId(&aminfo[i].dobj);
5190 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5191 aminfo[i].dobj.namespace = NULL;
5192 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5193 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5195 /* Decide whether we want to dump it */
5196 selectDumpableAccessMethod(&(aminfo[i]), fout);
5198 /* Access methods do not currently have ACLs. */
5199 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5204 destroyPQExpBuffer(query);
5212 * read all opclasses in the system catalogs and return them in the
5213 * OpclassInfo* structure
5215 * numOpclasses is set to the number of opclasses read in
5218 getOpclasses(Archive *fout, int *numOpclasses)
5223 PQExpBuffer query = createPQExpBuffer();
5224 OpclassInfo *opcinfo;
5232 * find all opclasses, including builtin opclasses; we filter out
5233 * system-defined opclasses at dump-out time.
5236 /* Make sure we are in proper schema */
5237 selectSourceSchema(fout, "pg_catalog");
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 /* Make sure we are in proper schema */
5324 selectSourceSchema(fout, "pg_catalog");
5326 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5328 "(%s opfowner) AS rolname "
5332 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5334 ntups = PQntuples(res);
5335 *numOpfamilies = ntups;
5337 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5339 i_tableoid = PQfnumber(res, "tableoid");
5340 i_oid = PQfnumber(res, "oid");
5341 i_opfname = PQfnumber(res, "opfname");
5342 i_opfnamespace = PQfnumber(res, "opfnamespace");
5343 i_rolname = PQfnumber(res, "rolname");
5345 for (i = 0; i < ntups; i++)
5347 opfinfo[i].dobj.objType = DO_OPFAMILY;
5348 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5349 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5350 AssignDumpId(&opfinfo[i].dobj);
5351 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5352 opfinfo[i].dobj.namespace =
5354 atooid(PQgetvalue(res, i, i_opfnamespace)));
5355 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5357 /* Decide whether we want to dump it */
5358 selectDumpableObject(&(opfinfo[i].dobj), fout);
5360 /* Extensions do not currently have ACLs. */
5361 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5363 if (strlen(opfinfo[i].rolname) == 0)
5364 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5365 opfinfo[i].dobj.name);
5370 destroyPQExpBuffer(query);
5377 * read all the user-defined aggregates in the system catalogs and
5378 * return them in the AggInfo* structure
5380 * numAggs is set to the number of aggregates read in
5383 getAggregates(Archive *fout, int *numAggs)
5385 DumpOptions *dopt = fout->dopt;
5389 PQExpBuffer query = createPQExpBuffer();
5403 /* Make sure we are in proper schema */
5404 selectSourceSchema(fout, "pg_catalog");
5407 * Find all interesting aggregates. See comment in getFuncs() for the
5408 * rationale behind the filtering logic.
5410 if (fout->remoteVersion >= 90600)
5412 PQExpBuffer acl_subquery = createPQExpBuffer();
5413 PQExpBuffer racl_subquery = createPQExpBuffer();
5414 PQExpBuffer initacl_subquery = createPQExpBuffer();
5415 PQExpBuffer initracl_subquery = createPQExpBuffer();
5417 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5418 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5419 dopt->binary_upgrade);
5421 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5422 "p.proname AS aggname, "
5423 "p.pronamespace AS aggnamespace, "
5424 "p.pronargs, p.proargtypes, "
5425 "(%s p.proowner) AS rolname, "
5428 "%s AS initaggacl, "
5429 "%s AS initraggacl "
5431 "LEFT JOIN pg_init_privs pip ON "
5432 "(p.oid = pip.objoid "
5433 "AND pip.classoid = 'pg_proc'::regclass "
5434 "AND pip.objsubid = 0) "
5435 "WHERE p.proisagg AND ("
5436 "p.pronamespace != "
5437 "(SELECT oid FROM pg_namespace "
5438 "WHERE nspname = 'pg_catalog') OR "
5439 "p.proacl IS DISTINCT FROM pip.initprivs",
5442 racl_subquery->data,
5443 initacl_subquery->data,
5444 initracl_subquery->data);
5445 if (dopt->binary_upgrade)
5446 appendPQExpBufferStr(query,
5447 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5448 "classid = 'pg_proc'::regclass AND "
5449 "objid = p.oid AND "
5450 "refclassid = 'pg_extension'::regclass AND "
5452 appendPQExpBufferChar(query, ')');
5454 destroyPQExpBuffer(acl_subquery);
5455 destroyPQExpBuffer(racl_subquery);
5456 destroyPQExpBuffer(initacl_subquery);
5457 destroyPQExpBuffer(initracl_subquery);
5459 else if (fout->remoteVersion >= 80200)
5461 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5462 "pronamespace AS aggnamespace, "
5463 "pronargs, proargtypes, "
5464 "(%s proowner) AS rolname, "
5465 "proacl AS aggacl, "
5467 "NULL AS initaggacl, NULL AS initraggacl "
5469 "WHERE proisagg AND ("
5471 "(SELECT oid FROM pg_namespace "
5472 "WHERE nspname = 'pg_catalog')",
5474 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5475 appendPQExpBufferStr(query,
5476 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5477 "classid = 'pg_proc'::regclass AND "
5478 "objid = p.oid AND "
5479 "refclassid = 'pg_extension'::regclass AND "
5481 appendPQExpBufferChar(query, ')');
5485 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5486 "pronamespace AS aggnamespace, "
5487 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5489 "(%s proowner) AS rolname, "
5490 "proacl AS aggacl, "
5492 "NULL AS initaggacl, NULL AS initraggacl "
5495 "AND pronamespace != "
5496 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5500 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5502 ntups = PQntuples(res);
5505 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5507 i_tableoid = PQfnumber(res, "tableoid");
5508 i_oid = PQfnumber(res, "oid");
5509 i_aggname = PQfnumber(res, "aggname");
5510 i_aggnamespace = PQfnumber(res, "aggnamespace");
5511 i_pronargs = PQfnumber(res, "pronargs");
5512 i_proargtypes = PQfnumber(res, "proargtypes");
5513 i_rolname = PQfnumber(res, "rolname");
5514 i_aggacl = PQfnumber(res, "aggacl");
5515 i_raggacl = PQfnumber(res, "raggacl");
5516 i_initaggacl = PQfnumber(res, "initaggacl");
5517 i_initraggacl = PQfnumber(res, "initraggacl");
5519 for (i = 0; i < ntups; i++)
5521 agginfo[i].aggfn.dobj.objType = DO_AGG;
5522 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5523 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5524 AssignDumpId(&agginfo[i].aggfn.dobj);
5525 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5526 agginfo[i].aggfn.dobj.namespace =
5528 atooid(PQgetvalue(res, i, i_aggnamespace)));
5529 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5530 if (strlen(agginfo[i].aggfn.rolname) == 0)
5531 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5532 agginfo[i].aggfn.dobj.name);
5533 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5534 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
5535 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5536 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5537 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5538 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5539 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5540 if (agginfo[i].aggfn.nargs == 0)
5541 agginfo[i].aggfn.argtypes = NULL;
5544 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5545 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5546 agginfo[i].aggfn.argtypes,
5547 agginfo[i].aggfn.nargs);
5550 /* Decide whether we want to dump it */
5551 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5553 /* Do not try to dump ACL if no ACL exists. */
5554 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5555 PQgetisnull(res, i, i_initaggacl) &&
5556 PQgetisnull(res, i, i_initraggacl))
5557 agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5562 destroyPQExpBuffer(query);
5569 * read all the user-defined functions in the system catalogs and
5570 * return them in the FuncInfo* structure
5572 * numFuncs is set to the number of functions read in
5575 getFuncs(Archive *fout, int *numFuncs)
5577 DumpOptions *dopt = fout->dopt;
5581 PQExpBuffer query = createPQExpBuffer();
5597 /* Make sure we are in proper schema */
5598 selectSourceSchema(fout, "pg_catalog");
5601 * Find all interesting functions. This is a bit complicated:
5603 * 1. Always exclude aggregates; those are handled elsewhere.
5605 * 2. Always exclude functions that are internally dependent on something
5606 * else, since presumably those will be created as a result of creating
5607 * the something else. This currently acts only to suppress constructor
5608 * functions for range types (so we only need it in 9.2 and up). Note
5609 * this is OK only because the constructors don't have any dependencies
5610 * the range type doesn't have; otherwise we might not get creation
5613 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5614 * they're members of extensions and we are in binary-upgrade mode then
5615 * include them, since we want to dump extension members individually in
5616 * that mode. Also, if they are used by casts or transforms then we need
5617 * to gather the information about them, though they won't be dumped if
5618 * they are built-in. Also, in 9.6 and up, include functions in
5619 * pg_catalog if they have an ACL different from what's shown in
5622 if (fout->remoteVersion >= 90600)
5624 PQExpBuffer acl_subquery = createPQExpBuffer();
5625 PQExpBuffer racl_subquery = createPQExpBuffer();
5626 PQExpBuffer initacl_subquery = createPQExpBuffer();
5627 PQExpBuffer initracl_subquery = createPQExpBuffer();
5629 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5630 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5631 dopt->binary_upgrade);
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) "
5647 "WHERE NOT proisagg"
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,
5668 g_last_builtin_oid);
5669 if (dopt->binary_upgrade)
5670 appendPQExpBufferStr(query,
5671 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5672 "classid = 'pg_proc'::regclass AND "
5673 "objid = p.oid AND "
5674 "refclassid = 'pg_extension'::regclass AND "
5676 appendPQExpBufferStr(query,
5677 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5678 appendPQExpBufferChar(query, ')');
5680 destroyPQExpBuffer(acl_subquery);
5681 destroyPQExpBuffer(racl_subquery);
5682 destroyPQExpBuffer(initacl_subquery);
5683 destroyPQExpBuffer(initracl_subquery);
5687 appendPQExpBuffer(query,
5688 "SELECT tableoid, oid, proname, prolang, "
5689 "pronargs, proargtypes, prorettype, proacl, "
5691 "NULL as initproacl, NULL AS initrproacl, "
5693 "(%s proowner) AS rolname "
5695 "WHERE NOT proisagg",
5697 if (fout->remoteVersion >= 90200)
5698 appendPQExpBufferStr(query,
5699 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5700 "WHERE classid = 'pg_proc'::regclass AND "
5701 "objid = p.oid AND deptype = 'i')");
5702 appendPQExpBuffer(query,
5704 "\n pronamespace != "
5705 "(SELECT oid FROM pg_namespace "
5706 "WHERE nspname = 'pg_catalog')"
5707 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5708 "\n WHERE pg_cast.oid > '%u'::oid"
5709 "\n AND p.oid = pg_cast.castfunc)",
5710 g_last_builtin_oid);
5712 if (fout->remoteVersion >= 90500)
5713 appendPQExpBuffer(query,
5714 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5715 "\n WHERE pg_transform.oid > '%u'::oid"
5716 "\n AND (p.oid = pg_transform.trffromsql"
5717 "\n OR p.oid = pg_transform.trftosql))",
5718 g_last_builtin_oid);
5720 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5721 appendPQExpBufferStr(query,
5722 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5723 "classid = 'pg_proc'::regclass AND "
5724 "objid = p.oid AND "
5725 "refclassid = 'pg_extension'::regclass AND "
5727 appendPQExpBufferChar(query, ')');
5730 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5732 ntups = PQntuples(res);
5736 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5738 i_tableoid = PQfnumber(res, "tableoid");
5739 i_oid = PQfnumber(res, "oid");
5740 i_proname = PQfnumber(res, "proname");
5741 i_pronamespace = PQfnumber(res, "pronamespace");
5742 i_rolname = PQfnumber(res, "rolname");
5743 i_prolang = PQfnumber(res, "prolang");
5744 i_pronargs = PQfnumber(res, "pronargs");
5745 i_proargtypes = PQfnumber(res, "proargtypes");
5746 i_prorettype = PQfnumber(res, "prorettype");
5747 i_proacl = PQfnumber(res, "proacl");
5748 i_rproacl = PQfnumber(res, "rproacl");
5749 i_initproacl = PQfnumber(res, "initproacl");
5750 i_initrproacl = PQfnumber(res, "initrproacl");
5752 for (i = 0; i < ntups; i++)
5754 finfo[i].dobj.objType = DO_FUNC;
5755 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5756 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5757 AssignDumpId(&finfo[i].dobj);
5758 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5759 finfo[i].dobj.namespace =
5761 atooid(PQgetvalue(res, i, i_pronamespace)));
5762 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5763 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5764 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5765 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5766 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5767 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5768 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5769 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5770 if (finfo[i].nargs == 0)
5771 finfo[i].argtypes = NULL;
5774 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5775 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5776 finfo[i].argtypes, finfo[i].nargs);
5779 /* Decide whether we want to dump it */
5780 selectDumpableObject(&(finfo[i].dobj), fout);
5782 /* Do not try to dump ACL if no ACL exists. */
5783 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5784 PQgetisnull(res, i, i_initproacl) &&
5785 PQgetisnull(res, i, i_initrproacl))
5786 finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5788 if (strlen(finfo[i].rolname) == 0)
5790 "WARNING: owner of function \"%s\" appears to be invalid\n",
5791 finfo[i].dobj.name);
5796 destroyPQExpBuffer(query);
5803 * read all the tables (no indexes)
5804 * in the system catalogs return them in the TableInfo* structure
5806 * numTables is set to the number of tables read in
5809 getTables(Archive *fout, int *numTables)
5811 DumpOptions *dopt = fout->dopt;
5815 PQExpBuffer query = createPQExpBuffer();
5828 int i_relhastriggers;
5832 int i_relforcerowsec;
5837 int i_toastfrozenxid;
5839 int i_relpersistence;
5840 int i_relispopulated;
5844 int i_reltablespace;
5847 int i_toastreloptions;
5850 int i_is_identity_sequence;
5856 /* Make sure we are in proper schema */
5857 selectSourceSchema(fout, "pg_catalog");
5860 * Find all the tables and table-like objects.
5862 * We include system catalogs, so that we can work if a user table is
5863 * defined to inherit from a system catalog (pretty weird, but...)
5865 * We ignore relations that are not ordinary tables, sequences, views,
5866 * materialized views, composite types, or foreign tables.
5868 * Composite-type table entries won't be dumped as such, but we have to
5869 * make a DumpableObject for them so that we can track dependencies of the
5870 * composite type (pg_depend entries for columns of the composite type
5871 * link to the pg_class entry not the pg_type entry).
5873 * Note: in this phase we should collect only a minimal amount of
5874 * information about each table, basically just enough to decide if it is
5875 * interesting. We must fetch all tables in this phase because otherwise
5876 * we cannot correctly identify inherited columns, owned sequences, etc.
5879 if (fout->remoteVersion >= 90600)
5881 char *partkeydef = "NULL";
5882 char *ispartition = "false";
5883 char *partbound = "NULL";
5885 PQExpBuffer acl_subquery = createPQExpBuffer();
5886 PQExpBuffer racl_subquery = createPQExpBuffer();
5887 PQExpBuffer initacl_subquery = createPQExpBuffer();
5888 PQExpBuffer initracl_subquery = createPQExpBuffer();
5890 PQExpBuffer attacl_subquery = createPQExpBuffer();
5891 PQExpBuffer attracl_subquery = createPQExpBuffer();
5892 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5893 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5896 * Collect the information about any partitioned tables, which were
5900 if (fout->remoteVersion >= 100000)
5902 partkeydef = "pg_get_partkeydef(c.oid)";
5903 ispartition = "c.relispartition";
5904 partbound = "pg_get_expr(c.relpartbound, c.oid)";
5908 * Left join to pick up dependency info linking sequences to their
5909 * owning column, if any (note this dependency is AUTO as of 8.2)
5911 * Left join to detect if any privileges are still as-set-at-init, in
5912 * which case we won't dump out ACL commands for those.
5915 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5916 initracl_subquery, "c.relacl", "c.relowner",
5917 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5918 " THEN 's' ELSE 'r' END::\"char\"",
5919 dopt->binary_upgrade);
5921 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5922 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5923 dopt->binary_upgrade);
5925 appendPQExpBuffer(query,
5926 "SELECT c.tableoid, c.oid, c.relname, "
5927 "%s AS relacl, %s as rrelacl, "
5928 "%s AS initrelacl, %s as initrrelacl, "
5929 "c.relkind, c.relnamespace, "
5930 "(%s c.relowner) AS rolname, "
5931 "c.relchecks, c.relhastriggers, "
5932 "c.relhasindex, c.relhasrules, c.relhasoids, "
5933 "c.relrowsecurity, c.relforcerowsecurity, "
5934 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5935 "tc.relfrozenxid AS tfrozenxid, "
5936 "tc.relminmxid AS tminmxid, "
5937 "c.relpersistence, c.relispopulated, "
5938 "c.relreplident, c.relpages, "
5939 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5940 "d.refobjid AS owning_tab, "
5941 "d.refobjsubid AS owning_col, "
5942 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5943 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5944 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5945 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5946 "tc.reloptions AS toast_reloptions, "
5947 "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, "
5948 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5949 "(c.oid = pip.objoid "
5950 "AND pip.classoid = 'pg_class'::regclass "
5951 "AND pip.objsubid = at.attnum)"
5952 "WHERE at.attrelid = c.oid AND ("
5954 "OR %s IS NOT NULL "
5955 "OR %s IS NOT NULL "
5959 "%s AS partkeydef, "
5960 "%s AS ispartition, "
5963 "LEFT JOIN pg_depend d ON "
5964 "(c.relkind = '%c' AND "
5965 "d.classid = c.tableoid AND d.objid = c.oid AND "
5966 "d.objsubid = 0 AND "
5967 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5968 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5969 "LEFT JOIN pg_init_privs pip ON "
5970 "(c.oid = pip.objoid "
5971 "AND pip.classoid = 'pg_class'::regclass "
5972 "AND pip.objsubid = 0) "
5973 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5976 racl_subquery->data,
5977 initacl_subquery->data,
5978 initracl_subquery->data,
5981 attacl_subquery->data,
5982 attracl_subquery->data,
5983 attinitacl_subquery->data,
5984 attinitracl_subquery->data,
5989 RELKIND_RELATION, RELKIND_SEQUENCE,
5990 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5991 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5992 RELKIND_PARTITIONED_TABLE);
5994 destroyPQExpBuffer(acl_subquery);
5995 destroyPQExpBuffer(racl_subquery);
5996 destroyPQExpBuffer(initacl_subquery);
5997 destroyPQExpBuffer(initracl_subquery);
5999 destroyPQExpBuffer(attacl_subquery);
6000 destroyPQExpBuffer(attracl_subquery);
6001 destroyPQExpBuffer(attinitacl_subquery);
6002 destroyPQExpBuffer(attinitracl_subquery);
6004 else if (fout->remoteVersion >= 90500)
6007 * Left join to pick up dependency info linking sequences to their
6008 * owning column, if any (note this dependency is AUTO as of 8.2)
6010 appendPQExpBuffer(query,
6011 "SELECT c.tableoid, c.oid, c.relname, "
6012 "c.relacl, NULL as rrelacl, "
6013 "NULL AS initrelacl, NULL AS initrrelacl, "
6016 "(%s c.relowner) AS rolname, "
6017 "c.relchecks, c.relhastriggers, "
6018 "c.relhasindex, c.relhasrules, c.relhasoids, "
6019 "c.relrowsecurity, c.relforcerowsecurity, "
6020 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6021 "tc.relfrozenxid AS tfrozenxid, "
6022 "tc.relminmxid AS tminmxid, "
6023 "c.relpersistence, c.relispopulated, "
6024 "c.relreplident, c.relpages, "
6025 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6026 "d.refobjid AS owning_tab, "
6027 "d.refobjsubid AS owning_col, "
6028 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6029 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6030 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6031 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6032 "tc.reloptions AS toast_reloptions, "
6033 "NULL AS changed_acl, "
6034 "NULL AS partkeydef, "
6035 "false AS ispartition, "
6036 "NULL AS partbound "
6038 "LEFT JOIN pg_depend d ON "
6039 "(c.relkind = '%c' AND "
6040 "d.classid = c.tableoid AND d.objid = c.oid AND "
6041 "d.objsubid = 0 AND "
6042 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6043 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6044 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6048 RELKIND_RELATION, RELKIND_SEQUENCE,
6049 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6050 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6052 else if (fout->remoteVersion >= 90400)
6055 * Left join to pick up dependency info linking sequences to their
6056 * owning column, if any (note this dependency is AUTO as of 8.2)
6058 appendPQExpBuffer(query,
6059 "SELECT c.tableoid, c.oid, c.relname, "
6060 "c.relacl, NULL as rrelacl, "
6061 "NULL AS initrelacl, NULL AS initrrelacl, "
6064 "(%s c.relowner) AS rolname, "
6065 "c.relchecks, c.relhastriggers, "
6066 "c.relhasindex, c.relhasrules, c.relhasoids, "
6067 "'f'::bool AS relrowsecurity, "
6068 "'f'::bool AS relforcerowsecurity, "
6069 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6070 "tc.relfrozenxid AS tfrozenxid, "
6071 "tc.relminmxid AS tminmxid, "
6072 "c.relpersistence, c.relispopulated, "
6073 "c.relreplident, c.relpages, "
6074 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6075 "d.refobjid AS owning_tab, "
6076 "d.refobjsubid AS owning_col, "
6077 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6078 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6079 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6080 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6081 "tc.reloptions AS toast_reloptions, "
6082 "NULL AS changed_acl, "
6083 "NULL AS partkeydef, "
6084 "false AS ispartition, "
6085 "NULL AS partbound "
6087 "LEFT JOIN pg_depend d ON "
6088 "(c.relkind = '%c' AND "
6089 "d.classid = c.tableoid AND d.objid = c.oid AND "
6090 "d.objsubid = 0 AND "
6091 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6092 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6093 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6097 RELKIND_RELATION, RELKIND_SEQUENCE,
6098 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6099 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6101 else if (fout->remoteVersion >= 90300)
6104 * Left join to pick up dependency info linking sequences to their
6105 * owning column, if any (note this dependency is AUTO as of 8.2)
6107 appendPQExpBuffer(query,
6108 "SELECT c.tableoid, c.oid, c.relname, "
6109 "c.relacl, NULL as rrelacl, "
6110 "NULL AS initrelacl, NULL AS initrrelacl, "
6113 "(%s c.relowner) AS rolname, "
6114 "c.relchecks, c.relhastriggers, "
6115 "c.relhasindex, c.relhasrules, c.relhasoids, "
6116 "'f'::bool AS relrowsecurity, "
6117 "'f'::bool AS relforcerowsecurity, "
6118 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6119 "tc.relfrozenxid AS tfrozenxid, "
6120 "tc.relminmxid AS tminmxid, "
6121 "c.relpersistence, c.relispopulated, "
6122 "'d' AS relreplident, c.relpages, "
6123 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6124 "d.refobjid AS owning_tab, "
6125 "d.refobjsubid AS owning_col, "
6126 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6127 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6128 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6129 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6130 "tc.reloptions AS toast_reloptions, "
6131 "NULL AS changed_acl, "
6132 "NULL AS partkeydef, "
6133 "false AS ispartition, "
6134 "NULL AS partbound "
6136 "LEFT JOIN pg_depend d ON "
6137 "(c.relkind = '%c' AND "
6138 "d.classid = c.tableoid AND d.objid = c.oid AND "
6139 "d.objsubid = 0 AND "
6140 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6141 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6142 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6146 RELKIND_RELATION, RELKIND_SEQUENCE,
6147 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6148 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6150 else if (fout->remoteVersion >= 90100)
6153 * Left join to pick up dependency info linking sequences to their
6154 * owning column, if any (note this dependency is AUTO as of 8.2)
6156 appendPQExpBuffer(query,
6157 "SELECT c.tableoid, c.oid, c.relname, "
6158 "c.relacl, NULL as rrelacl, "
6159 "NULL AS initrelacl, NULL AS initrrelacl, "
6162 "(%s c.relowner) AS rolname, "
6163 "c.relchecks, c.relhastriggers, "
6164 "c.relhasindex, c.relhasrules, c.relhasoids, "
6165 "'f'::bool AS relrowsecurity, "
6166 "'f'::bool AS relforcerowsecurity, "
6167 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6168 "tc.relfrozenxid AS tfrozenxid, "
6170 "c.relpersistence, 't' as relispopulated, "
6171 "'d' AS relreplident, c.relpages, "
6172 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6173 "d.refobjid AS owning_tab, "
6174 "d.refobjsubid AS owning_col, "
6175 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6176 "c.reloptions AS reloptions, "
6177 "tc.reloptions AS toast_reloptions, "
6178 "NULL AS changed_acl, "
6179 "NULL AS partkeydef, "
6180 "false AS ispartition, "
6181 "NULL AS partbound "
6183 "LEFT JOIN pg_depend d ON "
6184 "(c.relkind = '%c' AND "
6185 "d.classid = c.tableoid AND d.objid = c.oid AND "
6186 "d.objsubid = 0 AND "
6187 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6188 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6189 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6193 RELKIND_RELATION, RELKIND_SEQUENCE,
6194 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6195 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6197 else if (fout->remoteVersion >= 90000)
6200 * Left join to pick up dependency info linking sequences to their
6201 * owning column, if any (note this dependency is AUTO as of 8.2)
6203 appendPQExpBuffer(query,
6204 "SELECT c.tableoid, c.oid, c.relname, "
6205 "c.relacl, NULL as rrelacl, "
6206 "NULL AS initrelacl, NULL AS initrrelacl, "
6209 "(%s c.relowner) AS rolname, "
6210 "c.relchecks, c.relhastriggers, "
6211 "c.relhasindex, c.relhasrules, c.relhasoids, "
6212 "'f'::bool AS relrowsecurity, "
6213 "'f'::bool AS relforcerowsecurity, "
6214 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6215 "tc.relfrozenxid AS tfrozenxid, "
6217 "'p' AS relpersistence, 't' as relispopulated, "
6218 "'d' AS relreplident, c.relpages, "
6219 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6220 "d.refobjid AS owning_tab, "
6221 "d.refobjsubid AS owning_col, "
6222 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6223 "c.reloptions AS reloptions, "
6224 "tc.reloptions AS toast_reloptions, "
6225 "NULL AS changed_acl, "
6226 "NULL AS partkeydef, "
6227 "false AS ispartition, "
6228 "NULL AS partbound "
6230 "LEFT JOIN pg_depend d ON "
6231 "(c.relkind = '%c' AND "
6232 "d.classid = c.tableoid AND d.objid = c.oid AND "
6233 "d.objsubid = 0 AND "
6234 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6235 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6236 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6240 RELKIND_RELATION, RELKIND_SEQUENCE,
6241 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6243 else if (fout->remoteVersion >= 80400)
6246 * Left join to pick up dependency info linking sequences to their
6247 * owning column, if any (note this dependency is AUTO as of 8.2)
6249 appendPQExpBuffer(query,
6250 "SELECT c.tableoid, c.oid, c.relname, "
6251 "c.relacl, NULL as rrelacl, "
6252 "NULL AS initrelacl, NULL AS initrrelacl, "
6255 "(%s c.relowner) AS rolname, "
6256 "c.relchecks, c.relhastriggers, "
6257 "c.relhasindex, c.relhasrules, c.relhasoids, "
6258 "'f'::bool AS relrowsecurity, "
6259 "'f'::bool AS relforcerowsecurity, "
6260 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6261 "tc.relfrozenxid AS tfrozenxid, "
6263 "'p' AS relpersistence, 't' as relispopulated, "
6264 "'d' AS relreplident, c.relpages, "
6265 "NULL AS reloftype, "
6266 "d.refobjid AS owning_tab, "
6267 "d.refobjsubid AS owning_col, "
6268 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6269 "c.reloptions AS reloptions, "
6270 "tc.reloptions AS toast_reloptions, "
6271 "NULL AS changed_acl, "
6272 "NULL AS partkeydef, "
6273 "false AS ispartition, "
6274 "NULL AS partbound "
6276 "LEFT JOIN pg_depend d ON "
6277 "(c.relkind = '%c' AND "
6278 "d.classid = c.tableoid AND d.objid = c.oid AND "
6279 "d.objsubid = 0 AND "
6280 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6281 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6282 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6286 RELKIND_RELATION, RELKIND_SEQUENCE,
6287 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6289 else if (fout->remoteVersion >= 80200)
6292 * Left join to pick up dependency info linking sequences to their
6293 * owning column, if any (note this dependency is AUTO as of 8.2)
6295 appendPQExpBuffer(query,
6296 "SELECT c.tableoid, c.oid, c.relname, "
6297 "c.relacl, NULL as rrelacl, "
6298 "NULL AS initrelacl, NULL AS initrrelacl, "
6301 "(%s c.relowner) AS rolname, "
6302 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6303 "c.relhasindex, c.relhasrules, c.relhasoids, "
6304 "'f'::bool AS relrowsecurity, "
6305 "'f'::bool AS relforcerowsecurity, "
6306 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6307 "tc.relfrozenxid AS tfrozenxid, "
6309 "'p' AS relpersistence, 't' as relispopulated, "
6310 "'d' AS relreplident, c.relpages, "
6311 "NULL AS reloftype, "
6312 "d.refobjid AS owning_tab, "
6313 "d.refobjsubid AS owning_col, "
6314 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6315 "c.reloptions AS reloptions, "
6316 "NULL AS toast_reloptions, "
6317 "NULL AS changed_acl, "
6318 "NULL AS partkeydef, "
6319 "false AS ispartition, "
6320 "NULL AS partbound "
6322 "LEFT JOIN pg_depend d ON "
6323 "(c.relkind = '%c' AND "
6324 "d.classid = c.tableoid AND d.objid = c.oid AND "
6325 "d.objsubid = 0 AND "
6326 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6327 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6328 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6332 RELKIND_RELATION, RELKIND_SEQUENCE,
6333 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6338 * Left join to pick up dependency info linking sequences to their
6339 * owning column, if any
6341 appendPQExpBuffer(query,
6342 "SELECT c.tableoid, c.oid, relname, "
6343 "relacl, NULL as rrelacl, "
6344 "NULL AS initrelacl, NULL AS initrrelacl, "
6345 "relkind, relnamespace, "
6346 "(%s relowner) AS rolname, "
6347 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6348 "relhasindex, relhasrules, relhasoids, "
6349 "'f'::bool AS relrowsecurity, "
6350 "'f'::bool AS relforcerowsecurity, "
6351 "0 AS relfrozenxid, 0 AS relminmxid,"
6353 "0 AS tfrozenxid, 0 AS tminmxid,"
6354 "'p' AS relpersistence, 't' as relispopulated, "
6355 "'d' AS relreplident, relpages, "
6356 "NULL AS reloftype, "
6357 "d.refobjid AS owning_tab, "
6358 "d.refobjsubid AS owning_col, "
6359 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6360 "NULL AS reloptions, "
6361 "NULL AS toast_reloptions, "
6362 "NULL AS changed_acl, "
6363 "NULL AS partkeydef, "
6364 "false AS ispartition, "
6365 "NULL AS partbound "
6367 "LEFT JOIN pg_depend d ON "
6368 "(c.relkind = '%c' AND "
6369 "d.classid = c.tableoid AND d.objid = c.oid AND "
6370 "d.objsubid = 0 AND "
6371 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6372 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6376 RELKIND_RELATION, RELKIND_SEQUENCE,
6377 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6380 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6382 ntups = PQntuples(res);
6387 * Extract data from result and lock dumpable tables. We do the locking
6388 * before anything else, to minimize the window wherein a table could
6389 * disappear under us.
6391 * Note that we have to save info about all tables here, even when dumping
6392 * only one, because we don't yet know which tables might be inheritance
6393 * ancestors of the target table.
6395 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6397 i_reltableoid = PQfnumber(res, "tableoid");
6398 i_reloid = PQfnumber(res, "oid");
6399 i_relname = PQfnumber(res, "relname");
6400 i_relnamespace = PQfnumber(res, "relnamespace");
6401 i_relacl = PQfnumber(res, "relacl");
6402 i_rrelacl = PQfnumber(res, "rrelacl");
6403 i_initrelacl = PQfnumber(res, "initrelacl");
6404 i_initrrelacl = PQfnumber(res, "initrrelacl");
6405 i_relkind = PQfnumber(res, "relkind");
6406 i_rolname = PQfnumber(res, "rolname");
6407 i_relchecks = PQfnumber(res, "relchecks");
6408 i_relhastriggers = PQfnumber(res, "relhastriggers");
6409 i_relhasindex = PQfnumber(res, "relhasindex");
6410 i_relhasrules = PQfnumber(res, "relhasrules");
6411 i_relrowsec = PQfnumber(res, "relrowsecurity");
6412 i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6413 i_relhasoids = PQfnumber(res, "relhasoids");
6414 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6415 i_relminmxid = PQfnumber(res, "relminmxid");
6416 i_toastoid = PQfnumber(res, "toid");
6417 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6418 i_toastminmxid = PQfnumber(res, "tminmxid");
6419 i_relpersistence = PQfnumber(res, "relpersistence");
6420 i_relispopulated = PQfnumber(res, "relispopulated");
6421 i_relreplident = PQfnumber(res, "relreplident");
6422 i_relpages = PQfnumber(res, "relpages");
6423 i_owning_tab = PQfnumber(res, "owning_tab");
6424 i_owning_col = PQfnumber(res, "owning_col");
6425 i_reltablespace = PQfnumber(res, "reltablespace");
6426 i_reloptions = PQfnumber(res, "reloptions");
6427 i_checkoption = PQfnumber(res, "checkoption");
6428 i_toastreloptions = PQfnumber(res, "toast_reloptions");
6429 i_reloftype = PQfnumber(res, "reloftype");
6430 i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6431 i_changed_acl = PQfnumber(res, "changed_acl");
6432 i_partkeydef = PQfnumber(res, "partkeydef");
6433 i_ispartition = PQfnumber(res, "ispartition");
6434 i_partbound = PQfnumber(res, "partbound");
6436 if (dopt->lockWaitTimeout)
6439 * Arrange to fail instead of waiting forever for a table lock.
6441 * NB: this coding assumes that the only queries issued within the
6442 * following loop are LOCK TABLEs; else the timeout may be undesirably
6443 * applied to other things too.
6445 resetPQExpBuffer(query);
6446 appendPQExpBufferStr(query, "SET statement_timeout = ");
6447 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6448 ExecuteSqlStatement(fout, query->data);
6451 for (i = 0; i < ntups; i++)
6453 tblinfo[i].dobj.objType = DO_TABLE;
6454 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6455 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6456 AssignDumpId(&tblinfo[i].dobj);
6457 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6458 tblinfo[i].dobj.namespace =
6460 atooid(PQgetvalue(res, i, i_relnamespace)));
6461 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6462 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6463 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6464 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6465 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6466 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6467 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6468 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6469 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6470 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6471 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6472 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6473 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6474 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6475 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6476 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6477 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6478 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6479 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6480 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6481 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6482 if (PQgetisnull(res, i, i_reloftype))
6483 tblinfo[i].reloftype = NULL;
6485 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6486 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6487 if (PQgetisnull(res, i, i_owning_tab))
6489 tblinfo[i].owning_tab = InvalidOid;
6490 tblinfo[i].owning_col = 0;
6494 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6495 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6497 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6498 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6499 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6500 tblinfo[i].checkoption = NULL;
6502 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6503 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6505 /* other fields were zeroed above */
6508 * Decide whether we want to dump this table.
6510 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6511 tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6513 selectDumpableTable(&tblinfo[i], fout);
6516 * If the table-level and all column-level ACLs for this table are
6517 * unchanged, then we don't need to worry about including the ACLs for
6518 * this table. If any column-level ACLs have been changed, the
6519 * 'changed_acl' column from the query will indicate that.
6521 * This can result in a significant performance improvement in cases
6522 * where we are only looking to dump out the ACL (eg: pg_catalog).
6524 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6525 PQgetisnull(res, i, i_initrelacl) &&
6526 PQgetisnull(res, i, i_initrrelacl) &&
6527 strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6528 tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6530 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6531 tblinfo[i].dummy_view = false; /* might get set during sort */
6532 tblinfo[i].postponed_def = false; /* might get set during sort */
6534 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6535 strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6537 /* Partition key string or NULL */
6538 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6539 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6540 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6543 * Read-lock target tables to make sure they aren't DROPPED or altered
6544 * in schema before we get around to dumping them.
6546 * Note that we don't explicitly lock parents of the target tables; we
6547 * assume our lock on the child is enough to prevent schema
6548 * alterations to parent tables.
6550 * NOTE: it'd be kinda nice to lock other relations too, not only
6551 * plain tables, but the backend doesn't presently allow that.
6553 * We only need to lock the table for certain components; see
6556 if (tblinfo[i].dobj.dump &&
6557 (tblinfo[i].relkind == RELKIND_RELATION ||
6558 tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6559 (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6561 resetPQExpBuffer(query);
6562 appendPQExpBuffer(query,
6563 "LOCK TABLE %s IN ACCESS SHARE MODE",
6564 fmtQualifiedId(fout->remoteVersion,
6565 tblinfo[i].dobj.namespace->dobj.name,
6566 tblinfo[i].dobj.name));
6567 ExecuteSqlStatement(fout, query->data);
6570 /* Emit notice if join for owner failed */
6571 if (strlen(tblinfo[i].rolname) == 0)
6572 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6573 tblinfo[i].dobj.name);
6576 if (dopt->lockWaitTimeout)
6578 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6583 destroyPQExpBuffer(query);
6590 * identify owned sequences and mark them as dumpable if owning table is
6592 * We used to do this in getTables(), but it's better to do it after the
6593 * index used by findTableByOid() has been set up.
6596 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6601 * Force sequences that are "owned" by table columns to be dumped whenever
6602 * their owning table is being dumped.
6604 for (i = 0; i < numTables; i++)
6606 TableInfo *seqinfo = &tblinfo[i];
6607 TableInfo *owning_tab;
6609 if (!OidIsValid(seqinfo->owning_tab))
6610 continue; /* not an owned sequence */
6612 owning_tab = findTableByOid(seqinfo->owning_tab);
6613 if (owning_tab == NULL)
6614 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6615 seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6618 * We need to dump the components that are being dumped for the table
6619 * and any components which the sequence is explicitly marked with.
6621 * We can't simply use the set of components which are being dumped
6622 * for the table as the table might be in an extension (and only the
6623 * non-extension components, eg: ACLs if changed, security labels, and
6624 * policies, are being dumped) while the sequence is not (and
6625 * therefore the definition and other components should also be
6628 * If the sequence is part of the extension then it should be properly
6629 * marked by checkExtensionMembership() and this will be a no-op as
6630 * the table will be equivalently marked.
6632 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6634 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6635 seqinfo->interesting = true;
6641 * read all the inheritance information
6642 * from the system catalogs return them in the InhInfo* structure
6644 * numInherits is set to the number of pairs read in
6647 getInherits(Archive *fout, int *numInherits)
6652 PQExpBuffer query = createPQExpBuffer();
6658 /* Make sure we are in proper schema */
6659 selectSourceSchema(fout, "pg_catalog");
6662 * Find all the inheritance information, excluding implicit inheritance
6663 * via partitioning. We handle that case using getPartitions(), because
6664 * we want more information about partitions than just the parent-child
6667 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6669 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6671 ntups = PQntuples(res);
6673 *numInherits = ntups;
6675 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6677 i_inhrelid = PQfnumber(res, "inhrelid");
6678 i_inhparent = PQfnumber(res, "inhparent");
6680 for (i = 0; i < ntups; i++)
6682 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6683 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6688 destroyPQExpBuffer(query);
6695 * get information about every index on a dumpable table
6697 * Note: index data is not returned directly to the caller, but it
6698 * does get entered into the DumpableObject tables.
6701 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6705 PQExpBuffer query = createPQExpBuffer();
6708 ConstraintInfo *constrinfo;
6730 for (i = 0; i < numTables; i++)
6732 TableInfo *tbinfo = &tblinfo[i];
6734 if (!tbinfo->hasindex)
6738 * Ignore indexes of tables whose definitions are not to be dumped.
6740 * We also need indexes on partitioned tables which have partitions to
6741 * be dumped, in order to dump the indexes on the partitions.
6743 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6744 !tbinfo->interesting)
6748 write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6749 tbinfo->dobj.namespace->dobj.name,
6752 /* Make sure we are in proper schema so indexdef is right */
6753 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6756 * The point of the messy-looking outer join is to find a constraint
6757 * that is related by an internal dependency link to the index. If we
6758 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
6759 * assume an index won't have more than one internal dependency.
6761 * As of 9.0 we don't need to look at pg_depend but can check for a
6762 * match to pg_constraint.conindid. The check on conrelid is
6763 * redundant but useful because that column is indexed while conindid
6766 resetPQExpBuffer(query);
6767 if (fout->remoteVersion >= 110000)
6769 appendPQExpBuffer(query,
6770 "SELECT t.tableoid, t.oid, "
6771 "t.relname AS indexname, "
6772 "inh.inhparent AS parentidx, "
6773 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6774 "t.relnatts AS indnkeys, "
6775 "i.indkey, i.indisclustered, "
6776 "i.indisreplident, t.relpages, "
6777 "c.contype, c.conname, "
6778 "c.condeferrable, c.condeferred, "
6779 "c.tableoid AS contableoid, "
6781 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6782 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6783 "t.reloptions AS indreloptions "
6784 "FROM pg_catalog.pg_index i "
6785 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6786 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6787 "LEFT JOIN pg_catalog.pg_constraint c "
6788 "ON (i.indrelid = c.conrelid AND "
6789 "i.indexrelid = c.conindid AND "
6790 "c.contype IN ('p','u','x')) "
6791 "LEFT JOIN pg_catalog.pg_inherits inh "
6792 "ON (inh.inhrelid = indexrelid) "
6793 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6794 "AND (i.indisvalid OR t2.relkind = 'p') "
6796 "ORDER BY indexname",
6797 tbinfo->dobj.catId.oid);
6799 else if (fout->remoteVersion >= 90400)
6802 * the test on indisready is necessary in 9.2, and harmless in
6803 * earlier/later versions
6805 appendPQExpBuffer(query,
6806 "SELECT t.tableoid, t.oid, "
6807 "t.relname AS indexname, "
6809 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6810 "t.relnatts AS indnkeys, "
6811 "i.indkey, i.indisclustered, "
6812 "i.indisreplident, t.relpages, "
6813 "c.contype, c.conname, "
6814 "c.condeferrable, c.condeferred, "
6815 "c.tableoid AS contableoid, "
6817 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6818 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6819 "t.reloptions AS indreloptions "
6820 "FROM pg_catalog.pg_index i "
6821 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6822 "LEFT JOIN pg_catalog.pg_constraint c "
6823 "ON (i.indrelid = c.conrelid AND "
6824 "i.indexrelid = c.conindid AND "
6825 "c.contype IN ('p','u','x')) "
6826 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6827 "AND i.indisvalid AND i.indisready "
6828 "ORDER BY indexname",
6829 tbinfo->dobj.catId.oid);
6831 else if (fout->remoteVersion >= 90000)
6834 * the test on indisready is necessary in 9.2, and harmless in
6835 * earlier/later versions
6837 appendPQExpBuffer(query,
6838 "SELECT t.tableoid, t.oid, "
6839 "t.relname AS indexname, "
6841 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6842 "t.relnatts AS indnkeys, "
6843 "i.indkey, i.indisclustered, "
6844 "false AS indisreplident, t.relpages, "
6845 "c.contype, c.conname, "
6846 "c.condeferrable, c.condeferred, "
6847 "c.tableoid AS contableoid, "
6849 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6850 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6851 "t.reloptions AS indreloptions "
6852 "FROM pg_catalog.pg_index i "
6853 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6854 "LEFT JOIN pg_catalog.pg_constraint c "
6855 "ON (i.indrelid = c.conrelid AND "
6856 "i.indexrelid = c.conindid AND "
6857 "c.contype IN ('p','u','x')) "
6858 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6859 "AND i.indisvalid AND i.indisready "
6860 "ORDER BY indexname",
6861 tbinfo->dobj.catId.oid);
6863 else if (fout->remoteVersion >= 80200)
6865 appendPQExpBuffer(query,
6866 "SELECT t.tableoid, t.oid, "
6867 "t.relname AS indexname, "
6869 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6870 "t.relnatts AS indnkeys, "
6871 "i.indkey, i.indisclustered, "
6872 "false AS indisreplident, t.relpages, "
6873 "c.contype, c.conname, "
6874 "c.condeferrable, c.condeferred, "
6875 "c.tableoid AS contableoid, "
6878 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6879 "t.reloptions AS indreloptions "
6880 "FROM pg_catalog.pg_index i "
6881 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6882 "LEFT JOIN pg_catalog.pg_depend d "
6883 "ON (d.classid = t.tableoid "
6884 "AND d.objid = t.oid "
6885 "AND d.deptype = 'i') "
6886 "LEFT JOIN pg_catalog.pg_constraint c "
6887 "ON (d.refclassid = c.tableoid "
6888 "AND d.refobjid = c.oid) "
6889 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6891 "ORDER BY indexname",
6892 tbinfo->dobj.catId.oid);
6896 appendPQExpBuffer(query,
6897 "SELECT t.tableoid, t.oid, "
6898 "t.relname AS indexname, "
6900 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6901 "t.relnatts AS indnkeys, "
6902 "i.indkey, i.indisclustered, "
6903 "false AS indisreplident, t.relpages, "
6904 "c.contype, c.conname, "
6905 "c.condeferrable, c.condeferred, "
6906 "c.tableoid AS contableoid, "
6909 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6910 "null AS indreloptions "
6911 "FROM pg_catalog.pg_index i "
6912 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6913 "LEFT JOIN pg_catalog.pg_depend d "
6914 "ON (d.classid = t.tableoid "
6915 "AND d.objid = t.oid "
6916 "AND d.deptype = 'i') "
6917 "LEFT JOIN pg_catalog.pg_constraint c "
6918 "ON (d.refclassid = c.tableoid "
6919 "AND d.refobjid = c.oid) "
6920 "WHERE i.indrelid = '%u'::pg_catalog.oid "
6921 "ORDER BY indexname",
6922 tbinfo->dobj.catId.oid);
6925 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6927 ntups = PQntuples(res);
6929 i_tableoid = PQfnumber(res, "tableoid");
6930 i_oid = PQfnumber(res, "oid");
6931 i_indexname = PQfnumber(res, "indexname");
6932 i_parentidx = PQfnumber(res, "parentidx");
6933 i_indexdef = PQfnumber(res, "indexdef");
6934 i_indnkeys = PQfnumber(res, "indnkeys");
6935 i_indkey = PQfnumber(res, "indkey");
6936 i_indisclustered = PQfnumber(res, "indisclustered");
6937 i_indisreplident = PQfnumber(res, "indisreplident");
6938 i_relpages = PQfnumber(res, "relpages");
6939 i_contype = PQfnumber(res, "contype");
6940 i_conname = PQfnumber(res, "conname");
6941 i_condeferrable = PQfnumber(res, "condeferrable");
6942 i_condeferred = PQfnumber(res, "condeferred");
6943 i_contableoid = PQfnumber(res, "contableoid");
6944 i_conoid = PQfnumber(res, "conoid");
6945 i_condef = PQfnumber(res, "condef");
6946 i_tablespace = PQfnumber(res, "tablespace");
6947 i_indreloptions = PQfnumber(res, "indreloptions");
6949 tbinfo->indexes = indxinfo =
6950 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6951 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6952 tbinfo->numIndexes = ntups;
6954 for (j = 0; j < ntups; j++)
6958 indxinfo[j].dobj.objType = DO_INDEX;
6959 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6960 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6961 AssignDumpId(&indxinfo[j].dobj);
6962 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6963 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6964 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6965 indxinfo[j].indextable = tbinfo;
6966 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6967 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
6968 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6969 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6970 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnkeys * sizeof(Oid));
6971 parseOidArray(PQgetvalue(res, j, i_indkey),
6972 indxinfo[j].indkeys, indxinfo[j].indnkeys);
6973 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6974 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6975 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6976 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
6977 contype = *(PQgetvalue(res, j, i_contype));
6979 if (contype == 'p' || contype == 'u' || contype == 'x')
6982 * If we found a constraint matching the index, create an
6985 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6986 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6987 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6988 AssignDumpId(&constrinfo[j].dobj);
6989 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
6990 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6991 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6992 constrinfo[j].contable = tbinfo;
6993 constrinfo[j].condomain = NULL;
6994 constrinfo[j].contype = contype;
6996 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6998 constrinfo[j].condef = NULL;
6999 constrinfo[j].confrelid = InvalidOid;
7000 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7001 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7002 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7003 constrinfo[j].conislocal = true;
7004 constrinfo[j].separate = true;
7006 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7010 /* Plain secondary index */
7011 indxinfo[j].indexconstraint = 0;
7018 destroyPQExpBuffer(query);
7022 * getExtendedStatistics
7023 * get information about extended-statistics objects.
7025 * Note: extended statistics data is not returned directly to the caller, but
7026 * it does get entered into the DumpableObject tables.
7029 getExtendedStatistics(Archive *fout)
7033 StatsExtInfo *statsextinfo;
7042 /* Extended statistics were new in v10 */
7043 if (fout->remoteVersion < 100000)
7046 query = createPQExpBuffer();
7048 /* Make sure we are in proper schema */
7049 selectSourceSchema(fout, "pg_catalog");
7051 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7052 "stxnamespace, (%s stxowner) AS rolname "
7053 "FROM pg_catalog.pg_statistic_ext",
7056 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7058 ntups = PQntuples(res);
7060 i_tableoid = PQfnumber(res, "tableoid");
7061 i_oid = PQfnumber(res, "oid");
7062 i_stxname = PQfnumber(res, "stxname");
7063 i_stxnamespace = PQfnumber(res, "stxnamespace");
7064 i_rolname = PQfnumber(res, "rolname");
7066 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7068 for (i = 0; i < ntups; i++)
7070 statsextinfo[i].dobj.objType = DO_STATSEXT;
7071 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7072 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7073 AssignDumpId(&statsextinfo[i].dobj);
7074 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7075 statsextinfo[i].dobj.namespace =
7077 atooid(PQgetvalue(res, i, i_stxnamespace)));
7078 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7080 /* Decide whether we want to dump it */
7081 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7083 /* Stats objects do not currently have ACLs. */
7084 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7088 destroyPQExpBuffer(query);
7094 * Get info about constraints on dumpable tables.
7096 * Currently handles foreign keys only.
7097 * Unique and primary key constraints are handled with indexes,
7098 * while check constraints are processed in getTableAttrs().
7101 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7105 ConstraintInfo *constrinfo;
7115 query = createPQExpBuffer();
7117 for (i = 0; i < numTables; i++)
7119 TableInfo *tbinfo = &tblinfo[i];
7121 if (!tbinfo->hastriggers ||
7122 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7126 write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7127 tbinfo->dobj.namespace->dobj.name,
7131 * select table schema to ensure constraint expr is qualified if
7134 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7136 resetPQExpBuffer(query);
7137 appendPQExpBuffer(query,
7138 "SELECT tableoid, oid, conname, confrelid, "
7139 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7140 "FROM pg_catalog.pg_constraint "
7141 "WHERE conrelid = '%u'::pg_catalog.oid "
7142 "AND contype = 'f'",
7143 tbinfo->dobj.catId.oid);
7144 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7146 ntups = PQntuples(res);
7148 i_contableoid = PQfnumber(res, "tableoid");
7149 i_conoid = PQfnumber(res, "oid");
7150 i_conname = PQfnumber(res, "conname");
7151 i_confrelid = PQfnumber(res, "confrelid");
7152 i_condef = PQfnumber(res, "condef");
7154 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7156 for (j = 0; j < ntups; j++)
7158 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7159 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7160 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7161 AssignDumpId(&constrinfo[j].dobj);
7162 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7163 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7164 constrinfo[j].contable = tbinfo;
7165 constrinfo[j].condomain = NULL;
7166 constrinfo[j].contype = 'f';
7167 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7168 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7169 constrinfo[j].conindex = 0;
7170 constrinfo[j].condeferrable = false;
7171 constrinfo[j].condeferred = false;
7172 constrinfo[j].conislocal = true;
7173 constrinfo[j].separate = true;
7179 destroyPQExpBuffer(query);
7183 * getDomainConstraints
7185 * Get info about constraints on a domain.
7188 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7191 ConstraintInfo *constrinfo;
7201 * select appropriate schema to ensure names in constraint are properly
7204 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7206 query = createPQExpBuffer();
7208 if (fout->remoteVersion >= 90100)
7209 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7210 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7212 "FROM pg_catalog.pg_constraint "
7213 "WHERE contypid = '%u'::pg_catalog.oid "
7215 tyinfo->dobj.catId.oid);
7218 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7219 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7220 "true as convalidated "
7221 "FROM pg_catalog.pg_constraint "
7222 "WHERE contypid = '%u'::pg_catalog.oid "
7224 tyinfo->dobj.catId.oid);
7226 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7228 ntups = PQntuples(res);
7230 i_tableoid = PQfnumber(res, "tableoid");
7231 i_oid = PQfnumber(res, "oid");
7232 i_conname = PQfnumber(res, "conname");
7233 i_consrc = PQfnumber(res, "consrc");
7235 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7237 tyinfo->nDomChecks = ntups;
7238 tyinfo->domChecks = constrinfo;
7240 for (i = 0; i < ntups; i++)
7242 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7244 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7245 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7246 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7247 AssignDumpId(&constrinfo[i].dobj);
7248 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7249 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7250 constrinfo[i].contable = NULL;
7251 constrinfo[i].condomain = tyinfo;
7252 constrinfo[i].contype = 'c';
7253 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7254 constrinfo[i].confrelid = InvalidOid;
7255 constrinfo[i].conindex = 0;
7256 constrinfo[i].condeferrable = false;
7257 constrinfo[i].condeferred = false;
7258 constrinfo[i].conislocal = true;
7260 constrinfo[i].separate = !validated;
7263 * Make the domain depend on the constraint, ensuring it won't be
7264 * output till any constraint dependencies are OK. If the constraint
7265 * has not been validated, it's going to be dumped after the domain
7266 * anyway, so this doesn't matter.
7269 addObjectDependency(&tyinfo->dobj,
7270 constrinfo[i].dobj.dumpId);
7275 destroyPQExpBuffer(query);
7280 * get basic information about every rule in the system
7282 * numRules is set to the number of rules read in
7285 getRules(Archive *fout, int *numRules)
7290 PQExpBuffer query = createPQExpBuffer();
7300 /* Make sure we are in proper schema */
7301 selectSourceSchema(fout, "pg_catalog");
7303 if (fout->remoteVersion >= 80300)
7305 appendPQExpBufferStr(query, "SELECT "
7306 "tableoid, oid, rulename, "
7307 "ev_class AS ruletable, ev_type, is_instead, "
7314 appendPQExpBufferStr(query, "SELECT "
7315 "tableoid, oid, rulename, "
7316 "ev_class AS ruletable, ev_type, is_instead, "
7317 "'O'::char AS ev_enabled "
7322 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7324 ntups = PQntuples(res);
7328 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7330 i_tableoid = PQfnumber(res, "tableoid");
7331 i_oid = PQfnumber(res, "oid");
7332 i_rulename = PQfnumber(res, "rulename");
7333 i_ruletable = PQfnumber(res, "ruletable");
7334 i_ev_type = PQfnumber(res, "ev_type");
7335 i_is_instead = PQfnumber(res, "is_instead");
7336 i_ev_enabled = PQfnumber(res, "ev_enabled");
7338 for (i = 0; i < ntups; i++)
7342 ruleinfo[i].dobj.objType = DO_RULE;
7343 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7344 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7345 AssignDumpId(&ruleinfo[i].dobj);
7346 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7347 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7348 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7349 if (ruleinfo[i].ruletable == NULL)
7350 exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7351 ruletableoid, ruleinfo[i].dobj.catId.oid);
7352 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7353 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7354 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7355 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7356 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7357 if (ruleinfo[i].ruletable)
7360 * If the table is a view or materialized view, force its ON
7361 * SELECT rule to be sorted before the view itself --- this
7362 * ensures that any dependencies for the rule affect the table's
7363 * positioning. Other rules are forced to appear after their
7366 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7367 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7368 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7370 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7371 ruleinfo[i].dobj.dumpId);
7372 /* We'll merge the rule into CREATE VIEW, if possible */
7373 ruleinfo[i].separate = false;
7377 addObjectDependency(&ruleinfo[i].dobj,
7378 ruleinfo[i].ruletable->dobj.dumpId);
7379 ruleinfo[i].separate = true;
7383 ruleinfo[i].separate = true;
7388 destroyPQExpBuffer(query);
7395 * get information about every trigger on a dumpable table
7397 * Note: trigger data is not returned directly to the caller, but it
7398 * does get entered into the DumpableObject tables.
7401 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7405 PQExpBuffer query = createPQExpBuffer();
7407 TriggerInfo *tginfo;
7425 for (i = 0; i < numTables; i++)
7427 TableInfo *tbinfo = &tblinfo[i];
7429 if (!tbinfo->hastriggers ||
7430 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7434 write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7435 tbinfo->dobj.namespace->dobj.name,
7439 * select table schema to ensure regproc name is qualified if needed
7441 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7443 resetPQExpBuffer(query);
7444 if (fout->remoteVersion >= 90000)
7447 * NB: think not to use pretty=true in pg_get_triggerdef. It
7448 * could result in non-forward-compatible dumps of WHEN clauses
7449 * due to under-parenthesization.
7451 appendPQExpBuffer(query,
7453 "tgfoid::pg_catalog.regproc AS tgfname, "
7454 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7455 "tgenabled, tableoid, oid "
7456 "FROM pg_catalog.pg_trigger t "
7457 "WHERE tgrelid = '%u'::pg_catalog.oid "
7458 "AND NOT tgisinternal",
7459 tbinfo->dobj.catId.oid);
7461 else if (fout->remoteVersion >= 80300)
7464 * We ignore triggers that are tied to a foreign-key constraint
7466 appendPQExpBuffer(query,
7468 "tgfoid::pg_catalog.regproc AS tgfname, "
7469 "tgtype, tgnargs, tgargs, tgenabled, "
7470 "tgisconstraint, tgconstrname, tgdeferrable, "
7471 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7472 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7473 "FROM pg_catalog.pg_trigger t "
7474 "WHERE tgrelid = '%u'::pg_catalog.oid "
7475 "AND tgconstraint = 0",
7476 tbinfo->dobj.catId.oid);
7481 * We ignore triggers that are tied to a foreign-key constraint,
7482 * but in these versions we have to grovel through pg_constraint
7485 appendPQExpBuffer(query,
7487 "tgfoid::pg_catalog.regproc AS tgfname, "
7488 "tgtype, tgnargs, tgargs, tgenabled, "
7489 "tgisconstraint, tgconstrname, tgdeferrable, "
7490 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7491 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7492 "FROM pg_catalog.pg_trigger t "
7493 "WHERE tgrelid = '%u'::pg_catalog.oid "
7494 "AND (NOT tgisconstraint "
7496 " (SELECT 1 FROM pg_catalog.pg_depend d "
7497 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7498 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7499 tbinfo->dobj.catId.oid);
7502 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7504 ntups = PQntuples(res);
7506 i_tableoid = PQfnumber(res, "tableoid");
7507 i_oid = PQfnumber(res, "oid");
7508 i_tgname = PQfnumber(res, "tgname");
7509 i_tgfname = PQfnumber(res, "tgfname");
7510 i_tgtype = PQfnumber(res, "tgtype");
7511 i_tgnargs = PQfnumber(res, "tgnargs");
7512 i_tgargs = PQfnumber(res, "tgargs");
7513 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7514 i_tgconstrname = PQfnumber(res, "tgconstrname");
7515 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7516 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7517 i_tgenabled = PQfnumber(res, "tgenabled");
7518 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7519 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7520 i_tgdef = PQfnumber(res, "tgdef");
7522 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7524 tbinfo->numTriggers = ntups;
7525 tbinfo->triggers = tginfo;
7527 for (j = 0; j < ntups; j++)
7529 tginfo[j].dobj.objType = DO_TRIGGER;
7530 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7531 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7532 AssignDumpId(&tginfo[j].dobj);
7533 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7534 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7535 tginfo[j].tgtable = tbinfo;
7536 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7539 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7541 /* remaining fields are not valid if we have tgdef */
7542 tginfo[j].tgfname = NULL;
7543 tginfo[j].tgtype = 0;
7544 tginfo[j].tgnargs = 0;
7545 tginfo[j].tgargs = NULL;
7546 tginfo[j].tgisconstraint = false;
7547 tginfo[j].tgdeferrable = false;
7548 tginfo[j].tginitdeferred = false;
7549 tginfo[j].tgconstrname = NULL;
7550 tginfo[j].tgconstrrelid = InvalidOid;
7551 tginfo[j].tgconstrrelname = NULL;
7555 tginfo[j].tgdef = NULL;
7557 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7558 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7559 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7560 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7561 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7562 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7563 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7565 if (tginfo[j].tgisconstraint)
7567 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7568 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7569 if (OidIsValid(tginfo[j].tgconstrrelid))
7571 if (PQgetisnull(res, j, i_tgconstrrelname))
7572 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7573 tginfo[j].dobj.name,
7575 tginfo[j].tgconstrrelid);
7576 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7579 tginfo[j].tgconstrrelname = NULL;
7583 tginfo[j].tgconstrname = NULL;
7584 tginfo[j].tgconstrrelid = InvalidOid;
7585 tginfo[j].tgconstrrelname = NULL;
7593 destroyPQExpBuffer(query);
7598 * get information about event triggers
7601 getEventTriggers(Archive *fout, int *numEventTriggers)
7606 EventTriggerInfo *evtinfo;
7617 /* Before 9.3, there are no event triggers */
7618 if (fout->remoteVersion < 90300)
7620 *numEventTriggers = 0;
7624 query = createPQExpBuffer();
7626 /* Make sure we are in proper schema */
7627 selectSourceSchema(fout, "pg_catalog");
7629 appendPQExpBuffer(query,
7630 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7631 "evtevent, (%s evtowner) AS evtowner, "
7632 "array_to_string(array("
7633 "select quote_literal(x) "
7634 " from unnest(evttags) as t(x)), ', ') as evttags, "
7635 "e.evtfoid::regproc as evtfname "
7636 "FROM pg_event_trigger e "
7640 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7642 ntups = PQntuples(res);
7644 *numEventTriggers = ntups;
7646 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7648 i_tableoid = PQfnumber(res, "tableoid");
7649 i_oid = PQfnumber(res, "oid");
7650 i_evtname = PQfnumber(res, "evtname");
7651 i_evtevent = PQfnumber(res, "evtevent");
7652 i_evtowner = PQfnumber(res, "evtowner");
7653 i_evttags = PQfnumber(res, "evttags");
7654 i_evtfname = PQfnumber(res, "evtfname");
7655 i_evtenabled = PQfnumber(res, "evtenabled");
7657 for (i = 0; i < ntups; i++)
7659 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7660 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7661 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7662 AssignDumpId(&evtinfo[i].dobj);
7663 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7664 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7665 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7666 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7667 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7668 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7669 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7671 /* Decide whether we want to dump it */
7672 selectDumpableObject(&(evtinfo[i].dobj), fout);
7674 /* Event Triggers do not currently have ACLs. */
7675 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7680 destroyPQExpBuffer(query);
7687 * get basic information about every procedural language in the system
7689 * numProcLangs is set to the number of langs read in
7691 * NB: this must run after getFuncs() because we assume we can do
7695 getProcLangs(Archive *fout, int *numProcLangs)
7697 DumpOptions *dopt = fout->dopt;
7701 PQExpBuffer query = createPQExpBuffer();
7702 ProcLangInfo *planginfo;
7707 int i_lanplcallfoid;
7716 /* Make sure we are in proper schema */
7717 selectSourceSchema(fout, "pg_catalog");
7719 if (fout->remoteVersion >= 90600)
7721 PQExpBuffer acl_subquery = createPQExpBuffer();
7722 PQExpBuffer racl_subquery = createPQExpBuffer();
7723 PQExpBuffer initacl_subquery = createPQExpBuffer();
7724 PQExpBuffer initracl_subquery = createPQExpBuffer();
7726 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7727 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7728 dopt->binary_upgrade);
7730 /* pg_language has a laninline column */
7731 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7732 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7733 "l.laninline, l.lanvalidator, "
7736 "%s AS initlanacl, "
7737 "%s AS initrlanacl, "
7738 "(%s l.lanowner) AS lanowner "
7739 "FROM pg_language l "
7740 "LEFT JOIN pg_init_privs pip ON "
7741 "(l.oid = pip.objoid "
7742 "AND pip.classoid = 'pg_language'::regclass "
7743 "AND pip.objsubid = 0) "
7747 racl_subquery->data,
7748 initacl_subquery->data,
7749 initracl_subquery->data,
7752 destroyPQExpBuffer(acl_subquery);
7753 destroyPQExpBuffer(racl_subquery);
7754 destroyPQExpBuffer(initacl_subquery);
7755 destroyPQExpBuffer(initracl_subquery);
7757 else if (fout->remoteVersion >= 90000)
7759 /* pg_language has a laninline column */
7760 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7761 "lanname, lanpltrusted, lanplcallfoid, "
7762 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7763 "NULL AS initlanacl, NULL AS initrlanacl, "
7764 "(%s lanowner) AS lanowner "
7770 else if (fout->remoteVersion >= 80300)
7772 /* pg_language has a lanowner column */
7773 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7774 "lanname, lanpltrusted, lanplcallfoid, "
7775 "0 AS laninline, lanvalidator, lanacl, "
7777 "NULL AS initlanacl, NULL AS initrlanacl, "
7778 "(%s lanowner) AS lanowner "
7784 else if (fout->remoteVersion >= 80100)
7786 /* Languages are owned by the bootstrap superuser, OID 10 */
7787 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7788 "lanname, lanpltrusted, lanplcallfoid, "
7789 "0 AS laninline, lanvalidator, lanacl, "
7791 "NULL AS initlanacl, NULL AS initrlanacl, "
7792 "(%s '10') AS lanowner "
7800 /* Languages are owned by the bootstrap superuser, sysid 1 */
7801 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7802 "lanname, lanpltrusted, lanplcallfoid, "
7803 "0 AS laninline, lanvalidator, lanacl, "
7805 "NULL AS initlanacl, NULL AS initrlanacl, "
7806 "(%s '1') AS lanowner "
7813 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7815 ntups = PQntuples(res);
7817 *numProcLangs = ntups;
7819 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7821 i_tableoid = PQfnumber(res, "tableoid");
7822 i_oid = PQfnumber(res, "oid");
7823 i_lanname = PQfnumber(res, "lanname");
7824 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7825 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7826 i_laninline = PQfnumber(res, "laninline");
7827 i_lanvalidator = PQfnumber(res, "lanvalidator");
7828 i_lanacl = PQfnumber(res, "lanacl");
7829 i_rlanacl = PQfnumber(res, "rlanacl");
7830 i_initlanacl = PQfnumber(res, "initlanacl");
7831 i_initrlanacl = PQfnumber(res, "initrlanacl");
7832 i_lanowner = PQfnumber(res, "lanowner");
7834 for (i = 0; i < ntups; i++)
7836 planginfo[i].dobj.objType = DO_PROCLANG;
7837 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7838 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7839 AssignDumpId(&planginfo[i].dobj);
7841 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7842 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7843 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7844 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7845 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7846 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7847 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7848 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7849 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7850 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7852 /* Decide whether we want to dump it */
7853 selectDumpableProcLang(&(planginfo[i]), fout);
7855 /* Do not try to dump ACL if no ACL exists. */
7856 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7857 PQgetisnull(res, i, i_initlanacl) &&
7858 PQgetisnull(res, i, i_initrlanacl))
7859 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7864 destroyPQExpBuffer(query);
7871 * get basic information about every cast in the system
7873 * numCasts is set to the number of casts read in
7876 getCasts(Archive *fout, int *numCasts)
7881 PQExpBuffer query = createPQExpBuffer();
7891 /* Make sure we are in proper schema */
7892 selectSourceSchema(fout, "pg_catalog");
7894 if (fout->remoteVersion >= 80400)
7896 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7897 "castsource, casttarget, castfunc, castcontext, "
7899 "FROM pg_cast ORDER BY 3,4");
7903 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7904 "castsource, casttarget, castfunc, castcontext, "
7905 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7906 "FROM pg_cast ORDER BY 3,4");
7909 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7911 ntups = PQntuples(res);
7915 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7917 i_tableoid = PQfnumber(res, "tableoid");
7918 i_oid = PQfnumber(res, "oid");
7919 i_castsource = PQfnumber(res, "castsource");
7920 i_casttarget = PQfnumber(res, "casttarget");
7921 i_castfunc = PQfnumber(res, "castfunc");
7922 i_castcontext = PQfnumber(res, "castcontext");
7923 i_castmethod = PQfnumber(res, "castmethod");
7925 for (i = 0; i < ntups; i++)
7927 PQExpBufferData namebuf;
7928 TypeInfo *sTypeInfo;
7929 TypeInfo *tTypeInfo;
7931 castinfo[i].dobj.objType = DO_CAST;
7932 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7933 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7934 AssignDumpId(&castinfo[i].dobj);
7935 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7936 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7937 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7938 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7939 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7942 * Try to name cast as concatenation of typnames. This is only used
7943 * for purposes of sorting. If we fail to find either type, the name
7944 * will be an empty string.
7946 initPQExpBuffer(&namebuf);
7947 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7948 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7949 if (sTypeInfo && tTypeInfo)
7950 appendPQExpBuffer(&namebuf, "%s %s",
7951 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7952 castinfo[i].dobj.name = namebuf.data;
7954 /* Decide whether we want to dump it */
7955 selectDumpableCast(&(castinfo[i]), fout);
7957 /* Casts do not currently have ACLs. */
7958 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7963 destroyPQExpBuffer(query);
7969 get_language_name(Archive *fout, Oid langid)
7975 query = createPQExpBuffer();
7976 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7977 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7978 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7979 destroyPQExpBuffer(query);
7987 * get basic information about every transform in the system
7989 * numTransforms is set to the number of transforms read in
7992 getTransforms(Archive *fout, int *numTransforms)
7998 TransformInfo *transforminfo;
8006 /* Transforms didn't exist pre-9.5 */
8007 if (fout->remoteVersion < 90500)
8013 query = createPQExpBuffer();
8015 /* Make sure we are in proper schema */
8016 selectSourceSchema(fout, "pg_catalog");
8018 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8019 "trftype, trflang, trffromsql::oid, trftosql::oid "
8020 "FROM pg_transform "
8023 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8025 ntups = PQntuples(res);
8027 *numTransforms = ntups;
8029 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8031 i_tableoid = PQfnumber(res, "tableoid");
8032 i_oid = PQfnumber(res, "oid");
8033 i_trftype = PQfnumber(res, "trftype");
8034 i_trflang = PQfnumber(res, "trflang");
8035 i_trffromsql = PQfnumber(res, "trffromsql");
8036 i_trftosql = PQfnumber(res, "trftosql");
8038 for (i = 0; i < ntups; i++)
8040 PQExpBufferData namebuf;
8044 transforminfo[i].dobj.objType = DO_TRANSFORM;
8045 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8046 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8047 AssignDumpId(&transforminfo[i].dobj);
8048 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8049 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8050 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8051 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8054 * Try to name transform as concatenation of type and language name.
8055 * This is only used for purposes of sorting. If we fail to find
8056 * either, the name will be an empty string.
8058 initPQExpBuffer(&namebuf);
8059 typeInfo = findTypeByOid(transforminfo[i].trftype);
8060 lanname = get_language_name(fout, transforminfo[i].trflang);
8061 if (typeInfo && lanname)
8062 appendPQExpBuffer(&namebuf, "%s %s",
8063 typeInfo->dobj.name, lanname);
8064 transforminfo[i].dobj.name = namebuf.data;
8067 /* Decide whether we want to dump it */
8068 selectDumpableObject(&(transforminfo[i].dobj), fout);
8073 destroyPQExpBuffer(query);
8075 return transforminfo;
8080 * for each interesting table, read info about its attributes
8081 * (names, types, default values, CHECK constraints, etc)
8083 * This is implemented in a very inefficient way right now, looping
8084 * through the tblinfo and doing a join per table to find the attrs and their
8085 * types. However, because we want type names and so forth to be named
8086 * relative to the schema of each table, we couldn't do it in just one
8087 * query. (Maybe one query per schema?)
8092 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8094 DumpOptions *dopt = fout->dopt;
8097 PQExpBuffer q = createPQExpBuffer();
8102 int i_attstattarget;
8114 int i_attfdwoptions;
8119 for (i = 0; i < numTables; i++)
8121 TableInfo *tbinfo = &tblinfo[i];
8123 /* Don't bother to collect info for sequences */
8124 if (tbinfo->relkind == RELKIND_SEQUENCE)
8127 /* Don't bother with uninteresting tables, either */
8128 if (!tbinfo->interesting)
8132 * Make sure we are in proper schema for this table; this allows
8133 * correct retrieval of formatted type names and default exprs
8135 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
8137 /* find all the user attributes and their types */
8140 * we must read the attribute names in attribute number order! because
8141 * we will use the attnum to index into the attnames array later.
8144 write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8145 tbinfo->dobj.namespace->dobj.name,
8148 resetPQExpBuffer(q);
8150 if (fout->remoteVersion >= 100000)
8153 * attidentity is new in version 10.
8155 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8156 "a.attstattarget, a.attstorage, t.typstorage, "
8157 "a.attnotnull, a.atthasdef, a.attisdropped, "
8158 "a.attlen, a.attalign, a.attislocal, "
8159 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8160 "array_to_string(a.attoptions, ', ') AS attoptions, "
8161 "CASE WHEN a.attcollation <> t.typcollation "
8162 "THEN a.attcollation ELSE 0 END AS attcollation, "
8164 "pg_catalog.array_to_string(ARRAY("
8165 "SELECT pg_catalog.quote_ident(option_name) || "
8166 "' ' || pg_catalog.quote_literal(option_value) "
8167 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8168 "ORDER BY option_name"
8169 "), E',\n ') 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 >= 90200)
8180 * attfdwoptions is new in 9.2.
8182 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8183 "a.attstattarget, a.attstorage, t.typstorage, "
8184 "a.attnotnull, a.atthasdef, a.attisdropped, "
8185 "a.attlen, a.attalign, a.attislocal, "
8186 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8187 "array_to_string(a.attoptions, ', ') AS attoptions, "
8188 "CASE WHEN a.attcollation <> t.typcollation "
8189 "THEN a.attcollation ELSE 0 END AS attcollation, "
8190 "pg_catalog.array_to_string(ARRAY("
8191 "SELECT pg_catalog.quote_ident(option_name) || "
8192 "' ' || pg_catalog.quote_literal(option_value) "
8193 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8194 "ORDER BY option_name"
8195 "), E',\n ') AS attfdwoptions "
8196 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8197 "ON a.atttypid = t.oid "
8198 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8199 "AND a.attnum > 0::pg_catalog.int2 "
8200 "ORDER BY a.attnum",
8201 tbinfo->dobj.catId.oid);
8203 else if (fout->remoteVersion >= 90100)
8206 * attcollation is new in 9.1. Since we only want to dump COLLATE
8207 * clauses for attributes whose collation is different from their
8208 * type's default, we use a CASE here to suppress uninteresting
8209 * attcollations cheaply.
8211 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8212 "a.attstattarget, a.attstorage, t.typstorage, "
8213 "a.attnotnull, a.atthasdef, a.attisdropped, "
8214 "a.attlen, a.attalign, a.attislocal, "
8215 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8216 "array_to_string(a.attoptions, ', ') AS attoptions, "
8217 "CASE WHEN a.attcollation <> t.typcollation "
8218 "THEN a.attcollation ELSE 0 END AS attcollation, "
8219 "NULL AS attfdwoptions "
8220 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8221 "ON a.atttypid = t.oid "
8222 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8223 "AND a.attnum > 0::pg_catalog.int2 "
8224 "ORDER BY a.attnum",
8225 tbinfo->dobj.catId.oid);
8227 else if (fout->remoteVersion >= 90000)
8229 /* attoptions is new in 9.0 */
8230 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8231 "a.attstattarget, a.attstorage, t.typstorage, "
8232 "a.attnotnull, a.atthasdef, a.attisdropped, "
8233 "a.attlen, a.attalign, a.attislocal, "
8234 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8235 "array_to_string(a.attoptions, ', ') AS attoptions, "
8236 "0 AS attcollation, "
8237 "NULL AS attfdwoptions "
8238 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8239 "ON a.atttypid = t.oid "
8240 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8241 "AND a.attnum > 0::pg_catalog.int2 "
8242 "ORDER BY a.attnum",
8243 tbinfo->dobj.catId.oid);
8247 /* need left join here to not fail on dropped columns ... */
8248 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8249 "a.attstattarget, a.attstorage, t.typstorage, "
8250 "a.attnotnull, a.atthasdef, a.attisdropped, "
8251 "a.attlen, a.attalign, a.attislocal, "
8252 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8253 "'' AS attoptions, 0 AS attcollation, "
8254 "NULL AS attfdwoptions "
8255 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8256 "ON a.atttypid = t.oid "
8257 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8258 "AND a.attnum > 0::pg_catalog.int2 "
8259 "ORDER BY a.attnum",
8260 tbinfo->dobj.catId.oid);
8263 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8265 ntups = PQntuples(res);
8267 i_attnum = PQfnumber(res, "attnum");
8268 i_attname = PQfnumber(res, "attname");
8269 i_atttypname = PQfnumber(res, "atttypname");
8270 i_atttypmod = PQfnumber(res, "atttypmod");
8271 i_attstattarget = PQfnumber(res, "attstattarget");
8272 i_attstorage = PQfnumber(res, "attstorage");
8273 i_typstorage = PQfnumber(res, "typstorage");
8274 i_attnotnull = PQfnumber(res, "attnotnull");
8275 i_atthasdef = PQfnumber(res, "atthasdef");
8276 i_attidentity = PQfnumber(res, "attidentity");
8277 i_attisdropped = PQfnumber(res, "attisdropped");
8278 i_attlen = PQfnumber(res, "attlen");
8279 i_attalign = PQfnumber(res, "attalign");
8280 i_attislocal = PQfnumber(res, "attislocal");
8281 i_attoptions = PQfnumber(res, "attoptions");
8282 i_attcollation = PQfnumber(res, "attcollation");
8283 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8285 tbinfo->numatts = ntups;
8286 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8287 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8288 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8289 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8290 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8291 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8292 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8293 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8294 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8295 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8296 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8297 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8298 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8299 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8300 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8301 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8302 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8303 hasdefaults = false;
8305 for (j = 0; j < ntups; j++)
8307 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8309 "invalid column numbering in table \"%s\"\n",
8311 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8312 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8313 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8314 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8315 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8316 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8317 tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8318 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8319 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8320 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8321 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8322 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8323 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8324 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8325 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8326 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8327 tbinfo->attrdefs[j] = NULL; /* fix below */
8328 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8330 /* these flags will be set in flagInhAttrs() */
8331 tbinfo->inhNotNull[j] = false;
8337 * Get info about column defaults
8341 AttrDefInfo *attrdefs;
8345 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8346 tbinfo->dobj.namespace->dobj.name,
8349 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8350 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8351 "FROM pg_catalog.pg_attrdef "
8352 "WHERE adrelid = '%u'::pg_catalog.oid",
8353 tbinfo->dobj.catId.oid);
8355 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8357 numDefaults = PQntuples(res);
8358 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8360 for (j = 0; j < numDefaults; j++)
8364 adnum = atoi(PQgetvalue(res, j, 2));
8366 if (adnum <= 0 || adnum > ntups)
8368 "invalid adnum value %d for table \"%s\"\n",
8369 adnum, tbinfo->dobj.name);
8372 * dropped columns shouldn't have defaults, but just in case,
8375 if (tbinfo->attisdropped[adnum - 1])
8378 attrdefs[j].dobj.objType = DO_ATTRDEF;
8379 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8380 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8381 AssignDumpId(&attrdefs[j].dobj);
8382 attrdefs[j].adtable = tbinfo;
8383 attrdefs[j].adnum = adnum;
8384 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8386 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8387 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8389 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8392 * Defaults on a VIEW must always be dumped as separate ALTER
8393 * TABLE commands. Defaults on regular tables are dumped as
8394 * part of the CREATE TABLE if possible, which it won't be if
8395 * the column is not going to be emitted explicitly.
8397 if (tbinfo->relkind == RELKIND_VIEW)
8399 attrdefs[j].separate = true;
8401 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8403 /* column will be suppressed, print default separately */
8404 attrdefs[j].separate = true;
8408 attrdefs[j].separate = false;
8411 * Mark the default as needing to appear before the table,
8412 * so that any dependencies it has must be emitted before
8413 * the CREATE TABLE. If this is not possible, we'll
8414 * change to "separate" mode while sorting dependencies.
8416 addObjectDependency(&tbinfo->dobj,
8417 attrdefs[j].dobj.dumpId);
8420 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8426 * Get info about table CHECK constraints
8428 if (tbinfo->ncheck > 0)
8430 ConstraintInfo *constrs;
8434 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8435 tbinfo->dobj.namespace->dobj.name,
8438 resetPQExpBuffer(q);
8439 if (fout->remoteVersion >= 90200)
8442 * convalidated is new in 9.2 (actually, it is there in 9.1,
8443 * but it wasn't ever false for check constraints until 9.2).
8445 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8446 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8447 "conislocal, convalidated "
8448 "FROM pg_catalog.pg_constraint "
8449 "WHERE conrelid = '%u'::pg_catalog.oid "
8450 " AND contype = 'c' "
8452 tbinfo->dobj.catId.oid);
8454 else if (fout->remoteVersion >= 80400)
8456 /* conislocal is new in 8.4 */
8457 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8458 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8459 "conislocal, true AS convalidated "
8460 "FROM pg_catalog.pg_constraint "
8461 "WHERE conrelid = '%u'::pg_catalog.oid "
8462 " AND contype = 'c' "
8464 tbinfo->dobj.catId.oid);
8468 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8469 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8470 "true AS conislocal, true AS convalidated "
8471 "FROM pg_catalog.pg_constraint "
8472 "WHERE conrelid = '%u'::pg_catalog.oid "
8473 " AND contype = 'c' "
8475 tbinfo->dobj.catId.oid);
8478 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8480 numConstrs = PQntuples(res);
8481 if (numConstrs != tbinfo->ncheck)
8483 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8484 "expected %d check constraints on table \"%s\" but found %d\n",
8486 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8487 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8491 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8492 tbinfo->checkexprs = constrs;
8494 for (j = 0; j < numConstrs; j++)
8496 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8498 constrs[j].dobj.objType = DO_CONSTRAINT;
8499 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8500 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8501 AssignDumpId(&constrs[j].dobj);
8502 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8503 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8504 constrs[j].contable = tbinfo;
8505 constrs[j].condomain = NULL;
8506 constrs[j].contype = 'c';
8507 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8508 constrs[j].confrelid = InvalidOid;
8509 constrs[j].conindex = 0;
8510 constrs[j].condeferrable = false;
8511 constrs[j].condeferred = false;
8512 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8515 * An unvalidated constraint needs to be dumped separately, so
8516 * that potentially-violating existing data is loaded before
8519 constrs[j].separate = !validated;
8521 constrs[j].dobj.dump = tbinfo->dobj.dump;
8524 * Mark the constraint as needing to appear before the table
8525 * --- this is so that any other dependencies of the
8526 * constraint will be emitted before we try to create the
8527 * table. If the constraint is to be dumped separately, it
8528 * will be dumped after data is loaded anyway, so don't do it.
8529 * (There's an automatic dependency in the opposite direction
8530 * anyway, so don't need to add one manually here.)
8532 if (!constrs[j].separate)
8533 addObjectDependency(&tbinfo->dobj,
8534 constrs[j].dobj.dumpId);
8537 * If the constraint is inherited, this will be detected later
8538 * (in pre-8.4 databases). We also detect later if the
8539 * constraint must be split out from the table definition.
8546 destroyPQExpBuffer(q);
8550 * Test whether a column should be printed as part of table's CREATE TABLE.
8551 * Column number is zero-based.
8553 * Normally this is always true, but it's false for dropped columns, as well
8554 * as those that were inherited without any local definition. (If we print
8555 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8556 * However, in binary_upgrade mode, we must print all such columns anyway and
8557 * fix the attislocal/attisdropped state later, so as to keep control of the
8558 * physical column order.
8560 * This function exists because there are scattered nonobvious places that
8561 * must be kept in sync with this decision.
8564 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8566 if (dopt->binary_upgrade)
8568 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8574 * read all text search parsers in the system catalogs and return them
8575 * in the TSParserInfo* structure
8577 * numTSParsers is set to the number of parsers read in
8580 getTSParsers(Archive *fout, int *numTSParsers)
8586 TSParserInfo *prsinfo;
8597 /* Before 8.3, there is no built-in text search support */
8598 if (fout->remoteVersion < 80300)
8604 query = createPQExpBuffer();
8607 * find all text search objects, including builtin ones; we filter out
8608 * system-defined objects at dump-out time.
8611 /* Make sure we are in proper schema */
8612 selectSourceSchema(fout, "pg_catalog");
8614 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8615 "prsstart::oid, prstoken::oid, "
8616 "prsend::oid, prsheadline::oid, prslextype::oid "
8617 "FROM pg_ts_parser");
8619 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8621 ntups = PQntuples(res);
8622 *numTSParsers = ntups;
8624 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8626 i_tableoid = PQfnumber(res, "tableoid");
8627 i_oid = PQfnumber(res, "oid");
8628 i_prsname = PQfnumber(res, "prsname");
8629 i_prsnamespace = PQfnumber(res, "prsnamespace");
8630 i_prsstart = PQfnumber(res, "prsstart");
8631 i_prstoken = PQfnumber(res, "prstoken");
8632 i_prsend = PQfnumber(res, "prsend");
8633 i_prsheadline = PQfnumber(res, "prsheadline");
8634 i_prslextype = PQfnumber(res, "prslextype");
8636 for (i = 0; i < ntups; i++)
8638 prsinfo[i].dobj.objType = DO_TSPARSER;
8639 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8640 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8641 AssignDumpId(&prsinfo[i].dobj);
8642 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8643 prsinfo[i].dobj.namespace =
8645 atooid(PQgetvalue(res, i, i_prsnamespace)));
8646 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8647 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8648 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8649 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8650 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8652 /* Decide whether we want to dump it */
8653 selectDumpableObject(&(prsinfo[i].dobj), fout);
8655 /* Text Search Parsers do not currently have ACLs. */
8656 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8661 destroyPQExpBuffer(query);
8667 * getTSDictionaries:
8668 * read all text search dictionaries in the system catalogs and return them
8669 * in the TSDictInfo* structure
8671 * numTSDicts is set to the number of dictionaries read in
8674 getTSDictionaries(Archive *fout, int *numTSDicts)
8680 TSDictInfo *dictinfo;
8684 int i_dictnamespace;
8687 int i_dictinitoption;
8689 /* Before 8.3, there is no built-in text search support */
8690 if (fout->remoteVersion < 80300)
8696 query = createPQExpBuffer();
8698 /* Make sure we are in proper schema */
8699 selectSourceSchema(fout, "pg_catalog");
8701 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8702 "dictnamespace, (%s dictowner) AS rolname, "
8703 "dicttemplate, dictinitoption "
8707 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8709 ntups = PQntuples(res);
8710 *numTSDicts = ntups;
8712 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8714 i_tableoid = PQfnumber(res, "tableoid");
8715 i_oid = PQfnumber(res, "oid");
8716 i_dictname = PQfnumber(res, "dictname");
8717 i_dictnamespace = PQfnumber(res, "dictnamespace");
8718 i_rolname = PQfnumber(res, "rolname");
8719 i_dictinitoption = PQfnumber(res, "dictinitoption");
8720 i_dicttemplate = PQfnumber(res, "dicttemplate");
8722 for (i = 0; i < ntups; i++)
8724 dictinfo[i].dobj.objType = DO_TSDICT;
8725 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8726 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8727 AssignDumpId(&dictinfo[i].dobj);
8728 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8729 dictinfo[i].dobj.namespace =
8731 atooid(PQgetvalue(res, i, i_dictnamespace)));
8732 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8733 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8734 if (PQgetisnull(res, i, i_dictinitoption))
8735 dictinfo[i].dictinitoption = NULL;
8737 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8739 /* Decide whether we want to dump it */
8740 selectDumpableObject(&(dictinfo[i].dobj), fout);
8742 /* Text Search Dictionaries do not currently have ACLs. */
8743 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8748 destroyPQExpBuffer(query);
8755 * read all text search templates in the system catalogs and return them
8756 * in the TSTemplateInfo* structure
8758 * numTSTemplates is set to the number of templates read in
8761 getTSTemplates(Archive *fout, int *numTSTemplates)
8767 TSTemplateInfo *tmplinfo;
8771 int i_tmplnamespace;
8775 /* Before 8.3, there is no built-in text search support */
8776 if (fout->remoteVersion < 80300)
8778 *numTSTemplates = 0;
8782 query = createPQExpBuffer();
8784 /* Make sure we are in proper schema */
8785 selectSourceSchema(fout, "pg_catalog");
8787 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8788 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8789 "FROM pg_ts_template");
8791 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8793 ntups = PQntuples(res);
8794 *numTSTemplates = ntups;
8796 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8798 i_tableoid = PQfnumber(res, "tableoid");
8799 i_oid = PQfnumber(res, "oid");
8800 i_tmplname = PQfnumber(res, "tmplname");
8801 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8802 i_tmplinit = PQfnumber(res, "tmplinit");
8803 i_tmpllexize = PQfnumber(res, "tmpllexize");
8805 for (i = 0; i < ntups; i++)
8807 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8808 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8809 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8810 AssignDumpId(&tmplinfo[i].dobj);
8811 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8812 tmplinfo[i].dobj.namespace =
8814 atooid(PQgetvalue(res, i, i_tmplnamespace)));
8815 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8816 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8818 /* Decide whether we want to dump it */
8819 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8821 /* Text Search Templates do not currently have ACLs. */
8822 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8827 destroyPQExpBuffer(query);
8833 * getTSConfigurations:
8834 * read all text search configurations in the system catalogs and return
8835 * them in the TSConfigInfo* structure
8837 * numTSConfigs is set to the number of configurations read in
8840 getTSConfigurations(Archive *fout, int *numTSConfigs)
8846 TSConfigInfo *cfginfo;
8854 /* Before 8.3, there is no built-in text search support */
8855 if (fout->remoteVersion < 80300)
8861 query = createPQExpBuffer();
8863 /* Make sure we are in proper schema */
8864 selectSourceSchema(fout, "pg_catalog");
8866 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8867 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8868 "FROM pg_ts_config",
8871 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8873 ntups = PQntuples(res);
8874 *numTSConfigs = ntups;
8876 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8878 i_tableoid = PQfnumber(res, "tableoid");
8879 i_oid = PQfnumber(res, "oid");
8880 i_cfgname = PQfnumber(res, "cfgname");
8881 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8882 i_rolname = PQfnumber(res, "rolname");
8883 i_cfgparser = PQfnumber(res, "cfgparser");
8885 for (i = 0; i < ntups; i++)
8887 cfginfo[i].dobj.objType = DO_TSCONFIG;
8888 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8889 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8890 AssignDumpId(&cfginfo[i].dobj);
8891 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8892 cfginfo[i].dobj.namespace =
8894 atooid(PQgetvalue(res, i, i_cfgnamespace)));
8895 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8896 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8898 /* Decide whether we want to dump it */
8899 selectDumpableObject(&(cfginfo[i].dobj), fout);
8901 /* Text Search Configurations do not currently have ACLs. */
8902 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8907 destroyPQExpBuffer(query);
8913 * getForeignDataWrappers:
8914 * read all foreign-data wrappers in the system catalogs and return
8915 * them in the FdwInfo* structure
8917 * numForeignDataWrappers is set to the number of fdws read in
8920 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8922 DumpOptions *dopt = fout->dopt;
8940 /* Before 8.4, there are no foreign-data wrappers */
8941 if (fout->remoteVersion < 80400)
8943 *numForeignDataWrappers = 0;
8947 query = createPQExpBuffer();
8949 /* Make sure we are in proper schema */
8950 selectSourceSchema(fout, "pg_catalog");
8952 if (fout->remoteVersion >= 90600)
8954 PQExpBuffer acl_subquery = createPQExpBuffer();
8955 PQExpBuffer racl_subquery = createPQExpBuffer();
8956 PQExpBuffer initacl_subquery = createPQExpBuffer();
8957 PQExpBuffer initracl_subquery = createPQExpBuffer();
8959 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8960 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8961 dopt->binary_upgrade);
8963 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8964 "(%s f.fdwowner) AS rolname, "
8965 "f.fdwhandler::pg_catalog.regproc, "
8966 "f.fdwvalidator::pg_catalog.regproc, "
8969 "%s AS initfdwacl, "
8970 "%s AS initrfdwacl, "
8971 "array_to_string(ARRAY("
8972 "SELECT quote_ident(option_name) || ' ' || "
8973 "quote_literal(option_value) "
8974 "FROM pg_options_to_table(f.fdwoptions) "
8975 "ORDER BY option_name"
8976 "), E',\n ') AS fdwoptions "
8977 "FROM pg_foreign_data_wrapper f "
8978 "LEFT JOIN pg_init_privs pip ON "
8979 "(f.oid = pip.objoid "
8980 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8981 "AND pip.objsubid = 0) ",
8984 racl_subquery->data,
8985 initacl_subquery->data,
8986 initracl_subquery->data);
8988 destroyPQExpBuffer(acl_subquery);
8989 destroyPQExpBuffer(racl_subquery);
8990 destroyPQExpBuffer(initacl_subquery);
8991 destroyPQExpBuffer(initracl_subquery);
8993 else if (fout->remoteVersion >= 90100)
8995 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8996 "(%s fdwowner) AS rolname, "
8997 "fdwhandler::pg_catalog.regproc, "
8998 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9000 "NULL as initfdwacl, NULL AS initrfdwacl, "
9001 "array_to_string(ARRAY("
9002 "SELECT quote_ident(option_name) || ' ' || "
9003 "quote_literal(option_value) "
9004 "FROM pg_options_to_table(fdwoptions) "
9005 "ORDER BY option_name"
9006 "), E',\n ') AS fdwoptions "
9007 "FROM pg_foreign_data_wrapper",
9012 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9013 "(%s fdwowner) AS rolname, "
9014 "'-' AS fdwhandler, "
9015 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9017 "NULL as initfdwacl, NULL AS initrfdwacl, "
9018 "array_to_string(ARRAY("
9019 "SELECT quote_ident(option_name) || ' ' || "
9020 "quote_literal(option_value) "
9021 "FROM pg_options_to_table(fdwoptions) "
9022 "ORDER BY option_name"
9023 "), E',\n ') AS fdwoptions "
9024 "FROM pg_foreign_data_wrapper",
9028 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9030 ntups = PQntuples(res);
9031 *numForeignDataWrappers = ntups;
9033 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9035 i_tableoid = PQfnumber(res, "tableoid");
9036 i_oid = PQfnumber(res, "oid");
9037 i_fdwname = PQfnumber(res, "fdwname");
9038 i_rolname = PQfnumber(res, "rolname");
9039 i_fdwhandler = PQfnumber(res, "fdwhandler");
9040 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9041 i_fdwacl = PQfnumber(res, "fdwacl");
9042 i_rfdwacl = PQfnumber(res, "rfdwacl");
9043 i_initfdwacl = PQfnumber(res, "initfdwacl");
9044 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9045 i_fdwoptions = PQfnumber(res, "fdwoptions");
9047 for (i = 0; i < ntups; i++)
9049 fdwinfo[i].dobj.objType = DO_FDW;
9050 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9051 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9052 AssignDumpId(&fdwinfo[i].dobj);
9053 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9054 fdwinfo[i].dobj.namespace = NULL;
9055 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9056 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9057 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9058 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9059 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9060 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9061 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9062 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9064 /* Decide whether we want to dump it */
9065 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9067 /* Do not try to dump ACL if no ACL exists. */
9068 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9069 PQgetisnull(res, i, i_initfdwacl) &&
9070 PQgetisnull(res, i, i_initrfdwacl))
9071 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9076 destroyPQExpBuffer(query);
9082 * getForeignServers:
9083 * read all foreign servers in the system catalogs and return
9084 * them in the ForeignServerInfo * structure
9086 * numForeignServers is set to the number of servers read in
9089 getForeignServers(Archive *fout, int *numForeignServers)
9091 DumpOptions *dopt = fout->dopt;
9096 ForeignServerInfo *srvinfo;
9110 /* Before 8.4, there are no foreign servers */
9111 if (fout->remoteVersion < 80400)
9113 *numForeignServers = 0;
9117 query = createPQExpBuffer();
9119 /* Make sure we are in proper schema */
9120 selectSourceSchema(fout, "pg_catalog");
9122 if (fout->remoteVersion >= 90600)
9124 PQExpBuffer acl_subquery = createPQExpBuffer();
9125 PQExpBuffer racl_subquery = createPQExpBuffer();
9126 PQExpBuffer initacl_subquery = createPQExpBuffer();
9127 PQExpBuffer initracl_subquery = createPQExpBuffer();
9129 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9130 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9131 dopt->binary_upgrade);
9133 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9134 "(%s f.srvowner) AS rolname, "
9135 "f.srvfdw, f.srvtype, f.srvversion, "
9138 "%s AS initsrvacl, "
9139 "%s AS initrsrvacl, "
9140 "array_to_string(ARRAY("
9141 "SELECT quote_ident(option_name) || ' ' || "
9142 "quote_literal(option_value) "
9143 "FROM pg_options_to_table(f.srvoptions) "
9144 "ORDER BY option_name"
9145 "), E',\n ') AS srvoptions "
9146 "FROM pg_foreign_server f "
9147 "LEFT JOIN pg_init_privs pip "
9148 "ON (f.oid = pip.objoid "
9149 "AND pip.classoid = 'pg_foreign_server'::regclass "
9150 "AND pip.objsubid = 0) ",
9153 racl_subquery->data,
9154 initacl_subquery->data,
9155 initracl_subquery->data);
9157 destroyPQExpBuffer(acl_subquery);
9158 destroyPQExpBuffer(racl_subquery);
9159 destroyPQExpBuffer(initacl_subquery);
9160 destroyPQExpBuffer(initracl_subquery);
9164 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9165 "(%s srvowner) AS rolname, "
9166 "srvfdw, srvtype, srvversion, srvacl, "
9168 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9169 "array_to_string(ARRAY("
9170 "SELECT quote_ident(option_name) || ' ' || "
9171 "quote_literal(option_value) "
9172 "FROM pg_options_to_table(srvoptions) "
9173 "ORDER BY option_name"
9174 "), E',\n ') AS srvoptions "
9175 "FROM pg_foreign_server",
9179 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9181 ntups = PQntuples(res);
9182 *numForeignServers = ntups;
9184 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9186 i_tableoid = PQfnumber(res, "tableoid");
9187 i_oid = PQfnumber(res, "oid");
9188 i_srvname = PQfnumber(res, "srvname");
9189 i_rolname = PQfnumber(res, "rolname");
9190 i_srvfdw = PQfnumber(res, "srvfdw");
9191 i_srvtype = PQfnumber(res, "srvtype");
9192 i_srvversion = PQfnumber(res, "srvversion");
9193 i_srvacl = PQfnumber(res, "srvacl");
9194 i_rsrvacl = PQfnumber(res, "rsrvacl");
9195 i_initsrvacl = PQfnumber(res, "initsrvacl");
9196 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9197 i_srvoptions = PQfnumber(res, "srvoptions");
9199 for (i = 0; i < ntups; i++)
9201 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9202 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9203 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9204 AssignDumpId(&srvinfo[i].dobj);
9205 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9206 srvinfo[i].dobj.namespace = NULL;
9207 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9208 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9209 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9210 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9211 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9212 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9213 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9214 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9215 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9217 /* Decide whether we want to dump it */
9218 selectDumpableObject(&(srvinfo[i].dobj), fout);
9220 /* Do not try to dump ACL if no ACL exists. */
9221 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9222 PQgetisnull(res, i, i_initsrvacl) &&
9223 PQgetisnull(res, i, i_initrsrvacl))
9224 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9229 destroyPQExpBuffer(query);
9236 * read all default ACL information in the system catalogs and return
9237 * them in the DefaultACLInfo structure
9239 * numDefaultACLs is set to the number of ACLs read in
9242 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9244 DumpOptions *dopt = fout->dopt;
9245 DefaultACLInfo *daclinfo;
9251 int i_defaclnamespace;
9252 int i_defaclobjtype;
9255 int i_initdefaclacl;
9256 int i_initrdefaclacl;
9260 if (fout->remoteVersion < 90000)
9262 *numDefaultACLs = 0;
9266 query = createPQExpBuffer();
9268 /* Make sure we are in proper schema */
9269 selectSourceSchema(fout, "pg_catalog");
9271 if (fout->remoteVersion >= 90600)
9273 PQExpBuffer acl_subquery = createPQExpBuffer();
9274 PQExpBuffer racl_subquery = createPQExpBuffer();
9275 PQExpBuffer initacl_subquery = createPQExpBuffer();
9276 PQExpBuffer initracl_subquery = createPQExpBuffer();
9278 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9279 initracl_subquery, "defaclacl", "defaclrole",
9280 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9281 dopt->binary_upgrade);
9283 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9284 "(%s d.defaclrole) AS defaclrole, "
9285 "d.defaclnamespace, "
9288 "%s AS rdefaclacl, "
9289 "%s AS initdefaclacl, "
9290 "%s AS initrdefaclacl "
9291 "FROM pg_default_acl d "
9292 "LEFT JOIN pg_init_privs pip ON "
9293 "(d.oid = pip.objoid "
9294 "AND pip.classoid = 'pg_default_acl'::regclass "
9295 "AND pip.objsubid = 0) ",
9298 racl_subquery->data,
9299 initacl_subquery->data,
9300 initracl_subquery->data);
9304 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9305 "(%s defaclrole) AS defaclrole, "
9309 "NULL AS rdefaclacl, "
9310 "NULL AS initdefaclacl, "
9311 "NULL AS initrdefaclacl "
9312 "FROM pg_default_acl",
9316 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9318 ntups = PQntuples(res);
9319 *numDefaultACLs = ntups;
9321 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9323 i_oid = PQfnumber(res, "oid");
9324 i_tableoid = PQfnumber(res, "tableoid");
9325 i_defaclrole = PQfnumber(res, "defaclrole");
9326 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9327 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9328 i_defaclacl = PQfnumber(res, "defaclacl");
9329 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9330 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9331 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9333 for (i = 0; i < ntups; i++)
9335 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9337 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9338 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9339 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9340 AssignDumpId(&daclinfo[i].dobj);
9341 /* cheesy ... is it worth coming up with a better object name? */
9342 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9344 if (nspid != InvalidOid)
9345 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9347 daclinfo[i].dobj.namespace = NULL;
9349 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9350 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9351 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9352 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9353 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9354 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9356 /* Decide whether we want to dump it */
9357 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9362 destroyPQExpBuffer(query);
9370 * This routine is used to dump any comments associated with the
9371 * object handed to this routine. The routine takes a constant character
9372 * string for the target part of the comment-creation command, plus
9373 * the namespace and owner of the object (for labeling the ArchiveEntry),
9374 * plus catalog ID and subid which are the lookup key for pg_description,
9375 * plus the dump ID for the object (for setting a dependency).
9376 * If a matching pg_description entry is found, it is dumped.
9378 * Note: although this routine takes a dumpId for dependency purposes,
9379 * that purpose is just to mark the dependency in the emitted dump file
9380 * for possible future use by pg_restore. We do NOT use it for determining
9381 * ordering of the comment in the dump file, because this routine is called
9382 * after dependency sorting occurs. This routine should be called just after
9383 * calling ArchiveEntry() for the specified object.
9386 dumpComment(Archive *fout, const char *target,
9387 const char *namespace, const char *owner,
9388 CatalogId catalogId, int subid, DumpId dumpId)
9390 DumpOptions *dopt = fout->dopt;
9391 CommentItem *comments;
9394 /* do nothing, if --no-comments is supplied */
9395 if (dopt->no_comments)
9398 /* Comments are schema not data ... except blob comments are data */
9399 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
9406 /* We do dump blob comments in binary-upgrade mode */
9407 if (dopt->schemaOnly && !dopt->binary_upgrade)
9411 /* Search for comments associated with catalogId, using table */
9412 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9415 /* Is there one matching the subid? */
9416 while (ncomments > 0)
9418 if (comments->objsubid == subid)
9424 /* If a comment exists, build COMMENT ON statement */
9427 PQExpBuffer query = createPQExpBuffer();
9429 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
9430 appendStringLiteralAH(query, comments->descr, fout);
9431 appendPQExpBufferStr(query, ";\n");
9434 * We mark comments as SECTION_NONE because they really belong in the
9435 * same section as their parent, whether that is pre-data or
9438 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9439 target, namespace, NULL, owner,
9440 false, "COMMENT", SECTION_NONE,
9441 query->data, "", NULL,
9445 destroyPQExpBuffer(query);
9450 * dumpTableComment --
9452 * As above, but dump comments for both the specified table (or view)
9456 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9457 const char *reltypename)
9459 DumpOptions *dopt = fout->dopt;
9460 CommentItem *comments;
9465 /* do nothing, if --no-comments is supplied */
9466 if (dopt->no_comments)
9469 /* Comments are SCHEMA not data */
9473 /* Search for comments associated with relation, using table */
9474 ncomments = findComments(fout,
9475 tbinfo->dobj.catId.tableoid,
9476 tbinfo->dobj.catId.oid,
9479 /* If comments exist, build COMMENT ON statements */
9483 query = createPQExpBuffer();
9484 target = createPQExpBuffer();
9486 while (ncomments > 0)
9488 const char *descr = comments->descr;
9489 int objsubid = comments->objsubid;
9493 resetPQExpBuffer(target);
9494 appendPQExpBuffer(target, "%s %s", reltypename,
9495 fmtId(tbinfo->dobj.name));
9497 resetPQExpBuffer(query);
9498 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9499 appendStringLiteralAH(query, descr, fout);
9500 appendPQExpBufferStr(query, ";\n");
9502 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9504 tbinfo->dobj.namespace->dobj.name,
9505 NULL, tbinfo->rolname,
9506 false, "COMMENT", SECTION_NONE,
9507 query->data, "", NULL,
9508 &(tbinfo->dobj.dumpId), 1,
9511 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9513 resetPQExpBuffer(target);
9514 appendPQExpBuffer(target, "COLUMN %s.",
9515 fmtId(tbinfo->dobj.name));
9516 appendPQExpBufferStr(target, fmtId(tbinfo->attnames[objsubid - 1]));
9518 resetPQExpBuffer(query);
9519 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9520 appendStringLiteralAH(query, descr, fout);
9521 appendPQExpBufferStr(query, ";\n");
9523 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9525 tbinfo->dobj.namespace->dobj.name,
9526 NULL, tbinfo->rolname,
9527 false, "COMMENT", SECTION_NONE,
9528 query->data, "", NULL,
9529 &(tbinfo->dobj.dumpId), 1,
9537 destroyPQExpBuffer(query);
9538 destroyPQExpBuffer(target);
9544 * Find the comment(s), if any, associated with the given object. All the
9545 * objsubid values associated with the given classoid/objoid are found with
9549 findComments(Archive *fout, Oid classoid, Oid objoid,
9550 CommentItem **items)
9552 /* static storage for table of comments */
9553 static CommentItem *comments = NULL;
9554 static int ncomments = -1;
9556 CommentItem *middle = NULL;
9561 /* Get comments if we didn't already */
9563 ncomments = collectComments(fout, &comments);
9566 * Do binary search to find some item matching the object.
9569 high = &comments[ncomments - 1];
9572 middle = low + (high - low) / 2;
9574 if (classoid < middle->classoid)
9576 else if (classoid > middle->classoid)
9578 else if (objoid < middle->objoid)
9580 else if (objoid > middle->objoid)
9583 break; /* found a match */
9586 if (low > high) /* no matches */
9593 * Now determine how many items match the object. The search loop
9594 * invariant still holds: only items between low and high inclusive could
9598 while (middle > low)
9600 if (classoid != middle[-1].classoid ||
9601 objoid != middle[-1].objoid)
9610 while (middle <= high)
9612 if (classoid != middle->classoid ||
9613 objoid != middle->objoid)
9623 * collectComments --
9625 * Construct a table of all comments available for database objects.
9626 * We used to do per-object queries for the comments, but it's much faster
9627 * to pull them all over at once, and on most databases the memory cost
9630 * The table is sorted by classoid/objid/objsubid for speed in lookup.
9633 collectComments(Archive *fout, CommentItem **items)
9643 CommentItem *comments;
9646 * Note we do NOT change source schema here; preserve the caller's
9650 query = createPQExpBuffer();
9652 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9653 "FROM pg_catalog.pg_description "
9654 "ORDER BY classoid, objoid, objsubid");
9656 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9658 /* Construct lookup table containing OIDs in numeric form */
9660 i_description = PQfnumber(res, "description");
9661 i_classoid = PQfnumber(res, "classoid");
9662 i_objoid = PQfnumber(res, "objoid");
9663 i_objsubid = PQfnumber(res, "objsubid");
9665 ntups = PQntuples(res);
9667 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9669 for (i = 0; i < ntups; i++)
9671 comments[i].descr = PQgetvalue(res, i, i_description);
9672 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9673 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9674 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9677 /* Do NOT free the PGresult since we are keeping pointers into it */
9678 destroyPQExpBuffer(query);
9685 * dumpDumpableObject
9687 * This routine and its subsidiaries are responsible for creating
9688 * ArchiveEntries (TOC objects) for each object to be dumped.
9691 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9693 switch (dobj->objType)
9696 dumpNamespace(fout, (NamespaceInfo *) dobj);
9699 dumpExtension(fout, (ExtensionInfo *) dobj);
9702 dumpType(fout, (TypeInfo *) dobj);
9705 dumpShellType(fout, (ShellTypeInfo *) dobj);
9708 dumpFunc(fout, (FuncInfo *) dobj);
9711 dumpAgg(fout, (AggInfo *) dobj);
9714 dumpOpr(fout, (OprInfo *) dobj);
9716 case DO_ACCESS_METHOD:
9717 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9720 dumpOpclass(fout, (OpclassInfo *) dobj);
9723 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9726 dumpCollation(fout, (CollInfo *) dobj);
9729 dumpConversion(fout, (ConvInfo *) dobj);
9732 dumpTable(fout, (TableInfo *) dobj);
9735 dumpAttrDef(fout, (AttrDefInfo *) dobj);
9738 dumpIndex(fout, (IndxInfo *) dobj);
9740 case DO_INDEX_ATTACH:
9741 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9744 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9746 case DO_REFRESH_MATVIEW:
9747 refreshMatViewData(fout, (TableDataInfo *) dobj);
9750 dumpRule(fout, (RuleInfo *) dobj);
9753 dumpTrigger(fout, (TriggerInfo *) dobj);
9755 case DO_EVENT_TRIGGER:
9756 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9759 dumpConstraint(fout, (ConstraintInfo *) dobj);
9761 case DO_FK_CONSTRAINT:
9762 dumpConstraint(fout, (ConstraintInfo *) dobj);
9765 dumpProcLang(fout, (ProcLangInfo *) dobj);
9768 dumpCast(fout, (CastInfo *) dobj);
9771 dumpTransform(fout, (TransformInfo *) dobj);
9773 case DO_SEQUENCE_SET:
9774 dumpSequenceData(fout, (TableDataInfo *) dobj);
9777 dumpTableData(fout, (TableDataInfo *) dobj);
9780 /* table rowtypes and array types are never dumped separately */
9783 dumpTSParser(fout, (TSParserInfo *) dobj);
9786 dumpTSDictionary(fout, (TSDictInfo *) dobj);
9789 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9792 dumpTSConfig(fout, (TSConfigInfo *) dobj);
9795 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9797 case DO_FOREIGN_SERVER:
9798 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9800 case DO_DEFAULT_ACL:
9801 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9804 dumpBlob(fout, (BlobInfo *) dobj);
9807 if (dobj->dump & DUMP_COMPONENT_DATA)
9808 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9809 dobj->name, NULL, NULL, "",
9810 false, "BLOBS", SECTION_DATA,
9816 dumpPolicy(fout, (PolicyInfo *) dobj);
9818 case DO_PUBLICATION:
9819 dumpPublication(fout, (PublicationInfo *) dobj);
9821 case DO_PUBLICATION_REL:
9822 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9824 case DO_SUBSCRIPTION:
9825 dumpSubscription(fout, (SubscriptionInfo *) dobj);
9827 case DO_PRE_DATA_BOUNDARY:
9828 case DO_POST_DATA_BOUNDARY:
9829 /* never dumped, nothing to do */
9836 * writes out to fout the queries to recreate a user-defined namespace
9839 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9841 DumpOptions *dopt = fout->dopt;
9847 /* Skip if not to be dumped */
9848 if (!nspinfo->dobj.dump || dopt->dataOnly)
9851 q = createPQExpBuffer();
9852 delq = createPQExpBuffer();
9853 labelq = createPQExpBuffer();
9855 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9857 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9859 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9861 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
9863 if (dopt->binary_upgrade)
9864 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
9866 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9867 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9871 false, "SCHEMA", SECTION_PRE_DATA,
9872 q->data, delq->data, NULL,
9876 /* Dump Schema Comments and Security Labels */
9877 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9878 dumpComment(fout, labelq->data,
9879 NULL, nspinfo->rolname,
9880 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9882 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9883 dumpSecLabel(fout, labelq->data,
9884 NULL, nspinfo->rolname,
9885 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9887 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9888 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9889 qnspname, NULL, labelq->data, NULL,
9890 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9891 nspinfo->initnspacl, nspinfo->initrnspacl);
9895 destroyPQExpBuffer(q);
9896 destroyPQExpBuffer(delq);
9897 destroyPQExpBuffer(labelq);
9902 * writes out to fout the queries to recreate an extension
9905 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9907 DumpOptions *dopt = fout->dopt;
9913 /* Skip if not to be dumped */
9914 if (!extinfo->dobj.dump || dopt->dataOnly)
9917 q = createPQExpBuffer();
9918 delq = createPQExpBuffer();
9919 labelq = createPQExpBuffer();
9921 qextname = pg_strdup(fmtId(extinfo->dobj.name));
9923 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9925 if (!dopt->binary_upgrade)
9928 * In a regular dump, we simply create the extension, intentionally
9929 * not specifying a version, so that the destination installation's
9930 * default version is used.
9932 * Use of IF NOT EXISTS here is unlike our behavior for other object
9933 * types; but there are various scenarios in which it's convenient to
9934 * manually create the desired extension before restoring, so we
9935 * prefer to allow it to exist already.
9937 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9938 qextname, fmtId(extinfo->namespace));
9943 * In binary-upgrade mode, it's critical to reproduce the state of the
9944 * database exactly, so our procedure is to create an empty extension,
9945 * restore all the contained objects normally, and add them to the
9946 * extension one by one. This function performs just the first of
9947 * those steps. binary_upgrade_extension_member() takes care of
9948 * adding member objects as they're created.
9953 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9956 * We unconditionally create the extension, so we must drop it if it
9957 * exists. This could happen if the user deleted 'plpgsql' and then
9958 * readded it, causing its oid to be greater than g_last_builtin_oid.
9960 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9962 appendPQExpBufferStr(q,
9963 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9964 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9965 appendPQExpBufferStr(q, ", ");
9966 appendStringLiteralAH(q, extinfo->namespace, fout);
9967 appendPQExpBufferStr(q, ", ");
9968 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9969 appendStringLiteralAH(q, extinfo->extversion, fout);
9970 appendPQExpBufferStr(q, ", ");
9973 * Note that we're pushing extconfig (an OID array) back into
9974 * pg_extension exactly as-is. This is OK because pg_class OIDs are
9975 * preserved in binary upgrade.
9977 if (strlen(extinfo->extconfig) > 2)
9978 appendStringLiteralAH(q, extinfo->extconfig, fout);
9980 appendPQExpBufferStr(q, "NULL");
9981 appendPQExpBufferStr(q, ", ");
9982 if (strlen(extinfo->extcondition) > 2)
9983 appendStringLiteralAH(q, extinfo->extcondition, fout);
9985 appendPQExpBufferStr(q, "NULL");
9986 appendPQExpBufferStr(q, ", ");
9987 appendPQExpBufferStr(q, "ARRAY[");
9989 for (i = 0; i < extinfo->dobj.nDeps; i++)
9991 DumpableObject *extobj;
9993 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9994 if (extobj && extobj->objType == DO_EXTENSION)
9997 appendPQExpBufferChar(q, ',');
9998 appendStringLiteralAH(q, extobj->name, fout);
10001 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10002 appendPQExpBufferStr(q, ");\n");
10005 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
10007 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10008 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10009 extinfo->dobj.name,
10012 false, "EXTENSION", SECTION_PRE_DATA,
10013 q->data, delq->data, NULL,
10017 /* Dump Extension Comments and Security Labels */
10018 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10019 dumpComment(fout, labelq->data,
10021 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10023 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10024 dumpSecLabel(fout, labelq->data,
10026 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10030 destroyPQExpBuffer(q);
10031 destroyPQExpBuffer(delq);
10032 destroyPQExpBuffer(labelq);
10037 * writes out to fout the queries to recreate a user-defined type
10040 dumpType(Archive *fout, TypeInfo *tyinfo)
10042 DumpOptions *dopt = fout->dopt;
10044 /* Skip if not to be dumped */
10045 if (!tyinfo->dobj.dump || dopt->dataOnly)
10048 /* Dump out in proper style */
10049 if (tyinfo->typtype == TYPTYPE_BASE)
10050 dumpBaseType(fout, tyinfo);
10051 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10052 dumpDomain(fout, tyinfo);
10053 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10054 dumpCompositeType(fout, tyinfo);
10055 else if (tyinfo->typtype == TYPTYPE_ENUM)
10056 dumpEnumType(fout, tyinfo);
10057 else if (tyinfo->typtype == TYPTYPE_RANGE)
10058 dumpRangeType(fout, tyinfo);
10059 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10060 dumpUndefinedType(fout, tyinfo);
10062 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10063 tyinfo->dobj.name);
10068 * writes out to fout the queries to recreate a user-defined enum type
10071 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10073 DumpOptions *dopt = fout->dopt;
10074 PQExpBuffer q = createPQExpBuffer();
10075 PQExpBuffer delq = createPQExpBuffer();
10076 PQExpBuffer labelq = createPQExpBuffer();
10077 PQExpBuffer query = createPQExpBuffer();
10085 /* Set proper schema search path */
10086 selectSourceSchema(fout, "pg_catalog");
10088 if (fout->remoteVersion >= 90100)
10089 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10090 "FROM pg_catalog.pg_enum "
10091 "WHERE enumtypid = '%u'"
10092 "ORDER BY enumsortorder",
10093 tyinfo->dobj.catId.oid);
10095 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10096 "FROM pg_catalog.pg_enum "
10097 "WHERE enumtypid = '%u'"
10099 tyinfo->dobj.catId.oid);
10101 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10103 num = PQntuples(res);
10105 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10108 * DROP must be fully qualified in case same name appears in pg_catalog.
10109 * CASCADE shouldn't be required here as for normal types since the I/O
10110 * functions are generic and do not get dropped.
10112 appendPQExpBuffer(delq, "DROP TYPE %s.",
10113 fmtId(tyinfo->dobj.namespace->dobj.name));
10114 appendPQExpBuffer(delq, "%s;\n",
10117 if (dopt->binary_upgrade)
10118 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10119 tyinfo->dobj.catId.oid,
10122 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10125 if (!dopt->binary_upgrade)
10127 /* Labels with server-assigned oids */
10128 for (i = 0; i < num; i++)
10130 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10132 appendPQExpBufferChar(q, ',');
10133 appendPQExpBufferStr(q, "\n ");
10134 appendStringLiteralAH(q, label, fout);
10138 appendPQExpBufferStr(q, "\n);\n");
10140 if (dopt->binary_upgrade)
10142 /* Labels with dump-assigned (preserved) oids */
10143 for (i = 0; i < num; i++)
10145 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10146 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10149 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10150 appendPQExpBuffer(q,
10151 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10153 appendPQExpBuffer(q, "ALTER TYPE %s.",
10154 fmtId(tyinfo->dobj.namespace->dobj.name));
10155 appendPQExpBuffer(q, "%s ADD VALUE ",
10157 appendStringLiteralAH(q, label, fout);
10158 appendPQExpBufferStr(q, ";\n\n");
10162 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10164 if (dopt->binary_upgrade)
10165 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10167 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10168 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10170 tyinfo->dobj.namespace->dobj.name,
10172 tyinfo->rolname, false,
10173 "TYPE", SECTION_PRE_DATA,
10174 q->data, delq->data, NULL,
10178 /* Dump Type Comments and Security Labels */
10179 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10180 dumpComment(fout, labelq->data,
10181 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10182 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10184 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10185 dumpSecLabel(fout, labelq->data,
10186 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10187 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10189 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10190 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10191 qtypname, NULL, labelq->data,
10192 tyinfo->dobj.namespace->dobj.name,
10193 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10194 tyinfo->inittypacl, tyinfo->initrtypacl);
10197 destroyPQExpBuffer(q);
10198 destroyPQExpBuffer(delq);
10199 destroyPQExpBuffer(labelq);
10200 destroyPQExpBuffer(query);
10205 * writes out to fout the queries to recreate a user-defined range type
10208 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10210 DumpOptions *dopt = fout->dopt;
10211 PQExpBuffer q = createPQExpBuffer();
10212 PQExpBuffer delq = createPQExpBuffer();
10213 PQExpBuffer labelq = createPQExpBuffer();
10214 PQExpBuffer query = createPQExpBuffer();
10221 * select appropriate schema to ensure names in CREATE are properly
10224 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10226 appendPQExpBuffer(query,
10227 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10228 "opc.opcname AS opcname, "
10229 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10230 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10232 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10233 " ELSE rngcollation END AS collation, "
10234 "rngcanonical, rngsubdiff "
10235 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10236 " pg_catalog.pg_opclass opc "
10237 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10239 tyinfo->dobj.catId.oid);
10241 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10243 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10246 * DROP must be fully qualified in case same name appears in pg_catalog.
10247 * CASCADE shouldn't be required here as for normal types since the I/O
10248 * functions are generic and do not get dropped.
10250 appendPQExpBuffer(delq, "DROP TYPE %s.",
10251 fmtId(tyinfo->dobj.namespace->dobj.name));
10252 appendPQExpBuffer(delq, "%s;\n",
10255 if (dopt->binary_upgrade)
10256 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10257 tyinfo->dobj.catId.oid,
10260 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10263 appendPQExpBuffer(q, "\n subtype = %s",
10264 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10266 /* print subtype_opclass only if not default for subtype */
10267 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10269 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10270 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10272 /* always schema-qualify, don't try to be smart */
10273 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10275 appendPQExpBufferStr(q, fmtId(opcname));
10278 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10279 if (OidIsValid(collationOid))
10281 CollInfo *coll = findCollationByOid(collationOid);
10285 /* always schema-qualify, don't try to be smart */
10286 appendPQExpBuffer(q, ",\n collation = %s.",
10287 fmtId(coll->dobj.namespace->dobj.name));
10288 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10292 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10293 if (strcmp(procname, "-") != 0)
10294 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10296 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10297 if (strcmp(procname, "-") != 0)
10298 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10300 appendPQExpBufferStr(q, "\n);\n");
10302 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10304 if (dopt->binary_upgrade)
10305 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10307 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10308 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10310 tyinfo->dobj.namespace->dobj.name,
10312 tyinfo->rolname, false,
10313 "TYPE", SECTION_PRE_DATA,
10314 q->data, delq->data, NULL,
10318 /* Dump Type Comments and Security Labels */
10319 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10320 dumpComment(fout, labelq->data,
10321 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10322 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10324 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10325 dumpSecLabel(fout, labelq->data,
10326 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10327 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10329 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10330 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10331 qtypname, NULL, labelq->data,
10332 tyinfo->dobj.namespace->dobj.name,
10333 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10334 tyinfo->inittypacl, tyinfo->initrtypacl);
10337 destroyPQExpBuffer(q);
10338 destroyPQExpBuffer(delq);
10339 destroyPQExpBuffer(labelq);
10340 destroyPQExpBuffer(query);
10344 * dumpUndefinedType
10345 * writes out to fout the queries to recreate a !typisdefined type
10347 * This is a shell type, but we use different terminology to distinguish
10348 * this case from where we have to emit a shell type definition to break
10349 * circular dependencies. An undefined type shouldn't ever have anything
10353 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10355 DumpOptions *dopt = fout->dopt;
10356 PQExpBuffer q = createPQExpBuffer();
10357 PQExpBuffer delq = createPQExpBuffer();
10358 PQExpBuffer labelq = createPQExpBuffer();
10361 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10364 * DROP must be fully qualified in case same name appears in pg_catalog.
10366 appendPQExpBuffer(delq, "DROP TYPE %s.",
10367 fmtId(tyinfo->dobj.namespace->dobj.name));
10368 appendPQExpBuffer(delq, "%s;\n",
10371 if (dopt->binary_upgrade)
10372 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10373 tyinfo->dobj.catId.oid,
10376 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10379 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10381 if (dopt->binary_upgrade)
10382 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10384 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10385 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10387 tyinfo->dobj.namespace->dobj.name,
10389 tyinfo->rolname, false,
10390 "TYPE", SECTION_PRE_DATA,
10391 q->data, delq->data, NULL,
10395 /* Dump Type Comments and Security Labels */
10396 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10397 dumpComment(fout, labelq->data,
10398 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10399 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10401 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10402 dumpSecLabel(fout, labelq->data,
10403 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10404 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10406 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10407 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10408 qtypname, NULL, labelq->data,
10409 tyinfo->dobj.namespace->dobj.name,
10410 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10411 tyinfo->inittypacl, tyinfo->initrtypacl);
10413 destroyPQExpBuffer(q);
10414 destroyPQExpBuffer(delq);
10415 destroyPQExpBuffer(labelq);
10420 * writes out to fout the queries to recreate a user-defined base type
10423 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10425 DumpOptions *dopt = fout->dopt;
10426 PQExpBuffer q = createPQExpBuffer();
10427 PQExpBuffer delq = createPQExpBuffer();
10428 PQExpBuffer labelq = createPQExpBuffer();
10429 PQExpBuffer query = createPQExpBuffer();
10446 char *typispreferred;
10451 char *typcollatable;
10453 bool typdefault_is_literal = false;
10455 /* Set proper schema search path so regproc references list correctly */
10456 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10458 /* Fetch type-specific details */
10459 if (fout->remoteVersion >= 90100)
10461 appendPQExpBuffer(query, "SELECT typlen, "
10462 "typinput, typoutput, typreceive, typsend, "
10463 "typmodin, typmodout, typanalyze, "
10464 "typreceive::pg_catalog.oid AS typreceiveoid, "
10465 "typsend::pg_catalog.oid AS typsendoid, "
10466 "typmodin::pg_catalog.oid AS typmodinoid, "
10467 "typmodout::pg_catalog.oid AS typmodoutoid, "
10468 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10469 "typcategory, typispreferred, "
10470 "typdelim, typbyval, typalign, typstorage, "
10471 "(typcollation <> 0) AS typcollatable, "
10472 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10473 "FROM pg_catalog.pg_type "
10474 "WHERE oid = '%u'::pg_catalog.oid",
10475 tyinfo->dobj.catId.oid);
10477 else if (fout->remoteVersion >= 80400)
10479 appendPQExpBuffer(query, "SELECT typlen, "
10480 "typinput, typoutput, typreceive, typsend, "
10481 "typmodin, typmodout, typanalyze, "
10482 "typreceive::pg_catalog.oid AS typreceiveoid, "
10483 "typsend::pg_catalog.oid AS typsendoid, "
10484 "typmodin::pg_catalog.oid AS typmodinoid, "
10485 "typmodout::pg_catalog.oid AS typmodoutoid, "
10486 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10487 "typcategory, typispreferred, "
10488 "typdelim, typbyval, typalign, typstorage, "
10489 "false AS typcollatable, "
10490 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10491 "FROM pg_catalog.pg_type "
10492 "WHERE oid = '%u'::pg_catalog.oid",
10493 tyinfo->dobj.catId.oid);
10495 else if (fout->remoteVersion >= 80300)
10497 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10498 appendPQExpBuffer(query, "SELECT typlen, "
10499 "typinput, typoutput, typreceive, typsend, "
10500 "typmodin, typmodout, typanalyze, "
10501 "typreceive::pg_catalog.oid AS typreceiveoid, "
10502 "typsend::pg_catalog.oid AS typsendoid, "
10503 "typmodin::pg_catalog.oid AS typmodinoid, "
10504 "typmodout::pg_catalog.oid AS typmodoutoid, "
10505 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10506 "'U' AS typcategory, false AS typispreferred, "
10507 "typdelim, typbyval, typalign, typstorage, "
10508 "false AS typcollatable, "
10509 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10510 "FROM pg_catalog.pg_type "
10511 "WHERE oid = '%u'::pg_catalog.oid",
10512 tyinfo->dobj.catId.oid);
10516 appendPQExpBuffer(query, "SELECT typlen, "
10517 "typinput, typoutput, typreceive, typsend, "
10518 "'-' AS typmodin, '-' AS typmodout, "
10520 "typreceive::pg_catalog.oid AS typreceiveoid, "
10521 "typsend::pg_catalog.oid AS typsendoid, "
10522 "0 AS typmodinoid, 0 AS typmodoutoid, "
10523 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10524 "'U' AS typcategory, false AS typispreferred, "
10525 "typdelim, typbyval, typalign, typstorage, "
10526 "false AS typcollatable, "
10527 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10528 "FROM pg_catalog.pg_type "
10529 "WHERE oid = '%u'::pg_catalog.oid",
10530 tyinfo->dobj.catId.oid);
10533 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10535 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10536 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10537 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10538 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10539 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10540 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10541 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10542 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10543 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10544 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10545 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10546 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10547 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10548 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10549 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10550 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10551 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10552 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10553 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10554 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10555 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10556 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10557 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10559 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10560 typdefault_is_literal = true; /* it needs quotes */
10565 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10568 * DROP must be fully qualified in case same name appears in pg_catalog.
10569 * The reason we include CASCADE is that the circular dependency between
10570 * the type and its I/O functions makes it impossible to drop the type any
10573 appendPQExpBuffer(delq, "DROP TYPE %s.",
10574 fmtId(tyinfo->dobj.namespace->dobj.name));
10575 appendPQExpBuffer(delq, "%s CASCADE;\n",
10579 * We might already have a shell type, but setting pg_type_oid is
10580 * harmless, and in any case we'd better set the array type OID.
10582 if (dopt->binary_upgrade)
10583 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10584 tyinfo->dobj.catId.oid,
10587 appendPQExpBuffer(q,
10588 "CREATE TYPE %s (\n"
10589 " INTERNALLENGTH = %s",
10591 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10593 /* regproc result is sufficiently quoted already */
10594 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
10595 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
10596 if (OidIsValid(typreceiveoid))
10597 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
10598 if (OidIsValid(typsendoid))
10599 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
10600 if (OidIsValid(typmodinoid))
10601 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
10602 if (OidIsValid(typmodoutoid))
10603 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
10604 if (OidIsValid(typanalyzeoid))
10605 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
10607 if (strcmp(typcollatable, "t") == 0)
10608 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
10610 if (typdefault != NULL)
10612 appendPQExpBufferStr(q, ",\n DEFAULT = ");
10613 if (typdefault_is_literal)
10614 appendStringLiteralAH(q, typdefault, fout);
10616 appendPQExpBufferStr(q, typdefault);
10619 if (OidIsValid(tyinfo->typelem))
10623 /* reselect schema in case changed by function dump */
10624 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10625 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10626 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
10630 if (strcmp(typcategory, "U") != 0)
10632 appendPQExpBufferStr(q, ",\n CATEGORY = ");
10633 appendStringLiteralAH(q, typcategory, fout);
10636 if (strcmp(typispreferred, "t") == 0)
10637 appendPQExpBufferStr(q, ",\n PREFERRED = true");
10639 if (typdelim && strcmp(typdelim, ",") != 0)
10641 appendPQExpBufferStr(q, ",\n DELIMITER = ");
10642 appendStringLiteralAH(q, typdelim, fout);
10645 if (strcmp(typalign, "c") == 0)
10646 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
10647 else if (strcmp(typalign, "s") == 0)
10648 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
10649 else if (strcmp(typalign, "i") == 0)
10650 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
10651 else if (strcmp(typalign, "d") == 0)
10652 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
10654 if (strcmp(typstorage, "p") == 0)
10655 appendPQExpBufferStr(q, ",\n STORAGE = plain");
10656 else if (strcmp(typstorage, "e") == 0)
10657 appendPQExpBufferStr(q, ",\n STORAGE = external");
10658 else if (strcmp(typstorage, "x") == 0)
10659 appendPQExpBufferStr(q, ",\n STORAGE = extended");
10660 else if (strcmp(typstorage, "m") == 0)
10661 appendPQExpBufferStr(q, ",\n STORAGE = main");
10663 if (strcmp(typbyval, "t") == 0)
10664 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
10666 appendPQExpBufferStr(q, "\n);\n");
10668 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10670 if (dopt->binary_upgrade)
10671 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10673 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10674 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10676 tyinfo->dobj.namespace->dobj.name,
10678 tyinfo->rolname, false,
10679 "TYPE", SECTION_PRE_DATA,
10680 q->data, delq->data, NULL,
10684 /* Dump Type Comments and Security Labels */
10685 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10686 dumpComment(fout, labelq->data,
10687 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10688 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10690 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10691 dumpSecLabel(fout, labelq->data,
10692 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10693 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10695 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10696 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10697 qtypname, NULL, labelq->data,
10698 tyinfo->dobj.namespace->dobj.name,
10699 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10700 tyinfo->inittypacl, tyinfo->initrtypacl);
10703 destroyPQExpBuffer(q);
10704 destroyPQExpBuffer(delq);
10705 destroyPQExpBuffer(labelq);
10706 destroyPQExpBuffer(query);
10711 * writes out to fout the queries to recreate a user-defined domain
10714 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10716 DumpOptions *dopt = fout->dopt;
10717 PQExpBuffer q = createPQExpBuffer();
10718 PQExpBuffer delq = createPQExpBuffer();
10719 PQExpBuffer labelq = createPQExpBuffer();
10720 PQExpBuffer query = createPQExpBuffer();
10728 bool typdefault_is_literal = false;
10730 /* Set proper schema search path so type references list correctly */
10731 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10733 /* Fetch domain specific details */
10734 if (fout->remoteVersion >= 90100)
10736 /* typcollation is new in 9.1 */
10737 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10738 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10739 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10741 "CASE WHEN t.typcollation <> u.typcollation "
10742 "THEN t.typcollation ELSE 0 END AS typcollation "
10743 "FROM pg_catalog.pg_type t "
10744 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10745 "WHERE t.oid = '%u'::pg_catalog.oid",
10746 tyinfo->dobj.catId.oid);
10750 appendPQExpBuffer(query, "SELECT typnotnull, "
10751 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10752 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10753 "typdefault, 0 AS typcollation "
10754 "FROM pg_catalog.pg_type "
10755 "WHERE oid = '%u'::pg_catalog.oid",
10756 tyinfo->dobj.catId.oid);
10759 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10761 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10762 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10763 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10764 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10765 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10767 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10768 typdefault_is_literal = true; /* it needs quotes */
10772 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10774 if (dopt->binary_upgrade)
10775 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10776 tyinfo->dobj.catId.oid,
10777 true); /* force array type */
10779 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10781 appendPQExpBuffer(q,
10782 "CREATE DOMAIN %s AS %s",
10786 /* Print collation only if different from base type's collation */
10787 if (OidIsValid(typcollation))
10791 coll = findCollationByOid(typcollation);
10794 /* always schema-qualify, don't try to be smart */
10795 appendPQExpBuffer(q, " COLLATE %s.",
10796 fmtId(coll->dobj.namespace->dobj.name));
10797 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10801 if (typnotnull[0] == 't')
10802 appendPQExpBufferStr(q, " NOT NULL");
10804 if (typdefault != NULL)
10806 appendPQExpBufferStr(q, " DEFAULT ");
10807 if (typdefault_is_literal)
10808 appendStringLiteralAH(q, typdefault, fout);
10810 appendPQExpBufferStr(q, typdefault);
10816 * Add any CHECK constraints for the domain
10818 for (i = 0; i < tyinfo->nDomChecks; i++)
10820 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10822 if (!domcheck->separate)
10823 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10824 fmtId(domcheck->dobj.name), domcheck->condef);
10827 appendPQExpBufferStr(q, ";\n");
10830 * DROP must be fully qualified in case same name appears in pg_catalog
10832 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
10833 fmtId(tyinfo->dobj.namespace->dobj.name));
10834 appendPQExpBuffer(delq, "%s;\n",
10837 appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
10839 if (dopt->binary_upgrade)
10840 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10842 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10843 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10845 tyinfo->dobj.namespace->dobj.name,
10847 tyinfo->rolname, false,
10848 "DOMAIN", SECTION_PRE_DATA,
10849 q->data, delq->data, NULL,
10853 /* Dump Domain Comments and Security Labels */
10854 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10855 dumpComment(fout, labelq->data,
10856 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10857 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10859 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10860 dumpSecLabel(fout, labelq->data,
10861 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10862 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10864 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10865 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10866 qtypname, NULL, labelq->data,
10867 tyinfo->dobj.namespace->dobj.name,
10868 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10869 tyinfo->inittypacl, tyinfo->initrtypacl);
10871 /* Dump any per-constraint comments */
10872 for (i = 0; i < tyinfo->nDomChecks; i++)
10874 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10875 PQExpBuffer labelq = createPQExpBuffer();
10877 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
10878 fmtId(domcheck->dobj.name));
10879 appendPQExpBuffer(labelq, "ON DOMAIN %s",
10882 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10883 dumpComment(fout, labelq->data,
10884 tyinfo->dobj.namespace->dobj.name,
10886 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10888 destroyPQExpBuffer(labelq);
10891 destroyPQExpBuffer(q);
10892 destroyPQExpBuffer(delq);
10893 destroyPQExpBuffer(labelq);
10894 destroyPQExpBuffer(query);
10898 * dumpCompositeType
10899 * writes out to fout the queries to recreate a user-defined stand-alone
10903 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10905 DumpOptions *dopt = fout->dopt;
10906 PQExpBuffer q = createPQExpBuffer();
10907 PQExpBuffer dropped = createPQExpBuffer();
10908 PQExpBuffer delq = createPQExpBuffer();
10909 PQExpBuffer labelq = createPQExpBuffer();
10910 PQExpBuffer query = createPQExpBuffer();
10918 int i_attisdropped;
10919 int i_attcollation;
10923 /* Set proper schema search path so type references list correctly */
10924 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10926 /* Fetch type specific details */
10927 if (fout->remoteVersion >= 90100)
10930 * attcollation is new in 9.1. Since we only want to dump COLLATE
10931 * clauses for attributes whose collation is different from their
10932 * type's default, we use a CASE here to suppress uninteresting
10933 * attcollations cheaply. atttypid will be 0 for dropped columns;
10934 * collation does not matter for those.
10936 appendPQExpBuffer(query, "SELECT a.attname, "
10937 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10938 "a.attlen, a.attalign, a.attisdropped, "
10939 "CASE WHEN a.attcollation <> at.typcollation "
10940 "THEN a.attcollation ELSE 0 END AS attcollation "
10941 "FROM pg_catalog.pg_type ct "
10942 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10943 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10944 "WHERE ct.oid = '%u'::pg_catalog.oid "
10945 "ORDER BY a.attnum ",
10946 tyinfo->dobj.catId.oid);
10951 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10952 * should always be false.
10954 appendPQExpBuffer(query, "SELECT a.attname, "
10955 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10956 "a.attlen, a.attalign, a.attisdropped, "
10957 "0 AS attcollation "
10958 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10959 "WHERE ct.oid = '%u'::pg_catalog.oid "
10960 "AND a.attrelid = ct.typrelid "
10961 "ORDER BY a.attnum ",
10962 tyinfo->dobj.catId.oid);
10965 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10967 ntups = PQntuples(res);
10969 i_attname = PQfnumber(res, "attname");
10970 i_atttypdefn = PQfnumber(res, "atttypdefn");
10971 i_attlen = PQfnumber(res, "attlen");
10972 i_attalign = PQfnumber(res, "attalign");
10973 i_attisdropped = PQfnumber(res, "attisdropped");
10974 i_attcollation = PQfnumber(res, "attcollation");
10976 if (dopt->binary_upgrade)
10978 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10979 tyinfo->dobj.catId.oid,
10981 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10984 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10986 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10990 for (i = 0; i < ntups; i++)
10999 attname = PQgetvalue(res, i, i_attname);
11000 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
11001 attlen = PQgetvalue(res, i, i_attlen);
11002 attalign = PQgetvalue(res, i, i_attalign);
11003 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
11004 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
11006 if (attisdropped && !dopt->binary_upgrade)
11009 /* Format properly if not first attr */
11010 if (actual_atts++ > 0)
11011 appendPQExpBufferChar(q, ',');
11012 appendPQExpBufferStr(q, "\n\t");
11016 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
11018 /* Add collation if not default for the column type */
11019 if (OidIsValid(attcollation))
11023 coll = findCollationByOid(attcollation);
11026 /* always schema-qualify, don't try to be smart */
11027 appendPQExpBuffer(q, " COLLATE %s.",
11028 fmtId(coll->dobj.namespace->dobj.name));
11029 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
11036 * This is a dropped attribute and we're in binary_upgrade mode.
11037 * Insert a placeholder for it in the CREATE TYPE command, and set
11038 * length and alignment with direct UPDATE to the catalogs
11039 * afterwards. See similar code in dumpTableSchema().
11041 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11043 /* stash separately for insertion after the CREATE TYPE */
11044 appendPQExpBufferStr(dropped,
11045 "\n-- For binary upgrade, recreate dropped column.\n");
11046 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11047 "SET attlen = %s, "
11048 "attalign = '%s', attbyval = false\n"
11049 "WHERE attname = ", attlen, attalign);
11050 appendStringLiteralAH(dropped, attname, fout);
11051 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
11052 appendStringLiteralAH(dropped, qtypname, fout);
11053 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11055 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11057 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11061 appendPQExpBufferStr(q, "\n);\n");
11062 appendPQExpBufferStr(q, dropped->data);
11065 * DROP must be fully qualified in case same name appears in pg_catalog
11067 appendPQExpBuffer(delq, "DROP TYPE %s.",
11068 fmtId(tyinfo->dobj.namespace->dobj.name));
11069 appendPQExpBuffer(delq, "%s;\n",
11072 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
11074 if (dopt->binary_upgrade)
11075 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
11077 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11078 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11080 tyinfo->dobj.namespace->dobj.name,
11082 tyinfo->rolname, false,
11083 "TYPE", SECTION_PRE_DATA,
11084 q->data, delq->data, NULL,
11089 /* Dump Type Comments and Security Labels */
11090 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11091 dumpComment(fout, labelq->data,
11092 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11093 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11095 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11096 dumpSecLabel(fout, labelq->data,
11097 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11098 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11100 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11101 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
11102 qtypname, NULL, labelq->data,
11103 tyinfo->dobj.namespace->dobj.name,
11104 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11105 tyinfo->inittypacl, tyinfo->initrtypacl);
11108 destroyPQExpBuffer(q);
11109 destroyPQExpBuffer(dropped);
11110 destroyPQExpBuffer(delq);
11111 destroyPQExpBuffer(labelq);
11112 destroyPQExpBuffer(query);
11114 /* Dump any per-column comments */
11115 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11116 dumpCompositeTypeColComments(fout, tyinfo);
11120 * dumpCompositeTypeColComments
11121 * writes out to fout the queries to recreate comments on the columns of
11122 * a user-defined stand-alone composite type
11125 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11127 CommentItem *comments;
11131 PQExpBuffer target;
11138 /* do nothing, if --no-comments is supplied */
11139 if (fout->dopt->no_comments)
11142 query = createPQExpBuffer();
11144 appendPQExpBuffer(query,
11145 "SELECT c.tableoid, a.attname, a.attnum "
11146 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11147 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11148 " AND NOT a.attisdropped "
11149 "ORDER BY a.attnum ",
11152 /* Fetch column attnames */
11153 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11155 ntups = PQntuples(res);
11159 destroyPQExpBuffer(query);
11163 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11165 /* Search for comments associated with type's pg_class OID */
11166 ncomments = findComments(fout,
11171 /* If no comments exist, we're done */
11172 if (ncomments <= 0)
11175 destroyPQExpBuffer(query);
11179 /* Build COMMENT ON statements */
11180 target = createPQExpBuffer();
11182 i_attnum = PQfnumber(res, "attnum");
11183 i_attname = PQfnumber(res, "attname");
11184 while (ncomments > 0)
11186 const char *attname;
11189 for (i = 0; i < ntups; i++)
11191 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11193 attname = PQgetvalue(res, i, i_attname);
11197 if (attname) /* just in case we don't find it */
11199 const char *descr = comments->descr;
11201 resetPQExpBuffer(target);
11202 appendPQExpBuffer(target, "COLUMN %s.",
11203 fmtId(tyinfo->dobj.name));
11204 appendPQExpBufferStr(target, fmtId(attname));
11206 resetPQExpBuffer(query);
11207 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
11208 appendStringLiteralAH(query, descr, fout);
11209 appendPQExpBufferStr(query, ";\n");
11211 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11213 tyinfo->dobj.namespace->dobj.name,
11214 NULL, tyinfo->rolname,
11215 false, "COMMENT", SECTION_NONE,
11216 query->data, "", NULL,
11217 &(tyinfo->dobj.dumpId), 1,
11226 destroyPQExpBuffer(query);
11227 destroyPQExpBuffer(target);
11232 * writes out to fout the queries to create a shell type
11234 * We dump a shell definition in advance of the I/O functions for the type.
11237 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11239 DumpOptions *dopt = fout->dopt;
11242 /* Skip if not to be dumped */
11243 if (!stinfo->dobj.dump || dopt->dataOnly)
11246 q = createPQExpBuffer();
11249 * Note the lack of a DROP command for the shell type; any required DROP
11250 * is driven off the base type entry, instead. This interacts with
11251 * _printTocEntry()'s use of the presence of a DROP command to decide
11252 * whether an entry needs an ALTER OWNER command. We don't want to alter
11253 * the shell type's owner immediately on creation; that should happen only
11254 * after it's filled in, otherwise the backend complains.
11257 if (dopt->binary_upgrade)
11258 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11259 stinfo->baseType->dobj.catId.oid,
11262 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11263 fmtId(stinfo->dobj.name));
11265 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11266 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11268 stinfo->dobj.namespace->dobj.name,
11270 stinfo->baseType->rolname, false,
11271 "SHELL TYPE", SECTION_PRE_DATA,
11276 destroyPQExpBuffer(q);
11281 * writes out to fout the queries to recreate a user-defined
11282 * procedural language
11285 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11287 DumpOptions *dopt = fout->dopt;
11288 PQExpBuffer defqry;
11289 PQExpBuffer delqry;
11290 PQExpBuffer labelq;
11294 FuncInfo *funcInfo;
11295 FuncInfo *inlineInfo = NULL;
11296 FuncInfo *validatorInfo = NULL;
11298 /* Skip if not to be dumped */
11299 if (!plang->dobj.dump || dopt->dataOnly)
11303 * Try to find the support function(s). It is not an error if we don't
11304 * find them --- if the functions are in the pg_catalog schema, as is
11305 * standard in 8.1 and up, then we won't have loaded them. (In this case
11306 * we will emit a parameterless CREATE LANGUAGE command, which will
11307 * require PL template knowledge in the backend to reload.)
11310 funcInfo = findFuncByOid(plang->lanplcallfoid);
11311 if (funcInfo != NULL && !funcInfo->dobj.dump)
11312 funcInfo = NULL; /* treat not-dumped same as not-found */
11314 if (OidIsValid(plang->laninline))
11316 inlineInfo = findFuncByOid(plang->laninline);
11317 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11321 if (OidIsValid(plang->lanvalidator))
11323 validatorInfo = findFuncByOid(plang->lanvalidator);
11324 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11325 validatorInfo = NULL;
11329 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11330 * with parameters. Otherwise, we'll write a parameterless command, which
11331 * will rely on data from pg_pltemplate.
11333 useParams = (funcInfo != NULL &&
11334 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11335 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11337 defqry = createPQExpBuffer();
11338 delqry = createPQExpBuffer();
11339 labelq = createPQExpBuffer();
11341 qlanname = pg_strdup(fmtId(plang->dobj.name));
11344 * If dumping a HANDLER clause, treat the language as being in the handler
11345 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
11346 * it doesn't really have a schema.
11349 lanschema = funcInfo->dobj.namespace->dobj.name;
11353 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11358 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11359 plang->lanpltrusted ? "TRUSTED " : "",
11361 appendPQExpBuffer(defqry, " HANDLER %s",
11362 fmtId(funcInfo->dobj.name));
11363 if (OidIsValid(plang->laninline))
11365 appendPQExpBufferStr(defqry, " INLINE ");
11366 /* Cope with possibility that inline is in different schema */
11367 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
11368 appendPQExpBuffer(defqry, "%s.",
11369 fmtId(inlineInfo->dobj.namespace->dobj.name));
11370 appendPQExpBufferStr(defqry, fmtId(inlineInfo->dobj.name));
11372 if (OidIsValid(plang->lanvalidator))
11374 appendPQExpBufferStr(defqry, " VALIDATOR ");
11375 /* Cope with possibility that validator is in different schema */
11376 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
11377 appendPQExpBuffer(defqry, "%s.",
11378 fmtId(validatorInfo->dobj.namespace->dobj.name));
11379 appendPQExpBufferStr(defqry, fmtId(validatorInfo->dobj.name));
11385 * If not dumping parameters, then use CREATE OR REPLACE so that the
11386 * command will not fail if the language is preinstalled in the target
11387 * database. We restrict the use of REPLACE to this case so as to
11388 * eliminate the risk of replacing a language with incompatible
11389 * parameter settings: this command will only succeed at all if there
11390 * is a pg_pltemplate entry, and if there is one, the existing entry
11391 * must match it too.
11393 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11396 appendPQExpBufferStr(defqry, ";\n");
11398 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
11400 if (dopt->binary_upgrade)
11401 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
11403 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11404 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11406 lanschema, NULL, plang->lanowner,
11407 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11408 defqry->data, delqry->data, NULL,
11412 /* Dump Proc Lang Comments and Security Labels */
11413 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11414 dumpComment(fout, labelq->data,
11415 lanschema, plang->lanowner,
11416 plang->dobj.catId, 0, plang->dobj.dumpId);
11418 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11419 dumpSecLabel(fout, labelq->data,
11420 lanschema, plang->lanowner,
11421 plang->dobj.catId, 0, plang->dobj.dumpId);
11423 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11424 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11425 qlanname, NULL, labelq->data,
11427 plang->lanowner, plang->lanacl, plang->rlanacl,
11428 plang->initlanacl, plang->initrlanacl);
11432 destroyPQExpBuffer(defqry);
11433 destroyPQExpBuffer(delqry);
11434 destroyPQExpBuffer(labelq);
11438 * format_function_arguments: generate function name and argument list
11440 * This is used when we can rely on pg_get_function_arguments to format
11441 * the argument list. Note, however, that pg_get_function_arguments
11442 * does not special-case zero-argument aggregates.
11445 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11447 PQExpBufferData fn;
11449 initPQExpBuffer(&fn);
11450 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11451 if (is_agg && finfo->nargs == 0)
11452 appendPQExpBufferStr(&fn, "(*)");
11454 appendPQExpBuffer(&fn, "(%s)", funcargs);
11459 * format_function_arguments_old: generate function name and argument list
11461 * The argument type names are qualified if needed. The function name
11462 * is never qualified.
11464 * This is used only with pre-8.4 servers, so we aren't expecting to see
11465 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11467 * Any or all of allargtypes, argmodes, argnames may be NULL.
11470 format_function_arguments_old(Archive *fout,
11471 FuncInfo *finfo, int nallargs,
11472 char **allargtypes,
11476 PQExpBufferData fn;
11479 initPQExpBuffer(&fn);
11480 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11481 for (j = 0; j < nallargs; j++)
11485 const char *argmode;
11486 const char *argname;
11488 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11489 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11493 switch (argmodes[j][0])
11495 case PROARGMODE_IN:
11498 case PROARGMODE_OUT:
11501 case PROARGMODE_INOUT:
11502 argmode = "INOUT ";
11505 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11513 argname = argnames ? argnames[j] : (char *) NULL;
11514 if (argname && argname[0] == '\0')
11517 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11518 (j > 0) ? ", " : "",
11520 argname ? fmtId(argname) : "",
11521 argname ? " " : "",
11525 appendPQExpBufferChar(&fn, ')');
11530 * format_function_signature: generate function name and argument list
11532 * This is like format_function_arguments_old except that only a minimal
11533 * list of input argument types is generated; this is sufficient to
11534 * reference the function, but not to define it.
11536 * If honor_quotes is false then the function name is never quoted.
11537 * This is appropriate for use in TOC tags, but not in SQL commands.
11540 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11542 PQExpBufferData fn;
11545 initPQExpBuffer(&fn);
11547 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11549 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11550 for (j = 0; j < finfo->nargs; j++)
11555 appendPQExpBufferStr(&fn, ", ");
11557 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11559 appendPQExpBufferStr(&fn, typname);
11562 appendPQExpBufferChar(&fn, ')');
11569 * dump out one function
11572 dumpFunc(Archive *fout, FuncInfo *finfo)
11574 DumpOptions *dopt = fout->dopt;
11577 PQExpBuffer delqry;
11578 PQExpBuffer labelq;
11579 PQExpBuffer asPart;
11581 char *funcsig; /* identity signature */
11582 char *funcfullsig = NULL; /* full signature */
11591 char *proallargtypes;
11599 char *proleakproof;
11607 char **allargtypes = NULL;
11608 char **argmodes = NULL;
11609 char **argnames = NULL;
11610 char **configitems = NULL;
11611 int nconfigitems = 0;
11612 const char *keyword;
11615 /* Skip if not to be dumped */
11616 if (!finfo->dobj.dump || dopt->dataOnly)
11619 query = createPQExpBuffer();
11620 q = createPQExpBuffer();
11621 delqry = createPQExpBuffer();
11622 labelq = createPQExpBuffer();
11623 asPart = createPQExpBuffer();
11625 /* Set proper schema search path so type references list correctly */
11626 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
11628 /* Fetch function-specific details */
11629 if (fout->remoteVersion >= 90600)
11632 * proparallel was added in 9.6
11634 appendPQExpBuffer(query,
11635 "SELECT proretset, prosrc, probin, "
11636 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11637 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11638 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11639 "array_to_string(protrftypes, ' ') AS protrftypes, "
11640 "proiswindow, provolatile, proisstrict, prosecdef, "
11641 "proleakproof, proconfig, procost, prorows, "
11643 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11644 "FROM pg_catalog.pg_proc "
11645 "WHERE oid = '%u'::pg_catalog.oid",
11646 finfo->dobj.catId.oid);
11648 else if (fout->remoteVersion >= 90500)
11651 * protrftypes was added in 9.5
11653 appendPQExpBuffer(query,
11654 "SELECT proretset, prosrc, probin, "
11655 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11656 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11657 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11658 "array_to_string(protrftypes, ' ') AS protrftypes, "
11659 "proiswindow, provolatile, proisstrict, prosecdef, "
11660 "proleakproof, proconfig, procost, prorows, "
11661 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11662 "FROM pg_catalog.pg_proc "
11663 "WHERE oid = '%u'::pg_catalog.oid",
11664 finfo->dobj.catId.oid);
11666 else if (fout->remoteVersion >= 90200)
11669 * proleakproof was added in 9.2
11671 appendPQExpBuffer(query,
11672 "SELECT proretset, prosrc, probin, "
11673 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11674 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11675 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11676 "proiswindow, provolatile, proisstrict, prosecdef, "
11677 "proleakproof, proconfig, procost, prorows, "
11678 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11679 "FROM pg_catalog.pg_proc "
11680 "WHERE oid = '%u'::pg_catalog.oid",
11681 finfo->dobj.catId.oid);
11683 else if (fout->remoteVersion >= 80400)
11686 * In 8.4 and up we rely on pg_get_function_arguments and
11687 * pg_get_function_result instead of examining proallargtypes etc.
11689 appendPQExpBuffer(query,
11690 "SELECT proretset, prosrc, probin, "
11691 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11692 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11693 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11694 "proiswindow, provolatile, proisstrict, prosecdef, "
11695 "false AS proleakproof, "
11696 " proconfig, procost, prorows, "
11697 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11698 "FROM pg_catalog.pg_proc "
11699 "WHERE oid = '%u'::pg_catalog.oid",
11700 finfo->dobj.catId.oid);
11702 else if (fout->remoteVersion >= 80300)
11704 appendPQExpBuffer(query,
11705 "SELECT proretset, prosrc, probin, "
11706 "proallargtypes, proargmodes, proargnames, "
11707 "false AS proiswindow, "
11708 "provolatile, proisstrict, prosecdef, "
11709 "false AS proleakproof, "
11710 "proconfig, procost, prorows, "
11711 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11712 "FROM pg_catalog.pg_proc "
11713 "WHERE oid = '%u'::pg_catalog.oid",
11714 finfo->dobj.catId.oid);
11716 else if (fout->remoteVersion >= 80100)
11718 appendPQExpBuffer(query,
11719 "SELECT proretset, prosrc, probin, "
11720 "proallargtypes, proargmodes, proargnames, "
11721 "false AS proiswindow, "
11722 "provolatile, proisstrict, prosecdef, "
11723 "false AS proleakproof, "
11724 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11725 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11726 "FROM pg_catalog.pg_proc "
11727 "WHERE oid = '%u'::pg_catalog.oid",
11728 finfo->dobj.catId.oid);
11732 appendPQExpBuffer(query,
11733 "SELECT proretset, prosrc, probin, "
11734 "null AS proallargtypes, "
11735 "null AS proargmodes, "
11737 "false AS proiswindow, "
11738 "provolatile, proisstrict, prosecdef, "
11739 "false AS proleakproof, "
11740 "null AS proconfig, 0 AS procost, 0 AS prorows, "
11741 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11742 "FROM pg_catalog.pg_proc "
11743 "WHERE oid = '%u'::pg_catalog.oid",
11744 finfo->dobj.catId.oid);
11747 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11749 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11750 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11751 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11752 if (fout->remoteVersion >= 80400)
11754 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11755 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11756 is_procedure = PQgetisnull(res, 0, PQfnumber(res, "funcresult"));
11760 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11761 proallargtypes = proargmodes = proargnames = NULL;
11765 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11766 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11767 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11768 funcargs = funciargs = funcresult = NULL;
11769 is_procedure = false;
11771 if (PQfnumber(res, "protrftypes") != -1)
11772 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11774 protrftypes = NULL;
11775 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
11776 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11777 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11778 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11779 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11780 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11781 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11782 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11784 if (PQfnumber(res, "proparallel") != -1)
11785 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11787 proparallel = NULL;
11789 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11792 * See backend/commands/functioncmds.c for details of how the 'AS' clause
11793 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
11794 * versions would set it to "-". There are no known cases in which prosrc
11795 * is unused, so the tests below for "-" are probably useless.
11797 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11799 appendPQExpBufferStr(asPart, "AS ");
11800 appendStringLiteralAH(asPart, probin, fout);
11801 if (strcmp(prosrc, "-") != 0)
11803 appendPQExpBufferStr(asPart, ", ");
11806 * where we have bin, use dollar quoting if allowed and src
11807 * contains quote or backslash; else use regular quoting.
11809 if (dopt->disable_dollar_quoting ||
11810 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11811 appendStringLiteralAH(asPart, prosrc, fout);
11813 appendStringLiteralDQ(asPart, prosrc, NULL);
11818 if (strcmp(prosrc, "-") != 0)
11820 appendPQExpBufferStr(asPart, "AS ");
11821 /* with no bin, dollar quote src unconditionally if allowed */
11822 if (dopt->disable_dollar_quoting)
11823 appendStringLiteralAH(asPart, prosrc, fout);
11825 appendStringLiteralDQ(asPart, prosrc, NULL);
11829 nallargs = finfo->nargs; /* unless we learn different from allargs */
11831 if (proallargtypes && *proallargtypes)
11835 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11836 nitems < finfo->nargs)
11838 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11841 allargtypes = NULL;
11847 if (proargmodes && *proargmodes)
11851 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11852 nitems != nallargs)
11854 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11861 if (proargnames && *proargnames)
11865 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11866 nitems != nallargs)
11868 write_msg(NULL, "WARNING: could not parse proargnames array\n");
11875 if (proconfig && *proconfig)
11877 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11879 write_msg(NULL, "WARNING: could not parse proconfig array\n");
11882 configitems = NULL;
11889 /* 8.4 or later; we rely on server-side code for most of the work */
11890 funcfullsig = format_function_arguments(finfo, funcargs, false);
11891 funcsig = format_function_arguments(finfo, funciargs, false);
11894 /* pre-8.4, do it ourselves */
11895 funcsig = format_function_arguments_old(fout,
11896 finfo, nallargs, allargtypes,
11897 argmodes, argnames);
11899 funcsig_tag = format_function_signature(fout, finfo, false);
11901 keyword = is_procedure ? "PROCEDURE" : "FUNCTION";
11904 * DROP must be fully qualified in case same name appears in pg_catalog
11906 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11908 fmtId(finfo->dobj.namespace->dobj.name),
11911 appendPQExpBuffer(q, "CREATE %s %s",
11913 funcfullsig ? funcfullsig :
11917 else if (funcresult)
11918 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11921 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11923 appendPQExpBuffer(q, " RETURNS %s%s",
11924 (proretset[0] == 't') ? "SETOF " : "",
11929 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
11931 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11933 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11936 appendPQExpBufferStr(q, " TRANSFORM ");
11937 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11938 for (i = 0; typeids[i]; i++)
11941 appendPQExpBufferStr(q, ", ");
11942 appendPQExpBuffer(q, "FOR TYPE %s",
11943 getFormattedTypeName(fout, typeids[i], zeroAsNone));
11947 if (proiswindow[0] == 't')
11948 appendPQExpBufferStr(q, " WINDOW");
11950 if (provolatile[0] != PROVOLATILE_VOLATILE)
11952 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11953 appendPQExpBufferStr(q, " IMMUTABLE");
11954 else if (provolatile[0] == PROVOLATILE_STABLE)
11955 appendPQExpBufferStr(q, " STABLE");
11956 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11957 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11961 if (proisstrict[0] == 't')
11962 appendPQExpBufferStr(q, " STRICT");
11964 if (prosecdef[0] == 't')
11965 appendPQExpBufferStr(q, " SECURITY DEFINER");
11967 if (proleakproof[0] == 't')
11968 appendPQExpBufferStr(q, " LEAKPROOF");
11971 * COST and ROWS are emitted only if present and not default, so as not to
11972 * break backwards-compatibility of the dump without need. Keep this code
11973 * in sync with the defaults in functioncmds.c.
11975 if (strcmp(procost, "0") != 0)
11977 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11979 /* default cost is 1 */
11980 if (strcmp(procost, "1") != 0)
11981 appendPQExpBuffer(q, " COST %s", procost);
11985 /* default cost is 100 */
11986 if (strcmp(procost, "100") != 0)
11987 appendPQExpBuffer(q, " COST %s", procost);
11990 if (proretset[0] == 't' &&
11991 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11992 appendPQExpBuffer(q, " ROWS %s", prorows);
11994 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11996 if (proparallel[0] == PROPARALLEL_SAFE)
11997 appendPQExpBufferStr(q, " PARALLEL SAFE");
11998 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11999 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
12000 else if (proparallel[0] != PROPARALLEL_UNSAFE)
12001 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
12005 for (i = 0; i < nconfigitems; i++)
12007 /* we feel free to scribble on configitems[] here */
12008 char *configitem = configitems[i];
12011 pos = strchr(configitem, '=');
12015 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
12018 * Some GUC variable names are 'LIST' type and hence must not be
12021 if (pg_strcasecmp(configitem, "DateStyle") == 0
12022 || pg_strcasecmp(configitem, "search_path") == 0)
12023 appendPQExpBufferStr(q, pos);
12025 appendStringLiteralAH(q, pos, fout);
12028 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
12030 appendPQExpBuffer(labelq, "%s %s", keyword, funcsig);
12032 if (dopt->binary_upgrade)
12033 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
12035 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12036 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12038 finfo->dobj.namespace->dobj.name,
12040 finfo->rolname, false,
12041 keyword, SECTION_PRE_DATA,
12042 q->data, delqry->data, NULL,
12046 /* Dump Function Comments and Security Labels */
12047 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12048 dumpComment(fout, labelq->data,
12049 finfo->dobj.namespace->dobj.name, finfo->rolname,
12050 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12052 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12053 dumpSecLabel(fout, labelq->data,
12054 finfo->dobj.namespace->dobj.name, finfo->rolname,
12055 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12057 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12058 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
12059 funcsig, NULL, labelq->data,
12060 finfo->dobj.namespace->dobj.name,
12061 finfo->rolname, finfo->proacl, finfo->rproacl,
12062 finfo->initproacl, finfo->initrproacl);
12066 destroyPQExpBuffer(query);
12067 destroyPQExpBuffer(q);
12068 destroyPQExpBuffer(delqry);
12069 destroyPQExpBuffer(labelq);
12070 destroyPQExpBuffer(asPart);
12087 * Dump a user-defined cast
12090 dumpCast(Archive *fout, CastInfo *cast)
12092 DumpOptions *dopt = fout->dopt;
12093 PQExpBuffer defqry;
12094 PQExpBuffer delqry;
12095 PQExpBuffer labelq;
12096 FuncInfo *funcInfo = NULL;
12100 /* Skip if not to be dumped */
12101 if (!cast->dobj.dump || dopt->dataOnly)
12104 /* Cannot dump if we don't have the cast function's info */
12105 if (OidIsValid(cast->castfunc))
12107 funcInfo = findFuncByOid(cast->castfunc);
12108 if (funcInfo == NULL)
12109 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12114 * Make sure we are in proper schema (needed for getFormattedTypeName).
12115 * Casts don't have a schema of their own, so use pg_catalog.
12117 selectSourceSchema(fout, "pg_catalog");
12119 defqry = createPQExpBuffer();
12120 delqry = createPQExpBuffer();
12121 labelq = createPQExpBuffer();
12123 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12124 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12125 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12126 sourceType, targetType);
12128 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12129 sourceType, targetType);
12131 switch (cast->castmethod)
12133 case COERCION_METHOD_BINARY:
12134 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12136 case COERCION_METHOD_INOUT:
12137 appendPQExpBufferStr(defqry, "WITH INOUT");
12139 case COERCION_METHOD_FUNCTION:
12142 char *fsig = format_function_signature(fout, funcInfo, true);
12145 * Always qualify the function name, in case it is not in
12146 * pg_catalog schema (format_function_signature won't qualify
12149 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12150 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12154 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12157 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12160 if (cast->castcontext == 'a')
12161 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12162 else if (cast->castcontext == 'i')
12163 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12164 appendPQExpBufferStr(defqry, ";\n");
12166 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12167 sourceType, targetType);
12169 if (dopt->binary_upgrade)
12170 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
12172 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12173 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12175 "pg_catalog", NULL, "",
12176 false, "CAST", SECTION_PRE_DATA,
12177 defqry->data, delqry->data, NULL,
12181 /* Dump Cast Comments */
12182 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12183 dumpComment(fout, labelq->data,
12185 cast->dobj.catId, 0, cast->dobj.dumpId);
12190 destroyPQExpBuffer(defqry);
12191 destroyPQExpBuffer(delqry);
12192 destroyPQExpBuffer(labelq);
12199 dumpTransform(Archive *fout, TransformInfo *transform)
12201 DumpOptions *dopt = fout->dopt;
12202 PQExpBuffer defqry;
12203 PQExpBuffer delqry;
12204 PQExpBuffer labelq;
12205 FuncInfo *fromsqlFuncInfo = NULL;
12206 FuncInfo *tosqlFuncInfo = NULL;
12208 char *transformType;
12210 /* Skip if not to be dumped */
12211 if (!transform->dobj.dump || dopt->dataOnly)
12214 /* Cannot dump if we don't have the transform functions' info */
12215 if (OidIsValid(transform->trffromsql))
12217 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12218 if (fromsqlFuncInfo == NULL)
12219 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12220 transform->trffromsql);
12222 if (OidIsValid(transform->trftosql))
12224 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12225 if (tosqlFuncInfo == NULL)
12226 exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12227 transform->trftosql);
12230 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
12231 selectSourceSchema(fout, "pg_catalog");
12233 defqry = createPQExpBuffer();
12234 delqry = createPQExpBuffer();
12235 labelq = createPQExpBuffer();
12237 lanname = get_language_name(fout, transform->trflang);
12238 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12240 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12241 transformType, lanname);
12243 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12244 transformType, lanname);
12246 if (!transform->trffromsql && !transform->trftosql)
12247 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12249 if (transform->trffromsql)
12251 if (fromsqlFuncInfo)
12253 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12256 * Always qualify the function name, in case it is not in
12257 * pg_catalog schema (format_function_signature won't qualify it).
12259 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12260 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12264 write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12267 if (transform->trftosql)
12269 if (transform->trffromsql)
12270 appendPQExpBuffer(defqry, ", ");
12274 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12277 * Always qualify the function name, in case it is not in
12278 * pg_catalog schema (format_function_signature won't qualify it).
12280 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12281 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12285 write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12288 appendPQExpBuffer(defqry, ");\n");
12290 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12291 transformType, lanname);
12293 if (dopt->binary_upgrade)
12294 binary_upgrade_extension_member(defqry, &transform->dobj, labelq->data);
12296 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12297 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12299 "pg_catalog", NULL, "",
12300 false, "TRANSFORM", SECTION_PRE_DATA,
12301 defqry->data, delqry->data, NULL,
12302 transform->dobj.dependencies, transform->dobj.nDeps,
12305 /* Dump Transform Comments */
12306 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12307 dumpComment(fout, labelq->data,
12309 transform->dobj.catId, 0, transform->dobj.dumpId);
12312 free(transformType);
12313 destroyPQExpBuffer(defqry);
12314 destroyPQExpBuffer(delqry);
12315 destroyPQExpBuffer(labelq);
12321 * write out a single operator definition
12324 dumpOpr(Archive *fout, OprInfo *oprinfo)
12326 DumpOptions *dopt = fout->dopt;
12330 PQExpBuffer labelq;
12332 PQExpBuffer details;
12357 /* Skip if not to be dumped */
12358 if (!oprinfo->dobj.dump || dopt->dataOnly)
12362 * some operators are invalid because they were the result of user
12363 * defining operators before commutators exist
12365 if (!OidIsValid(oprinfo->oprcode))
12368 query = createPQExpBuffer();
12369 q = createPQExpBuffer();
12370 delq = createPQExpBuffer();
12371 labelq = createPQExpBuffer();
12372 oprid = createPQExpBuffer();
12373 details = createPQExpBuffer();
12375 /* Make sure we are in proper schema so regoperator works correctly */
12376 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
12378 if (fout->remoteVersion >= 80300)
12380 appendPQExpBuffer(query, "SELECT oprkind, "
12381 "oprcode::pg_catalog.regprocedure, "
12382 "oprleft::pg_catalog.regtype, "
12383 "oprright::pg_catalog.regtype, "
12384 "oprcom::pg_catalog.regoperator, "
12385 "oprnegate::pg_catalog.regoperator, "
12386 "oprrest::pg_catalog.regprocedure, "
12387 "oprjoin::pg_catalog.regprocedure, "
12388 "oprcanmerge, oprcanhash "
12389 "FROM pg_catalog.pg_operator "
12390 "WHERE oid = '%u'::pg_catalog.oid",
12391 oprinfo->dobj.catId.oid);
12395 appendPQExpBuffer(query, "SELECT oprkind, "
12396 "oprcode::pg_catalog.regprocedure, "
12397 "oprleft::pg_catalog.regtype, "
12398 "oprright::pg_catalog.regtype, "
12399 "oprcom::pg_catalog.regoperator, "
12400 "oprnegate::pg_catalog.regoperator, "
12401 "oprrest::pg_catalog.regprocedure, "
12402 "oprjoin::pg_catalog.regprocedure, "
12403 "(oprlsortop != 0) AS oprcanmerge, "
12405 "FROM pg_catalog.pg_operator "
12406 "WHERE oid = '%u'::pg_catalog.oid",
12407 oprinfo->dobj.catId.oid);
12410 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12412 i_oprkind = PQfnumber(res, "oprkind");
12413 i_oprcode = PQfnumber(res, "oprcode");
12414 i_oprleft = PQfnumber(res, "oprleft");
12415 i_oprright = PQfnumber(res, "oprright");
12416 i_oprcom = PQfnumber(res, "oprcom");
12417 i_oprnegate = PQfnumber(res, "oprnegate");
12418 i_oprrest = PQfnumber(res, "oprrest");
12419 i_oprjoin = PQfnumber(res, "oprjoin");
12420 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12421 i_oprcanhash = PQfnumber(res, "oprcanhash");
12423 oprkind = PQgetvalue(res, 0, i_oprkind);
12424 oprcode = PQgetvalue(res, 0, i_oprcode);
12425 oprleft = PQgetvalue(res, 0, i_oprleft);
12426 oprright = PQgetvalue(res, 0, i_oprright);
12427 oprcom = PQgetvalue(res, 0, i_oprcom);
12428 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12429 oprrest = PQgetvalue(res, 0, i_oprrest);
12430 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12431 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12432 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12434 oprregproc = convertRegProcReference(fout, oprcode);
12437 appendPQExpBuffer(details, " PROCEDURE = %s", oprregproc);
12441 appendPQExpBuffer(oprid, "%s (",
12442 oprinfo->dobj.name);
12445 * right unary means there's a left arg and left unary means there's a
12448 if (strcmp(oprkind, "r") == 0 ||
12449 strcmp(oprkind, "b") == 0)
12451 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12452 appendPQExpBufferStr(oprid, oprleft);
12455 appendPQExpBufferStr(oprid, "NONE");
12457 if (strcmp(oprkind, "l") == 0 ||
12458 strcmp(oprkind, "b") == 0)
12460 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12461 appendPQExpBuffer(oprid, ", %s)", oprright);
12464 appendPQExpBufferStr(oprid, ", NONE)");
12466 oprref = convertOperatorReference(fout, oprcom);
12469 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12473 oprref = convertOperatorReference(fout, oprnegate);
12476 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12480 if (strcmp(oprcanmerge, "t") == 0)
12481 appendPQExpBufferStr(details, ",\n MERGES");
12483 if (strcmp(oprcanhash, "t") == 0)
12484 appendPQExpBufferStr(details, ",\n HASHES");
12486 oprregproc = convertRegProcReference(fout, oprrest);
12489 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12493 oprregproc = convertRegProcReference(fout, oprjoin);
12496 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12501 * DROP must be fully qualified in case same name appears in pg_catalog
12503 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12504 fmtId(oprinfo->dobj.namespace->dobj.name),
12507 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
12508 oprinfo->dobj.name, details->data);
12510 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
12512 if (dopt->binary_upgrade)
12513 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
12515 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12516 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12517 oprinfo->dobj.name,
12518 oprinfo->dobj.namespace->dobj.name,
12521 false, "OPERATOR", SECTION_PRE_DATA,
12522 q->data, delq->data, NULL,
12526 /* Dump Operator Comments */
12527 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12528 dumpComment(fout, labelq->data,
12529 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12530 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12534 destroyPQExpBuffer(query);
12535 destroyPQExpBuffer(q);
12536 destroyPQExpBuffer(delq);
12537 destroyPQExpBuffer(labelq);
12538 destroyPQExpBuffer(oprid);
12539 destroyPQExpBuffer(details);
12543 * Convert a function reference obtained from pg_operator
12545 * Returns allocated string of what to print, or NULL if function references
12546 * is InvalidOid. Returned string is expected to be free'd by the caller.
12548 * The input is a REGPROCEDURE display; we have to strip the argument-types
12552 convertRegProcReference(Archive *fout, const char *proc)
12558 /* In all cases "-" means a null reference */
12559 if (strcmp(proc, "-") == 0)
12562 name = pg_strdup(proc);
12563 /* find non-double-quoted left paren */
12565 for (paren = name; *paren; paren++)
12567 if (*paren == '(' && !inquote)
12573 inquote = !inquote;
12579 * Convert an operator cross-reference obtained from pg_operator
12581 * Returns an allocated string of what to print, or NULL to print nothing.
12582 * Caller is responsible for free'ing result string.
12584 * The input is a REGOPERATOR display; we have to strip the argument-types
12585 * part, and add OPERATOR() decoration if the name is schema-qualified.
12588 convertOperatorReference(Archive *fout, const char *opr)
12596 /* In all cases "0" means a null reference */
12597 if (strcmp(opr, "0") == 0)
12600 name = pg_strdup(opr);
12601 /* find non-double-quoted left paren, and check for non-quoted dot */
12604 for (ptr = name; *ptr; ptr++)
12607 inquote = !inquote;
12608 else if (*ptr == '.' && !inquote)
12610 else if (*ptr == '(' && !inquote)
12616 /* If not schema-qualified, don't need to add OPERATOR() */
12619 oname = psprintf("OPERATOR(%s)", name);
12625 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12627 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12628 * argument lists of these functions are predetermined. Note that the
12629 * caller should ensure we are in the proper schema, because the results
12630 * are search path dependent!
12633 convertTSFunction(Archive *fout, Oid funcOid)
12639 snprintf(query, sizeof(query),
12640 "SELECT '%u'::pg_catalog.regproc", funcOid);
12641 res = ExecuteSqlQueryForSingleRow(fout, query);
12643 result = pg_strdup(PQgetvalue(res, 0, 0));
12652 * write out a single access method definition
12655 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12657 DumpOptions *dopt = fout->dopt;
12660 PQExpBuffer labelq;
12663 /* Skip if not to be dumped */
12664 if (!aminfo->dobj.dump || dopt->dataOnly)
12667 q = createPQExpBuffer();
12668 delq = createPQExpBuffer();
12669 labelq = createPQExpBuffer();
12671 qamname = pg_strdup(fmtId(aminfo->dobj.name));
12673 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12675 switch (aminfo->amtype)
12678 appendPQExpBuffer(q, "TYPE INDEX ");
12681 write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12682 aminfo->amtype, qamname);
12684 destroyPQExpBuffer(q);
12685 destroyPQExpBuffer(delq);
12686 destroyPQExpBuffer(labelq);
12690 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12692 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12695 appendPQExpBuffer(labelq, "ACCESS METHOD %s",
12698 if (dopt->binary_upgrade)
12699 binary_upgrade_extension_member(q, &aminfo->dobj, labelq->data);
12701 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12702 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12707 false, "ACCESS METHOD", SECTION_PRE_DATA,
12708 q->data, delq->data, NULL,
12712 /* Dump Access Method Comments */
12713 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12714 dumpComment(fout, labelq->data,
12716 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12720 destroyPQExpBuffer(q);
12721 destroyPQExpBuffer(delq);
12722 destroyPQExpBuffer(labelq);
12727 * write out a single operator class definition
12730 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12732 DumpOptions *dopt = fout->dopt;
12736 PQExpBuffer labelq;
12743 int i_opcfamilyname;
12744 int i_opcfamilynsp;
12746 int i_amopstrategy;
12747 int i_amopreqcheck;
12750 int i_sortfamilynsp;
12753 int i_amproclefttype;
12754 int i_amprocrighttype;
12759 char *opcfamilyname;
12760 char *opcfamilynsp;
12762 char *amopstrategy;
12763 char *amopreqcheck;
12766 char *sortfamilynsp;
12769 char *amproclefttype;
12770 char *amprocrighttype;
12774 /* Skip if not to be dumped */
12775 if (!opcinfo->dobj.dump || dopt->dataOnly)
12778 query = createPQExpBuffer();
12779 q = createPQExpBuffer();
12780 delq = createPQExpBuffer();
12781 labelq = createPQExpBuffer();
12783 /* Make sure we are in proper schema so regoperator works correctly */
12784 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
12786 /* Get additional fields from the pg_opclass row */
12787 if (fout->remoteVersion >= 80300)
12789 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12790 "opckeytype::pg_catalog.regtype, "
12791 "opcdefault, opcfamily, "
12792 "opfname AS opcfamilyname, "
12793 "nspname AS opcfamilynsp, "
12794 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12795 "FROM pg_catalog.pg_opclass c "
12796 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12797 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12798 "WHERE c.oid = '%u'::pg_catalog.oid",
12799 opcinfo->dobj.catId.oid);
12803 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12804 "opckeytype::pg_catalog.regtype, "
12805 "opcdefault, NULL AS opcfamily, "
12806 "NULL AS opcfamilyname, "
12807 "NULL AS opcfamilynsp, "
12808 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12809 "FROM pg_catalog.pg_opclass "
12810 "WHERE oid = '%u'::pg_catalog.oid",
12811 opcinfo->dobj.catId.oid);
12814 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12816 i_opcintype = PQfnumber(res, "opcintype");
12817 i_opckeytype = PQfnumber(res, "opckeytype");
12818 i_opcdefault = PQfnumber(res, "opcdefault");
12819 i_opcfamily = PQfnumber(res, "opcfamily");
12820 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12821 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12822 i_amname = PQfnumber(res, "amname");
12824 /* opcintype may still be needed after we PQclear res */
12825 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12826 opckeytype = PQgetvalue(res, 0, i_opckeytype);
12827 opcdefault = PQgetvalue(res, 0, i_opcdefault);
12828 /* opcfamily will still be needed after we PQclear res */
12829 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12830 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12831 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12832 /* amname will still be needed after we PQclear res */
12833 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12836 * DROP must be fully qualified in case same name appears in pg_catalog
12838 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12839 fmtId(opcinfo->dobj.namespace->dobj.name));
12840 appendPQExpBuffer(delq, ".%s",
12841 fmtId(opcinfo->dobj.name));
12842 appendPQExpBuffer(delq, " USING %s;\n",
12845 /* Build the fixed portion of the CREATE command */
12846 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
12847 fmtId(opcinfo->dobj.name));
12848 if (strcmp(opcdefault, "t") == 0)
12849 appendPQExpBufferStr(q, "DEFAULT ");
12850 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12853 if (strlen(opcfamilyname) > 0)
12855 appendPQExpBufferStr(q, " FAMILY ");
12856 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12857 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12858 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12860 appendPQExpBufferStr(q, " AS\n ");
12864 if (strcmp(opckeytype, "-") != 0)
12866 appendPQExpBuffer(q, "STORAGE %s",
12874 * Now fetch and print the OPERATOR entries (pg_amop rows).
12876 * Print only those opfamily members that are tied to the opclass by
12877 * pg_depend entries.
12879 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12880 * older server's opclass in which it is used. This is to avoid
12881 * hard-to-detect breakage if a newer pg_dump is used to dump from an
12882 * older server and then reload into that old version. This can go away
12883 * once 8.3 is so old as to not be of interest to anyone.
12885 resetPQExpBuffer(query);
12887 if (fout->remoteVersion >= 90100)
12889 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12890 "amopopr::pg_catalog.regoperator, "
12891 "opfname AS sortfamily, "
12892 "nspname AS sortfamilynsp "
12893 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12894 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12895 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12896 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12897 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12898 "AND refobjid = '%u'::pg_catalog.oid "
12899 "AND amopfamily = '%s'::pg_catalog.oid "
12900 "ORDER BY amopstrategy",
12901 opcinfo->dobj.catId.oid,
12904 else if (fout->remoteVersion >= 80400)
12906 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12907 "amopopr::pg_catalog.regoperator, "
12908 "NULL AS sortfamily, "
12909 "NULL AS sortfamilynsp "
12910 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12911 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12912 "AND refobjid = '%u'::pg_catalog.oid "
12913 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12914 "AND objid = ao.oid "
12915 "ORDER BY amopstrategy",
12916 opcinfo->dobj.catId.oid);
12918 else if (fout->remoteVersion >= 80300)
12920 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12921 "amopopr::pg_catalog.regoperator, "
12922 "NULL AS sortfamily, "
12923 "NULL AS sortfamilynsp "
12924 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12925 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12926 "AND refobjid = '%u'::pg_catalog.oid "
12927 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12928 "AND objid = ao.oid "
12929 "ORDER BY amopstrategy",
12930 opcinfo->dobj.catId.oid);
12935 * Here, we print all entries since there are no opfamilies and hence
12936 * no loose operators to worry about.
12938 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12939 "amopopr::pg_catalog.regoperator, "
12940 "NULL AS sortfamily, "
12941 "NULL AS sortfamilynsp "
12942 "FROM pg_catalog.pg_amop "
12943 "WHERE amopclaid = '%u'::pg_catalog.oid "
12944 "ORDER BY amopstrategy",
12945 opcinfo->dobj.catId.oid);
12948 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12950 ntups = PQntuples(res);
12952 i_amopstrategy = PQfnumber(res, "amopstrategy");
12953 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12954 i_amopopr = PQfnumber(res, "amopopr");
12955 i_sortfamily = PQfnumber(res, "sortfamily");
12956 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12958 for (i = 0; i < ntups; i++)
12960 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12961 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12962 amopopr = PQgetvalue(res, i, i_amopopr);
12963 sortfamily = PQgetvalue(res, i, i_sortfamily);
12964 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12967 appendPQExpBufferStr(q, " ,\n ");
12969 appendPQExpBuffer(q, "OPERATOR %s %s",
12970 amopstrategy, amopopr);
12972 if (strlen(sortfamily) > 0)
12974 appendPQExpBufferStr(q, " FOR ORDER BY ");
12975 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12976 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12977 appendPQExpBufferStr(q, fmtId(sortfamily));
12980 if (strcmp(amopreqcheck, "t") == 0)
12981 appendPQExpBufferStr(q, " RECHECK");
12989 * Now fetch and print the FUNCTION entries (pg_amproc rows).
12991 * Print only those opfamily members that are tied to the opclass by
12992 * pg_depend entries.
12994 * We print the amproclefttype/amprocrighttype even though in most cases
12995 * the backend could deduce the right values, because of the corner case
12996 * of a btree sort support function for a cross-type comparison. That's
12997 * only allowed in 9.2 and later, but for simplicity print them in all
12998 * versions that have the columns.
13000 resetPQExpBuffer(query);
13002 if (fout->remoteVersion >= 80300)
13004 appendPQExpBuffer(query, "SELECT amprocnum, "
13005 "amproc::pg_catalog.regprocedure, "
13006 "amproclefttype::pg_catalog.regtype, "
13007 "amprocrighttype::pg_catalog.regtype "
13008 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13009 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13010 "AND refobjid = '%u'::pg_catalog.oid "
13011 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13012 "AND objid = ap.oid "
13013 "ORDER BY amprocnum",
13014 opcinfo->dobj.catId.oid);
13018 appendPQExpBuffer(query, "SELECT amprocnum, "
13019 "amproc::pg_catalog.regprocedure, "
13020 "'' AS amproclefttype, "
13021 "'' AS amprocrighttype "
13022 "FROM pg_catalog.pg_amproc "
13023 "WHERE amopclaid = '%u'::pg_catalog.oid "
13024 "ORDER BY amprocnum",
13025 opcinfo->dobj.catId.oid);
13028 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13030 ntups = PQntuples(res);
13032 i_amprocnum = PQfnumber(res, "amprocnum");
13033 i_amproc = PQfnumber(res, "amproc");
13034 i_amproclefttype = PQfnumber(res, "amproclefttype");
13035 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
13037 for (i = 0; i < ntups; i++)
13039 amprocnum = PQgetvalue(res, i, i_amprocnum);
13040 amproc = PQgetvalue(res, i, i_amproc);
13041 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
13042 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
13045 appendPQExpBufferStr(q, " ,\n ");
13047 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
13049 if (*amproclefttype && *amprocrighttype)
13050 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13052 appendPQExpBuffer(q, " %s", amproc);
13060 * If needComma is still false it means we haven't added anything after
13061 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13062 * clause with the same datatype. This isn't sanctioned by the
13063 * documentation, but actually DefineOpClass will treat it as a no-op.
13066 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13068 appendPQExpBufferStr(q, ";\n");
13070 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
13071 fmtId(opcinfo->dobj.name));
13072 appendPQExpBuffer(labelq, " USING %s",
13075 if (dopt->binary_upgrade)
13076 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
13078 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13079 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13080 opcinfo->dobj.name,
13081 opcinfo->dobj.namespace->dobj.name,
13084 false, "OPERATOR CLASS", SECTION_PRE_DATA,
13085 q->data, delq->data, NULL,
13089 /* Dump Operator Class Comments */
13090 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13091 dumpComment(fout, labelq->data,
13092 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13093 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13098 destroyPQExpBuffer(query);
13099 destroyPQExpBuffer(q);
13100 destroyPQExpBuffer(delq);
13101 destroyPQExpBuffer(labelq);
13106 * write out a single operator family definition
13108 * Note: this also dumps any "loose" operator members that aren't bound to a
13109 * specific opclass within the opfamily.
13112 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13114 DumpOptions *dopt = fout->dopt;
13118 PQExpBuffer labelq;
13121 PGresult *res_procs;
13124 int i_amopstrategy;
13125 int i_amopreqcheck;
13128 int i_sortfamilynsp;
13131 int i_amproclefttype;
13132 int i_amprocrighttype;
13134 char *amopstrategy;
13135 char *amopreqcheck;
13138 char *sortfamilynsp;
13141 char *amproclefttype;
13142 char *amprocrighttype;
13146 /* Skip if not to be dumped */
13147 if (!opfinfo->dobj.dump || dopt->dataOnly)
13150 query = createPQExpBuffer();
13151 q = createPQExpBuffer();
13152 delq = createPQExpBuffer();
13153 labelq = createPQExpBuffer();
13155 /* Make sure we are in proper schema so regoperator works correctly */
13156 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
13159 * Fetch only those opfamily members that are tied directly to the
13160 * opfamily by pg_depend entries.
13162 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13163 * older server's opclass in which it is used. This is to avoid
13164 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13165 * older server and then reload into that old version. This can go away
13166 * once 8.3 is so old as to not be of interest to anyone.
13168 if (fout->remoteVersion >= 90100)
13170 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13171 "amopopr::pg_catalog.regoperator, "
13172 "opfname AS sortfamily, "
13173 "nspname AS sortfamilynsp "
13174 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13175 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13176 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13177 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13178 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13179 "AND refobjid = '%u'::pg_catalog.oid "
13180 "AND amopfamily = '%u'::pg_catalog.oid "
13181 "ORDER BY amopstrategy",
13182 opfinfo->dobj.catId.oid,
13183 opfinfo->dobj.catId.oid);
13185 else if (fout->remoteVersion >= 80400)
13187 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13188 "amopopr::pg_catalog.regoperator, "
13189 "NULL AS sortfamily, "
13190 "NULL AS sortfamilynsp "
13191 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13192 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13193 "AND refobjid = '%u'::pg_catalog.oid "
13194 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13195 "AND objid = ao.oid "
13196 "ORDER BY amopstrategy",
13197 opfinfo->dobj.catId.oid);
13201 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13202 "amopopr::pg_catalog.regoperator, "
13203 "NULL AS sortfamily, "
13204 "NULL AS sortfamilynsp "
13205 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13206 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13207 "AND refobjid = '%u'::pg_catalog.oid "
13208 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13209 "AND objid = ao.oid "
13210 "ORDER BY amopstrategy",
13211 opfinfo->dobj.catId.oid);
13214 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13216 resetPQExpBuffer(query);
13218 appendPQExpBuffer(query, "SELECT amprocnum, "
13219 "amproc::pg_catalog.regprocedure, "
13220 "amproclefttype::pg_catalog.regtype, "
13221 "amprocrighttype::pg_catalog.regtype "
13222 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13223 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13224 "AND refobjid = '%u'::pg_catalog.oid "
13225 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13226 "AND objid = ap.oid "
13227 "ORDER BY amprocnum",
13228 opfinfo->dobj.catId.oid);
13230 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13232 /* Get additional fields from the pg_opfamily row */
13233 resetPQExpBuffer(query);
13235 appendPQExpBuffer(query, "SELECT "
13236 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13237 "FROM pg_catalog.pg_opfamily "
13238 "WHERE oid = '%u'::pg_catalog.oid",
13239 opfinfo->dobj.catId.oid);
13241 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13243 i_amname = PQfnumber(res, "amname");
13245 /* amname will still be needed after we PQclear res */
13246 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13249 * DROP must be fully qualified in case same name appears in pg_catalog
13251 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13252 fmtId(opfinfo->dobj.namespace->dobj.name));
13253 appendPQExpBuffer(delq, ".%s",
13254 fmtId(opfinfo->dobj.name));
13255 appendPQExpBuffer(delq, " USING %s;\n",
13258 /* Build the fixed portion of the CREATE command */
13259 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13260 fmtId(opfinfo->dobj.name));
13261 appendPQExpBuffer(q, " USING %s;\n",
13266 /* Do we need an ALTER to add loose members? */
13267 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13269 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13270 fmtId(opfinfo->dobj.name));
13271 appendPQExpBuffer(q, " USING %s ADD\n ",
13277 * Now fetch and print the OPERATOR entries (pg_amop rows).
13279 ntups = PQntuples(res_ops);
13281 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13282 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13283 i_amopopr = PQfnumber(res_ops, "amopopr");
13284 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13285 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13287 for (i = 0; i < ntups; i++)
13289 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13290 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13291 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13292 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13293 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13296 appendPQExpBufferStr(q, " ,\n ");
13298 appendPQExpBuffer(q, "OPERATOR %s %s",
13299 amopstrategy, amopopr);
13301 if (strlen(sortfamily) > 0)
13303 appendPQExpBufferStr(q, " FOR ORDER BY ");
13304 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
13305 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13306 appendPQExpBufferStr(q, fmtId(sortfamily));
13309 if (strcmp(amopreqcheck, "t") == 0)
13310 appendPQExpBufferStr(q, " RECHECK");
13316 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13318 ntups = PQntuples(res_procs);
13320 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13321 i_amproc = PQfnumber(res_procs, "amproc");
13322 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13323 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13325 for (i = 0; i < ntups; i++)
13327 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13328 amproc = PQgetvalue(res_procs, i, i_amproc);
13329 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13330 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13333 appendPQExpBufferStr(q, " ,\n ");
13335 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13336 amprocnum, amproclefttype, amprocrighttype,
13342 appendPQExpBufferStr(q, ";\n");
13345 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
13346 fmtId(opfinfo->dobj.name));
13347 appendPQExpBuffer(labelq, " USING %s",
13350 if (dopt->binary_upgrade)
13351 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
13353 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13354 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13355 opfinfo->dobj.name,
13356 opfinfo->dobj.namespace->dobj.name,
13359 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13360 q->data, delq->data, NULL,
13364 /* Dump Operator Family Comments */
13365 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13366 dumpComment(fout, labelq->data,
13367 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13368 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13372 PQclear(res_procs);
13373 destroyPQExpBuffer(query);
13374 destroyPQExpBuffer(q);
13375 destroyPQExpBuffer(delq);
13376 destroyPQExpBuffer(labelq);
13381 * write out a single collation definition
13384 dumpCollation(Archive *fout, CollInfo *collinfo)
13386 DumpOptions *dopt = fout->dopt;
13390 PQExpBuffer labelq;
13392 int i_collprovider;
13395 const char *collprovider;
13396 const char *collcollate;
13397 const char *collctype;
13399 /* Skip if not to be dumped */
13400 if (!collinfo->dobj.dump || dopt->dataOnly)
13403 query = createPQExpBuffer();
13404 q = createPQExpBuffer();
13405 delq = createPQExpBuffer();
13406 labelq = createPQExpBuffer();
13408 /* Make sure we are in proper schema */
13409 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
13411 /* Get collation-specific details */
13412 if (fout->remoteVersion >= 100000)
13413 appendPQExpBuffer(query, "SELECT "
13418 "FROM pg_catalog.pg_collation c "
13419 "WHERE c.oid = '%u'::pg_catalog.oid",
13420 collinfo->dobj.catId.oid);
13422 appendPQExpBuffer(query, "SELECT "
13423 "'c' AS collprovider, "
13426 "NULL AS collversion "
13427 "FROM pg_catalog.pg_collation c "
13428 "WHERE c.oid = '%u'::pg_catalog.oid",
13429 collinfo->dobj.catId.oid);
13431 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13433 i_collprovider = PQfnumber(res, "collprovider");
13434 i_collcollate = PQfnumber(res, "collcollate");
13435 i_collctype = PQfnumber(res, "collctype");
13437 collprovider = PQgetvalue(res, 0, i_collprovider);
13438 collcollate = PQgetvalue(res, 0, i_collcollate);
13439 collctype = PQgetvalue(res, 0, i_collctype);
13442 * DROP must be fully qualified in case same name appears in pg_catalog
13444 appendPQExpBuffer(delq, "DROP COLLATION %s",
13445 fmtId(collinfo->dobj.namespace->dobj.name));
13446 appendPQExpBuffer(delq, ".%s;\n",
13447 fmtId(collinfo->dobj.name));
13449 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13450 fmtId(collinfo->dobj.name));
13452 appendPQExpBufferStr(q, "provider = ");
13453 if (collprovider[0] == 'c')
13454 appendPQExpBufferStr(q, "libc");
13455 else if (collprovider[0] == 'i')
13456 appendPQExpBufferStr(q, "icu");
13457 else if (collprovider[0] == 'd')
13458 /* to allow dumping pg_catalog; not accepted on input */
13459 appendPQExpBufferStr(q, "default");
13461 exit_horribly(NULL,
13462 "unrecognized collation provider: %s\n",
13465 if (strcmp(collcollate, collctype) == 0)
13467 appendPQExpBufferStr(q, ", locale = ");
13468 appendStringLiteralAH(q, collcollate, fout);
13472 appendPQExpBufferStr(q, ", lc_collate = ");
13473 appendStringLiteralAH(q, collcollate, fout);
13474 appendPQExpBufferStr(q, ", lc_ctype = ");
13475 appendStringLiteralAH(q, collctype, fout);
13479 * For binary upgrade, carry over the collation version. For normal
13480 * dump/restore, omit the version, so that it is computed upon restore.
13482 if (dopt->binary_upgrade)
13486 i_collversion = PQfnumber(res, "collversion");
13487 if (!PQgetisnull(res, 0, i_collversion))
13489 appendPQExpBufferStr(q, ", version = ");
13490 appendStringLiteralAH(q,
13491 PQgetvalue(res, 0, i_collversion),
13496 appendPQExpBufferStr(q, ");\n");
13498 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
13500 if (dopt->binary_upgrade)
13501 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
13503 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13504 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13505 collinfo->dobj.name,
13506 collinfo->dobj.namespace->dobj.name,
13509 false, "COLLATION", SECTION_PRE_DATA,
13510 q->data, delq->data, NULL,
13514 /* Dump Collation Comments */
13515 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13516 dumpComment(fout, labelq->data,
13517 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13518 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13522 destroyPQExpBuffer(query);
13523 destroyPQExpBuffer(q);
13524 destroyPQExpBuffer(delq);
13525 destroyPQExpBuffer(labelq);
13530 * write out a single conversion definition
13533 dumpConversion(Archive *fout, ConvInfo *convinfo)
13535 DumpOptions *dopt = fout->dopt;
13539 PQExpBuffer labelq;
13541 int i_conforencoding;
13542 int i_contoencoding;
13545 const char *conforencoding;
13546 const char *contoencoding;
13547 const char *conproc;
13550 /* Skip if not to be dumped */
13551 if (!convinfo->dobj.dump || dopt->dataOnly)
13554 query = createPQExpBuffer();
13555 q = createPQExpBuffer();
13556 delq = createPQExpBuffer();
13557 labelq = createPQExpBuffer();
13559 /* Make sure we are in proper schema */
13560 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
13562 /* Get conversion-specific details */
13563 appendPQExpBuffer(query, "SELECT "
13564 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13565 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13566 "conproc, condefault "
13567 "FROM pg_catalog.pg_conversion c "
13568 "WHERE c.oid = '%u'::pg_catalog.oid",
13569 convinfo->dobj.catId.oid);
13571 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13573 i_conforencoding = PQfnumber(res, "conforencoding");
13574 i_contoencoding = PQfnumber(res, "contoencoding");
13575 i_conproc = PQfnumber(res, "conproc");
13576 i_condefault = PQfnumber(res, "condefault");
13578 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13579 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13580 conproc = PQgetvalue(res, 0, i_conproc);
13581 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13584 * DROP must be fully qualified in case same name appears in pg_catalog
13586 appendPQExpBuffer(delq, "DROP CONVERSION %s",
13587 fmtId(convinfo->dobj.namespace->dobj.name));
13588 appendPQExpBuffer(delq, ".%s;\n",
13589 fmtId(convinfo->dobj.name));
13591 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13592 (condefault) ? "DEFAULT " : "",
13593 fmtId(convinfo->dobj.name));
13594 appendStringLiteralAH(q, conforencoding, fout);
13595 appendPQExpBufferStr(q, " TO ");
13596 appendStringLiteralAH(q, contoencoding, fout);
13597 /* regproc output is already sufficiently quoted */
13598 appendPQExpBuffer(q, " FROM %s;\n", conproc);
13600 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
13602 if (dopt->binary_upgrade)
13603 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
13605 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13606 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13607 convinfo->dobj.name,
13608 convinfo->dobj.namespace->dobj.name,
13611 false, "CONVERSION", SECTION_PRE_DATA,
13612 q->data, delq->data, NULL,
13616 /* Dump Conversion Comments */
13617 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13618 dumpComment(fout, labelq->data,
13619 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13620 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13624 destroyPQExpBuffer(query);
13625 destroyPQExpBuffer(q);
13626 destroyPQExpBuffer(delq);
13627 destroyPQExpBuffer(labelq);
13631 * format_aggregate_signature: generate aggregate name and argument list
13633 * The argument type names are qualified if needed. The aggregate name
13634 * is never qualified.
13637 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13639 PQExpBufferData buf;
13642 initPQExpBuffer(&buf);
13644 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13646 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13648 if (agginfo->aggfn.nargs == 0)
13649 appendPQExpBuffer(&buf, "(*)");
13652 appendPQExpBufferChar(&buf, '(');
13653 for (j = 0; j < agginfo->aggfn.nargs; j++)
13657 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13660 appendPQExpBuffer(&buf, "%s%s",
13661 (j > 0) ? ", " : "",
13665 appendPQExpBufferChar(&buf, ')');
13672 * write out a single aggregate definition
13675 dumpAgg(Archive *fout, AggInfo *agginfo)
13677 DumpOptions *dopt = fout->dopt;
13681 PQExpBuffer labelq;
13682 PQExpBuffer details;
13683 char *aggsig; /* identity signature */
13684 char *aggfullsig = NULL; /* full signature */
13689 int i_aggcombinefn;
13691 int i_aggdeserialfn;
13693 int i_aggminvtransfn;
13695 int i_aggfinalextra;
13696 int i_aggmfinalextra;
13697 int i_aggfinalmodify;
13698 int i_aggmfinalmodify;
13701 int i_aggtranstype;
13702 int i_aggtransspace;
13703 int i_aggmtranstype;
13704 int i_aggmtransspace;
13709 const char *aggtransfn;
13710 const char *aggfinalfn;
13711 const char *aggcombinefn;
13712 const char *aggserialfn;
13713 const char *aggdeserialfn;
13714 const char *aggmtransfn;
13715 const char *aggminvtransfn;
13716 const char *aggmfinalfn;
13717 bool aggfinalextra;
13718 bool aggmfinalextra;
13719 char aggfinalmodify;
13720 char aggmfinalmodify;
13721 const char *aggsortop;
13722 char *aggsortconvop;
13724 const char *aggtranstype;
13725 const char *aggtransspace;
13726 const char *aggmtranstype;
13727 const char *aggmtransspace;
13728 const char *agginitval;
13729 const char *aggminitval;
13731 const char *proparallel;
13732 char defaultfinalmodify;
13734 /* Skip if not to be dumped */
13735 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13738 query = createPQExpBuffer();
13739 q = createPQExpBuffer();
13740 delq = createPQExpBuffer();
13741 labelq = createPQExpBuffer();
13742 details = createPQExpBuffer();
13744 /* Make sure we are in proper schema */
13745 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
13747 /* Get aggregate-specific details */
13748 if (fout->remoteVersion >= 110000)
13750 appendPQExpBuffer(query, "SELECT aggtransfn, "
13751 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13752 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13753 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13754 "aggfinalextra, aggmfinalextra, "
13755 "aggfinalmodify, aggmfinalmodify, "
13756 "aggsortop::pg_catalog.regoperator, "
13758 "aggtransspace, agginitval, "
13759 "aggmtransspace, aggminitval, "
13760 "true AS convertok, "
13761 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13762 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13764 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13765 "WHERE a.aggfnoid = p.oid "
13766 "AND p.oid = '%u'::pg_catalog.oid",
13767 agginfo->aggfn.dobj.catId.oid);
13769 else if (fout->remoteVersion >= 90600)
13771 appendPQExpBuffer(query, "SELECT aggtransfn, "
13772 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13773 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13774 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13775 "aggfinalextra, aggmfinalextra, "
13776 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13777 "aggsortop::pg_catalog.regoperator, "
13779 "aggtransspace, agginitval, "
13780 "aggmtransspace, aggminitval, "
13781 "true AS convertok, "
13782 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13783 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13785 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13786 "WHERE a.aggfnoid = p.oid "
13787 "AND p.oid = '%u'::pg_catalog.oid",
13788 agginfo->aggfn.dobj.catId.oid);
13790 else if (fout->remoteVersion >= 90400)
13792 appendPQExpBuffer(query, "SELECT aggtransfn, "
13793 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13794 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13795 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13796 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13797 "aggfinalextra, aggmfinalextra, "
13798 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13799 "aggsortop::pg_catalog.regoperator, "
13801 "aggtransspace, agginitval, "
13802 "aggmtransspace, aggminitval, "
13803 "true AS convertok, "
13804 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13805 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13806 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13807 "WHERE a.aggfnoid = p.oid "
13808 "AND p.oid = '%u'::pg_catalog.oid",
13809 agginfo->aggfn.dobj.catId.oid);
13811 else if (fout->remoteVersion >= 80400)
13813 appendPQExpBuffer(query, "SELECT aggtransfn, "
13814 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13815 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13816 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13817 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13818 "0 AS aggmtranstype, false AS aggfinalextra, "
13819 "false AS aggmfinalextra, "
13820 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13821 "aggsortop::pg_catalog.regoperator, "
13823 "0 AS aggtransspace, agginitval, "
13824 "0 AS aggmtransspace, NULL AS aggminitval, "
13825 "true AS convertok, "
13826 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13827 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13828 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13829 "WHERE a.aggfnoid = p.oid "
13830 "AND p.oid = '%u'::pg_catalog.oid",
13831 agginfo->aggfn.dobj.catId.oid);
13833 else if (fout->remoteVersion >= 80100)
13835 appendPQExpBuffer(query, "SELECT aggtransfn, "
13836 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13837 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13838 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13839 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13840 "0 AS aggmtranstype, false AS aggfinalextra, "
13841 "false AS aggmfinalextra, "
13842 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13843 "aggsortop::pg_catalog.regoperator, "
13845 "0 AS aggtransspace, agginitval, "
13846 "0 AS aggmtransspace, NULL AS aggminitval, "
13847 "true AS convertok "
13848 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13849 "WHERE a.aggfnoid = p.oid "
13850 "AND p.oid = '%u'::pg_catalog.oid",
13851 agginfo->aggfn.dobj.catId.oid);
13855 appendPQExpBuffer(query, "SELECT aggtransfn, "
13856 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13857 "'-' AS aggcombinefn, '-' AS aggserialfn, "
13858 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13859 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13860 "0 AS aggmtranstype, false AS aggfinalextra, "
13861 "false AS aggmfinalextra, "
13862 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13865 "0 AS aggtransspace, agginitval, "
13866 "0 AS aggmtransspace, NULL AS aggminitval, "
13867 "true AS convertok "
13868 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13869 "WHERE a.aggfnoid = p.oid "
13870 "AND p.oid = '%u'::pg_catalog.oid",
13871 agginfo->aggfn.dobj.catId.oid);
13874 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13876 i_aggtransfn = PQfnumber(res, "aggtransfn");
13877 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13878 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13879 i_aggserialfn = PQfnumber(res, "aggserialfn");
13880 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13881 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13882 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13883 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13884 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13885 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13886 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13887 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13888 i_aggsortop = PQfnumber(res, "aggsortop");
13889 i_aggkind = PQfnumber(res, "aggkind");
13890 i_aggtranstype = PQfnumber(res, "aggtranstype");
13891 i_aggtransspace = PQfnumber(res, "aggtransspace");
13892 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13893 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13894 i_agginitval = PQfnumber(res, "agginitval");
13895 i_aggminitval = PQfnumber(res, "aggminitval");
13896 i_convertok = PQfnumber(res, "convertok");
13897 i_proparallel = PQfnumber(res, "proparallel");
13899 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13900 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13901 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13902 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13903 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13904 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13905 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13906 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13907 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13908 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13909 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13910 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13911 aggsortop = PQgetvalue(res, 0, i_aggsortop);
13912 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13913 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13914 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13915 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13916 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13917 agginitval = PQgetvalue(res, 0, i_agginitval);
13918 aggminitval = PQgetvalue(res, 0, i_aggminitval);
13919 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13921 if (fout->remoteVersion >= 80400)
13923 /* 8.4 or later; we rely on server-side code for most of the work */
13927 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13928 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13929 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13930 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13933 /* pre-8.4, do it ourselves */
13934 aggsig = format_aggregate_signature(agginfo, fout, true);
13936 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13938 if (i_proparallel != -1)
13939 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13941 proparallel = NULL;
13945 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13956 /* identify default modify flag for aggkind (must match DefineAggregate) */
13957 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13958 /* replace omitted flags for old versions */
13959 if (aggfinalmodify == '0')
13960 aggfinalmodify = defaultfinalmodify;
13961 if (aggmfinalmodify == '0')
13962 aggmfinalmodify = defaultfinalmodify;
13964 /* regproc and regtype output is already sufficiently quoted */
13965 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
13966 aggtransfn, aggtranstype);
13968 if (strcmp(aggtransspace, "0") != 0)
13970 appendPQExpBuffer(details, ",\n SSPACE = %s",
13974 if (!PQgetisnull(res, 0, i_agginitval))
13976 appendPQExpBufferStr(details, ",\n INITCOND = ");
13977 appendStringLiteralAH(details, agginitval, fout);
13980 if (strcmp(aggfinalfn, "-") != 0)
13982 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
13985 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
13986 if (aggfinalmodify != defaultfinalmodify)
13988 switch (aggfinalmodify)
13990 case AGGMODIFY_READ_ONLY:
13991 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
13993 case AGGMODIFY_SHARABLE:
13994 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHARABLE");
13996 case AGGMODIFY_READ_WRITE:
13997 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
14000 exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
14001 agginfo->aggfn.dobj.name);
14007 if (strcmp(aggcombinefn, "-") != 0)
14008 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
14010 if (strcmp(aggserialfn, "-") != 0)
14011 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
14013 if (strcmp(aggdeserialfn, "-") != 0)
14014 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
14016 if (strcmp(aggmtransfn, "-") != 0)
14018 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
14024 if (strcmp(aggmtransspace, "0") != 0)
14026 appendPQExpBuffer(details, ",\n MSSPACE = %s",
14030 if (!PQgetisnull(res, 0, i_aggminitval))
14032 appendPQExpBufferStr(details, ",\n MINITCOND = ");
14033 appendStringLiteralAH(details, aggminitval, fout);
14036 if (strcmp(aggmfinalfn, "-") != 0)
14038 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
14040 if (aggmfinalextra)
14041 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
14042 if (aggmfinalmodify != defaultfinalmodify)
14044 switch (aggmfinalmodify)
14046 case AGGMODIFY_READ_ONLY:
14047 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
14049 case AGGMODIFY_SHARABLE:
14050 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHARABLE");
14052 case AGGMODIFY_READ_WRITE:
14053 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
14056 exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
14057 agginfo->aggfn.dobj.name);
14063 aggsortconvop = convertOperatorReference(fout, aggsortop);
14066 appendPQExpBuffer(details, ",\n SORTOP = %s",
14068 free(aggsortconvop);
14071 if (aggkind == AGGKIND_HYPOTHETICAL)
14072 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
14074 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
14076 if (proparallel[0] == PROPARALLEL_SAFE)
14077 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
14078 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14079 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
14080 else if (proparallel[0] != PROPARALLEL_UNSAFE)
14081 exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
14082 agginfo->aggfn.dobj.name);
14086 * DROP must be fully qualified in case same name appears in pg_catalog
14088 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14089 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14092 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
14093 aggfullsig ? aggfullsig : aggsig, details->data);
14095 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
14097 if (dopt->binary_upgrade)
14098 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
14100 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14101 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14102 agginfo->aggfn.dobj.dumpId,
14104 agginfo->aggfn.dobj.namespace->dobj.name,
14106 agginfo->aggfn.rolname,
14107 false, "AGGREGATE", SECTION_PRE_DATA,
14108 q->data, delq->data, NULL,
14112 /* Dump Aggregate Comments */
14113 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14114 dumpComment(fout, labelq->data,
14115 agginfo->aggfn.dobj.namespace->dobj.name,
14116 agginfo->aggfn.rolname,
14117 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14119 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14120 dumpSecLabel(fout, labelq->data,
14121 agginfo->aggfn.dobj.namespace->dobj.name,
14122 agginfo->aggfn.rolname,
14123 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14126 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14127 * command look like a function's GRANT; in particular this affects the
14128 * syntax for zero-argument aggregates and ordered-set aggregates.
14132 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14134 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14135 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
14137 aggsig, NULL, labelq->data,
14138 agginfo->aggfn.dobj.namespace->dobj.name,
14139 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14140 agginfo->aggfn.rproacl,
14141 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14150 destroyPQExpBuffer(query);
14151 destroyPQExpBuffer(q);
14152 destroyPQExpBuffer(delq);
14153 destroyPQExpBuffer(labelq);
14154 destroyPQExpBuffer(details);
14159 * write out a single text search parser
14162 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14164 DumpOptions *dopt = fout->dopt;
14167 PQExpBuffer labelq;
14169 /* Skip if not to be dumped */
14170 if (!prsinfo->dobj.dump || dopt->dataOnly)
14173 q = createPQExpBuffer();
14174 delq = createPQExpBuffer();
14175 labelq = createPQExpBuffer();
14177 /* Make sure we are in proper schema */
14178 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
14180 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14181 fmtId(prsinfo->dobj.name));
14183 appendPQExpBuffer(q, " START = %s,\n",
14184 convertTSFunction(fout, prsinfo->prsstart));
14185 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14186 convertTSFunction(fout, prsinfo->prstoken));
14187 appendPQExpBuffer(q, " END = %s,\n",
14188 convertTSFunction(fout, prsinfo->prsend));
14189 if (prsinfo->prsheadline != InvalidOid)
14190 appendPQExpBuffer(q, " HEADLINE = %s,\n",
14191 convertTSFunction(fout, prsinfo->prsheadline));
14192 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14193 convertTSFunction(fout, prsinfo->prslextype));
14196 * DROP must be fully qualified in case same name appears in pg_catalog
14198 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
14199 fmtId(prsinfo->dobj.namespace->dobj.name));
14200 appendPQExpBuffer(delq, ".%s;\n",
14201 fmtId(prsinfo->dobj.name));
14203 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
14204 fmtId(prsinfo->dobj.name));
14206 if (dopt->binary_upgrade)
14207 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
14209 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14210 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14211 prsinfo->dobj.name,
14212 prsinfo->dobj.namespace->dobj.name,
14215 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14216 q->data, delq->data, NULL,
14220 /* Dump Parser Comments */
14221 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14222 dumpComment(fout, labelq->data,
14223 prsinfo->dobj.namespace->dobj.name, "",
14224 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14226 destroyPQExpBuffer(q);
14227 destroyPQExpBuffer(delq);
14228 destroyPQExpBuffer(labelq);
14233 * write out a single text search dictionary
14236 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14238 DumpOptions *dopt = fout->dopt;
14241 PQExpBuffer labelq;
14247 /* Skip if not to be dumped */
14248 if (!dictinfo->dobj.dump || dopt->dataOnly)
14251 q = createPQExpBuffer();
14252 delq = createPQExpBuffer();
14253 labelq = createPQExpBuffer();
14254 query = createPQExpBuffer();
14256 /* Fetch name and namespace of the dictionary's template */
14257 selectSourceSchema(fout, "pg_catalog");
14258 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14259 "FROM pg_ts_template p, pg_namespace n "
14260 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14261 dictinfo->dicttemplate);
14262 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14263 nspname = PQgetvalue(res, 0, 0);
14264 tmplname = PQgetvalue(res, 0, 1);
14266 /* Make sure we are in proper schema */
14267 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
14269 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14270 fmtId(dictinfo->dobj.name));
14272 appendPQExpBufferStr(q, " TEMPLATE = ");
14273 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
14274 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14275 appendPQExpBufferStr(q, fmtId(tmplname));
14279 /* the dictinitoption can be dumped straight into the command */
14280 if (dictinfo->dictinitoption)
14281 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14283 appendPQExpBufferStr(q, " );\n");
14286 * DROP must be fully qualified in case same name appears in pg_catalog
14288 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
14289 fmtId(dictinfo->dobj.namespace->dobj.name));
14290 appendPQExpBuffer(delq, ".%s;\n",
14291 fmtId(dictinfo->dobj.name));
14293 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
14294 fmtId(dictinfo->dobj.name));
14296 if (dopt->binary_upgrade)
14297 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
14299 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14300 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14301 dictinfo->dobj.name,
14302 dictinfo->dobj.namespace->dobj.name,
14305 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14306 q->data, delq->data, NULL,
14310 /* Dump Dictionary Comments */
14311 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14312 dumpComment(fout, labelq->data,
14313 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14314 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14316 destroyPQExpBuffer(q);
14317 destroyPQExpBuffer(delq);
14318 destroyPQExpBuffer(labelq);
14319 destroyPQExpBuffer(query);
14324 * write out a single text search template
14327 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14329 DumpOptions *dopt = fout->dopt;
14332 PQExpBuffer labelq;
14334 /* Skip if not to be dumped */
14335 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14338 q = createPQExpBuffer();
14339 delq = createPQExpBuffer();
14340 labelq = createPQExpBuffer();
14342 /* Make sure we are in proper schema */
14343 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
14345 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14346 fmtId(tmplinfo->dobj.name));
14348 if (tmplinfo->tmplinit != InvalidOid)
14349 appendPQExpBuffer(q, " INIT = %s,\n",
14350 convertTSFunction(fout, tmplinfo->tmplinit));
14351 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14352 convertTSFunction(fout, tmplinfo->tmpllexize));
14355 * DROP must be fully qualified in case same name appears in pg_catalog
14357 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
14358 fmtId(tmplinfo->dobj.namespace->dobj.name));
14359 appendPQExpBuffer(delq, ".%s;\n",
14360 fmtId(tmplinfo->dobj.name));
14362 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
14363 fmtId(tmplinfo->dobj.name));
14365 if (dopt->binary_upgrade)
14366 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
14368 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14369 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14370 tmplinfo->dobj.name,
14371 tmplinfo->dobj.namespace->dobj.name,
14374 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14375 q->data, delq->data, NULL,
14379 /* Dump Template Comments */
14380 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14381 dumpComment(fout, labelq->data,
14382 tmplinfo->dobj.namespace->dobj.name, "",
14383 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14385 destroyPQExpBuffer(q);
14386 destroyPQExpBuffer(delq);
14387 destroyPQExpBuffer(labelq);
14392 * write out a single text search configuration
14395 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14397 DumpOptions *dopt = fout->dopt;
14400 PQExpBuffer labelq;
14410 /* Skip if not to be dumped */
14411 if (!cfginfo->dobj.dump || dopt->dataOnly)
14414 q = createPQExpBuffer();
14415 delq = createPQExpBuffer();
14416 labelq = createPQExpBuffer();
14417 query = createPQExpBuffer();
14419 /* Fetch name and namespace of the config's parser */
14420 selectSourceSchema(fout, "pg_catalog");
14421 appendPQExpBuffer(query, "SELECT nspname, prsname "
14422 "FROM pg_ts_parser p, pg_namespace n "
14423 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14424 cfginfo->cfgparser);
14425 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14426 nspname = PQgetvalue(res, 0, 0);
14427 prsname = PQgetvalue(res, 0, 1);
14429 /* Make sure we are in proper schema */
14430 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
14432 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14433 fmtId(cfginfo->dobj.name));
14435 appendPQExpBufferStr(q, " PARSER = ");
14436 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
14437 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14438 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14442 resetPQExpBuffer(query);
14443 appendPQExpBuffer(query,
14445 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14446 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14447 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14448 "FROM pg_catalog.pg_ts_config_map AS m\n"
14449 "WHERE m.mapcfg = '%u'\n"
14450 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14451 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14453 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14454 ntups = PQntuples(res);
14456 i_tokenname = PQfnumber(res, "tokenname");
14457 i_dictname = PQfnumber(res, "dictname");
14459 for (i = 0; i < ntups; i++)
14461 char *tokenname = PQgetvalue(res, i, i_tokenname);
14462 char *dictname = PQgetvalue(res, i, i_dictname);
14465 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14467 /* starting a new token type, so start a new command */
14469 appendPQExpBufferStr(q, ";\n");
14470 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14471 fmtId(cfginfo->dobj.name));
14472 /* tokenname needs quoting, dictname does NOT */
14473 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14474 fmtId(tokenname), dictname);
14477 appendPQExpBuffer(q, ", %s", dictname);
14481 appendPQExpBufferStr(q, ";\n");
14486 * DROP must be fully qualified in case same name appears in pg_catalog
14488 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
14489 fmtId(cfginfo->dobj.namespace->dobj.name));
14490 appendPQExpBuffer(delq, ".%s;\n",
14491 fmtId(cfginfo->dobj.name));
14493 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
14494 fmtId(cfginfo->dobj.name));
14496 if (dopt->binary_upgrade)
14497 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
14499 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14500 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14501 cfginfo->dobj.name,
14502 cfginfo->dobj.namespace->dobj.name,
14505 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14506 q->data, delq->data, NULL,
14510 /* Dump Configuration Comments */
14511 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14512 dumpComment(fout, labelq->data,
14513 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14514 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14516 destroyPQExpBuffer(q);
14517 destroyPQExpBuffer(delq);
14518 destroyPQExpBuffer(labelq);
14519 destroyPQExpBuffer(query);
14523 * dumpForeignDataWrapper
14524 * write out a single foreign-data wrapper definition
14527 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14529 DumpOptions *dopt = fout->dopt;
14532 PQExpBuffer labelq;
14535 /* Skip if not to be dumped */
14536 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14539 q = createPQExpBuffer();
14540 delq = createPQExpBuffer();
14541 labelq = createPQExpBuffer();
14543 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14545 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14548 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14549 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14551 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14552 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14554 if (strlen(fdwinfo->fdwoptions) > 0)
14555 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14557 appendPQExpBufferStr(q, ";\n");
14559 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14562 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
14565 if (dopt->binary_upgrade)
14566 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
14568 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14569 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14570 fdwinfo->dobj.name,
14574 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14575 q->data, delq->data, NULL,
14579 /* Dump Foreign Data Wrapper Comments */
14580 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14581 dumpComment(fout, labelq->data,
14582 NULL, fdwinfo->rolname,
14583 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14585 /* Handle the ACL */
14586 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14587 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14588 "FOREIGN DATA WRAPPER",
14589 qfdwname, NULL, labelq->data,
14590 NULL, fdwinfo->rolname,
14591 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14592 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14596 destroyPQExpBuffer(q);
14597 destroyPQExpBuffer(delq);
14598 destroyPQExpBuffer(labelq);
14602 * dumpForeignServer
14603 * write out a foreign server definition
14606 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14608 DumpOptions *dopt = fout->dopt;
14611 PQExpBuffer labelq;
14617 /* Skip if not to be dumped */
14618 if (!srvinfo->dobj.dump || dopt->dataOnly)
14621 q = createPQExpBuffer();
14622 delq = createPQExpBuffer();
14623 labelq = createPQExpBuffer();
14624 query = createPQExpBuffer();
14626 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14628 /* look up the foreign-data wrapper */
14629 selectSourceSchema(fout, "pg_catalog");
14630 appendPQExpBuffer(query, "SELECT fdwname "
14631 "FROM pg_foreign_data_wrapper w "
14632 "WHERE w.oid = '%u'",
14634 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14635 fdwname = PQgetvalue(res, 0, 0);
14637 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14638 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14640 appendPQExpBufferStr(q, " TYPE ");
14641 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14643 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14645 appendPQExpBufferStr(q, " VERSION ");
14646 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14649 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14650 appendPQExpBufferStr(q, fmtId(fdwname));
14652 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14653 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14655 appendPQExpBufferStr(q, ";\n");
14657 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14660 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
14662 if (dopt->binary_upgrade)
14663 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
14665 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14666 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14667 srvinfo->dobj.name,
14671 false, "SERVER", SECTION_PRE_DATA,
14672 q->data, delq->data, NULL,
14676 /* Dump Foreign Server Comments */
14677 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14678 dumpComment(fout, labelq->data,
14679 NULL, srvinfo->rolname,
14680 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14682 /* Handle the ACL */
14683 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14684 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14686 qsrvname, NULL, labelq->data,
14687 NULL, srvinfo->rolname,
14688 srvinfo->srvacl, srvinfo->rsrvacl,
14689 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14691 /* Dump user mappings */
14692 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14693 dumpUserMappings(fout,
14694 srvinfo->dobj.name, NULL,
14696 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14700 destroyPQExpBuffer(q);
14701 destroyPQExpBuffer(delq);
14702 destroyPQExpBuffer(labelq);
14703 destroyPQExpBuffer(query);
14709 * This routine is used to dump any user mappings associated with the
14710 * server handed to this routine. Should be called after ArchiveEntry()
14714 dumpUserMappings(Archive *fout,
14715 const char *servername, const char *namespace,
14717 CatalogId catalogId, DumpId dumpId)
14729 q = createPQExpBuffer();
14730 tag = createPQExpBuffer();
14731 delq = createPQExpBuffer();
14732 query = createPQExpBuffer();
14735 * We read from the publicly accessible view pg_user_mappings, so as not
14736 * to fail if run by a non-superuser. Note that the view will show
14737 * umoptions as null if the user hasn't got privileges for the associated
14738 * server; this means that pg_dump will dump such a mapping, but with no
14739 * OPTIONS clause. A possible alternative is to skip such mappings
14740 * altogether, but it's not clear that that's an improvement.
14742 selectSourceSchema(fout, "pg_catalog");
14744 appendPQExpBuffer(query,
14746 "array_to_string(ARRAY("
14747 "SELECT quote_ident(option_name) || ' ' || "
14748 "quote_literal(option_value) "
14749 "FROM pg_options_to_table(umoptions) "
14750 "ORDER BY option_name"
14751 "), E',\n ') AS umoptions "
14752 "FROM pg_user_mappings "
14753 "WHERE srvid = '%u' "
14754 "ORDER BY usename",
14757 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14759 ntups = PQntuples(res);
14760 i_usename = PQfnumber(res, "usename");
14761 i_umoptions = PQfnumber(res, "umoptions");
14763 for (i = 0; i < ntups; i++)
14768 usename = PQgetvalue(res, i, i_usename);
14769 umoptions = PQgetvalue(res, i, i_umoptions);
14771 resetPQExpBuffer(q);
14772 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14773 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14775 if (umoptions && strlen(umoptions) > 0)
14776 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
14778 appendPQExpBufferStr(q, ";\n");
14780 resetPQExpBuffer(delq);
14781 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14782 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14784 resetPQExpBuffer(tag);
14785 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14786 usename, servername);
14788 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14793 "USER MAPPING", SECTION_PRE_DATA,
14794 q->data, delq->data, NULL,
14801 destroyPQExpBuffer(query);
14802 destroyPQExpBuffer(delq);
14803 destroyPQExpBuffer(tag);
14804 destroyPQExpBuffer(q);
14808 * Write out default privileges information
14811 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14813 DumpOptions *dopt = fout->dopt;
14818 /* Skip if not to be dumped */
14819 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14822 q = createPQExpBuffer();
14823 tag = createPQExpBuffer();
14825 switch (daclinfo->defaclobjtype)
14827 case DEFACLOBJ_RELATION:
14830 case DEFACLOBJ_SEQUENCE:
14831 type = "SEQUENCES";
14833 case DEFACLOBJ_FUNCTION:
14834 type = "FUNCTIONS";
14836 case DEFACLOBJ_TYPE:
14839 case DEFACLOBJ_NAMESPACE:
14843 /* shouldn't get here */
14844 exit_horribly(NULL,
14845 "unrecognized object type in default privileges: %d\n",
14846 (int) daclinfo->defaclobjtype);
14847 type = ""; /* keep compiler quiet */
14850 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14852 /* build the actual command(s) for this tuple */
14853 if (!buildDefaultACLCommands(type,
14854 daclinfo->dobj.namespace != NULL ?
14855 daclinfo->dobj.namespace->dobj.name : NULL,
14856 daclinfo->defaclacl,
14857 daclinfo->rdefaclacl,
14858 daclinfo->initdefaclacl,
14859 daclinfo->initrdefaclacl,
14860 daclinfo->defaclrole,
14861 fout->remoteVersion,
14863 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14864 daclinfo->defaclacl);
14866 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14867 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14869 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14871 daclinfo->defaclrole,
14872 false, "DEFAULT ACL", SECTION_POST_DATA,
14877 destroyPQExpBuffer(tag);
14878 destroyPQExpBuffer(q);
14882 * Write out grant/revoke information
14884 * 'objCatId' is the catalog ID of the underlying object.
14885 * 'objDumpId' is the dump ID of the underlying object.
14886 * 'type' must be one of
14887 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14888 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14889 * 'name' is the formatted name of the object. Must be quoted etc. already.
14890 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
14891 * 'tag' is the tag for the archive entry (should be the same tag as would be
14892 * used for comments etc; for example "TABLE foo").
14893 * 'nspname' is the namespace the object is in (NULL if none).
14894 * 'owner' is the owner, NULL if there is no owner (for languages).
14895 * 'acls' contains the ACL string of the object from the appropriate system
14896 * catalog field; it will be passed to buildACLCommands for building the
14897 * appropriate GRANT commands.
14898 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14899 * object; it will be passed to buildACLCommands for building the
14900 * appropriate REVOKE commands.
14901 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14902 * privileges, to be recorded into pg_init_privs
14903 * 'initracls' In binary-upgrade mode, ACL string of the object's
14904 * revoked-from-default privileges, to be recorded into pg_init_privs
14906 * NB: initacls/initracls are needed because extensions can set privileges on
14907 * an object during the extension's script file and we record those into
14908 * pg_init_privs as that object's initial privileges.
14912 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14913 const char *type, const char *name, const char *subname,
14914 const char *tag, const char *nspname, const char *owner,
14915 const char *acls, const char *racls,
14916 const char *initacls, const char *initracls)
14918 DumpOptions *dopt = fout->dopt;
14921 /* Do nothing if ACL dump is not enabled */
14922 if (dopt->aclsSkip)
14925 /* --data-only skips ACLs *except* BLOB ACLs */
14926 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14929 sql = createPQExpBuffer();
14932 * Check to see if this object has had any initial ACLs included for it.
14933 * If so, we are in binary upgrade mode and these are the ACLs to turn
14934 * into GRANT and REVOKE statements to set and record the initial
14935 * privileges for an extension object. Let the backend know that these
14936 * are to be recorded by calling binary_upgrade_set_record_init_privs()
14937 * before and after.
14939 if (strlen(initacls) != 0 || strlen(initracls) != 0)
14941 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14942 if (!buildACLCommands(name, subname, type, initacls, initracls, owner,
14943 "", fout->remoteVersion, sql))
14944 exit_horribly(NULL,
14945 "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14946 initacls, initracls, name, type);
14947 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14950 if (!buildACLCommands(name, subname, type, acls, racls, owner,
14951 "", fout->remoteVersion, sql))
14952 exit_horribly(NULL,
14953 "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14954 acls, racls, name, type);
14957 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14960 owner ? owner : "",
14961 false, "ACL", SECTION_NONE,
14962 sql->data, "", NULL,
14966 destroyPQExpBuffer(sql);
14972 * This routine is used to dump any security labels associated with the
14973 * object handed to this routine. The routine takes a constant character
14974 * string for the target part of the security-label command, plus
14975 * the namespace and owner of the object (for labeling the ArchiveEntry),
14976 * plus catalog ID and subid which are the lookup key for pg_seclabel,
14977 * plus the dump ID for the object (for setting a dependency).
14978 * If a matching pg_seclabel entry is found, it is dumped.
14980 * Note: although this routine takes a dumpId for dependency purposes,
14981 * that purpose is just to mark the dependency in the emitted dump file
14982 * for possible future use by pg_restore. We do NOT use it for determining
14983 * ordering of the label in the dump file, because this routine is called
14984 * after dependency sorting occurs. This routine should be called just after
14985 * calling ArchiveEntry() for the specified object.
14988 dumpSecLabel(Archive *fout, const char *target,
14989 const char *namespace, const char *owner,
14990 CatalogId catalogId, int subid, DumpId dumpId)
14992 DumpOptions *dopt = fout->dopt;
14993 SecLabelItem *labels;
14998 /* do nothing, if --no-security-labels is supplied */
14999 if (dopt->no_security_labels)
15002 /* Security labels are schema not data ... except blob labels are data */
15003 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
15005 if (dopt->dataOnly)
15010 /* We do dump blob security labels in binary-upgrade mode */
15011 if (dopt->schemaOnly && !dopt->binary_upgrade)
15015 /* Search for security labels associated with catalogId, using table */
15016 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
15018 query = createPQExpBuffer();
15020 for (i = 0; i < nlabels; i++)
15023 * Ignore label entries for which the subid doesn't match.
15025 if (labels[i].objsubid != subid)
15028 appendPQExpBuffer(query,
15029 "SECURITY LABEL FOR %s ON %s IS ",
15030 fmtId(labels[i].provider), target);
15031 appendStringLiteralAH(query, labels[i].label, fout);
15032 appendPQExpBufferStr(query, ";\n");
15035 if (query->len > 0)
15037 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15038 target, namespace, NULL, owner,
15039 false, "SECURITY LABEL", SECTION_NONE,
15040 query->data, "", NULL,
15044 destroyPQExpBuffer(query);
15048 * dumpTableSecLabel
15050 * As above, but dump security label for both the specified table (or view)
15054 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
15056 DumpOptions *dopt = fout->dopt;
15057 SecLabelItem *labels;
15061 PQExpBuffer target;
15063 /* do nothing, if --no-security-labels is supplied */
15064 if (dopt->no_security_labels)
15067 /* SecLabel are SCHEMA not data */
15068 if (dopt->dataOnly)
15071 /* Search for comments associated with relation, using table */
15072 nlabels = findSecLabels(fout,
15073 tbinfo->dobj.catId.tableoid,
15074 tbinfo->dobj.catId.oid,
15077 /* If security labels exist, build SECURITY LABEL statements */
15081 query = createPQExpBuffer();
15082 target = createPQExpBuffer();
15084 for (i = 0; i < nlabels; i++)
15086 const char *colname;
15087 const char *provider = labels[i].provider;
15088 const char *label = labels[i].label;
15089 int objsubid = labels[i].objsubid;
15091 resetPQExpBuffer(target);
15094 appendPQExpBuffer(target, "%s %s", reltypename,
15095 fmtId(tbinfo->dobj.name));
15099 colname = getAttrName(objsubid, tbinfo);
15100 /* first fmtId result must be consumed before calling it again */
15101 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
15102 appendPQExpBuffer(target, ".%s", fmtId(colname));
15104 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
15105 fmtId(provider), target->data);
15106 appendStringLiteralAH(query, label, fout);
15107 appendPQExpBufferStr(query, ";\n");
15109 if (query->len > 0)
15111 resetPQExpBuffer(target);
15112 appendPQExpBuffer(target, "%s %s", reltypename,
15113 fmtId(tbinfo->dobj.name));
15114 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15116 tbinfo->dobj.namespace->dobj.name,
15117 NULL, tbinfo->rolname,
15118 false, "SECURITY LABEL", SECTION_NONE,
15119 query->data, "", NULL,
15120 &(tbinfo->dobj.dumpId), 1,
15123 destroyPQExpBuffer(query);
15124 destroyPQExpBuffer(target);
15130 * Find the security label(s), if any, associated with the given object.
15131 * All the objsubid values associated with the given classoid/objoid are
15132 * found with one search.
15135 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15137 /* static storage for table of security labels */
15138 static SecLabelItem *labels = NULL;
15139 static int nlabels = -1;
15141 SecLabelItem *middle = NULL;
15143 SecLabelItem *high;
15146 /* Get security labels if we didn't already */
15148 nlabels = collectSecLabels(fout, &labels);
15150 if (nlabels <= 0) /* no labels, so no match is possible */
15157 * Do binary search to find some item matching the object.
15160 high = &labels[nlabels - 1];
15161 while (low <= high)
15163 middle = low + (high - low) / 2;
15165 if (classoid < middle->classoid)
15167 else if (classoid > middle->classoid)
15169 else if (objoid < middle->objoid)
15171 else if (objoid > middle->objoid)
15174 break; /* found a match */
15177 if (low > high) /* no matches */
15184 * Now determine how many items match the object. The search loop
15185 * invariant still holds: only items between low and high inclusive could
15189 while (middle > low)
15191 if (classoid != middle[-1].classoid ||
15192 objoid != middle[-1].objoid)
15201 while (middle <= high)
15203 if (classoid != middle->classoid ||
15204 objoid != middle->objoid)
15216 * Construct a table of all security labels available for database objects.
15217 * It's much faster to pull them all at once.
15219 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15222 collectSecLabels(Archive *fout, SecLabelItem **items)
15233 SecLabelItem *labels;
15235 query = createPQExpBuffer();
15237 appendPQExpBufferStr(query,
15238 "SELECT label, provider, classoid, objoid, objsubid "
15239 "FROM pg_catalog.pg_seclabel "
15240 "ORDER BY classoid, objoid, objsubid");
15242 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15244 /* Construct lookup table containing OIDs in numeric form */
15245 i_label = PQfnumber(res, "label");
15246 i_provider = PQfnumber(res, "provider");
15247 i_classoid = PQfnumber(res, "classoid");
15248 i_objoid = PQfnumber(res, "objoid");
15249 i_objsubid = PQfnumber(res, "objsubid");
15251 ntups = PQntuples(res);
15253 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15255 for (i = 0; i < ntups; i++)
15257 labels[i].label = PQgetvalue(res, i, i_label);
15258 labels[i].provider = PQgetvalue(res, i, i_provider);
15259 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15260 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15261 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15264 /* Do NOT free the PGresult since we are keeping pointers into it */
15265 destroyPQExpBuffer(query);
15273 * write out to fout the declarations (not data) of a user-defined table
15276 dumpTable(Archive *fout, TableInfo *tbinfo)
15278 DumpOptions *dopt = fout->dopt;
15282 * noop if we are not dumping anything about this table, or if we are
15283 * doing a data-only dump
15285 if (!tbinfo->dobj.dump || dopt->dataOnly)
15288 if (tbinfo->relkind == RELKIND_SEQUENCE)
15289 dumpSequence(fout, tbinfo);
15291 dumpTableSchema(fout, tbinfo);
15293 /* Handle the ACL here */
15294 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15295 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15297 const char *objtype =
15298 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15299 char *acltag = psprintf("%s %s", objtype, namecopy);
15301 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15302 objtype, namecopy, NULL, acltag,
15303 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15304 tbinfo->relacl, tbinfo->rrelacl,
15305 tbinfo->initrelacl, tbinfo->initrrelacl);
15310 * Handle column ACLs, if any. Note: we pull these with a separate query
15311 * rather than trying to fetch them during getTableAttrs, so that we won't
15312 * miss ACLs on system columns.
15314 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15316 PQExpBuffer query = createPQExpBuffer();
15320 if (fout->remoteVersion >= 90600)
15322 PQExpBuffer acl_subquery = createPQExpBuffer();
15323 PQExpBuffer racl_subquery = createPQExpBuffer();
15324 PQExpBuffer initacl_subquery = createPQExpBuffer();
15325 PQExpBuffer initracl_subquery = createPQExpBuffer();
15327 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15328 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15329 dopt->binary_upgrade);
15331 appendPQExpBuffer(query,
15332 "SELECT at.attname, "
15335 "%s AS initattacl, "
15336 "%s AS initrattacl "
15337 "FROM pg_catalog.pg_attribute at "
15338 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15339 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15340 "(at.attrelid = pip.objoid "
15341 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15342 "AND at.attnum = pip.objsubid) "
15343 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15344 "NOT at.attisdropped "
15346 "%s IS NOT NULL OR "
15347 "%s IS NOT NULL OR "
15348 "%s IS NOT NULL OR "
15350 "ORDER BY at.attnum",
15351 acl_subquery->data,
15352 racl_subquery->data,
15353 initacl_subquery->data,
15354 initracl_subquery->data,
15355 tbinfo->dobj.catId.oid,
15356 acl_subquery->data,
15357 racl_subquery->data,
15358 initacl_subquery->data,
15359 initracl_subquery->data);
15361 destroyPQExpBuffer(acl_subquery);
15362 destroyPQExpBuffer(racl_subquery);
15363 destroyPQExpBuffer(initacl_subquery);
15364 destroyPQExpBuffer(initracl_subquery);
15368 appendPQExpBuffer(query,
15369 "SELECT attname, attacl, NULL as rattacl, "
15370 "NULL AS initattacl, NULL AS initrattacl "
15371 "FROM pg_catalog.pg_attribute "
15372 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15373 "AND attacl IS NOT NULL "
15375 tbinfo->dobj.catId.oid);
15378 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15380 for (i = 0; i < PQntuples(res); i++)
15382 char *attname = PQgetvalue(res, i, 0);
15383 char *attacl = PQgetvalue(res, i, 1);
15384 char *rattacl = PQgetvalue(res, i, 2);
15385 char *initattacl = PQgetvalue(res, i, 3);
15386 char *initrattacl = PQgetvalue(res, i, 4);
15390 attnamecopy = pg_strdup(fmtId(attname));
15391 acltag = psprintf("COLUMN %s.%s", namecopy, attnamecopy);
15392 /* Column's GRANT type is always TABLE */
15393 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
15394 namecopy, attnamecopy, acltag,
15395 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15396 attacl, rattacl, initattacl, initrattacl);
15401 destroyPQExpBuffer(query);
15410 * Create the AS clause for a view or materialized view. The semicolon is
15411 * stripped because a materialized view must add a WITH NO DATA clause.
15413 * This returns a new buffer which must be freed by the caller.
15416 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15418 PQExpBuffer query = createPQExpBuffer();
15419 PQExpBuffer result = createPQExpBuffer();
15423 /* Fetch the view definition */
15424 appendPQExpBuffer(query,
15425 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15426 tbinfo->dobj.catId.oid);
15428 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15430 if (PQntuples(res) != 1)
15432 if (PQntuples(res) < 1)
15433 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15434 tbinfo->dobj.name);
15436 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15437 tbinfo->dobj.name);
15440 len = PQgetlength(res, 0, 0);
15443 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15444 tbinfo->dobj.name);
15446 /* Strip off the trailing semicolon so that other things may follow. */
15447 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15448 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15451 destroyPQExpBuffer(query);
15457 * Create a dummy AS clause for a view. This is used when the real view
15458 * definition has to be postponed because of circular dependencies.
15459 * We must duplicate the view's external properties -- column names and types
15460 * (including collation) -- so that it works for subsequent references.
15462 * This returns a new buffer which must be freed by the caller.
15465 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15467 PQExpBuffer result = createPQExpBuffer();
15470 appendPQExpBufferStr(result, "SELECT");
15472 for (j = 0; j < tbinfo->numatts; j++)
15475 appendPQExpBufferChar(result, ',');
15476 appendPQExpBufferStr(result, "\n ");
15478 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15481 * Must add collation if not default for the type, because CREATE OR
15482 * REPLACE VIEW won't change it
15484 if (OidIsValid(tbinfo->attcollation[j]))
15488 coll = findCollationByOid(tbinfo->attcollation[j]);
15491 /* always schema-qualify, don't try to be smart */
15492 appendPQExpBuffer(result, " COLLATE %s.",
15493 fmtId(coll->dobj.namespace->dobj.name));
15494 appendPQExpBufferStr(result, fmtId(coll->dobj.name));
15498 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15506 * write the declaration (not data) of one user-defined table or view
15509 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15511 DumpOptions *dopt = fout->dopt;
15512 PQExpBuffer q = createPQExpBuffer();
15513 PQExpBuffer delq = createPQExpBuffer();
15514 PQExpBuffer labelq = createPQExpBuffer();
15516 TableInfo **parents;
15517 int actual_atts; /* number of attrs in this CREATE statement */
15518 const char *reltypename;
15525 /* Make sure we are in proper schema */
15526 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
15528 if (dopt->binary_upgrade)
15529 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15530 tbinfo->dobj.catId.oid);
15532 /* Is it a table or a view? */
15533 if (tbinfo->relkind == RELKIND_VIEW)
15535 PQExpBuffer result;
15538 * Note: keep this code in sync with the is_view case in dumpRule()
15541 reltypename = "VIEW";
15544 * DROP must be fully qualified in case same name appears in
15547 appendPQExpBuffer(delq, "DROP VIEW %s.",
15548 fmtId(tbinfo->dobj.namespace->dobj.name));
15549 appendPQExpBuffer(delq, "%s;\n",
15550 fmtId(tbinfo->dobj.name));
15552 if (dopt->binary_upgrade)
15553 binary_upgrade_set_pg_class_oids(fout, q,
15554 tbinfo->dobj.catId.oid, false);
15556 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
15557 if (tbinfo->dummy_view)
15558 result = createDummyViewAsClause(fout, tbinfo);
15561 if (nonemptyReloptions(tbinfo->reloptions))
15563 appendPQExpBufferStr(q, " WITH (");
15564 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15565 appendPQExpBufferChar(q, ')');
15567 result = createViewAsClause(fout, tbinfo);
15569 appendPQExpBuffer(q, " AS\n%s", result->data);
15570 destroyPQExpBuffer(result);
15572 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15573 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15574 appendPQExpBufferStr(q, ";\n");
15576 appendPQExpBuffer(labelq, "VIEW %s",
15577 fmtId(tbinfo->dobj.name));
15581 switch (tbinfo->relkind)
15583 case RELKIND_FOREIGN_TABLE:
15585 PQExpBuffer query = createPQExpBuffer();
15590 reltypename = "FOREIGN TABLE";
15592 /* retrieve name of foreign server and generic options */
15593 appendPQExpBuffer(query,
15594 "SELECT fs.srvname, "
15595 "pg_catalog.array_to_string(ARRAY("
15596 "SELECT pg_catalog.quote_ident(option_name) || "
15597 "' ' || pg_catalog.quote_literal(option_value) "
15598 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15599 "ORDER BY option_name"
15600 "), E',\n ') AS ftoptions "
15601 "FROM pg_catalog.pg_foreign_table ft "
15602 "JOIN pg_catalog.pg_foreign_server fs "
15603 "ON (fs.oid = ft.ftserver) "
15604 "WHERE ft.ftrelid = '%u'",
15605 tbinfo->dobj.catId.oid);
15606 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15607 i_srvname = PQfnumber(res, "srvname");
15608 i_ftoptions = PQfnumber(res, "ftoptions");
15609 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15610 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15612 destroyPQExpBuffer(query);
15615 case RELKIND_MATVIEW:
15616 reltypename = "MATERIALIZED VIEW";
15621 reltypename = "TABLE";
15626 numParents = tbinfo->numParents;
15627 parents = tbinfo->parents;
15630 * DROP must be fully qualified in case same name appears in
15633 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
15634 fmtId(tbinfo->dobj.namespace->dobj.name));
15635 appendPQExpBuffer(delq, "%s;\n",
15636 fmtId(tbinfo->dobj.name));
15638 appendPQExpBuffer(labelq, "%s %s", reltypename,
15639 fmtId(tbinfo->dobj.name));
15641 if (dopt->binary_upgrade)
15642 binary_upgrade_set_pg_class_oids(fout, q,
15643 tbinfo->dobj.catId.oid, false);
15645 appendPQExpBuffer(q, "CREATE %s%s %s",
15646 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15649 fmtId(tbinfo->dobj.name));
15652 * Attach to type, if reloftype; except in case of a binary upgrade,
15653 * we dump the table normally and attach it to the type afterward.
15655 if (tbinfo->reloftype && !dopt->binary_upgrade)
15656 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15659 * If the table is a partition, dump it as such; except in the case of
15660 * a binary upgrade, we dump the table normally and attach it to the
15661 * parent afterward.
15663 if (tbinfo->ispartition && !dopt->binary_upgrade)
15665 TableInfo *parentRel = tbinfo->parents[0];
15668 * With partitions, unlike inheritance, there can only be one
15671 if (tbinfo->numParents != 1)
15672 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15673 tbinfo->numParents, tbinfo->dobj.name);
15675 appendPQExpBuffer(q, " PARTITION OF ");
15676 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15677 appendPQExpBuffer(q, "%s.",
15678 fmtId(parentRel->dobj.namespace->dobj.name));
15679 appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15682 if (tbinfo->relkind != RELKIND_MATVIEW)
15684 /* Dump the attributes */
15686 for (j = 0; j < tbinfo->numatts; j++)
15689 * Normally, dump if it's locally defined in this table, and
15690 * not dropped. But for binary upgrade, we'll dump all the
15691 * columns, and then fix up the dropped and nonlocal cases
15694 if (shouldPrintColumn(dopt, tbinfo, j))
15697 * Default value --- suppress if to be printed separately.
15699 bool has_default = (tbinfo->attrdefs[j] != NULL &&
15700 !tbinfo->attrdefs[j]->separate);
15703 * Not Null constraint --- suppress if inherited, except
15704 * in binary-upgrade case where that won't work.
15706 bool has_notnull = (tbinfo->notnull[j] &&
15707 (!tbinfo->inhNotNull[j] ||
15708 dopt->binary_upgrade));
15711 * Skip column if fully defined by reloftype or the
15712 * partition parent.
15714 if ((tbinfo->reloftype || tbinfo->ispartition) &&
15715 !has_default && !has_notnull && !dopt->binary_upgrade)
15718 /* Format properly if not first attr */
15719 if (actual_atts == 0)
15720 appendPQExpBufferStr(q, " (");
15722 appendPQExpBufferChar(q, ',');
15723 appendPQExpBufferStr(q, "\n ");
15726 /* Attribute name */
15727 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15729 if (tbinfo->attisdropped[j])
15732 * ALTER TABLE DROP COLUMN clears
15733 * pg_attribute.atttypid, so we will not have gotten a
15734 * valid type name; insert INTEGER as a stopgap. We'll
15735 * clean things up later.
15737 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15738 /* Skip all the rest, too */
15745 * In binary-upgrade mode, we always include the type. If
15746 * we aren't in binary-upgrade mode, then we skip the type
15747 * when creating a typed table ('OF type_name') or a
15748 * partition ('PARTITION OF'), since the type comes from
15749 * the parent/partitioned table.
15751 if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15753 appendPQExpBuffer(q, " %s",
15754 tbinfo->atttypnames[j]);
15757 /* Add collation if not default for the type */
15758 if (OidIsValid(tbinfo->attcollation[j]))
15762 coll = findCollationByOid(tbinfo->attcollation[j]);
15765 /* always schema-qualify, don't try to be smart */
15766 appendPQExpBuffer(q, " COLLATE %s.",
15767 fmtId(coll->dobj.namespace->dobj.name));
15768 appendPQExpBufferStr(q, fmtId(coll->dobj.name));
15773 appendPQExpBuffer(q, " DEFAULT %s",
15774 tbinfo->attrdefs[j]->adef_expr);
15777 appendPQExpBufferStr(q, " NOT NULL");
15782 * Add non-inherited CHECK constraints, if any.
15784 for (j = 0; j < tbinfo->ncheck; j++)
15786 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15788 if (constr->separate || !constr->conislocal)
15791 if (actual_atts == 0)
15792 appendPQExpBufferStr(q, " (\n ");
15794 appendPQExpBufferStr(q, ",\n ");
15796 appendPQExpBuffer(q, "CONSTRAINT %s ",
15797 fmtId(constr->dobj.name));
15798 appendPQExpBufferStr(q, constr->condef);
15804 appendPQExpBufferStr(q, "\n)");
15805 else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15806 !dopt->binary_upgrade))
15809 * We must have a parenthesized attribute list, even though
15810 * empty, when not using the OF TYPE or PARTITION OF syntax.
15812 appendPQExpBufferStr(q, " (\n)");
15815 if (tbinfo->ispartition && !dopt->binary_upgrade)
15817 appendPQExpBufferChar(q, '\n');
15818 appendPQExpBufferStr(q, tbinfo->partbound);
15821 /* Emit the INHERITS clause, except if this is a partition. */
15822 if (numParents > 0 &&
15823 !tbinfo->ispartition &&
15824 !dopt->binary_upgrade)
15826 appendPQExpBufferStr(q, "\nINHERITS (");
15827 for (k = 0; k < numParents; k++)
15829 TableInfo *parentRel = parents[k];
15832 appendPQExpBufferStr(q, ", ");
15833 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15834 appendPQExpBuffer(q, "%s.",
15835 fmtId(parentRel->dobj.namespace->dobj.name));
15836 appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15838 appendPQExpBufferChar(q, ')');
15841 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15842 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15844 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15845 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15848 if (nonemptyReloptions(tbinfo->reloptions) ||
15849 nonemptyReloptions(tbinfo->toast_reloptions))
15851 bool addcomma = false;
15853 appendPQExpBufferStr(q, "\nWITH (");
15854 if (nonemptyReloptions(tbinfo->reloptions))
15857 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15859 if (nonemptyReloptions(tbinfo->toast_reloptions))
15862 appendPQExpBufferStr(q, ", ");
15863 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15866 appendPQExpBufferChar(q, ')');
15869 /* Dump generic options if any */
15870 if (ftoptions && ftoptions[0])
15871 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
15874 * For materialized views, create the AS clause just like a view. At
15875 * this point, we always mark the view as not populated.
15877 if (tbinfo->relkind == RELKIND_MATVIEW)
15879 PQExpBuffer result;
15881 result = createViewAsClause(fout, tbinfo);
15882 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
15884 destroyPQExpBuffer(result);
15887 appendPQExpBufferStr(q, ";\n");
15890 * To create binary-compatible heap files, we have to ensure the same
15891 * physical column order, including dropped columns, as in the
15892 * original. Therefore, we create dropped columns above and drop them
15893 * here, also updating their attlen/attalign values so that the
15894 * dropped column can be skipped properly. (We do not bother with
15895 * restoring the original attbyval setting.) Also, inheritance
15896 * relationships are set up by doing ALTER TABLE INHERIT rather than
15897 * using an INHERITS clause --- the latter would possibly mess up the
15898 * column order. That also means we have to take care about setting
15899 * attislocal correctly, plus fix up any inherited CHECK constraints.
15900 * Analogously, we set up typed tables using ALTER TABLE / OF here.
15902 if (dopt->binary_upgrade &&
15903 (tbinfo->relkind == RELKIND_RELATION ||
15904 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15905 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15907 for (j = 0; j < tbinfo->numatts; j++)
15909 if (tbinfo->attisdropped[j])
15911 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15912 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15913 "SET attlen = %d, "
15914 "attalign = '%c', attbyval = false\n"
15915 "WHERE attname = ",
15917 tbinfo->attalign[j]);
15918 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15919 appendPQExpBufferStr(q, "\n AND attrelid = ");
15920 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15921 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15923 if (tbinfo->relkind == RELKIND_RELATION ||
15924 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15925 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15926 fmtId(tbinfo->dobj.name));
15928 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15929 fmtId(tbinfo->dobj.name));
15930 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15931 fmtId(tbinfo->attnames[j]));
15933 else if (!tbinfo->attislocal[j])
15935 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15936 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15937 "SET attislocal = false\n"
15938 "WHERE attname = ");
15939 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15940 appendPQExpBufferStr(q, "\n AND attrelid = ");
15941 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15942 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15946 for (k = 0; k < tbinfo->ncheck; k++)
15948 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15950 if (constr->separate || constr->conislocal)
15953 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15954 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15955 fmtId(tbinfo->dobj.name));
15956 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15957 fmtId(constr->dobj.name));
15958 appendPQExpBuffer(q, "%s;\n", constr->condef);
15959 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15960 "SET conislocal = false\n"
15961 "WHERE contype = 'c' AND conname = ");
15962 appendStringLiteralAH(q, constr->dobj.name, fout);
15963 appendPQExpBufferStr(q, "\n AND conrelid = ");
15964 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15965 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15968 if (numParents > 0)
15970 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15971 for (k = 0; k < numParents; k++)
15973 TableInfo *parentRel = parents[k];
15974 PQExpBuffer parentname = createPQExpBuffer();
15976 /* Schema-qualify the parent table, if necessary */
15977 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15978 appendPQExpBuffer(parentname, "%s.",
15979 fmtId(parentRel->dobj.namespace->dobj.name));
15981 appendPQExpBuffer(parentname, "%s",
15982 fmtId(parentRel->dobj.name));
15984 /* In the partitioning case, we alter the parent */
15985 if (tbinfo->ispartition)
15986 appendPQExpBuffer(q,
15987 "ALTER TABLE ONLY %s ATTACH PARTITION ",
15990 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15991 fmtId(tbinfo->dobj.name));
15993 /* Partition needs specifying the bounds */
15994 if (tbinfo->ispartition)
15995 appendPQExpBuffer(q, "%s %s;\n",
15996 fmtId(tbinfo->dobj.name),
15997 tbinfo->partbound);
15999 appendPQExpBuffer(q, "%s;\n", parentname->data);
16001 destroyPQExpBuffer(parentname);
16005 if (tbinfo->reloftype)
16007 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
16008 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
16009 fmtId(tbinfo->dobj.name),
16010 tbinfo->reloftype);
16013 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
16014 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16015 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16017 tbinfo->frozenxid, tbinfo->minmxid);
16018 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
16019 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16021 if (tbinfo->toast_oid)
16023 /* We preserve the toast oids, so we can use it during restore */
16024 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
16025 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16026 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16027 "WHERE oid = '%u';\n",
16028 tbinfo->toast_frozenxid,
16029 tbinfo->toast_minmxid, tbinfo->toast_oid);
16034 * In binary_upgrade mode, restore matviews' populated status by
16035 * poking pg_class directly. This is pretty ugly, but we can't use
16036 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
16037 * matview is not populated even though this matview is.
16039 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
16040 tbinfo->relispopulated)
16042 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
16043 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
16044 "SET relispopulated = 't'\n"
16046 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
16047 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16051 * Dump additional per-column properties that we can't handle in the
16052 * main CREATE TABLE command.
16054 for (j = 0; j < tbinfo->numatts; j++)
16056 /* None of this applies to dropped columns */
16057 if (tbinfo->attisdropped[j])
16061 * If we didn't dump the column definition explicitly above, and
16062 * it is NOT NULL and did not inherit that property from a parent,
16063 * we have to mark it separately.
16065 if (!shouldPrintColumn(dopt, tbinfo, j) &&
16066 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
16068 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16069 fmtId(tbinfo->dobj.name));
16070 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
16071 fmtId(tbinfo->attnames[j]));
16075 * Dump per-column statistics information. We only issue an ALTER
16076 * TABLE statement if the attstattarget entry for this column is
16077 * non-negative (i.e. it's not the default value)
16079 if (tbinfo->attstattarget[j] >= 0)
16081 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16082 fmtId(tbinfo->dobj.name));
16083 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16084 fmtId(tbinfo->attnames[j]));
16085 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
16086 tbinfo->attstattarget[j]);
16090 * Dump per-column storage information. The statement is only
16091 * dumped if the storage has been changed from the type's default.
16093 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
16095 switch (tbinfo->attstorage[j])
16101 storage = "EXTERNAL";
16107 storage = "EXTENDED";
16114 * Only dump the statement if it's a storage type we recognize
16116 if (storage != NULL)
16118 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16119 fmtId(tbinfo->dobj.name));
16120 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16121 fmtId(tbinfo->attnames[j]));
16122 appendPQExpBuffer(q, "SET STORAGE %s;\n",
16128 * Dump per-column attributes.
16130 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
16132 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16133 fmtId(tbinfo->dobj.name));
16134 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16135 fmtId(tbinfo->attnames[j]));
16136 appendPQExpBuffer(q, "SET (%s);\n",
16137 tbinfo->attoptions[j]);
16141 * Dump per-column fdw options.
16143 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16144 tbinfo->attfdwoptions[j] &&
16145 tbinfo->attfdwoptions[j][0] != '\0')
16147 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16148 fmtId(tbinfo->dobj.name));
16149 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16150 fmtId(tbinfo->attnames[j]));
16151 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
16152 tbinfo->attfdwoptions[j]);
16158 * dump properties we only have ALTER TABLE syntax for
16160 if ((tbinfo->relkind == RELKIND_RELATION ||
16161 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16162 tbinfo->relkind == RELKIND_MATVIEW) &&
16163 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16165 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16167 /* nothing to do, will be set when the index is dumped */
16169 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16171 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16172 fmtId(tbinfo->dobj.name));
16174 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16176 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16177 fmtId(tbinfo->dobj.name));
16181 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
16182 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
16183 fmtId(tbinfo->dobj.name));
16185 if (tbinfo->forcerowsec)
16186 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16187 fmtId(tbinfo->dobj.name));
16189 if (dopt->binary_upgrade)
16190 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
16192 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16193 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16195 tbinfo->dobj.namespace->dobj.name,
16196 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16198 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
16200 tbinfo->postponed_def ?
16201 SECTION_POST_DATA : SECTION_PRE_DATA,
16202 q->data, delq->data, NULL,
16207 /* Dump Table Comments */
16208 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16209 dumpTableComment(fout, tbinfo, reltypename);
16211 /* Dump Table Security Labels */
16212 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16213 dumpTableSecLabel(fout, tbinfo, reltypename);
16215 /* Dump comments on inlined table constraints */
16216 for (j = 0; j < tbinfo->ncheck; j++)
16218 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16220 if (constr->separate || !constr->conislocal)
16223 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16224 dumpTableConstraintComment(fout, constr);
16227 destroyPQExpBuffer(q);
16228 destroyPQExpBuffer(delq);
16229 destroyPQExpBuffer(labelq);
16233 * dumpAttrDef --- dump an attribute's default-value declaration
16236 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16238 DumpOptions *dopt = fout->dopt;
16239 TableInfo *tbinfo = adinfo->adtable;
16240 int adnum = adinfo->adnum;
16245 /* Skip if table definition not to be dumped */
16246 if (!tbinfo->dobj.dump || dopt->dataOnly)
16249 /* Skip if not "separate"; it was dumped in the table's definition */
16250 if (!adinfo->separate)
16253 q = createPQExpBuffer();
16254 delq = createPQExpBuffer();
16256 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16257 fmtId(tbinfo->dobj.name));
16258 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16259 fmtId(tbinfo->attnames[adnum - 1]),
16260 adinfo->adef_expr);
16263 * DROP must be fully qualified in case same name appears in pg_catalog
16265 appendPQExpBuffer(delq, "ALTER TABLE %s.",
16266 fmtId(tbinfo->dobj.namespace->dobj.name));
16267 appendPQExpBuffer(delq, "%s ",
16268 fmtId(tbinfo->dobj.name));
16269 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16270 fmtId(tbinfo->attnames[adnum - 1]));
16272 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16274 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16275 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16277 tbinfo->dobj.namespace->dobj.name,
16280 false, "DEFAULT", SECTION_PRE_DATA,
16281 q->data, delq->data, NULL,
16286 destroyPQExpBuffer(q);
16287 destroyPQExpBuffer(delq);
16291 * getAttrName: extract the correct name for an attribute
16293 * The array tblInfo->attnames[] only provides names of user attributes;
16294 * if a system attribute number is supplied, we have to fake it.
16295 * We also do a little bit of bounds checking for safety's sake.
16297 static const char *
16298 getAttrName(int attrnum, TableInfo *tblInfo)
16300 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16301 return tblInfo->attnames[attrnum - 1];
16304 case SelfItemPointerAttributeNumber:
16306 case ObjectIdAttributeNumber:
16308 case MinTransactionIdAttributeNumber:
16310 case MinCommandIdAttributeNumber:
16312 case MaxTransactionIdAttributeNumber:
16314 case MaxCommandIdAttributeNumber:
16316 case TableOidAttributeNumber:
16319 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16320 attrnum, tblInfo->dobj.name);
16321 return NULL; /* keep compiler quiet */
16326 * write out to fout a user-defined index
16329 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16331 DumpOptions *dopt = fout->dopt;
16332 TableInfo *tbinfo = indxinfo->indextable;
16333 bool is_constraint = (indxinfo->indexconstraint != 0);
16336 PQExpBuffer labelq;
16338 if (dopt->dataOnly)
16341 q = createPQExpBuffer();
16342 delq = createPQExpBuffer();
16343 labelq = createPQExpBuffer();
16345 appendPQExpBuffer(labelq, "INDEX %s",
16346 fmtId(indxinfo->dobj.name));
16349 * If there's an associated constraint, don't dump the index per se, but
16350 * do dump any comment for it. (This is safe because dependency ordering
16351 * will have ensured the constraint is emitted first.) Note that the
16352 * emitted comment has to be shown as depending on the constraint, not the
16353 * index, in such cases.
16355 if (!is_constraint)
16357 if (dopt->binary_upgrade)
16358 binary_upgrade_set_pg_class_oids(fout, q,
16359 indxinfo->dobj.catId.oid, true);
16361 /* Plain secondary index */
16362 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16364 /* If the index is clustered, we need to record that. */
16365 if (indxinfo->indisclustered)
16367 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16368 fmtId(tbinfo->dobj.name));
16369 appendPQExpBuffer(q, " ON %s;\n",
16370 fmtId(indxinfo->dobj.name));
16373 /* If the index defines identity, we need to record that. */
16374 if (indxinfo->indisreplident)
16376 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16377 fmtId(tbinfo->dobj.name));
16378 appendPQExpBuffer(q, " INDEX %s;\n",
16379 fmtId(indxinfo->dobj.name));
16383 * DROP must be fully qualified in case same name appears in
16386 appendPQExpBuffer(delq, "DROP INDEX %s.",
16387 fmtId(tbinfo->dobj.namespace->dobj.name));
16388 appendPQExpBuffer(delq, "%s;\n",
16389 fmtId(indxinfo->dobj.name));
16391 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16392 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16393 indxinfo->dobj.name,
16394 tbinfo->dobj.namespace->dobj.name,
16395 indxinfo->tablespace,
16396 tbinfo->rolname, false,
16397 "INDEX", SECTION_POST_DATA,
16398 q->data, delq->data, NULL,
16403 /* Dump Index Comments */
16404 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16405 dumpComment(fout, labelq->data,
16406 tbinfo->dobj.namespace->dobj.name,
16408 indxinfo->dobj.catId, 0,
16409 is_constraint ? indxinfo->indexconstraint :
16410 indxinfo->dobj.dumpId);
16412 destroyPQExpBuffer(q);
16413 destroyPQExpBuffer(delq);
16414 destroyPQExpBuffer(labelq);
16419 * write out to fout a partitioned-index attachment clause
16422 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16424 if (fout->dopt->dataOnly)
16427 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16429 PQExpBuffer q = createPQExpBuffer();
16431 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16432 fmtQualifiedId(fout->remoteVersion,
16433 attachinfo->parentIdx->dobj.namespace->dobj.name,
16434 attachinfo->parentIdx->dobj.name));
16435 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16436 fmtQualifiedId(fout->remoteVersion,
16437 attachinfo->partitionIdx->dobj.namespace->dobj.name,
16438 attachinfo->partitionIdx->dobj.name));
16440 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16441 attachinfo->dobj.name,
16444 false, "INDEX ATTACH", SECTION_POST_DATA,
16449 destroyPQExpBuffer(q);
16454 * dumpStatisticsExt
16455 * write out to fout an extended statistics object
16458 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16460 DumpOptions *dopt = fout->dopt;
16463 PQExpBuffer labelq;
16468 /* Skip if not to be dumped */
16469 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16472 q = createPQExpBuffer();
16473 delq = createPQExpBuffer();
16474 labelq = createPQExpBuffer();
16475 query = createPQExpBuffer();
16477 /* Make sure we are in proper schema so references are qualified */
16478 selectSourceSchema(fout, statsextinfo->dobj.namespace->dobj.name);
16480 appendPQExpBuffer(query, "SELECT "
16481 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16482 statsextinfo->dobj.catId.oid);
16484 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16486 stxdef = PQgetvalue(res, 0, 0);
16488 appendPQExpBuffer(labelq, "STATISTICS %s",
16489 fmtId(statsextinfo->dobj.name));
16491 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16492 appendPQExpBuffer(q, "%s;\n", stxdef);
16494 appendPQExpBuffer(delq, "DROP STATISTICS %s.",
16495 fmtId(statsextinfo->dobj.namespace->dobj.name));
16496 appendPQExpBuffer(delq, "%s;\n",
16497 fmtId(statsextinfo->dobj.name));
16499 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16500 ArchiveEntry(fout, statsextinfo->dobj.catId,
16501 statsextinfo->dobj.dumpId,
16502 statsextinfo->dobj.name,
16503 statsextinfo->dobj.namespace->dobj.name,
16505 statsextinfo->rolname, false,
16506 "STATISTICS", SECTION_POST_DATA,
16507 q->data, delq->data, NULL,
16511 /* Dump Statistics Comments */
16512 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16513 dumpComment(fout, labelq->data,
16514 statsextinfo->dobj.namespace->dobj.name,
16515 statsextinfo->rolname,
16516 statsextinfo->dobj.catId, 0,
16517 statsextinfo->dobj.dumpId);
16520 destroyPQExpBuffer(q);
16521 destroyPQExpBuffer(delq);
16522 destroyPQExpBuffer(labelq);
16523 destroyPQExpBuffer(query);
16528 * write out to fout a user-defined constraint
16531 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16533 DumpOptions *dopt = fout->dopt;
16534 TableInfo *tbinfo = coninfo->contable;
16539 /* Skip if not to be dumped */
16540 if (!coninfo->dobj.dump || dopt->dataOnly)
16543 q = createPQExpBuffer();
16544 delq = createPQExpBuffer();
16546 if (coninfo->contype == 'p' ||
16547 coninfo->contype == 'u' ||
16548 coninfo->contype == 'x')
16550 /* Index-related constraint */
16551 IndxInfo *indxinfo;
16554 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16556 if (indxinfo == NULL)
16557 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16558 coninfo->dobj.name);
16560 if (dopt->binary_upgrade)
16561 binary_upgrade_set_pg_class_oids(fout, q,
16562 indxinfo->dobj.catId.oid, true);
16564 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16565 fmtId(tbinfo->dobj.name));
16566 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16567 fmtId(coninfo->dobj.name));
16569 if (coninfo->condef)
16571 /* pg_get_constraintdef should have provided everything */
16572 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16576 appendPQExpBuffer(q, "%s (",
16577 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16578 for (k = 0; k < indxinfo->indnkeys; k++)
16580 int indkey = (int) indxinfo->indkeys[k];
16581 const char *attname;
16583 if (indkey == InvalidAttrNumber)
16585 attname = getAttrName(indkey, tbinfo);
16587 appendPQExpBuffer(q, "%s%s",
16588 (k == 0) ? "" : ", ",
16592 appendPQExpBufferChar(q, ')');
16594 if (nonemptyReloptions(indxinfo->indreloptions))
16596 appendPQExpBufferStr(q, " WITH (");
16597 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16598 appendPQExpBufferChar(q, ')');
16601 if (coninfo->condeferrable)
16603 appendPQExpBufferStr(q, " DEFERRABLE");
16604 if (coninfo->condeferred)
16605 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16608 appendPQExpBufferStr(q, ";\n");
16611 /* If the index is clustered, we need to record that. */
16612 if (indxinfo->indisclustered)
16614 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16615 fmtId(tbinfo->dobj.name));
16616 appendPQExpBuffer(q, " ON %s;\n",
16617 fmtId(indxinfo->dobj.name));
16621 * DROP must be fully qualified in case same name appears in
16624 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16625 fmtId(tbinfo->dobj.namespace->dobj.name));
16626 appendPQExpBuffer(delq, "%s ",
16627 fmtId(tbinfo->dobj.name));
16628 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16629 fmtId(coninfo->dobj.name));
16631 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16633 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16634 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16636 tbinfo->dobj.namespace->dobj.name,
16637 indxinfo->tablespace,
16638 tbinfo->rolname, false,
16639 "CONSTRAINT", SECTION_POST_DATA,
16640 q->data, delq->data, NULL,
16644 else if (coninfo->contype == 'f')
16647 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16648 * current table data is not processed
16650 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16651 fmtId(tbinfo->dobj.name));
16652 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16653 fmtId(coninfo->dobj.name),
16657 * DROP must be fully qualified in case same name appears in
16660 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16661 fmtId(tbinfo->dobj.namespace->dobj.name));
16662 appendPQExpBuffer(delq, "%s ",
16663 fmtId(tbinfo->dobj.name));
16664 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16665 fmtId(coninfo->dobj.name));
16667 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16669 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16670 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16672 tbinfo->dobj.namespace->dobj.name,
16674 tbinfo->rolname, false,
16675 "FK CONSTRAINT", SECTION_POST_DATA,
16676 q->data, delq->data, NULL,
16680 else if (coninfo->contype == 'c' && tbinfo)
16682 /* CHECK constraint on a table */
16684 /* Ignore if not to be dumped separately, or if it was inherited */
16685 if (coninfo->separate && coninfo->conislocal)
16687 /* not ONLY since we want it to propagate to children */
16688 appendPQExpBuffer(q, "ALTER TABLE %s\n",
16689 fmtId(tbinfo->dobj.name));
16690 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16691 fmtId(coninfo->dobj.name),
16695 * DROP must be fully qualified in case same name appears in
16698 appendPQExpBuffer(delq, "ALTER TABLE %s.",
16699 fmtId(tbinfo->dobj.namespace->dobj.name));
16700 appendPQExpBuffer(delq, "%s ",
16701 fmtId(tbinfo->dobj.name));
16702 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16703 fmtId(coninfo->dobj.name));
16705 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16707 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16708 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16710 tbinfo->dobj.namespace->dobj.name,
16712 tbinfo->rolname, false,
16713 "CHECK CONSTRAINT", SECTION_POST_DATA,
16714 q->data, delq->data, NULL,
16719 else if (coninfo->contype == 'c' && tbinfo == NULL)
16721 /* CHECK constraint on a domain */
16722 TypeInfo *tyinfo = coninfo->condomain;
16724 /* Ignore if not to be dumped separately */
16725 if (coninfo->separate)
16727 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16728 fmtId(tyinfo->dobj.name));
16729 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
16730 fmtId(coninfo->dobj.name),
16734 * DROP must be fully qualified in case same name appears in
16737 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
16738 fmtId(tyinfo->dobj.namespace->dobj.name));
16739 appendPQExpBuffer(delq, "%s ",
16740 fmtId(tyinfo->dobj.name));
16741 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16742 fmtId(coninfo->dobj.name));
16744 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16746 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16747 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16749 tyinfo->dobj.namespace->dobj.name,
16751 tyinfo->rolname, false,
16752 "CHECK CONSTRAINT", SECTION_POST_DATA,
16753 q->data, delq->data, NULL,
16760 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16764 /* Dump Constraint Comments --- only works for table constraints */
16765 if (tbinfo && coninfo->separate &&
16766 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16767 dumpTableConstraintComment(fout, coninfo);
16770 destroyPQExpBuffer(q);
16771 destroyPQExpBuffer(delq);
16775 * dumpTableConstraintComment --- dump a constraint's comment if any
16777 * This is split out because we need the function in two different places
16778 * depending on whether the constraint is dumped as part of CREATE TABLE
16779 * or as a separate ALTER command.
16782 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16784 TableInfo *tbinfo = coninfo->contable;
16785 PQExpBuffer labelq = createPQExpBuffer();
16787 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
16788 fmtId(coninfo->dobj.name));
16789 appendPQExpBuffer(labelq, "ON %s",
16790 fmtId(tbinfo->dobj.name));
16792 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16793 dumpComment(fout, labelq->data,
16794 tbinfo->dobj.namespace->dobj.name,
16796 coninfo->dobj.catId, 0,
16797 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16799 destroyPQExpBuffer(labelq);
16803 * findLastBuiltinOid_V71 -
16805 * find the last built in oid
16807 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16808 * pg_database entry for the current database.
16811 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
16815 PQExpBuffer query = createPQExpBuffer();
16817 resetPQExpBuffer(query);
16818 appendPQExpBufferStr(query, "SELECT datlastsysoid from pg_database where datname = ");
16819 appendStringLiteralAH(query, dbname, fout);
16821 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16822 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16824 destroyPQExpBuffer(query);
16831 * write the declaration (not data) of one user-defined sequence
16834 dumpSequence(Archive *fout, TableInfo *tbinfo)
16836 DumpOptions *dopt = fout->dopt;
16846 int64 default_minv,
16850 PQExpBuffer query = createPQExpBuffer();
16851 PQExpBuffer delqry = createPQExpBuffer();
16852 PQExpBuffer labelq = createPQExpBuffer();
16854 if (fout->remoteVersion >= 100000)
16856 /* Make sure we are in proper schema */
16857 selectSourceSchema(fout, "pg_catalog");
16859 appendPQExpBuffer(query,
16860 "SELECT format_type(seqtypid, NULL), "
16861 "seqstart, seqincrement, "
16863 "seqcache, seqcycle "
16865 "JOIN pg_sequence s ON (s.seqrelid = c.oid) "
16866 "WHERE c.oid = '%u'::oid",
16867 tbinfo->dobj.catId.oid);
16869 else if (fout->remoteVersion >= 80400)
16872 * Before PostgreSQL 10, sequence metadata is in the sequence itself,
16873 * so switch to the sequence's schema instead of pg_catalog.
16875 * Note: it might seem that 'bigint' potentially needs to be
16876 * schema-qualified, but actually that's a keyword.
16879 /* Make sure we are in proper schema */
16880 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16882 appendPQExpBuffer(query,
16883 "SELECT 'bigint' AS sequence_type, "
16884 "start_value, increment_by, max_value, min_value, "
16885 "cache_value, is_cycled FROM %s",
16886 fmtId(tbinfo->dobj.name));
16890 /* Make sure we are in proper schema */
16891 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16893 appendPQExpBuffer(query,
16894 "SELECT 'bigint' AS sequence_type, "
16895 "0 AS start_value, increment_by, max_value, min_value, "
16896 "cache_value, is_cycled FROM %s",
16897 fmtId(tbinfo->dobj.name));
16900 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16902 if (PQntuples(res) != 1)
16904 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16905 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16907 tbinfo->dobj.name, PQntuples(res));
16911 seqtype = PQgetvalue(res, 0, 0);
16912 startv = PQgetvalue(res, 0, 1);
16913 incby = PQgetvalue(res, 0, 2);
16914 maxv = PQgetvalue(res, 0, 3);
16915 minv = PQgetvalue(res, 0, 4);
16916 cache = PQgetvalue(res, 0, 5);
16917 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16919 /* Calculate default limits for a sequence of this type */
16920 is_ascending = (incby[0] != '-');
16921 if (strcmp(seqtype, "smallint") == 0)
16923 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16924 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16926 else if (strcmp(seqtype, "integer") == 0)
16928 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16929 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16931 else if (strcmp(seqtype, "bigint") == 0)
16933 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16934 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16938 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16939 default_minv = default_maxv = 0; /* keep compiler quiet */
16943 * 64-bit strtol() isn't very portable, so convert the limits to strings
16944 * and compare that way.
16946 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16947 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16949 /* Don't print minv/maxv if they match the respective default limit */
16950 if (strcmp(minv, bufm) == 0)
16952 if (strcmp(maxv, bufx) == 0)
16956 * DROP must be fully qualified in case same name appears in pg_catalog
16958 if (!tbinfo->is_identity_sequence)
16960 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
16961 fmtId(tbinfo->dobj.namespace->dobj.name));
16962 appendPQExpBuffer(delqry, "%s;\n",
16963 fmtId(tbinfo->dobj.name));
16966 resetPQExpBuffer(query);
16968 if (dopt->binary_upgrade)
16970 binary_upgrade_set_pg_class_oids(fout, query,
16971 tbinfo->dobj.catId.oid, false);
16972 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16973 tbinfo->dobj.catId.oid);
16976 if (tbinfo->is_identity_sequence)
16978 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
16980 appendPQExpBuffer(query,
16982 fmtId(owning_tab->dobj.name));
16983 appendPQExpBuffer(query,
16984 "ALTER COLUMN %s ADD GENERATED ",
16985 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16986 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16987 appendPQExpBuffer(query, "ALWAYS");
16988 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16989 appendPQExpBuffer(query, "BY DEFAULT");
16990 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
16991 fmtId(tbinfo->dobj.name));
16995 appendPQExpBuffer(query,
16996 "CREATE SEQUENCE %s\n",
16997 fmtId(tbinfo->dobj.name));
16999 if (strcmp(seqtype, "bigint") != 0)
17000 appendPQExpBuffer(query, " AS %s\n", seqtype);
17003 if (fout->remoteVersion >= 80400)
17004 appendPQExpBuffer(query, " START WITH %s\n", startv);
17006 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
17009 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
17011 appendPQExpBufferStr(query, " NO MINVALUE\n");
17014 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
17016 appendPQExpBufferStr(query, " NO MAXVALUE\n");
17018 appendPQExpBuffer(query,
17020 cache, (cycled ? "\n CYCLE" : ""));
17022 if (tbinfo->is_identity_sequence)
17023 appendPQExpBufferStr(query, "\n);\n");
17025 appendPQExpBufferStr(query, ";\n");
17027 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
17029 /* binary_upgrade: no need to clear TOAST table oid */
17031 if (dopt->binary_upgrade)
17032 binary_upgrade_extension_member(query, &tbinfo->dobj,
17035 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17036 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
17038 tbinfo->dobj.namespace->dobj.name,
17041 false, "SEQUENCE", SECTION_PRE_DATA,
17042 query->data, delqry->data, NULL,
17047 * If the sequence is owned by a table column, emit the ALTER for it as a
17048 * separate TOC entry immediately following the sequence's own entry. It's
17049 * OK to do this rather than using full sorting logic, because the
17050 * dependency that tells us it's owned will have forced the table to be
17051 * created first. We can't just include the ALTER in the TOC entry
17052 * because it will fail if we haven't reassigned the sequence owner to
17053 * match the table's owner.
17055 * We need not schema-qualify the table reference because both sequence
17056 * and table must be in the same schema.
17058 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
17060 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
17062 if (owning_tab == NULL)
17063 exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
17064 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
17066 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
17068 resetPQExpBuffer(query);
17069 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
17070 fmtId(tbinfo->dobj.name));
17071 appendPQExpBuffer(query, " OWNED BY %s",
17072 fmtId(owning_tab->dobj.name));
17073 appendPQExpBuffer(query, ".%s;\n",
17074 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17076 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17077 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17079 tbinfo->dobj.namespace->dobj.name,
17082 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
17083 query->data, "", NULL,
17084 &(tbinfo->dobj.dumpId), 1,
17089 /* Dump Sequence Comments and Security Labels */
17090 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17091 dumpComment(fout, labelq->data,
17092 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17093 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17095 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
17096 dumpSecLabel(fout, labelq->data,
17097 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17098 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17102 destroyPQExpBuffer(query);
17103 destroyPQExpBuffer(delqry);
17104 destroyPQExpBuffer(labelq);
17109 * write the data of one user-defined sequence
17112 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
17114 TableInfo *tbinfo = tdinfo->tdtable;
17118 PQExpBuffer query = createPQExpBuffer();
17120 /* Make sure we are in proper schema */
17121 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
17123 appendPQExpBuffer(query,
17124 "SELECT last_value, is_called FROM %s",
17125 fmtId(tbinfo->dobj.name));
17127 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17129 if (PQntuples(res) != 1)
17131 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
17132 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
17134 tbinfo->dobj.name, PQntuples(res));
17138 last = PQgetvalue(res, 0, 0);
17139 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17141 resetPQExpBuffer(query);
17142 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17143 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
17144 appendPQExpBuffer(query, ", %s, %s);\n",
17145 last, (called ? "true" : "false"));
17147 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17148 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17150 tbinfo->dobj.namespace->dobj.name,
17153 false, "SEQUENCE SET", SECTION_DATA,
17154 query->data, "", NULL,
17155 &(tbinfo->dobj.dumpId), 1,
17160 destroyPQExpBuffer(query);
17165 * write the declaration of one user-defined table trigger
17168 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17170 DumpOptions *dopt = fout->dopt;
17171 TableInfo *tbinfo = tginfo->tgtable;
17173 PQExpBuffer delqry;
17174 PQExpBuffer labelq;
17182 * we needn't check dobj.dump because TriggerInfo wouldn't have been
17183 * created in the first place for non-dumpable triggers
17185 if (dopt->dataOnly)
17188 query = createPQExpBuffer();
17189 delqry = createPQExpBuffer();
17190 labelq = createPQExpBuffer();
17193 * DROP must be fully qualified in case same name appears in pg_catalog
17195 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17196 fmtId(tginfo->dobj.name));
17197 appendPQExpBuffer(delqry, "ON %s.",
17198 fmtId(tbinfo->dobj.namespace->dobj.name));
17199 appendPQExpBuffer(delqry, "%s;\n",
17200 fmtId(tbinfo->dobj.name));
17204 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17208 if (tginfo->tgisconstraint)
17210 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17211 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17215 appendPQExpBufferStr(query, "CREATE TRIGGER ");
17216 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17218 appendPQExpBufferStr(query, "\n ");
17221 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17222 appendPQExpBufferStr(query, "BEFORE");
17223 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17224 appendPQExpBufferStr(query, "AFTER");
17225 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17226 appendPQExpBufferStr(query, "INSTEAD OF");
17229 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17234 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17236 appendPQExpBufferStr(query, " INSERT");
17239 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17242 appendPQExpBufferStr(query, " OR DELETE");
17244 appendPQExpBufferStr(query, " DELETE");
17247 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17250 appendPQExpBufferStr(query, " OR UPDATE");
17252 appendPQExpBufferStr(query, " UPDATE");
17255 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17258 appendPQExpBufferStr(query, " OR TRUNCATE");
17260 appendPQExpBufferStr(query, " TRUNCATE");
17263 appendPQExpBuffer(query, " ON %s\n",
17264 fmtId(tbinfo->dobj.name));
17266 if (tginfo->tgisconstraint)
17268 if (OidIsValid(tginfo->tgconstrrelid))
17270 /* regclass output is already quoted */
17271 appendPQExpBuffer(query, " FROM %s\n ",
17272 tginfo->tgconstrrelname);
17274 if (!tginfo->tgdeferrable)
17275 appendPQExpBufferStr(query, "NOT ");
17276 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17277 if (tginfo->tginitdeferred)
17278 appendPQExpBufferStr(query, "DEFERRED\n");
17280 appendPQExpBufferStr(query, "IMMEDIATE\n");
17283 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17284 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
17286 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
17288 /* regproc output is already sufficiently quoted */
17289 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17292 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17295 for (findx = 0; findx < tginfo->tgnargs; findx++)
17297 /* find the embedded null that terminates this trigger argument */
17298 size_t tlen = strlen(p);
17300 if (p + tlen >= tgargs + lentgargs)
17302 /* hm, not found before end of bytea value... */
17303 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17306 tbinfo->dobj.name);
17311 appendPQExpBufferStr(query, ", ");
17312 appendStringLiteralAH(query, p, fout);
17316 appendPQExpBufferStr(query, ");\n");
17319 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17321 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17322 fmtId(tbinfo->dobj.name));
17323 switch (tginfo->tgenabled)
17327 appendPQExpBufferStr(query, "DISABLE");
17330 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17333 appendPQExpBufferStr(query, "ENABLE REPLICA");
17336 appendPQExpBufferStr(query, "ENABLE");
17339 appendPQExpBuffer(query, " TRIGGER %s;\n",
17340 fmtId(tginfo->dobj.name));
17343 appendPQExpBuffer(labelq, "TRIGGER %s ",
17344 fmtId(tginfo->dobj.name));
17345 appendPQExpBuffer(labelq, "ON %s",
17346 fmtId(tbinfo->dobj.name));
17348 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17350 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17351 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17353 tbinfo->dobj.namespace->dobj.name,
17355 tbinfo->rolname, false,
17356 "TRIGGER", SECTION_POST_DATA,
17357 query->data, delqry->data, NULL,
17361 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17362 dumpComment(fout, labelq->data,
17363 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17364 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17367 destroyPQExpBuffer(query);
17368 destroyPQExpBuffer(delqry);
17369 destroyPQExpBuffer(labelq);
17374 * write the declaration of one user-defined event trigger
17377 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17379 DumpOptions *dopt = fout->dopt;
17381 PQExpBuffer delqry;
17382 PQExpBuffer labelq;
17384 /* Skip if not to be dumped */
17385 if (!evtinfo->dobj.dump || dopt->dataOnly)
17388 query = createPQExpBuffer();
17389 delqry = createPQExpBuffer();
17390 labelq = createPQExpBuffer();
17392 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17393 appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
17394 appendPQExpBufferStr(query, " ON ");
17395 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17397 if (strcmp("", evtinfo->evttags) != 0)
17399 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17400 appendPQExpBufferStr(query, evtinfo->evttags);
17401 appendPQExpBufferChar(query, ')');
17404 appendPQExpBufferStr(query, "\n EXECUTE PROCEDURE ");
17405 appendPQExpBufferStr(query, evtinfo->evtfname);
17406 appendPQExpBufferStr(query, "();\n");
17408 if (evtinfo->evtenabled != 'O')
17410 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17411 fmtId(evtinfo->dobj.name));
17412 switch (evtinfo->evtenabled)
17415 appendPQExpBufferStr(query, "DISABLE");
17418 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17421 appendPQExpBufferStr(query, "ENABLE REPLICA");
17424 appendPQExpBufferStr(query, "ENABLE");
17427 appendPQExpBufferStr(query, ";\n");
17430 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17431 fmtId(evtinfo->dobj.name));
17433 appendPQExpBuffer(labelq, "EVENT TRIGGER %s",
17434 fmtId(evtinfo->dobj.name));
17436 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17437 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17438 evtinfo->dobj.name, NULL, NULL,
17439 evtinfo->evtowner, false,
17440 "EVENT TRIGGER", SECTION_POST_DATA,
17441 query->data, delqry->data, NULL,
17445 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17446 dumpComment(fout, labelq->data,
17447 NULL, evtinfo->evtowner,
17448 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17450 destroyPQExpBuffer(query);
17451 destroyPQExpBuffer(delqry);
17452 destroyPQExpBuffer(labelq);
17460 dumpRule(Archive *fout, RuleInfo *rinfo)
17462 DumpOptions *dopt = fout->dopt;
17463 TableInfo *tbinfo = rinfo->ruletable;
17467 PQExpBuffer delcmd;
17468 PQExpBuffer labelq;
17472 /* Skip if not to be dumped */
17473 if (!rinfo->dobj.dump || dopt->dataOnly)
17477 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17478 * we do not want to dump it as a separate object.
17480 if (!rinfo->separate)
17484 * If it's an ON SELECT rule, we want to print it as a view definition,
17485 * instead of a rule.
17487 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17490 * Make sure we are in proper schema.
17492 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
17494 query = createPQExpBuffer();
17495 cmd = createPQExpBuffer();
17496 delcmd = createPQExpBuffer();
17497 labelq = createPQExpBuffer();
17501 PQExpBuffer result;
17504 * We need OR REPLACE here because we'll be replacing a dummy view.
17505 * Otherwise this should look largely like the regular view dump code.
17507 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17508 fmtId(tbinfo->dobj.name));
17509 if (nonemptyReloptions(tbinfo->reloptions))
17511 appendPQExpBufferStr(cmd, " WITH (");
17512 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17513 appendPQExpBufferChar(cmd, ')');
17515 result = createViewAsClause(fout, tbinfo);
17516 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17517 destroyPQExpBuffer(result);
17518 if (tbinfo->checkoption != NULL)
17519 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
17520 tbinfo->checkoption);
17521 appendPQExpBufferStr(cmd, ";\n");
17525 /* In the rule case, just print pg_get_ruledef's result verbatim */
17526 appendPQExpBuffer(query,
17527 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17528 rinfo->dobj.catId.oid);
17530 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17532 if (PQntuples(res) != 1)
17534 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17535 rinfo->dobj.name, tbinfo->dobj.name);
17539 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17545 * Add the command to alter the rules replication firing semantics if it
17546 * differs from the default.
17548 if (rinfo->ev_enabled != 'O')
17550 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
17551 switch (rinfo->ev_enabled)
17554 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17555 fmtId(rinfo->dobj.name));
17558 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17559 fmtId(rinfo->dobj.name));
17562 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17563 fmtId(rinfo->dobj.name));
17569 * DROP must be fully qualified in case same name appears in pg_catalog
17574 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
17575 * REPLACE VIEW to replace the rule with something with minimal
17578 PQExpBuffer result;
17580 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s.",
17581 fmtId(tbinfo->dobj.namespace->dobj.name));
17582 appendPQExpBufferStr(delcmd, fmtId(tbinfo->dobj.name));
17583 result = createDummyViewAsClause(fout, tbinfo);
17584 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17585 destroyPQExpBuffer(result);
17589 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17590 fmtId(rinfo->dobj.name));
17591 appendPQExpBuffer(delcmd, "ON %s.",
17592 fmtId(tbinfo->dobj.namespace->dobj.name));
17593 appendPQExpBuffer(delcmd, "%s;\n",
17594 fmtId(tbinfo->dobj.name));
17597 appendPQExpBuffer(labelq, "RULE %s",
17598 fmtId(rinfo->dobj.name));
17599 appendPQExpBuffer(labelq, " ON %s",
17600 fmtId(tbinfo->dobj.name));
17602 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17604 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17605 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17607 tbinfo->dobj.namespace->dobj.name,
17609 tbinfo->rolname, false,
17610 "RULE", SECTION_POST_DATA,
17611 cmd->data, delcmd->data, NULL,
17615 /* Dump rule comments */
17616 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17617 dumpComment(fout, labelq->data,
17618 tbinfo->dobj.namespace->dobj.name,
17620 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17623 destroyPQExpBuffer(query);
17624 destroyPQExpBuffer(cmd);
17625 destroyPQExpBuffer(delcmd);
17626 destroyPQExpBuffer(labelq);
17630 * getExtensionMembership --- obtain extension membership data
17632 * We need to identify objects that are extension members as soon as they're
17633 * loaded, so that we can correctly determine whether they need to be dumped.
17634 * Generally speaking, extension member objects will get marked as *not* to
17635 * be dumped, as they will be recreated by the single CREATE EXTENSION
17636 * command. However, in binary upgrade mode we still need to dump the members
17640 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17651 ExtensionMemberId *extmembers;
17652 ExtensionInfo *ext;
17654 /* Nothing to do if no extensions */
17655 if (numExtensions == 0)
17658 /* Make sure we are in proper schema */
17659 selectSourceSchema(fout, "pg_catalog");
17661 query = createPQExpBuffer();
17663 /* refclassid constraint is redundant but may speed the search */
17664 appendPQExpBufferStr(query, "SELECT "
17665 "classid, objid, refobjid "
17667 "WHERE refclassid = 'pg_extension'::regclass "
17668 "AND deptype = 'e' "
17671 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17673 ntups = PQntuples(res);
17675 i_classid = PQfnumber(res, "classid");
17676 i_objid = PQfnumber(res, "objid");
17677 i_refobjid = PQfnumber(res, "refobjid");
17679 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17683 * Accumulate data into extmembers[].
17685 * Since we ordered the SELECT by referenced ID, we can expect that
17686 * multiple entries for the same extension will appear together; this
17687 * saves on searches.
17691 for (i = 0; i < ntups; i++)
17696 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17697 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17698 extId = atooid(PQgetvalue(res, i, i_refobjid));
17701 ext->dobj.catId.oid != extId)
17702 ext = findExtensionByOid(extId);
17706 /* shouldn't happen */
17707 fprintf(stderr, "could not find referenced extension %u\n", extId);
17711 extmembers[nextmembers].catId = objId;
17712 extmembers[nextmembers].ext = ext;
17718 /* Remember the data for use later */
17719 setExtensionMembership(extmembers, nextmembers);
17721 destroyPQExpBuffer(query);
17725 * processExtensionTables --- deal with extension configuration tables
17727 * There are two parts to this process:
17729 * 1. Identify and create dump records for extension configuration tables.
17731 * Extensions can mark tables as "configuration", which means that the user
17732 * is able and expected to modify those tables after the extension has been
17733 * loaded. For these tables, we dump out only the data- the structure is
17734 * expected to be handled at CREATE EXTENSION time, including any indexes or
17735 * foreign keys, which brings us to-
17737 * 2. Record FK dependencies between configuration tables.
17739 * Due to the FKs being created at CREATE EXTENSION time and therefore before
17740 * the data is loaded, we have to work out what the best order for reloading
17741 * the data is, to avoid FK violations when the tables are restored. This is
17742 * not perfect- we can't handle circular dependencies and if any exist they
17743 * will cause an invalid dump to be produced (though at least all of the data
17744 * is included for a user to manually restore). This is currently documented
17745 * but perhaps we can provide a better solution in the future.
17748 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17751 DumpOptions *dopt = fout->dopt;
17759 /* Nothing to do if no extensions */
17760 if (numExtensions == 0)
17764 * Identify extension configuration tables and create TableDataInfo
17765 * objects for them, ensuring their data will be dumped even though the
17766 * tables themselves won't be.
17768 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17769 * user data in a configuration table is treated like schema data. This
17770 * seems appropriate since system data in a config table would get
17771 * reloaded by CREATE EXTENSION.
17773 for (i = 0; i < numExtensions; i++)
17775 ExtensionInfo *curext = &(extinfo[i]);
17776 char *extconfig = curext->extconfig;
17777 char *extcondition = curext->extcondition;
17778 char **extconfigarray = NULL;
17779 char **extconditionarray = NULL;
17781 int nconditionitems;
17783 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17784 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17785 nconfigitems == nconditionitems)
17789 for (j = 0; j < nconfigitems; j++)
17791 TableInfo *configtbl;
17792 Oid configtbloid = atooid(extconfigarray[j]);
17794 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17796 configtbl = findTableByOid(configtbloid);
17797 if (configtbl == NULL)
17801 * Tables of not-to-be-dumped extensions shouldn't be dumped
17802 * unless the table or its schema is explicitly included
17804 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17806 /* check table explicitly requested */
17807 if (table_include_oids.head != NULL &&
17808 simple_oid_list_member(&table_include_oids,
17812 /* check table's schema explicitly requested */
17813 if (configtbl->dobj.namespace->dobj.dump &
17814 DUMP_COMPONENT_DATA)
17818 /* check table excluded by an exclusion switch */
17819 if (table_exclude_oids.head != NULL &&
17820 simple_oid_list_member(&table_exclude_oids,
17824 /* check schema excluded by an exclusion switch */
17825 if (simple_oid_list_member(&schema_exclude_oids,
17826 configtbl->dobj.namespace->dobj.catId.oid))
17832 * Note: config tables are dumped without OIDs regardless
17833 * of the --oids setting. This is because row filtering
17834 * conditions aren't compatible with dumping OIDs.
17836 makeTableDataInfo(dopt, configtbl, false);
17837 if (configtbl->dataObj != NULL)
17839 if (strlen(extconditionarray[j]) > 0)
17840 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17845 if (extconfigarray)
17846 free(extconfigarray);
17847 if (extconditionarray)
17848 free(extconditionarray);
17852 * Now that all the TableInfoData objects have been created for all the
17853 * extensions, check their FK dependencies and register them to try and
17854 * dump the data out in an order that they can be restored in.
17856 * Note that this is not a problem for user tables as their FKs are
17857 * recreated after the data has been loaded.
17860 /* Make sure we are in proper schema */
17861 selectSourceSchema(fout, "pg_catalog");
17863 query = createPQExpBuffer();
17865 printfPQExpBuffer(query,
17866 "SELECT conrelid, confrelid "
17867 "FROM pg_constraint "
17868 "JOIN pg_depend ON (objid = confrelid) "
17869 "WHERE contype = 'f' "
17870 "AND refclassid = 'pg_extension'::regclass "
17871 "AND classid = 'pg_class'::regclass;");
17873 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17874 ntups = PQntuples(res);
17876 i_conrelid = PQfnumber(res, "conrelid");
17877 i_confrelid = PQfnumber(res, "confrelid");
17879 /* Now get the dependencies and register them */
17880 for (i = 0; i < ntups; i++)
17884 TableInfo *reftable,
17887 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17888 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17889 contable = findTableByOid(conrelid);
17890 reftable = findTableByOid(confrelid);
17892 if (reftable == NULL ||
17893 reftable->dataObj == NULL ||
17894 contable == NULL ||
17895 contable->dataObj == NULL)
17899 * Make referencing TABLE_DATA object depend on the referenced table's
17900 * TABLE_DATA object.
17902 addObjectDependency(&contable->dataObj->dobj,
17903 reftable->dataObj->dobj.dumpId);
17906 destroyPQExpBuffer(query);
17910 * getDependencies --- obtain available dependency data
17913 getDependencies(Archive *fout)
17924 DumpableObject *dobj,
17928 write_msg(NULL, "reading dependency data\n");
17930 /* Make sure we are in proper schema */
17931 selectSourceSchema(fout, "pg_catalog");
17933 query = createPQExpBuffer();
17936 * PIN dependencies aren't interesting, and EXTENSION dependencies were
17937 * already processed by getExtensionMembership.
17939 appendPQExpBufferStr(query, "SELECT "
17940 "classid, objid, refclassid, refobjid, deptype "
17942 "WHERE deptype != 'p' AND deptype != 'e' "
17945 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17947 ntups = PQntuples(res);
17949 i_classid = PQfnumber(res, "classid");
17950 i_objid = PQfnumber(res, "objid");
17951 i_refclassid = PQfnumber(res, "refclassid");
17952 i_refobjid = PQfnumber(res, "refobjid");
17953 i_deptype = PQfnumber(res, "deptype");
17956 * Since we ordered the SELECT by referencing ID, we can expect that
17957 * multiple entries for the same object will appear together; this saves
17962 for (i = 0; i < ntups; i++)
17965 CatalogId refobjId;
17968 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17969 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17970 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17971 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17972 deptype = *(PQgetvalue(res, i, i_deptype));
17974 if (dobj == NULL ||
17975 dobj->catId.tableoid != objId.tableoid ||
17976 dobj->catId.oid != objId.oid)
17977 dobj = findObjectByCatalogId(objId);
17980 * Failure to find objects mentioned in pg_depend is not unexpected,
17981 * since for example we don't collect info about TOAST tables.
17986 fprintf(stderr, "no referencing object %u %u\n",
17987 objId.tableoid, objId.oid);
17992 refdobj = findObjectByCatalogId(refobjId);
17994 if (refdobj == NULL)
17997 fprintf(stderr, "no referenced object %u %u\n",
17998 refobjId.tableoid, refobjId.oid);
18004 * Ordinarily, table rowtypes have implicit dependencies on their
18005 * tables. However, for a composite type the implicit dependency goes
18006 * the other way in pg_depend; which is the right thing for DROP but
18007 * it doesn't produce the dependency ordering we need. So in that one
18008 * case, we reverse the direction of the dependency.
18010 if (deptype == 'i' &&
18011 dobj->objType == DO_TABLE &&
18012 refdobj->objType == DO_TYPE)
18013 addObjectDependency(refdobj, dobj->dumpId);
18016 addObjectDependency(dobj, refdobj->dumpId);
18021 destroyPQExpBuffer(query);
18026 * createBoundaryObjects - create dummy DumpableObjects to represent
18027 * dump section boundaries.
18029 static DumpableObject *
18030 createBoundaryObjects(void)
18032 DumpableObject *dobjs;
18034 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
18036 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
18037 dobjs[0].catId = nilCatalogId;
18038 AssignDumpId(dobjs + 0);
18039 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
18041 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
18042 dobjs[1].catId = nilCatalogId;
18043 AssignDumpId(dobjs + 1);
18044 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
18050 * addBoundaryDependencies - add dependencies as needed to enforce the dump
18051 * section boundaries.
18054 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
18055 DumpableObject *boundaryObjs)
18057 DumpableObject *preDataBound = boundaryObjs + 0;
18058 DumpableObject *postDataBound = boundaryObjs + 1;
18061 for (i = 0; i < numObjs; i++)
18063 DumpableObject *dobj = dobjs[i];
18066 * The classification of object types here must match the SECTION_xxx
18067 * values assigned during subsequent ArchiveEntry calls!
18069 switch (dobj->objType)
18074 case DO_SHELL_TYPE:
18078 case DO_ACCESS_METHOD:
18082 case DO_CONVERSION:
18087 case DO_DUMMY_TYPE:
18090 case DO_TSTEMPLATE:
18093 case DO_FOREIGN_SERVER:
18096 /* Pre-data objects: must come before the pre-data boundary */
18097 addObjectDependency(preDataBound, dobj->dumpId);
18099 case DO_TABLE_DATA:
18100 case DO_SEQUENCE_SET:
18102 /* Data objects: must come between the boundaries */
18103 addObjectDependency(dobj, preDataBound->dumpId);
18104 addObjectDependency(postDataBound, dobj->dumpId);
18107 case DO_INDEX_ATTACH:
18109 case DO_REFRESH_MATVIEW:
18111 case DO_EVENT_TRIGGER:
18112 case DO_DEFAULT_ACL:
18114 case DO_PUBLICATION:
18115 case DO_PUBLICATION_REL:
18116 case DO_SUBSCRIPTION:
18117 /* Post-data objects: must come after the post-data boundary */
18118 addObjectDependency(dobj, postDataBound->dumpId);
18121 /* Rules are post-data, but only if dumped separately */
18122 if (((RuleInfo *) dobj)->separate)
18123 addObjectDependency(dobj, postDataBound->dumpId);
18125 case DO_CONSTRAINT:
18126 case DO_FK_CONSTRAINT:
18127 /* Constraints are post-data, but only if dumped separately */
18128 if (((ConstraintInfo *) dobj)->separate)
18129 addObjectDependency(dobj, postDataBound->dumpId);
18131 case DO_PRE_DATA_BOUNDARY:
18132 /* nothing to do */
18134 case DO_POST_DATA_BOUNDARY:
18135 /* must come after the pre-data boundary */
18136 addObjectDependency(dobj, preDataBound->dumpId);
18144 * BuildArchiveDependencies - create dependency data for archive TOC entries
18146 * The raw dependency data obtained by getDependencies() is not terribly
18147 * useful in an archive dump, because in many cases there are dependency
18148 * chains linking through objects that don't appear explicitly in the dump.
18149 * For example, a view will depend on its _RETURN rule while the _RETURN rule
18150 * will depend on other objects --- but the rule will not appear as a separate
18151 * object in the dump. We need to adjust the view's dependencies to include
18152 * whatever the rule depends on that is included in the dump.
18154 * Just to make things more complicated, there are also "special" dependencies
18155 * such as the dependency of a TABLE DATA item on its TABLE, which we must
18156 * not rearrange because pg_restore knows that TABLE DATA only depends on
18157 * its table. In these cases we must leave the dependencies strictly as-is
18158 * even if they refer to not-to-be-dumped objects.
18160 * To handle this, the convention is that "special" dependencies are created
18161 * during ArchiveEntry calls, and an archive TOC item that has any such
18162 * entries will not be touched here. Otherwise, we recursively search the
18163 * DumpableObject data structures to build the correct dependencies for each
18164 * archive TOC item.
18167 BuildArchiveDependencies(Archive *fout)
18169 ArchiveHandle *AH = (ArchiveHandle *) fout;
18172 /* Scan all TOC entries in the archive */
18173 for (te = AH->toc->next; te != AH->toc; te = te->next)
18175 DumpableObject *dobj;
18176 DumpId *dependencies;
18180 /* No need to process entries that will not be dumped */
18183 /* Ignore entries that already have "special" dependencies */
18186 /* Otherwise, look up the item's original DumpableObject, if any */
18187 dobj = findObjectByDumpId(te->dumpId);
18190 /* No work if it has no dependencies */
18191 if (dobj->nDeps <= 0)
18193 /* Set up work array */
18195 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18197 /* Recursively find all dumpable dependencies */
18198 findDumpableDependencies(AH, dobj,
18199 &dependencies, &nDeps, &allocDeps);
18200 /* And save 'em ... */
18203 dependencies = (DumpId *) pg_realloc(dependencies,
18204 nDeps * sizeof(DumpId));
18205 te->dependencies = dependencies;
18209 free(dependencies);
18213 /* Recursive search subroutine for BuildArchiveDependencies */
18215 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18216 DumpId **dependencies, int *nDeps, int *allocDeps)
18221 * Ignore section boundary objects: if we search through them, we'll
18222 * report lots of bogus dependencies.
18224 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18225 dobj->objType == DO_POST_DATA_BOUNDARY)
18228 for (i = 0; i < dobj->nDeps; i++)
18230 DumpId depid = dobj->dependencies[i];
18232 if (TocIDRequired(AH, depid) != 0)
18234 /* Object will be dumped, so just reference it as a dependency */
18235 if (*nDeps >= *allocDeps)
18238 *dependencies = (DumpId *) pg_realloc(*dependencies,
18239 *allocDeps * sizeof(DumpId));
18241 (*dependencies)[*nDeps] = depid;
18247 * Object will not be dumped, so recursively consider its deps. We
18248 * rely on the assumption that sortDumpableObjects already broke
18249 * any dependency loops, else we might recurse infinitely.
18251 DumpableObject *otherdobj = findObjectByDumpId(depid);
18254 findDumpableDependencies(AH, otherdobj,
18255 dependencies, nDeps, allocDeps);
18262 * selectSourceSchema - make the specified schema the active search path
18263 * in the source database.
18265 * NB: pg_catalog is explicitly searched after the specified schema;
18266 * so user names are only qualified if they are cross-schema references,
18267 * and system names are only qualified if they conflict with a user name
18268 * in the current schema.
18270 * Whenever the selected schema is not pg_catalog, be careful to qualify
18271 * references to system catalogs and types in our emitted commands!
18273 * This function is called only from selectSourceSchemaOnAH and
18274 * selectSourceSchema.
18277 selectSourceSchema(Archive *fout, const char *schemaName)
18281 /* This is checked by the callers already */
18282 Assert(schemaName != NULL && *schemaName != '\0');
18284 query = createPQExpBuffer();
18285 appendPQExpBuffer(query, "SET search_path = %s",
18286 fmtId(schemaName));
18287 if (strcmp(schemaName, "pg_catalog") != 0)
18288 appendPQExpBufferStr(query, ", pg_catalog");
18290 ExecuteSqlStatement(fout, query->data);
18292 destroyPQExpBuffer(query);
18296 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18299 * NB: the result may depend on the currently-selected search_path; this is
18300 * why we don't try to cache the names.
18303 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18311 if ((opts & zeroAsOpaque) != 0)
18312 return pg_strdup(g_opaque_type);
18313 else if ((opts & zeroAsAny) != 0)
18314 return pg_strdup("'any'");
18315 else if ((opts & zeroAsStar) != 0)
18316 return pg_strdup("*");
18317 else if ((opts & zeroAsNone) != 0)
18318 return pg_strdup("NONE");
18321 query = createPQExpBuffer();
18322 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18325 res = ExecuteSqlQueryForSingleRow(fout, query->data);
18327 /* result of format_type is already quoted */
18328 result = pg_strdup(PQgetvalue(res, 0, 0));
18331 destroyPQExpBuffer(query);
18337 * Return a column list clause for the given relation.
18339 * Special case: if there are no undropped columns in the relation, return
18340 * "", not an invalid "()" column list.
18342 static const char *
18343 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18345 int numatts = ti->numatts;
18346 char **attnames = ti->attnames;
18347 bool *attisdropped = ti->attisdropped;
18351 appendPQExpBufferChar(buffer, '(');
18353 for (i = 0; i < numatts; i++)
18355 if (attisdropped[i])
18358 appendPQExpBufferStr(buffer, ", ");
18359 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18364 return ""; /* no undropped columns */
18366 appendPQExpBufferChar(buffer, ')');
18367 return buffer->data;
18371 * Check if a reloptions array is nonempty.
18374 nonemptyReloptions(const char *reloptions)
18376 /* Don't want to print it if it's just "{}" */
18377 return (reloptions != NULL && strlen(reloptions) > 2);
18381 * Format a reloptions array and append it to the given buffer.
18383 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18386 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18387 const char *prefix, Archive *fout)
18391 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18392 fout->std_strings);
18394 write_msg(NULL, "WARNING: could not parse reloptions array\n");