In pg_dump, don't dump a stats object unless dumping underlying table.
[pgsql.git] / src / bin / pg_dump / pg_dump.c
blob1ac09fa161da77b35886c273d29076fc4832285d
1 /*-------------------------------------------------------------------------
3 * pg_dump.c
4 * pg_dump is a utility for dumping out a postgres database
5 * into a script file.
7 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
12 * by PostgreSQL
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,
23 * but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
27 * IDENTIFICATION
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
32 #include "postgres_fe.h"
34 #include <unistd.h>
35 #include <ctype.h>
36 #include <limits.h>
37 #ifdef HAVE_TERMIOS_H
38 #include <termios.h>
39 #endif
41 #include "getopt_long.h"
43 #include "access/attnum.h"
44 #include "access/sysattr.h"
45 #include "access/transam.h"
46 #include "catalog/pg_aggregate_d.h"
47 #include "catalog/pg_am_d.h"
48 #include "catalog/pg_attribute_d.h"
49 #include "catalog/pg_cast_d.h"
50 #include "catalog/pg_class_d.h"
51 #include "catalog/pg_default_acl_d.h"
52 #include "catalog/pg_largeobject_d.h"
53 #include "catalog/pg_largeobject_metadata_d.h"
54 #include "catalog/pg_proc_d.h"
55 #include "catalog/pg_trigger_d.h"
56 #include "catalog/pg_type_d.h"
57 #include "libpq/libpq-fs.h"
58 #include "storage/block.h"
60 #include "dumputils.h"
61 #include "parallel.h"
62 #include "pg_backup_db.h"
63 #include "pg_backup_utils.h"
64 #include "pg_dump.h"
65 #include "fe_utils/connect.h"
66 #include "fe_utils/string_utils.h"
69 typedef struct
71 const char *descr; /* comment for an object */
72 Oid classoid; /* object class (catalog OID) */
73 Oid objoid; /* object OID */
74 int objsubid; /* subobject (table column #) */
75 } CommentItem;
77 typedef struct
79 const char *provider; /* label provider of this security label */
80 const char *label; /* security label for an object */
81 Oid classoid; /* object class (catalog OID) */
82 Oid objoid; /* object OID */
83 int objsubid; /* subobject (table column #) */
84 } SecLabelItem;
86 typedef enum OidOptions
88 zeroAsOpaque = 1,
89 zeroAsAny = 2,
90 zeroAsStar = 4,
91 zeroAsNone = 8
92 } OidOptions;
94 /* global decls */
95 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
101 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102 * FirstNormalObjectId - 1.
104 static Oid g_last_builtin_oid; /* value of the last builtin oid */
106 /* The specified names/patterns should to match at least one entity */
107 static int strict_names = 0;
110 * Object inclusion/exclusion lists
112 * The string lists record the patterns given by command-line switches,
113 * which we then convert to lists of OIDs of matching objects.
115 static SimpleStringList schema_include_patterns = {NULL, NULL};
116 static SimpleOidList schema_include_oids = {NULL, NULL};
117 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
118 static SimpleOidList schema_exclude_oids = {NULL, NULL};
120 static SimpleStringList table_include_patterns = {NULL, NULL};
121 static SimpleOidList table_include_oids = {NULL, NULL};
122 static SimpleStringList table_exclude_patterns = {NULL, NULL};
123 static SimpleOidList table_exclude_oids = {NULL, NULL};
124 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
125 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
128 char g_opaque_type[10]; /* name for the opaque type */
130 /* placeholders for the delimiters for comments */
131 char g_comment_start[10];
132 char g_comment_end[10];
134 static const CatalogId nilCatalogId = {0, 0};
136 /* override for standard extra_float_digits setting */
137 static bool have_extra_float_digits = false;
138 static int extra_float_digits;
141 * The default number of rows per INSERT when
142 * --inserts is specified without --rows-per-insert
144 #define DUMP_DEFAULT_ROWS_PER_INSERT 1
147 * Macro for producing quoted, schema-qualified name of a dumpable object.
149 #define fmtQualifiedDumpable(obj) \
150 fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
151 (obj)->dobj.name)
153 static void help(const char *progname);
154 static void setup_connection(Archive *AH,
155 const char *dumpencoding, const char *dumpsnapshot,
156 char *use_role);
157 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
158 static void expand_schema_name_patterns(Archive *fout,
159 SimpleStringList *patterns,
160 SimpleOidList *oids,
161 bool strict_names);
162 static void expand_table_name_patterns(Archive *fout,
163 SimpleStringList *patterns,
164 SimpleOidList *oids,
165 bool strict_names);
166 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
167 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
168 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
169 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
170 static void dumpComment(Archive *fout, const char *type, const char *name,
171 const char *namespace, const char *owner,
172 CatalogId catalogId, int subid, DumpId dumpId);
173 static int findComments(Archive *fout, Oid classoid, Oid objoid,
174 CommentItem **items);
175 static int collectComments(Archive *fout, CommentItem **items);
176 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
177 const char *namespace, const char *owner,
178 CatalogId catalogId, int subid, DumpId dumpId);
179 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
180 SecLabelItem **items);
181 static int collectSecLabels(Archive *fout, SecLabelItem **items);
182 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
183 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
184 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
185 static void dumpType(Archive *fout, TypeInfo *tyinfo);
186 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
187 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
188 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
189 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
190 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
191 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
192 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
193 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
194 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
195 static void dumpFunc(Archive *fout, FuncInfo *finfo);
196 static void dumpCast(Archive *fout, CastInfo *cast);
197 static void dumpTransform(Archive *fout, TransformInfo *transform);
198 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
199 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
200 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
201 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
202 static void dumpCollation(Archive *fout, CollInfo *collinfo);
203 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
204 static void dumpRule(Archive *fout, RuleInfo *rinfo);
205 static void dumpAgg(Archive *fout, AggInfo *agginfo);
206 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
207 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
208 static void dumpTable(Archive *fout, TableInfo *tbinfo);
209 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
210 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
211 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
212 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
213 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
214 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
215 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
216 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
217 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
218 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
219 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
220 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
221 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
222 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
223 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
224 static void dumpUserMappings(Archive *fout,
225 const char *servername, const char *namespace,
226 const char *owner, CatalogId catalogId, DumpId dumpId);
227 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
229 static DumpId dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId,
230 const char *type, const char *name, const char *subname,
231 const char *nspname, const char *owner,
232 const char *acls, const char *racls,
233 const char *initacls, const char *initracls);
235 static void getDependencies(Archive *fout);
236 static void BuildArchiveDependencies(Archive *fout);
237 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
238 DumpId **dependencies, int *nDeps, int *allocDeps);
240 static DumpableObject *createBoundaryObjects(void);
241 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
242 DumpableObject *boundaryObjs);
244 static void addConstrChildIdxDeps(DumpableObject *dobj, IndxInfo *refidx);
245 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
246 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind);
247 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo);
248 static void buildMatViewRefreshDependencies(Archive *fout);
249 static void getTableDataFKConstraints(void);
250 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
251 bool is_agg);
252 static char *format_function_arguments_old(Archive *fout,
253 FuncInfo *finfo, int nallargs,
254 char **allargtypes,
255 char **argmodes,
256 char **argnames);
257 static char *format_function_signature(Archive *fout,
258 FuncInfo *finfo, bool honor_quotes);
259 static char *convertRegProcReference(Archive *fout,
260 const char *proc);
261 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
262 static char *convertTSFunction(Archive *fout, Oid funcOid);
263 static Oid findLastBuiltinOid_V71(Archive *fout);
264 static const char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
265 static void getBlobs(Archive *fout);
266 static void dumpBlob(Archive *fout, BlobInfo *binfo);
267 static int dumpBlobs(Archive *fout, void *arg);
268 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
269 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
270 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
271 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
272 static void dumpDatabase(Archive *AH);
273 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
274 const char *dbname, Oid dboid);
275 static void dumpEncoding(Archive *AH);
276 static void dumpStdStrings(Archive *AH);
277 static void dumpSearchPath(Archive *AH);
278 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
279 PQExpBuffer upgrade_buffer,
280 Oid pg_type_oid,
281 bool force_array_type);
282 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
283 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
284 static void binary_upgrade_set_pg_class_oids(Archive *fout,
285 PQExpBuffer upgrade_buffer,
286 Oid pg_class_oid, bool is_index);
287 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
288 DumpableObject *dobj,
289 const char *objtype,
290 const char *objname,
291 const char *objnamespace);
292 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
293 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
294 static bool nonemptyReloptions(const char *reloptions);
295 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
296 const char *prefix, Archive *fout);
297 static char *get_synchronized_snapshot(Archive *fout);
298 static void setupDumpWorker(Archive *AHX);
299 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
300 static bool forcePartitionRootLoad(const TableInfo *tbinfo);
304 main(int argc, char **argv)
306 int c;
307 const char *filename = NULL;
308 const char *format = "p";
309 TableInfo *tblinfo;
310 int numTables;
311 DumpableObject **dobjs;
312 int numObjs;
313 DumpableObject *boundaryObjs;
314 int i;
315 int optindex;
316 char *endptr;
317 RestoreOptions *ropt;
318 Archive *fout; /* the script file */
319 bool g_verbose = false;
320 const char *dumpencoding = NULL;
321 const char *dumpsnapshot = NULL;
322 char *use_role = NULL;
323 long rowsPerInsert;
324 int numWorkers = 1;
325 int compressLevel = -1;
326 int plainText = 0;
327 ArchiveFormat archiveFormat = archUnknown;
328 ArchiveMode archiveMode;
330 static DumpOptions dopt;
332 static struct option long_options[] = {
333 {"data-only", no_argument, NULL, 'a'},
334 {"blobs", no_argument, NULL, 'b'},
335 {"no-blobs", no_argument, NULL, 'B'},
336 {"clean", no_argument, NULL, 'c'},
337 {"create", no_argument, NULL, 'C'},
338 {"dbname", required_argument, NULL, 'd'},
339 {"file", required_argument, NULL, 'f'},
340 {"format", required_argument, NULL, 'F'},
341 {"host", required_argument, NULL, 'h'},
342 {"jobs", 1, NULL, 'j'},
343 {"no-reconnect", no_argument, NULL, 'R'},
344 {"no-owner", no_argument, NULL, 'O'},
345 {"port", required_argument, NULL, 'p'},
346 {"schema", required_argument, NULL, 'n'},
347 {"exclude-schema", required_argument, NULL, 'N'},
348 {"schema-only", no_argument, NULL, 's'},
349 {"superuser", required_argument, NULL, 'S'},
350 {"table", required_argument, NULL, 't'},
351 {"exclude-table", required_argument, NULL, 'T'},
352 {"no-password", no_argument, NULL, 'w'},
353 {"password", no_argument, NULL, 'W'},
354 {"username", required_argument, NULL, 'U'},
355 {"verbose", no_argument, NULL, 'v'},
356 {"no-privileges", no_argument, NULL, 'x'},
357 {"no-acl", no_argument, NULL, 'x'},
358 {"compress", required_argument, NULL, 'Z'},
359 {"encoding", required_argument, NULL, 'E'},
360 {"help", no_argument, NULL, '?'},
361 {"version", no_argument, NULL, 'V'},
364 * the following options don't have an equivalent short option letter
366 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
367 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
368 {"column-inserts", no_argument, &dopt.column_inserts, 1},
369 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
370 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
371 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
372 {"exclude-table-data", required_argument, NULL, 4},
373 {"extra-float-digits", required_argument, NULL, 8},
374 {"if-exists", no_argument, &dopt.if_exists, 1},
375 {"inserts", no_argument, NULL, 9},
376 {"lock-wait-timeout", required_argument, NULL, 2},
377 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
378 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
379 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
380 {"role", required_argument, NULL, 3},
381 {"section", required_argument, NULL, 5},
382 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
383 {"snapshot", required_argument, NULL, 6},
384 {"strict-names", no_argument, &strict_names, 1},
385 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
386 {"no-comments", no_argument, &dopt.no_comments, 1},
387 {"no-publications", no_argument, &dopt.no_publications, 1},
388 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
389 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
390 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
391 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
392 {"no-sync", no_argument, NULL, 7},
393 {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
394 {"rows-per-insert", required_argument, NULL, 10},
396 {NULL, 0, NULL, 0}
399 pg_logging_init(argv[0]);
400 pg_logging_set_level(PG_LOG_WARNING);
401 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
404 * Initialize what we need for parallel execution, especially for thread
405 * support on Windows.
407 init_parallel_dump_utils();
409 strcpy(g_comment_start, "-- ");
410 g_comment_end[0] = '\0';
411 strcpy(g_opaque_type, "opaque");
413 progname = get_progname(argv[0]);
415 if (argc > 1)
417 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
419 help(progname);
420 exit_nicely(0);
422 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
424 puts("pg_dump (PostgreSQL) " PG_VERSION);
425 exit_nicely(0);
429 InitDumpOptions(&dopt);
431 while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:Op:RsS:t:T:U:vwWxZ:",
432 long_options, &optindex)) != -1)
434 switch (c)
436 case 'a': /* Dump data only */
437 dopt.dataOnly = true;
438 break;
440 case 'b': /* Dump blobs */
441 dopt.outputBlobs = true;
442 break;
444 case 'B': /* Don't dump blobs */
445 dopt.dontOutputBlobs = true;
446 break;
448 case 'c': /* clean (i.e., drop) schema prior to create */
449 dopt.outputClean = 1;
450 break;
452 case 'C': /* Create DB */
453 dopt.outputCreateDB = 1;
454 break;
456 case 'd': /* database name */
457 dopt.cparams.dbname = pg_strdup(optarg);
458 break;
460 case 'E': /* Dump encoding */
461 dumpencoding = pg_strdup(optarg);
462 break;
464 case 'f':
465 filename = pg_strdup(optarg);
466 break;
468 case 'F':
469 format = pg_strdup(optarg);
470 break;
472 case 'h': /* server host */
473 dopt.cparams.pghost = pg_strdup(optarg);
474 break;
476 case 'j': /* number of dump jobs */
477 numWorkers = atoi(optarg);
478 break;
480 case 'n': /* include schema(s) */
481 simple_string_list_append(&schema_include_patterns, optarg);
482 dopt.include_everything = false;
483 break;
485 case 'N': /* exclude schema(s) */
486 simple_string_list_append(&schema_exclude_patterns, optarg);
487 break;
489 case 'O': /* Don't reconnect to match owner */
490 dopt.outputNoOwner = 1;
491 break;
493 case 'p': /* server port */
494 dopt.cparams.pgport = pg_strdup(optarg);
495 break;
497 case 'R':
498 /* no-op, still accepted for backwards compatibility */
499 break;
501 case 's': /* dump schema only */
502 dopt.schemaOnly = true;
503 break;
505 case 'S': /* Username for superuser in plain text output */
506 dopt.outputSuperuser = pg_strdup(optarg);
507 break;
509 case 't': /* include table(s) */
510 simple_string_list_append(&table_include_patterns, optarg);
511 dopt.include_everything = false;
512 break;
514 case 'T': /* exclude table(s) */
515 simple_string_list_append(&table_exclude_patterns, optarg);
516 break;
518 case 'U':
519 dopt.cparams.username = pg_strdup(optarg);
520 break;
522 case 'v': /* verbose */
523 g_verbose = true;
524 pg_logging_set_level(PG_LOG_INFO);
525 break;
527 case 'w':
528 dopt.cparams.promptPassword = TRI_NO;
529 break;
531 case 'W':
532 dopt.cparams.promptPassword = TRI_YES;
533 break;
535 case 'x': /* skip ACL dump */
536 dopt.aclsSkip = true;
537 break;
539 case 'Z': /* Compression Level */
540 compressLevel = atoi(optarg);
541 if (compressLevel < 0 || compressLevel > 9)
543 pg_log_error("compression level must be in range 0..9");
544 exit_nicely(1);
546 break;
548 case 0:
549 /* This covers the long options. */
550 break;
552 case 2: /* lock-wait-timeout */
553 dopt.lockWaitTimeout = pg_strdup(optarg);
554 break;
556 case 3: /* SET ROLE */
557 use_role = pg_strdup(optarg);
558 break;
560 case 4: /* exclude table(s) data */
561 simple_string_list_append(&tabledata_exclude_patterns, optarg);
562 break;
564 case 5: /* section */
565 set_dump_section(optarg, &dopt.dumpSections);
566 break;
568 case 6: /* snapshot */
569 dumpsnapshot = pg_strdup(optarg);
570 break;
572 case 7: /* no-sync */
573 dosync = false;
574 break;
576 case 8:
577 have_extra_float_digits = true;
578 extra_float_digits = atoi(optarg);
579 if (extra_float_digits < -15 || extra_float_digits > 3)
581 pg_log_error("extra_float_digits must be in range -15..3");
582 exit_nicely(1);
584 break;
586 case 9: /* inserts */
589 * dump_inserts also stores --rows-per-insert, careful not to
590 * overwrite that.
592 if (dopt.dump_inserts == 0)
593 dopt.dump_inserts = DUMP_DEFAULT_ROWS_PER_INSERT;
594 break;
596 case 10: /* rows per insert */
597 errno = 0;
598 rowsPerInsert = strtol(optarg, &endptr, 10);
600 if (endptr == optarg || *endptr != '\0' ||
601 rowsPerInsert <= 0 || rowsPerInsert > INT_MAX ||
602 errno == ERANGE)
604 pg_log_error("rows-per-insert must be in range %d..%d",
605 1, INT_MAX);
606 exit_nicely(1);
608 dopt.dump_inserts = (int) rowsPerInsert;
609 break;
611 default:
612 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
613 exit_nicely(1);
618 * Non-option argument specifies database name as long as it wasn't
619 * already specified with -d / --dbname
621 if (optind < argc && dopt.cparams.dbname == NULL)
622 dopt.cparams.dbname = argv[optind++];
624 /* Complain if any arguments remain */
625 if (optind < argc)
627 pg_log_error("too many command-line arguments (first is \"%s\")",
628 argv[optind]);
629 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
630 progname);
631 exit_nicely(1);
634 /* --column-inserts implies --inserts */
635 if (dopt.column_inserts && dopt.dump_inserts == 0)
636 dopt.dump_inserts = DUMP_DEFAULT_ROWS_PER_INSERT;
639 * Binary upgrade mode implies dumping sequence data even in schema-only
640 * mode. This is not exposed as a separate option, but kept separate
641 * internally for clarity.
643 if (dopt.binary_upgrade)
644 dopt.sequence_data = 1;
646 if (dopt.dataOnly && dopt.schemaOnly)
648 pg_log_error("options -s/--schema-only and -a/--data-only cannot be used together");
649 exit_nicely(1);
652 if (dopt.dataOnly && dopt.outputClean)
654 pg_log_error("options -c/--clean and -a/--data-only cannot be used together");
655 exit_nicely(1);
658 if (dopt.if_exists && !dopt.outputClean)
659 fatal("option --if-exists requires option -c/--clean");
662 * --inserts are already implied above if --column-inserts or
663 * --rows-per-insert were specified.
665 if (dopt.do_nothing && dopt.dump_inserts == 0)
666 fatal("option --on-conflict-do-nothing requires option --inserts, --rows-per-insert, or --column-inserts");
668 /* Identify archive format to emit */
669 archiveFormat = parseArchiveFormat(format, &archiveMode);
671 /* archiveFormat specific setup */
672 if (archiveFormat == archNull)
673 plainText = 1;
675 /* Custom and directory formats are compressed by default, others not */
676 if (compressLevel == -1)
678 #ifdef HAVE_LIBZ
679 if (archiveFormat == archCustom || archiveFormat == archDirectory)
680 compressLevel = Z_DEFAULT_COMPRESSION;
681 else
682 #endif
683 compressLevel = 0;
686 #ifndef HAVE_LIBZ
687 if (compressLevel != 0)
688 pg_log_warning("requested compression not available in this installation -- archive will be uncompressed");
689 compressLevel = 0;
690 #endif
693 * If emitting an archive format, we always want to emit a DATABASE item,
694 * in case --create is specified at pg_restore time.
696 if (!plainText)
697 dopt.outputCreateDB = 1;
700 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
701 * parallel jobs because that's the maximum limit for the
702 * WaitForMultipleObjects() call.
704 if (numWorkers <= 0
705 #ifdef WIN32
706 || numWorkers > MAXIMUM_WAIT_OBJECTS
707 #endif
709 fatal("invalid number of parallel jobs");
711 /* Parallel backup only in the directory archive format so far */
712 if (archiveFormat != archDirectory && numWorkers > 1)
713 fatal("parallel backup only supported by the directory format");
715 /* Open the output file */
716 fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
717 archiveMode, setupDumpWorker);
719 /* Make dump options accessible right away */
720 SetArchiveOptions(fout, &dopt, NULL);
722 /* Register the cleanup hook */
723 on_exit_close_archive(fout);
725 /* Let the archiver know how noisy to be */
726 fout->verbose = g_verbose;
730 * We allow the server to be back to 8.0, and up to any minor release of
731 * our own major version. (See also version check in pg_dumpall.c.)
733 fout->minRemoteVersion = 80000;
734 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
736 fout->numWorkers = numWorkers;
739 * Open the database using the Archiver, so it knows about it. Errors mean
740 * death.
742 ConnectDatabase(fout, &dopt.cparams, false);
743 setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
746 * Disable security label support if server version < v9.1.x (prevents
747 * access to nonexistent pg_seclabel catalog)
749 if (fout->remoteVersion < 90100)
750 dopt.no_security_labels = 1;
753 * On hot standbys, never try to dump unlogged table data, since it will
754 * just throw an error.
756 if (fout->isStandby)
757 dopt.no_unlogged_table_data = true;
759 /* Select the appropriate subquery to convert user IDs to names */
760 if (fout->remoteVersion >= 80100)
761 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
762 else
763 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
765 /* check the version for the synchronized snapshots feature */
766 if (numWorkers > 1 && fout->remoteVersion < 90200
767 && !dopt.no_synchronized_snapshots)
768 fatal("Synchronized snapshots are not supported by this server version.\n"
769 "Run with --no-synchronized-snapshots instead if you do not need\n"
770 "synchronized snapshots.");
772 /* check the version when a snapshot is explicitly specified by user */
773 if (dumpsnapshot && fout->remoteVersion < 90200)
774 fatal("Exported snapshots are not supported by this server version.");
777 * Find the last built-in OID, if needed (prior to 8.1)
779 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
781 if (fout->remoteVersion < 80100)
782 g_last_builtin_oid = findLastBuiltinOid_V71(fout);
783 else
784 g_last_builtin_oid = FirstNormalObjectId - 1;
786 pg_log_info("last built-in OID is %u", g_last_builtin_oid);
788 /* Expand schema selection patterns into OID lists */
789 if (schema_include_patterns.head != NULL)
791 expand_schema_name_patterns(fout, &schema_include_patterns,
792 &schema_include_oids,
793 strict_names);
794 if (schema_include_oids.head == NULL)
795 fatal("no matching schemas were found");
797 expand_schema_name_patterns(fout, &schema_exclude_patterns,
798 &schema_exclude_oids,
799 false);
800 /* non-matching exclusion patterns aren't an error */
802 /* Expand table selection patterns into OID lists */
803 if (table_include_patterns.head != NULL)
805 expand_table_name_patterns(fout, &table_include_patterns,
806 &table_include_oids,
807 strict_names);
808 if (table_include_oids.head == NULL)
809 fatal("no matching tables were found");
811 expand_table_name_patterns(fout, &table_exclude_patterns,
812 &table_exclude_oids,
813 false);
815 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
816 &tabledata_exclude_oids,
817 false);
819 /* non-matching exclusion patterns aren't an error */
822 * Dumping blobs is the default for dumps where an inclusion switch is not
823 * used (an "include everything" dump). -B can be used to exclude blobs
824 * from those dumps. -b can be used to include blobs even when an
825 * inclusion switch is used.
827 * -s means "schema only" and blobs are data, not schema, so we never
828 * include blobs when -s is used.
830 if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
831 dopt.outputBlobs = true;
834 * Now scan the database and create DumpableObject structs for all the
835 * objects we intend to dump.
837 tblinfo = getSchemaData(fout, &numTables);
839 if (fout->remoteVersion < 80400)
840 guessConstraintInheritance(tblinfo, numTables);
842 if (!dopt.schemaOnly)
844 getTableData(&dopt, tblinfo, numTables, 0);
845 buildMatViewRefreshDependencies(fout);
846 if (dopt.dataOnly)
847 getTableDataFKConstraints();
850 if (dopt.schemaOnly && dopt.sequence_data)
851 getTableData(&dopt, tblinfo, numTables, RELKIND_SEQUENCE);
854 * In binary-upgrade mode, we do not have to worry about the actual blob
855 * data or the associated metadata that resides in the pg_largeobject and
856 * pg_largeobject_metadata tables, respectively.
858 * However, we do need to collect blob information as there may be
859 * comments or other information on blobs that we do need to dump out.
861 if (dopt.outputBlobs || dopt.binary_upgrade)
862 getBlobs(fout);
865 * Collect dependency data to assist in ordering the objects.
867 getDependencies(fout);
869 /* Lastly, create dummy objects to represent the section boundaries */
870 boundaryObjs = createBoundaryObjects();
872 /* Get pointers to all the known DumpableObjects */
873 getDumpableObjects(&dobjs, &numObjs);
876 * Add dummy dependencies to enforce the dump section ordering.
878 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
881 * Sort the objects into a safe dump order (no forward references).
883 * We rely on dependency information to help us determine a safe order, so
884 * the initial sort is mostly for cosmetic purposes: we sort by name to
885 * ensure that logically identical schemas will dump identically.
887 sortDumpableObjectsByTypeName(dobjs, numObjs);
889 sortDumpableObjects(dobjs, numObjs,
890 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
893 * Create archive TOC entries for all the objects to be dumped, in a safe
894 * order.
897 /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
898 dumpEncoding(fout);
899 dumpStdStrings(fout);
900 dumpSearchPath(fout);
902 /* The database items are always next, unless we don't want them at all */
903 if (dopt.outputCreateDB)
904 dumpDatabase(fout);
906 /* Now the rearrangeable objects. */
907 for (i = 0; i < numObjs; i++)
908 dumpDumpableObject(fout, dobjs[i]);
911 * Set up options info to ensure we dump what we want.
913 ropt = NewRestoreOptions();
914 ropt->filename = filename;
916 /* if you change this list, see dumpOptionsFromRestoreOptions */
917 ropt->cparams.dbname = dopt.cparams.dbname ? pg_strdup(dopt.cparams.dbname) : NULL;
918 ropt->cparams.pgport = dopt.cparams.pgport ? pg_strdup(dopt.cparams.pgport) : NULL;
919 ropt->cparams.pghost = dopt.cparams.pghost ? pg_strdup(dopt.cparams.pghost) : NULL;
920 ropt->cparams.username = dopt.cparams.username ? pg_strdup(dopt.cparams.username) : NULL;
921 ropt->cparams.promptPassword = dopt.cparams.promptPassword;
922 ropt->dropSchema = dopt.outputClean;
923 ropt->dataOnly = dopt.dataOnly;
924 ropt->schemaOnly = dopt.schemaOnly;
925 ropt->if_exists = dopt.if_exists;
926 ropt->column_inserts = dopt.column_inserts;
927 ropt->dumpSections = dopt.dumpSections;
928 ropt->aclsSkip = dopt.aclsSkip;
929 ropt->superuser = dopt.outputSuperuser;
930 ropt->createDB = dopt.outputCreateDB;
931 ropt->noOwner = dopt.outputNoOwner;
932 ropt->noTablespace = dopt.outputNoTablespaces;
933 ropt->disable_triggers = dopt.disable_triggers;
934 ropt->use_setsessauth = dopt.use_setsessauth;
935 ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
936 ropt->dump_inserts = dopt.dump_inserts;
937 ropt->no_comments = dopt.no_comments;
938 ropt->no_publications = dopt.no_publications;
939 ropt->no_security_labels = dopt.no_security_labels;
940 ropt->no_subscriptions = dopt.no_subscriptions;
941 ropt->lockWaitTimeout = dopt.lockWaitTimeout;
942 ropt->include_everything = dopt.include_everything;
943 ropt->enable_row_security = dopt.enable_row_security;
944 ropt->sequence_data = dopt.sequence_data;
945 ropt->binary_upgrade = dopt.binary_upgrade;
947 if (compressLevel == -1)
948 ropt->compression = 0;
949 else
950 ropt->compression = compressLevel;
952 ropt->suppressDumpWarnings = true; /* We've already shown them */
954 SetArchiveOptions(fout, &dopt, ropt);
956 /* Mark which entries should be output */
957 ProcessArchiveRestoreOptions(fout);
960 * The archive's TOC entries are now marked as to which ones will actually
961 * be output, so we can set up their dependency lists properly. This isn't
962 * necessary for plain-text output, though.
964 if (!plainText)
965 BuildArchiveDependencies(fout);
968 * And finally we can do the actual output.
970 * Note: for non-plain-text output formats, the output file is written
971 * inside CloseArchive(). This is, um, bizarre; but not worth changing
972 * right now.
974 if (plainText)
975 RestoreArchive(fout);
977 CloseArchive(fout);
979 exit_nicely(0);
983 static void
984 help(const char *progname)
986 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
987 printf(_("Usage:\n"));
988 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
990 printf(_("\nGeneral options:\n"));
991 printf(_(" -f, --file=FILENAME output file or directory name\n"));
992 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
993 " plain text (default))\n"));
994 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
995 printf(_(" -v, --verbose verbose mode\n"));
996 printf(_(" -V, --version output version information, then exit\n"));
997 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
998 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
999 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
1000 printf(_(" -?, --help show this help, then exit\n"));
1002 printf(_("\nOptions controlling the output content:\n"));
1003 printf(_(" -a, --data-only dump only the data, not the schema\n"));
1004 printf(_(" -b, --blobs include large objects in dump\n"));
1005 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
1006 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
1007 printf(_(" -C, --create include commands to create database in dump\n"));
1008 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
1009 printf(_(" -n, --schema=PATTERN dump the specified schema(s) only\n"));
1010 printf(_(" -N, --exclude-schema=PATTERN do NOT dump the specified schema(s)\n"));
1011 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
1012 " plain-text format\n"));
1013 printf(_(" -s, --schema-only dump only the schema, no data\n"));
1014 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
1015 printf(_(" -t, --table=PATTERN dump the specified table(s) only\n"));
1016 printf(_(" -T, --exclude-table=PATTERN do NOT dump the specified table(s)\n"));
1017 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
1018 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
1019 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
1020 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
1021 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
1022 printf(_(" --enable-row-security enable row security (dump only content user has\n"
1023 " access to)\n"));
1024 printf(_(" --exclude-table-data=PATTERN do NOT dump data for the specified table(s)\n"));
1025 printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
1026 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
1027 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
1028 printf(_(" --load-via-partition-root load partitions via the root table\n"));
1029 printf(_(" --no-comments do not dump comments\n"));
1030 printf(_(" --no-publications do not dump publications\n"));
1031 printf(_(" --no-security-labels do not dump security label assignments\n"));
1032 printf(_(" --no-subscriptions do not dump subscriptions\n"));
1033 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
1034 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
1035 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
1036 printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
1037 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
1038 printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
1039 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
1040 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
1041 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
1042 printf(_(" --strict-names require table and/or schema include patterns to\n"
1043 " match at least one entity each\n"));
1044 printf(_(" --use-set-session-authorization\n"
1045 " use SET SESSION AUTHORIZATION commands instead of\n"
1046 " ALTER OWNER commands to set ownership\n"));
1048 printf(_("\nConnection options:\n"));
1049 printf(_(" -d, --dbname=DBNAME database to dump\n"));
1050 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1051 printf(_(" -p, --port=PORT database server port number\n"));
1052 printf(_(" -U, --username=NAME connect as specified database user\n"));
1053 printf(_(" -w, --no-password never prompt for password\n"));
1054 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1055 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1057 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1058 "variable value is used.\n\n"));
1059 printf(_("Report bugs to <pgsql-bugs@lists.postgresql.org>.\n"));
1062 static void
1063 setup_connection(Archive *AH, const char *dumpencoding,
1064 const char *dumpsnapshot, char *use_role)
1066 DumpOptions *dopt = AH->dopt;
1067 PGconn *conn = GetConnection(AH);
1068 const char *std_strings;
1070 PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1073 * Set the client encoding if requested.
1075 if (dumpencoding)
1077 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1078 fatal("invalid client encoding \"%s\" specified",
1079 dumpencoding);
1083 * Get the active encoding and the standard_conforming_strings setting, so
1084 * we know how to escape strings.
1086 AH->encoding = PQclientEncoding(conn);
1088 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1089 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1092 * Set the role if requested. In a parallel dump worker, we'll be passed
1093 * use_role == NULL, but AH->use_role is already set (if user specified it
1094 * originally) and we should use that.
1096 if (!use_role && AH->use_role)
1097 use_role = AH->use_role;
1099 /* Set the role if requested */
1100 if (use_role && AH->remoteVersion >= 80100)
1102 PQExpBuffer query = createPQExpBuffer();
1104 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1105 ExecuteSqlStatement(AH, query->data);
1106 destroyPQExpBuffer(query);
1108 /* save it for possible later use by parallel workers */
1109 if (!AH->use_role)
1110 AH->use_role = pg_strdup(use_role);
1113 /* Set the datestyle to ISO to ensure the dump's portability */
1114 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1116 /* Likewise, avoid using sql_standard intervalstyle */
1117 if (AH->remoteVersion >= 80400)
1118 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1121 * Use an explicitly specified extra_float_digits if it has been provided.
1122 * Otherwise, set extra_float_digits so that we can dump float data
1123 * exactly (given correctly implemented float I/O code, anyway).
1125 if (have_extra_float_digits)
1127 PQExpBuffer q = createPQExpBuffer();
1129 appendPQExpBuffer(q, "SET extra_float_digits TO %d",
1130 extra_float_digits);
1131 ExecuteSqlStatement(AH, q->data);
1132 destroyPQExpBuffer(q);
1134 else if (AH->remoteVersion >= 90000)
1135 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1136 else
1137 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1140 * If synchronized scanning is supported, disable it, to prevent
1141 * unpredictable changes in row ordering across a dump and reload.
1143 if (AH->remoteVersion >= 80300)
1144 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1147 * Disable timeouts if supported.
1149 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1150 if (AH->remoteVersion >= 90300)
1151 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1152 if (AH->remoteVersion >= 90600)
1153 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1156 * Quote all identifiers, if requested.
1158 if (quote_all_identifiers && AH->remoteVersion >= 90100)
1159 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1162 * Adjust row-security mode, if supported.
1164 if (AH->remoteVersion >= 90500)
1166 if (dopt->enable_row_security)
1167 ExecuteSqlStatement(AH, "SET row_security = on");
1168 else
1169 ExecuteSqlStatement(AH, "SET row_security = off");
1173 * Start transaction-snapshot mode transaction to dump consistent data.
1175 ExecuteSqlStatement(AH, "BEGIN");
1176 if (AH->remoteVersion >= 90100)
1179 * To support the combination of serializable_deferrable with the jobs
1180 * option we use REPEATABLE READ for the worker connections that are
1181 * passed a snapshot. As long as the snapshot is acquired in a
1182 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1183 * REPEATABLE READ transaction provides the appropriate integrity
1184 * guarantees. This is a kluge, but safe for back-patching.
1186 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1187 ExecuteSqlStatement(AH,
1188 "SET TRANSACTION ISOLATION LEVEL "
1189 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1190 else
1191 ExecuteSqlStatement(AH,
1192 "SET TRANSACTION ISOLATION LEVEL "
1193 "REPEATABLE READ, READ ONLY");
1195 else
1197 ExecuteSqlStatement(AH,
1198 "SET TRANSACTION ISOLATION LEVEL "
1199 "SERIALIZABLE, READ ONLY");
1203 * If user specified a snapshot to use, select that. In a parallel dump
1204 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1205 * is already set (if the server can handle it) and we should use that.
1207 if (dumpsnapshot)
1208 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1210 if (AH->sync_snapshot_id)
1212 PQExpBuffer query = createPQExpBuffer();
1214 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1215 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1216 ExecuteSqlStatement(AH, query->data);
1217 destroyPQExpBuffer(query);
1219 else if (AH->numWorkers > 1 &&
1220 AH->remoteVersion >= 90200 &&
1221 !dopt->no_synchronized_snapshots)
1223 if (AH->isStandby && AH->remoteVersion < 100000)
1224 fatal("Synchronized snapshots on standby servers are not supported by this server version.\n"
1225 "Run with --no-synchronized-snapshots instead if you do not need\n"
1226 "synchronized snapshots.");
1229 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1233 /* Set up connection for a parallel worker process */
1234 static void
1235 setupDumpWorker(Archive *AH)
1238 * We want to re-select all the same values the master connection is
1239 * using. We'll have inherited directly-usable values in
1240 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1241 * inherited encoding value back to a string to pass to setup_connection.
1243 setup_connection(AH,
1244 pg_encoding_to_char(AH->encoding),
1245 NULL,
1246 NULL);
1249 static char *
1250 get_synchronized_snapshot(Archive *fout)
1252 char *query = "SELECT pg_catalog.pg_export_snapshot()";
1253 char *result;
1254 PGresult *res;
1256 res = ExecuteSqlQueryForSingleRow(fout, query);
1257 result = pg_strdup(PQgetvalue(res, 0, 0));
1258 PQclear(res);
1260 return result;
1263 static ArchiveFormat
1264 parseArchiveFormat(const char *format, ArchiveMode *mode)
1266 ArchiveFormat archiveFormat;
1268 *mode = archModeWrite;
1270 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1272 /* This is used by pg_dumpall, and is not documented */
1273 archiveFormat = archNull;
1274 *mode = archModeAppend;
1276 else if (pg_strcasecmp(format, "c") == 0)
1277 archiveFormat = archCustom;
1278 else if (pg_strcasecmp(format, "custom") == 0)
1279 archiveFormat = archCustom;
1280 else if (pg_strcasecmp(format, "d") == 0)
1281 archiveFormat = archDirectory;
1282 else if (pg_strcasecmp(format, "directory") == 0)
1283 archiveFormat = archDirectory;
1284 else if (pg_strcasecmp(format, "p") == 0)
1285 archiveFormat = archNull;
1286 else if (pg_strcasecmp(format, "plain") == 0)
1287 archiveFormat = archNull;
1288 else if (pg_strcasecmp(format, "t") == 0)
1289 archiveFormat = archTar;
1290 else if (pg_strcasecmp(format, "tar") == 0)
1291 archiveFormat = archTar;
1292 else
1293 fatal("invalid output format \"%s\" specified", format);
1294 return archiveFormat;
1298 * Find the OIDs of all schemas matching the given list of patterns,
1299 * and append them to the given OID list.
1301 static void
1302 expand_schema_name_patterns(Archive *fout,
1303 SimpleStringList *patterns,
1304 SimpleOidList *oids,
1305 bool strict_names)
1307 PQExpBuffer query;
1308 PGresult *res;
1309 SimpleStringListCell *cell;
1310 int i;
1312 if (patterns->head == NULL)
1313 return; /* nothing to do */
1315 query = createPQExpBuffer();
1318 * The loop below runs multiple SELECTs might sometimes result in
1319 * duplicate entries in the OID list, but we don't care.
1322 for (cell = patterns->head; cell; cell = cell->next)
1324 appendPQExpBuffer(query,
1325 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1326 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1327 false, NULL, "n.nspname", NULL, NULL);
1329 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1330 if (strict_names && PQntuples(res) == 0)
1331 fatal("no matching schemas were found for pattern \"%s\"", cell->val);
1333 for (i = 0; i < PQntuples(res); i++)
1335 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1338 PQclear(res);
1339 resetPQExpBuffer(query);
1342 destroyPQExpBuffer(query);
1346 * Find the OIDs of all tables matching the given list of patterns,
1347 * and append them to the given OID list. See also expand_dbname_patterns()
1348 * in pg_dumpall.c
1350 static void
1351 expand_table_name_patterns(Archive *fout,
1352 SimpleStringList *patterns, SimpleOidList *oids,
1353 bool strict_names)
1355 PQExpBuffer query;
1356 PGresult *res;
1357 SimpleStringListCell *cell;
1358 int i;
1360 if (patterns->head == NULL)
1361 return; /* nothing to do */
1363 query = createPQExpBuffer();
1366 * this might sometimes result in duplicate entries in the OID list, but
1367 * we don't care.
1370 for (cell = patterns->head; cell; cell = cell->next)
1373 * Query must remain ABSOLUTELY devoid of unqualified names. This
1374 * would be unnecessary given a pg_table_is_visible() variant taking a
1375 * search_path argument.
1377 appendPQExpBuffer(query,
1378 "SELECT c.oid"
1379 "\nFROM pg_catalog.pg_class c"
1380 "\n LEFT JOIN pg_catalog.pg_namespace n"
1381 "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1382 "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1383 "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1384 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1385 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1386 RELKIND_PARTITIONED_TABLE);
1387 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1388 false, "n.nspname", "c.relname", NULL,
1389 "pg_catalog.pg_table_is_visible(c.oid)");
1391 ExecuteSqlStatement(fout, "RESET search_path");
1392 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1393 PQclear(ExecuteSqlQueryForSingleRow(fout,
1394 ALWAYS_SECURE_SEARCH_PATH_SQL));
1395 if (strict_names && PQntuples(res) == 0)
1396 fatal("no matching tables were found for pattern \"%s\"", cell->val);
1398 for (i = 0; i < PQntuples(res); i++)
1400 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1403 PQclear(res);
1404 resetPQExpBuffer(query);
1407 destroyPQExpBuffer(query);
1411 * checkExtensionMembership
1412 * Determine whether object is an extension member, and if so,
1413 * record an appropriate dependency and set the object's dump flag.
1415 * It's important to call this for each object that could be an extension
1416 * member. Generally, we integrate this with determining the object's
1417 * to-be-dumped-ness, since extension membership overrides other rules for that.
1419 * Returns true if object is an extension member, else false.
1421 static bool
1422 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1424 ExtensionInfo *ext = findOwningExtension(dobj->catId);
1426 if (ext == NULL)
1427 return false;
1429 dobj->ext_member = true;
1431 /* Record dependency so that getDependencies needn't deal with that */
1432 addObjectDependency(dobj, ext->dobj.dumpId);
1435 * In 9.6 and above, mark the member object to have any non-initial ACLs
1436 * dumped. (Any initial ACLs will be removed later, using data from
1437 * pg_init_privs, so that we'll dump only the delta from the extension's
1438 * initial setup.)
1440 * Prior to 9.6, we do not include any extension member components.
1442 * In binary upgrades, we still dump all components of the members
1443 * individually, since the idea is to exactly reproduce the database
1444 * contents rather than replace the extension contents with something
1445 * different.
1447 * Note: it might be interesting someday to implement storage and delta
1448 * dumping of extension members' RLS policies and/or security labels.
1449 * However there is a pitfall for RLS policies: trying to dump them
1450 * requires getting a lock on their tables, and the calling user might not
1451 * have privileges for that. We need no lock to examine a table's ACLs,
1452 * so the current feature doesn't have a problem of that sort.
1454 if (fout->dopt->binary_upgrade)
1455 dobj->dump = ext->dobj.dump;
1456 else
1458 if (fout->remoteVersion < 90600)
1459 dobj->dump = DUMP_COMPONENT_NONE;
1460 else
1461 dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL);
1464 return true;
1468 * selectDumpableNamespace: policy-setting subroutine
1469 * Mark a namespace as to be dumped or not
1471 static void
1472 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1475 * If specific tables are being dumped, do not dump any complete
1476 * namespaces. If specific namespaces are being dumped, dump just those
1477 * namespaces. Otherwise, dump all non-system namespaces.
1479 if (table_include_oids.head != NULL)
1480 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1481 else if (schema_include_oids.head != NULL)
1482 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1483 simple_oid_list_member(&schema_include_oids,
1484 nsinfo->dobj.catId.oid) ?
1485 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1486 else if (fout->remoteVersion >= 90600 &&
1487 strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1490 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1491 * they are interesting (and not the original ACLs which were set at
1492 * initdb time, see pg_init_privs).
1494 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1496 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1497 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1499 /* Other system schemas don't get dumped */
1500 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1502 else if (strcmp(nsinfo->dobj.name, "public") == 0)
1505 * The public schema is a strange beast that sits in a sort of
1506 * no-mans-land between being a system object and a user object. We
1507 * don't want to dump creation or comment commands for it, because
1508 * that complicates matters for non-superuser use of pg_dump. But we
1509 * should dump any ACL changes that have occurred for it, and of
1510 * course we should dump contained objects.
1512 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1513 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1515 else
1516 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1519 * In any case, a namespace can be excluded by an exclusion switch
1521 if (nsinfo->dobj.dump_contains &&
1522 simple_oid_list_member(&schema_exclude_oids,
1523 nsinfo->dobj.catId.oid))
1524 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1527 * If the schema belongs to an extension, allow extension membership to
1528 * override the dump decision for the schema itself. However, this does
1529 * not change dump_contains, so this won't change what we do with objects
1530 * within the schema. (If they belong to the extension, they'll get
1531 * suppressed by it, otherwise not.)
1533 (void) checkExtensionMembership(&nsinfo->dobj, fout);
1537 * selectDumpableTable: policy-setting subroutine
1538 * Mark a table as to be dumped or not
1540 static void
1541 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1543 if (checkExtensionMembership(&tbinfo->dobj, fout))
1544 return; /* extension membership overrides all else */
1547 * If specific tables are being dumped, dump just those tables; else, dump
1548 * according to the parent namespace's dump flag.
1550 if (table_include_oids.head != NULL)
1551 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1552 tbinfo->dobj.catId.oid) ?
1553 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1554 else
1555 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1558 * In any case, a table can be excluded by an exclusion switch
1560 if (tbinfo->dobj.dump &&
1561 simple_oid_list_member(&table_exclude_oids,
1562 tbinfo->dobj.catId.oid))
1563 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1567 * selectDumpableType: policy-setting subroutine
1568 * Mark a type as to be dumped or not
1570 * If it's a table's rowtype or an autogenerated array type, we also apply a
1571 * special type code to facilitate sorting into the desired order. (We don't
1572 * want to consider those to be ordinary types because that would bring tables
1573 * up into the datatype part of the dump order.) We still set the object's
1574 * dump flag; that's not going to cause the dummy type to be dumped, but we
1575 * need it so that casts involving such types will be dumped correctly -- see
1576 * dumpCast. This means the flag should be set the same as for the underlying
1577 * object (the table or base type).
1579 static void
1580 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1582 /* skip complex types, except for standalone composite types */
1583 if (OidIsValid(tyinfo->typrelid) &&
1584 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1586 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1588 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1589 if (tytable != NULL)
1590 tyinfo->dobj.dump = tytable->dobj.dump;
1591 else
1592 tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1593 return;
1596 /* skip auto-generated array types */
1597 if (tyinfo->isArray)
1599 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1602 * Fall through to set the dump flag; we assume that the subsequent
1603 * rules will do the same thing as they would for the array's base
1604 * type. (We cannot reliably look up the base type here, since
1605 * getTypes may not have processed it yet.)
1609 if (checkExtensionMembership(&tyinfo->dobj, fout))
1610 return; /* extension membership overrides all else */
1612 /* Dump based on if the contents of the namespace are being dumped */
1613 tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1617 * selectDumpableDefaultACL: policy-setting subroutine
1618 * Mark a default ACL as to be dumped or not
1620 * For per-schema default ACLs, dump if the schema is to be dumped.
1621 * Otherwise dump if we are dumping "everything". Note that dataOnly
1622 * and aclsSkip are checked separately.
1624 static void
1625 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1627 /* Default ACLs can't be extension members */
1629 if (dinfo->dobj.namespace)
1630 /* default ACLs are considered part of the namespace */
1631 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1632 else
1633 dinfo->dobj.dump = dopt->include_everything ?
1634 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1638 * selectDumpableCast: policy-setting subroutine
1639 * Mark a cast as to be dumped or not
1641 * Casts do not belong to any particular namespace (since they haven't got
1642 * names), nor do they have identifiable owners. To distinguish user-defined
1643 * casts from built-in ones, we must resort to checking whether the cast's
1644 * OID is in the range reserved for initdb.
1646 static void
1647 selectDumpableCast(CastInfo *cast, Archive *fout)
1649 if (checkExtensionMembership(&cast->dobj, fout))
1650 return; /* extension membership overrides all else */
1653 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1654 * support ACLs currently.
1656 if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1657 cast->dobj.dump = DUMP_COMPONENT_NONE;
1658 else
1659 cast->dobj.dump = fout->dopt->include_everything ?
1660 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1664 * selectDumpableProcLang: policy-setting subroutine
1665 * Mark a procedural language as to be dumped or not
1667 * Procedural languages do not belong to any particular namespace. To
1668 * identify built-in languages, we must resort to checking whether the
1669 * language's OID is in the range reserved for initdb.
1671 static void
1672 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1674 if (checkExtensionMembership(&plang->dobj, fout))
1675 return; /* extension membership overrides all else */
1678 * Only include procedural languages when we are dumping everything.
1680 * For from-initdb procedural languages, only include ACLs, as we do for
1681 * the pg_catalog namespace. We need this because procedural languages do
1682 * not live in any namespace.
1684 if (!fout->dopt->include_everything)
1685 plang->dobj.dump = DUMP_COMPONENT_NONE;
1686 else
1688 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1689 plang->dobj.dump = fout->remoteVersion < 90600 ?
1690 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1691 else
1692 plang->dobj.dump = DUMP_COMPONENT_ALL;
1697 * selectDumpableAccessMethod: policy-setting subroutine
1698 * Mark an access method as to be dumped or not
1700 * Access methods do not belong to any particular namespace. To identify
1701 * built-in access methods, we must resort to checking whether the
1702 * method's OID is in the range reserved for initdb.
1704 static void
1705 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1707 if (checkExtensionMembership(&method->dobj, fout))
1708 return; /* extension membership overrides all else */
1711 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1712 * they do not support ACLs currently.
1714 if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1715 method->dobj.dump = DUMP_COMPONENT_NONE;
1716 else
1717 method->dobj.dump = fout->dopt->include_everything ?
1718 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1722 * selectDumpableExtension: policy-setting subroutine
1723 * Mark an extension as to be dumped or not
1725 * Built-in extensions should be skipped except for checking ACLs, since we
1726 * assume those will already be installed in the target database. We identify
1727 * such extensions by their having OIDs in the range reserved for initdb.
1728 * We dump all user-added extensions by default, or none of them if
1729 * include_everything is false (i.e., a --schema or --table switch was given).
1731 static void
1732 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1735 * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1736 * change permissions on their member objects, if they wish to, and have
1737 * those changes preserved.
1739 if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1740 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1741 else
1742 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1743 dopt->include_everything ? DUMP_COMPONENT_ALL :
1744 DUMP_COMPONENT_NONE;
1748 * selectDumpablePublicationTable: policy-setting subroutine
1749 * Mark a publication table as to be dumped or not
1751 * Publication tables have schemas, but those are ignored in decision making,
1752 * because publications are only dumped when we are dumping everything.
1754 static void
1755 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1757 if (checkExtensionMembership(dobj, fout))
1758 return; /* extension membership overrides all else */
1760 dobj->dump = fout->dopt->include_everything ?
1761 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1765 * selectDumpableStatisticsObject: policy-setting subroutine
1766 * Mark an extended statistics object as to be dumped or not
1768 * We dump an extended statistics object if the schema it's in and the table
1769 * it's for are being dumped. (This'll need more thought if statistics
1770 * objects ever support cross-table stats.)
1772 static void
1773 selectDumpableStatisticsObject(StatsExtInfo *sobj, Archive *fout)
1775 if (checkExtensionMembership(&sobj->dobj, fout))
1776 return; /* extension membership overrides all else */
1778 sobj->dobj.dump = sobj->dobj.namespace->dobj.dump_contains;
1779 if (sobj->stattable == NULL ||
1780 !(sobj->stattable->dobj.dump & DUMP_COMPONENT_DEFINITION))
1781 sobj->dobj.dump = DUMP_COMPONENT_NONE;
1785 * selectDumpableObject: policy-setting subroutine
1786 * Mark a generic dumpable object as to be dumped or not
1788 * Use this only for object types without a special-case routine above.
1790 static void
1791 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1793 if (checkExtensionMembership(dobj, fout))
1794 return; /* extension membership overrides all else */
1797 * Default policy is to dump if parent namespace is dumpable, or for
1798 * non-namespace-associated items, dump if we're dumping "everything".
1800 if (dobj->namespace)
1801 dobj->dump = dobj->namespace->dobj.dump_contains;
1802 else
1803 dobj->dump = fout->dopt->include_everything ?
1804 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1808 * Dump a table's contents for loading using the COPY command
1809 * - this routine is called by the Archiver when it wants the table
1810 * to be dumped.
1813 static int
1814 dumpTableData_copy(Archive *fout, void *dcontext)
1816 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1817 TableInfo *tbinfo = tdinfo->tdtable;
1818 const char *classname = tbinfo->dobj.name;
1819 PQExpBuffer q = createPQExpBuffer();
1822 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1823 * which uses it already.
1825 PQExpBuffer clistBuf = createPQExpBuffer();
1826 PGconn *conn = GetConnection(fout);
1827 PGresult *res;
1828 int ret;
1829 char *copybuf;
1830 const char *column_list;
1832 pg_log_info("dumping contents of table \"%s.%s\"",
1833 tbinfo->dobj.namespace->dobj.name, classname);
1836 * Specify the column list explicitly so that we have no possibility of
1837 * retrieving data in the wrong column order. (The default column
1838 * ordering of COPY will not be what we want in certain corner cases
1839 * involving ADD COLUMN and inheritance.)
1841 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1843 if (tdinfo->filtercond)
1845 /* Note: this syntax is only supported in 8.2 and up */
1846 appendPQExpBufferStr(q, "COPY (SELECT ");
1847 /* klugery to get rid of parens in column list */
1848 if (strlen(column_list) > 2)
1850 appendPQExpBufferStr(q, column_list + 1);
1851 q->data[q->len - 1] = ' ';
1853 else
1854 appendPQExpBufferStr(q, "* ");
1855 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1856 fmtQualifiedDumpable(tbinfo),
1857 tdinfo->filtercond);
1859 else
1861 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1862 fmtQualifiedDumpable(tbinfo),
1863 column_list);
1865 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1866 PQclear(res);
1867 destroyPQExpBuffer(clistBuf);
1869 for (;;)
1871 ret = PQgetCopyData(conn, &copybuf, 0);
1873 if (ret < 0)
1874 break; /* done or error */
1876 if (copybuf)
1878 WriteData(fout, copybuf, ret);
1879 PQfreemem(copybuf);
1882 /* ----------
1883 * THROTTLE:
1885 * There was considerable discussion in late July, 2000 regarding
1886 * slowing down pg_dump when backing up large tables. Users with both
1887 * slow & fast (multi-processor) machines experienced performance
1888 * degradation when doing a backup.
1890 * Initial attempts based on sleeping for a number of ms for each ms
1891 * of work were deemed too complex, then a simple 'sleep in each loop'
1892 * implementation was suggested. The latter failed because the loop
1893 * was too tight. Finally, the following was implemented:
1895 * If throttle is non-zero, then
1896 * See how long since the last sleep.
1897 * Work out how long to sleep (based on ratio).
1898 * If sleep is more than 100ms, then
1899 * sleep
1900 * reset timer
1901 * EndIf
1902 * EndIf
1904 * where the throttle value was the number of ms to sleep per ms of
1905 * work. The calculation was done in each loop.
1907 * Most of the hard work is done in the backend, and this solution
1908 * still did not work particularly well: on slow machines, the ratio
1909 * was 50:1, and on medium paced machines, 1:1, and on fast
1910 * multi-processor machines, it had little or no effect, for reasons
1911 * that were unclear.
1913 * Further discussion ensued, and the proposal was dropped.
1915 * For those people who want this feature, it can be implemented using
1916 * gettimeofday in each loop, calculating the time since last sleep,
1917 * multiplying that by the sleep ratio, then if the result is more
1918 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1919 * function to sleep for a subsecond period ie.
1921 * select(0, NULL, NULL, NULL, &tvi);
1923 * This will return after the interval specified in the structure tvi.
1924 * Finally, call gettimeofday again to save the 'last sleep time'.
1925 * ----------
1928 archprintf(fout, "\\.\n\n\n");
1930 if (ret == -2)
1932 /* copy data transfer failed */
1933 pg_log_error("Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.", classname);
1934 pg_log_error("Error message from server: %s", PQerrorMessage(conn));
1935 pg_log_error("The command was: %s", q->data);
1936 exit_nicely(1);
1939 /* Check command status and return to normal libpq state */
1940 res = PQgetResult(conn);
1941 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1943 pg_log_error("Dumping the contents of table \"%s\" failed: PQgetResult() failed.", classname);
1944 pg_log_error("Error message from server: %s", PQerrorMessage(conn));
1945 pg_log_error("The command was: %s", q->data);
1946 exit_nicely(1);
1948 PQclear(res);
1950 /* Do this to ensure we've pumped libpq back to idle state */
1951 if (PQgetResult(conn) != NULL)
1952 pg_log_warning("unexpected extra results during COPY of table \"%s\"",
1953 classname);
1955 destroyPQExpBuffer(q);
1956 return 1;
1960 * Dump table data using INSERT commands.
1962 * Caution: when we restore from an archive file direct to database, the
1963 * INSERT commands emitted by this function have to be parsed by
1964 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1965 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1967 static int
1968 dumpTableData_insert(Archive *fout, void *dcontext)
1970 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1971 TableInfo *tbinfo = tdinfo->tdtable;
1972 DumpOptions *dopt = fout->dopt;
1973 PQExpBuffer q = createPQExpBuffer();
1974 PQExpBuffer insertStmt = NULL;
1975 char *attgenerated;
1976 PGresult *res;
1977 int nfields,
1979 int rows_per_statement = dopt->dump_inserts;
1980 int rows_this_statement = 0;
1983 * If we're going to emit INSERTs with column names, the most efficient
1984 * way to deal with generated columns is to exclude them entirely. For
1985 * INSERTs without column names, we have to emit DEFAULT rather than the
1986 * actual column value --- but we can save a few cycles by fetching nulls
1987 * rather than the uninteresting-to-us value.
1989 attgenerated = (char *) pg_malloc(tbinfo->numatts * sizeof(char));
1990 appendPQExpBufferStr(q, "DECLARE _pg_dump_cursor CURSOR FOR SELECT ");
1991 nfields = 0;
1992 for (i = 0; i < tbinfo->numatts; i++)
1994 if (tbinfo->attisdropped[i])
1995 continue;
1996 if (tbinfo->attgenerated[i] && dopt->column_inserts)
1997 continue;
1998 if (nfields > 0)
1999 appendPQExpBufferStr(q, ", ");
2000 if (tbinfo->attgenerated[i])
2001 appendPQExpBufferStr(q, "NULL");
2002 else
2003 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[i]));
2004 attgenerated[nfields] = tbinfo->attgenerated[i];
2005 nfields++;
2007 /* Servers before 9.4 will complain about zero-column SELECT */
2008 if (nfields == 0)
2009 appendPQExpBufferStr(q, "NULL");
2010 appendPQExpBuffer(q, " FROM ONLY %s",
2011 fmtQualifiedDumpable(tbinfo));
2012 if (tdinfo->filtercond)
2013 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
2015 ExecuteSqlStatement(fout, q->data);
2017 while (1)
2019 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
2020 PGRES_TUPLES_OK);
2022 /* cross-check field count, allowing for dummy NULL if any */
2023 if (nfields != PQnfields(res) &&
2024 !(nfields == 0 && PQnfields(res) == 1))
2025 fatal("wrong number of fields retrieved from table \"%s\"",
2026 tbinfo->dobj.name);
2029 * First time through, we build as much of the INSERT statement as
2030 * possible in "insertStmt", which we can then just print for each
2031 * statement. If the table happens to have zero dumpable columns then
2032 * this will be a complete statement, otherwise it will end in
2033 * "VALUES" and be ready to have the row's column values printed.
2035 if (insertStmt == NULL)
2037 TableInfo *targettab;
2039 insertStmt = createPQExpBuffer();
2042 * When load-via-partition-root is set or forced, get the root
2043 * table name for the partition table, so that we can reload data
2044 * through the root table.
2046 if (tbinfo->ispartition &&
2047 (dopt->load_via_partition_root ||
2048 forcePartitionRootLoad(tbinfo)))
2049 targettab = getRootTableInfo(tbinfo);
2050 else
2051 targettab = tbinfo;
2053 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
2054 fmtQualifiedDumpable(targettab));
2056 /* corner case for zero-column table */
2057 if (nfields == 0)
2059 appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
2061 else
2063 /* append the list of column names if required */
2064 if (dopt->column_inserts)
2066 appendPQExpBufferChar(insertStmt, '(');
2067 for (int field = 0; field < nfields; field++)
2069 if (field > 0)
2070 appendPQExpBufferStr(insertStmt, ", ");
2071 appendPQExpBufferStr(insertStmt,
2072 fmtId(PQfname(res, field)));
2074 appendPQExpBufferStr(insertStmt, ") ");
2077 if (tbinfo->needs_override)
2078 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
2080 appendPQExpBufferStr(insertStmt, "VALUES");
2084 for (int tuple = 0; tuple < PQntuples(res); tuple++)
2086 /* Write the INSERT if not in the middle of a multi-row INSERT. */
2087 if (rows_this_statement == 0)
2088 archputs(insertStmt->data, fout);
2091 * If it is zero-column table then we've already written the
2092 * complete statement, which will mean we've disobeyed
2093 * --rows-per-insert when it's set greater than 1. We do support
2094 * a way to make this multi-row with: SELECT UNION ALL SELECT
2095 * UNION ALL ... but that's non-standard so we should avoid it
2096 * given that using INSERTs is mostly only ever needed for
2097 * cross-database exports.
2099 if (nfields == 0)
2100 continue;
2102 /* Emit a row heading */
2103 if (rows_per_statement == 1)
2104 archputs(" (", fout);
2105 else if (rows_this_statement > 0)
2106 archputs(",\n\t(", fout);
2107 else
2108 archputs("\n\t(", fout);
2110 for (int field = 0; field < nfields; field++)
2112 if (field > 0)
2113 archputs(", ", fout);
2114 if (attgenerated[field])
2116 archputs("DEFAULT", fout);
2117 continue;
2119 if (PQgetisnull(res, tuple, field))
2121 archputs("NULL", fout);
2122 continue;
2125 /* XXX This code is partially duplicated in ruleutils.c */
2126 switch (PQftype(res, field))
2128 case INT2OID:
2129 case INT4OID:
2130 case INT8OID:
2131 case OIDOID:
2132 case FLOAT4OID:
2133 case FLOAT8OID:
2134 case NUMERICOID:
2137 * These types are printed without quotes unless
2138 * they contain values that aren't accepted by the
2139 * scanner unquoted (e.g., 'NaN'). Note that
2140 * strtod() and friends might accept NaN, so we
2141 * can't use that to test.
2143 * In reality we only need to defend against
2144 * infinity and NaN, so we need not get too crazy
2145 * about pattern matching here.
2147 const char *s = PQgetvalue(res, tuple, field);
2149 if (strspn(s, "0123456789 +-eE.") == strlen(s))
2150 archputs(s, fout);
2151 else
2152 archprintf(fout, "'%s'", s);
2154 break;
2156 case BITOID:
2157 case VARBITOID:
2158 archprintf(fout, "B'%s'",
2159 PQgetvalue(res, tuple, field));
2160 break;
2162 case BOOLOID:
2163 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2164 archputs("true", fout);
2165 else
2166 archputs("false", fout);
2167 break;
2169 default:
2170 /* All other types are printed as string literals. */
2171 resetPQExpBuffer(q);
2172 appendStringLiteralAH(q,
2173 PQgetvalue(res, tuple, field),
2174 fout);
2175 archputs(q->data, fout);
2176 break;
2180 /* Terminate the row ... */
2181 archputs(")", fout);
2183 /* ... and the statement, if the target no. of rows is reached */
2184 if (++rows_this_statement >= rows_per_statement)
2186 if (dopt->do_nothing)
2187 archputs(" ON CONFLICT DO NOTHING;\n", fout);
2188 else
2189 archputs(";\n", fout);
2190 /* Reset the row counter */
2191 rows_this_statement = 0;
2195 if (PQntuples(res) <= 0)
2197 PQclear(res);
2198 break;
2200 PQclear(res);
2203 /* Terminate any statements that didn't make the row count. */
2204 if (rows_this_statement > 0)
2206 if (dopt->do_nothing)
2207 archputs(" ON CONFLICT DO NOTHING;\n", fout);
2208 else
2209 archputs(";\n", fout);
2212 archputs("\n\n", fout);
2214 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2216 destroyPQExpBuffer(q);
2217 if (insertStmt != NULL)
2218 destroyPQExpBuffer(insertStmt);
2219 free(attgenerated);
2221 return 1;
2225 * getRootTableInfo:
2226 * get the root TableInfo for the given partition table.
2228 static TableInfo *
2229 getRootTableInfo(TableInfo *tbinfo)
2231 TableInfo *parentTbinfo;
2233 Assert(tbinfo->ispartition);
2234 Assert(tbinfo->numParents == 1);
2236 parentTbinfo = tbinfo->parents[0];
2237 while (parentTbinfo->ispartition)
2239 Assert(parentTbinfo->numParents == 1);
2240 parentTbinfo = parentTbinfo->parents[0];
2243 return parentTbinfo;
2247 * forcePartitionRootLoad
2248 * Check if we must force load_via_partition_root for this partition.
2250 * This is required if any level of ancestral partitioned table has an
2251 * unsafe partitioning scheme.
2253 static bool
2254 forcePartitionRootLoad(const TableInfo *tbinfo)
2256 TableInfo *parentTbinfo;
2258 Assert(tbinfo->ispartition);
2259 Assert(tbinfo->numParents == 1);
2261 parentTbinfo = tbinfo->parents[0];
2262 if (parentTbinfo->unsafe_partitions)
2263 return true;
2264 while (parentTbinfo->ispartition)
2266 Assert(parentTbinfo->numParents == 1);
2267 parentTbinfo = parentTbinfo->parents[0];
2268 if (parentTbinfo->unsafe_partitions)
2269 return true;
2272 return false;
2276 * dumpTableData -
2277 * dump the contents of a single table
2279 * Actually, this just makes an ArchiveEntry for the table contents.
2281 static void
2282 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2284 DumpOptions *dopt = fout->dopt;
2285 TableInfo *tbinfo = tdinfo->tdtable;
2286 PQExpBuffer copyBuf = createPQExpBuffer();
2287 PQExpBuffer clistBuf = createPQExpBuffer();
2288 DataDumperPtr dumpFn;
2289 char *tdDefn = NULL;
2290 char *copyStmt;
2291 const char *copyFrom;
2293 /* We had better have loaded per-column details about this table */
2294 Assert(tbinfo->interesting);
2297 * When load-via-partition-root is set or forced, get the root table name
2298 * for the partition table, so that we can reload data through the root
2299 * table. Then construct a comment to be inserted into the TOC entry's
2300 * defn field, so that such cases can be identified reliably.
2302 if (tbinfo->ispartition &&
2303 (dopt->load_via_partition_root ||
2304 forcePartitionRootLoad(tbinfo)))
2306 TableInfo *parentTbinfo;
2308 parentTbinfo = getRootTableInfo(tbinfo);
2309 copyFrom = fmtQualifiedDumpable(parentTbinfo);
2310 printfPQExpBuffer(copyBuf, "-- load via partition root %s",
2311 copyFrom);
2312 tdDefn = pg_strdup(copyBuf->data);
2314 else
2315 copyFrom = fmtQualifiedDumpable(tbinfo);
2317 if (!dopt->dump_inserts)
2319 /* Dump/restore using COPY */
2320 dumpFn = dumpTableData_copy;
2321 /* must use 2 steps here 'cause fmtId is nonreentrant */
2322 printfPQExpBuffer(copyBuf, "COPY %s ",
2323 copyFrom);
2324 appendPQExpBuffer(copyBuf, "%s FROM stdin;\n",
2325 fmtCopyColumnList(tbinfo, clistBuf));
2326 copyStmt = copyBuf->data;
2328 else
2330 /* Restore using INSERT */
2331 dumpFn = dumpTableData_insert;
2332 copyStmt = NULL;
2336 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2337 * dependency on its table as "special" and pass it to ArchiveEntry now.
2338 * See comments for BuildArchiveDependencies.
2340 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2342 TocEntry *te;
2344 te = ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2345 ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2346 .namespace = tbinfo->dobj.namespace->dobj.name,
2347 .owner = tbinfo->rolname,
2348 .description = "TABLE DATA",
2349 .section = SECTION_DATA,
2350 .createStmt = tdDefn,
2351 .copyStmt = copyStmt,
2352 .deps = &(tbinfo->dobj.dumpId),
2353 .nDeps = 1,
2354 .dumpFn = dumpFn,
2355 .dumpArg = tdinfo));
2358 * Set the TocEntry's dataLength in case we are doing a parallel dump
2359 * and want to order dump jobs by table size. We choose to measure
2360 * dataLength in table pages during dump, so no scaling is needed.
2361 * However, relpages is declared as "integer" in pg_class, and hence
2362 * also in TableInfo, but it's really BlockNumber a/k/a unsigned int.
2363 * Cast so that we get the right interpretation of table sizes
2364 * exceeding INT_MAX pages.
2366 te->dataLength = (BlockNumber) tbinfo->relpages;
2369 destroyPQExpBuffer(copyBuf);
2370 destroyPQExpBuffer(clistBuf);
2374 * refreshMatViewData -
2375 * load or refresh the contents of a single materialized view
2377 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2378 * statement.
2380 static void
2381 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2383 TableInfo *tbinfo = tdinfo->tdtable;
2384 PQExpBuffer q;
2386 /* If the materialized view is not flagged as populated, skip this. */
2387 if (!tbinfo->relispopulated)
2388 return;
2390 q = createPQExpBuffer();
2392 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2393 fmtQualifiedDumpable(tbinfo));
2395 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2396 ArchiveEntry(fout,
2397 tdinfo->dobj.catId, /* catalog ID */
2398 tdinfo->dobj.dumpId, /* dump ID */
2399 ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2400 .namespace = tbinfo->dobj.namespace->dobj.name,
2401 .owner = tbinfo->rolname,
2402 .description = "MATERIALIZED VIEW DATA",
2403 .section = SECTION_POST_DATA,
2404 .createStmt = q->data,
2405 .deps = tdinfo->dobj.dependencies,
2406 .nDeps = tdinfo->dobj.nDeps));
2408 destroyPQExpBuffer(q);
2412 * getTableData -
2413 * set up dumpable objects representing the contents of tables
2415 static void
2416 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind)
2418 int i;
2420 for (i = 0; i < numTables; i++)
2422 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2423 (!relkind || tblinfo[i].relkind == relkind))
2424 makeTableDataInfo(dopt, &(tblinfo[i]));
2429 * Make a dumpable object for the data of this specific table
2431 * Note: we make a TableDataInfo if and only if we are going to dump the
2432 * table data; the "dump" flag in such objects isn't used.
2434 static void
2435 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo)
2437 TableDataInfo *tdinfo;
2440 * Nothing to do if we already decided to dump the table. This will
2441 * happen for "config" tables.
2443 if (tbinfo->dataObj != NULL)
2444 return;
2446 /* Skip VIEWs (no data to dump) */
2447 if (tbinfo->relkind == RELKIND_VIEW)
2448 return;
2449 /* Skip FOREIGN TABLEs (no data to dump) */
2450 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2451 return;
2452 /* Skip partitioned tables (data in partitions) */
2453 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2454 return;
2456 /* Don't dump data in unlogged tables, if so requested */
2457 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2458 dopt->no_unlogged_table_data)
2459 return;
2461 /* Check that the data is not explicitly excluded */
2462 if (simple_oid_list_member(&tabledata_exclude_oids,
2463 tbinfo->dobj.catId.oid))
2464 return;
2466 /* OK, let's dump it */
2467 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2469 if (tbinfo->relkind == RELKIND_MATVIEW)
2470 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2471 else if (tbinfo->relkind == RELKIND_SEQUENCE)
2472 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2473 else
2474 tdinfo->dobj.objType = DO_TABLE_DATA;
2477 * Note: use tableoid 0 so that this object won't be mistaken for
2478 * something that pg_depend entries apply to.
2480 tdinfo->dobj.catId.tableoid = 0;
2481 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2482 AssignDumpId(&tdinfo->dobj);
2483 tdinfo->dobj.name = tbinfo->dobj.name;
2484 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2485 tdinfo->tdtable = tbinfo;
2486 tdinfo->filtercond = NULL; /* might get set later */
2487 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2489 tbinfo->dataObj = tdinfo;
2491 /* Make sure that we'll collect per-column info for this table. */
2492 tbinfo->interesting = true;
2496 * The refresh for a materialized view must be dependent on the refresh for
2497 * any materialized view that this one is dependent on.
2499 * This must be called after all the objects are created, but before they are
2500 * sorted.
2502 static void
2503 buildMatViewRefreshDependencies(Archive *fout)
2505 PQExpBuffer query;
2506 PGresult *res;
2507 int ntups,
2509 int i_classid,
2510 i_objid,
2511 i_refobjid;
2513 /* No Mat Views before 9.3. */
2514 if (fout->remoteVersion < 90300)
2515 return;
2517 query = createPQExpBuffer();
2519 appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2520 "( "
2521 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2522 "FROM pg_depend d1 "
2523 "JOIN pg_class c1 ON c1.oid = d1.objid "
2524 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2525 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2526 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2527 "AND d2.objid = r1.oid "
2528 "AND d2.refobjid <> d1.objid "
2529 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2530 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2531 CppAsString2(RELKIND_VIEW) ") "
2532 "WHERE d1.classid = 'pg_class'::regclass "
2533 "UNION "
2534 "SELECT w.objid, d3.refobjid, c3.relkind "
2535 "FROM w "
2536 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2537 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2538 "AND d3.objid = r3.oid "
2539 "AND d3.refobjid <> w.refobjid "
2540 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2541 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2542 CppAsString2(RELKIND_VIEW) ") "
2543 ") "
2544 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2545 "FROM w "
2546 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2548 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2550 ntups = PQntuples(res);
2552 i_classid = PQfnumber(res, "classid");
2553 i_objid = PQfnumber(res, "objid");
2554 i_refobjid = PQfnumber(res, "refobjid");
2556 for (i = 0; i < ntups; i++)
2558 CatalogId objId;
2559 CatalogId refobjId;
2560 DumpableObject *dobj;
2561 DumpableObject *refdobj;
2562 TableInfo *tbinfo;
2563 TableInfo *reftbinfo;
2565 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2566 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2567 refobjId.tableoid = objId.tableoid;
2568 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2570 dobj = findObjectByCatalogId(objId);
2571 if (dobj == NULL)
2572 continue;
2574 Assert(dobj->objType == DO_TABLE);
2575 tbinfo = (TableInfo *) dobj;
2576 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2577 dobj = (DumpableObject *) tbinfo->dataObj;
2578 if (dobj == NULL)
2579 continue;
2580 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2582 refdobj = findObjectByCatalogId(refobjId);
2583 if (refdobj == NULL)
2584 continue;
2586 Assert(refdobj->objType == DO_TABLE);
2587 reftbinfo = (TableInfo *) refdobj;
2588 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2589 refdobj = (DumpableObject *) reftbinfo->dataObj;
2590 if (refdobj == NULL)
2591 continue;
2592 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2594 addObjectDependency(dobj, refdobj->dumpId);
2596 if (!reftbinfo->relispopulated)
2597 tbinfo->relispopulated = false;
2600 PQclear(res);
2602 destroyPQExpBuffer(query);
2606 * getTableDataFKConstraints -
2607 * add dump-order dependencies reflecting foreign key constraints
2609 * This code is executed only in a data-only dump --- in schema+data dumps
2610 * we handle foreign key issues by not creating the FK constraints until
2611 * after the data is loaded. In a data-only dump, however, we want to
2612 * order the table data objects in such a way that a table's referenced
2613 * tables are restored first. (In the presence of circular references or
2614 * self-references this may be impossible; we'll detect and complain about
2615 * that during the dependency sorting step.)
2617 static void
2618 getTableDataFKConstraints(void)
2620 DumpableObject **dobjs;
2621 int numObjs;
2622 int i;
2624 /* Search through all the dumpable objects for FK constraints */
2625 getDumpableObjects(&dobjs, &numObjs);
2626 for (i = 0; i < numObjs; i++)
2628 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2630 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2631 TableInfo *ftable;
2633 /* Not interesting unless both tables are to be dumped */
2634 if (cinfo->contable == NULL ||
2635 cinfo->contable->dataObj == NULL)
2636 continue;
2637 ftable = findTableByOid(cinfo->confrelid);
2638 if (ftable == NULL ||
2639 ftable->dataObj == NULL)
2640 continue;
2643 * Okay, make referencing table's TABLE_DATA object depend on the
2644 * referenced table's TABLE_DATA object.
2646 addObjectDependency(&cinfo->contable->dataObj->dobj,
2647 ftable->dataObj->dobj.dumpId);
2650 free(dobjs);
2655 * guessConstraintInheritance:
2656 * In pre-8.4 databases, we can't tell for certain which constraints
2657 * are inherited. We assume a CHECK constraint is inherited if its name
2658 * matches the name of any constraint in the parent. Originally this code
2659 * tried to compare the expression texts, but that can fail for various
2660 * reasons --- for example, if the parent and child tables are in different
2661 * schemas, reverse-listing of function calls may produce different text
2662 * (schema-qualified or not) depending on search path.
2664 * In 8.4 and up we can rely on the conislocal field to decide which
2665 * constraints must be dumped; much safer.
2667 * This function assumes all conislocal flags were initialized to true.
2668 * It clears the flag on anything that seems to be inherited.
2670 static void
2671 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2673 int i,
2677 for (i = 0; i < numTables; i++)
2679 TableInfo *tbinfo = &(tblinfo[i]);
2680 int numParents;
2681 TableInfo **parents;
2682 TableInfo *parent;
2684 /* Sequences and views never have parents */
2685 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2686 tbinfo->relkind == RELKIND_VIEW)
2687 continue;
2689 /* Don't bother computing anything for non-target tables, either */
2690 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2691 continue;
2693 numParents = tbinfo->numParents;
2694 parents = tbinfo->parents;
2696 if (numParents == 0)
2697 continue; /* nothing to see here, move along */
2699 /* scan for inherited CHECK constraints */
2700 for (j = 0; j < tbinfo->ncheck; j++)
2702 ConstraintInfo *constr;
2704 constr = &(tbinfo->checkexprs[j]);
2706 for (k = 0; k < numParents; k++)
2708 int l;
2710 parent = parents[k];
2711 for (l = 0; l < parent->ncheck; l++)
2713 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2715 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2717 constr->conislocal = false;
2718 break;
2721 if (!constr->conislocal)
2722 break;
2730 * dumpDatabase:
2731 * dump the database definition
2733 static void
2734 dumpDatabase(Archive *fout)
2736 DumpOptions *dopt = fout->dopt;
2737 PQExpBuffer dbQry = createPQExpBuffer();
2738 PQExpBuffer delQry = createPQExpBuffer();
2739 PQExpBuffer creaQry = createPQExpBuffer();
2740 PQExpBuffer labelq = createPQExpBuffer();
2741 PGconn *conn = GetConnection(fout);
2742 PGresult *res;
2743 int i_tableoid,
2744 i_oid,
2745 i_datname,
2746 i_dba,
2747 i_encoding,
2748 i_collate,
2749 i_ctype,
2750 i_frozenxid,
2751 i_minmxid,
2752 i_datacl,
2753 i_rdatacl,
2754 i_datistemplate,
2755 i_datconnlimit,
2756 i_tablespace;
2757 CatalogId dbCatId;
2758 DumpId dbDumpId;
2759 const char *datname,
2760 *dba,
2761 *encoding,
2762 *collate,
2763 *ctype,
2764 *datacl,
2765 *rdatacl,
2766 *datistemplate,
2767 *datconnlimit,
2768 *tablespace;
2769 uint32 frozenxid,
2770 minmxid;
2771 char *qdatname;
2773 pg_log_info("saving database definition");
2776 * Fetch the database-level properties for this database.
2778 * The order in which privileges are in the ACL string (the order they
2779 * have been GRANT'd in, which the backend maintains) must be preserved to
2780 * ensure that GRANTs WITH GRANT OPTION and subsequent GRANTs based on
2781 * those are dumped in the correct order. Note that initial privileges
2782 * (pg_init_privs) are not supported on databases, so this logic cannot
2783 * make use of buildACLQueries().
2785 if (fout->remoteVersion >= 90600)
2787 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2788 "(%s datdba) AS dba, "
2789 "pg_encoding_to_char(encoding) AS encoding, "
2790 "datcollate, datctype, datfrozenxid, datminmxid, "
2791 "(SELECT array_agg(acl ORDER BY row_n) FROM "
2792 " (SELECT acl, row_n FROM "
2793 " unnest(coalesce(datacl,acldefault('d',datdba))) "
2794 " WITH ORDINALITY AS perm(acl,row_n) "
2795 " WHERE NOT EXISTS ( "
2796 " SELECT 1 "
2797 " FROM unnest(acldefault('d',datdba)) "
2798 " AS init(init_acl) "
2799 " WHERE acl = init_acl)) AS datacls) "
2800 " AS datacl, "
2801 "(SELECT array_agg(acl ORDER BY row_n) FROM "
2802 " (SELECT acl, row_n FROM "
2803 " unnest(acldefault('d',datdba)) "
2804 " WITH ORDINALITY AS initp(acl,row_n) "
2805 " WHERE NOT EXISTS ( "
2806 " SELECT 1 "
2807 " FROM unnest(coalesce(datacl,acldefault('d',datdba))) "
2808 " AS permp(orig_acl) "
2809 " WHERE acl = orig_acl)) AS rdatacls) "
2810 " AS rdatacl, "
2811 "datistemplate, datconnlimit, "
2812 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2813 "shobj_description(oid, 'pg_database') AS description "
2815 "FROM pg_database "
2816 "WHERE datname = current_database()",
2817 username_subquery);
2819 else if (fout->remoteVersion >= 90300)
2821 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2822 "(%s datdba) AS dba, "
2823 "pg_encoding_to_char(encoding) AS encoding, "
2824 "datcollate, datctype, datfrozenxid, datminmxid, "
2825 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2826 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2827 "shobj_description(oid, 'pg_database') AS description "
2829 "FROM pg_database "
2830 "WHERE datname = current_database()",
2831 username_subquery);
2833 else if (fout->remoteVersion >= 80400)
2835 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2836 "(%s datdba) AS dba, "
2837 "pg_encoding_to_char(encoding) AS encoding, "
2838 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2839 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2840 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2841 "shobj_description(oid, 'pg_database') AS description "
2843 "FROM pg_database "
2844 "WHERE datname = current_database()",
2845 username_subquery);
2847 else if (fout->remoteVersion >= 80200)
2849 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2850 "(%s datdba) AS dba, "
2851 "pg_encoding_to_char(encoding) AS encoding, "
2852 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2853 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2854 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2855 "shobj_description(oid, 'pg_database') AS description "
2857 "FROM pg_database "
2858 "WHERE datname = current_database()",
2859 username_subquery);
2861 else
2863 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2864 "(%s datdba) AS dba, "
2865 "pg_encoding_to_char(encoding) AS encoding, "
2866 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2867 "datacl, '' as rdatacl, datistemplate, "
2868 "-1 as datconnlimit, "
2869 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2870 "FROM pg_database "
2871 "WHERE datname = current_database()",
2872 username_subquery);
2875 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2877 i_tableoid = PQfnumber(res, "tableoid");
2878 i_oid = PQfnumber(res, "oid");
2879 i_datname = PQfnumber(res, "datname");
2880 i_dba = PQfnumber(res, "dba");
2881 i_encoding = PQfnumber(res, "encoding");
2882 i_collate = PQfnumber(res, "datcollate");
2883 i_ctype = PQfnumber(res, "datctype");
2884 i_frozenxid = PQfnumber(res, "datfrozenxid");
2885 i_minmxid = PQfnumber(res, "datminmxid");
2886 i_datacl = PQfnumber(res, "datacl");
2887 i_rdatacl = PQfnumber(res, "rdatacl");
2888 i_datistemplate = PQfnumber(res, "datistemplate");
2889 i_datconnlimit = PQfnumber(res, "datconnlimit");
2890 i_tablespace = PQfnumber(res, "tablespace");
2892 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2893 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2894 datname = PQgetvalue(res, 0, i_datname);
2895 dba = PQgetvalue(res, 0, i_dba);
2896 encoding = PQgetvalue(res, 0, i_encoding);
2897 collate = PQgetvalue(res, 0, i_collate);
2898 ctype = PQgetvalue(res, 0, i_ctype);
2899 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2900 minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2901 datacl = PQgetvalue(res, 0, i_datacl);
2902 rdatacl = PQgetvalue(res, 0, i_rdatacl);
2903 datistemplate = PQgetvalue(res, 0, i_datistemplate);
2904 datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2905 tablespace = PQgetvalue(res, 0, i_tablespace);
2907 qdatname = pg_strdup(fmtId(datname));
2910 * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2911 * and tablespace since those can't be altered later. Other DB properties
2912 * are left to the DATABASE PROPERTIES entry, so that they can be applied
2913 * after reconnecting to the target DB.
2915 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2916 qdatname);
2917 if (strlen(encoding) > 0)
2919 appendPQExpBufferStr(creaQry, " ENCODING = ");
2920 appendStringLiteralAH(creaQry, encoding, fout);
2922 if (strlen(collate) > 0)
2924 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2925 appendStringLiteralAH(creaQry, collate, fout);
2927 if (strlen(ctype) > 0)
2929 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2930 appendStringLiteralAH(creaQry, ctype, fout);
2934 * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2935 * thing; the decision whether to specify a tablespace should be left till
2936 * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2937 * label the DATABASE entry with the tablespace and let the normal
2938 * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2939 * attention to default_tablespace, so that won't work.
2941 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2942 !dopt->outputNoTablespaces)
2943 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2944 fmtId(tablespace));
2945 appendPQExpBufferStr(creaQry, ";\n");
2947 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2948 qdatname);
2950 dbDumpId = createDumpId();
2952 ArchiveEntry(fout,
2953 dbCatId, /* catalog ID */
2954 dbDumpId, /* dump ID */
2955 ARCHIVE_OPTS(.tag = datname,
2956 .owner = dba,
2957 .description = "DATABASE",
2958 .section = SECTION_PRE_DATA,
2959 .createStmt = creaQry->data,
2960 .dropStmt = delQry->data));
2962 /* Compute correct tag for archive entry */
2963 appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2965 /* Dump DB comment if any */
2966 if (fout->remoteVersion >= 80200)
2969 * 8.2 and up keep comments on shared objects in a shared table, so we
2970 * cannot use the dumpComment() code used for other database objects.
2971 * Be careful that the ArchiveEntry parameters match that function.
2973 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2975 if (comment && *comment && !dopt->no_comments)
2977 resetPQExpBuffer(dbQry);
2980 * Generates warning when loaded into a differently-named
2981 * database.
2983 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2984 appendStringLiteralAH(dbQry, comment, fout);
2985 appendPQExpBufferStr(dbQry, ";\n");
2987 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2988 ARCHIVE_OPTS(.tag = labelq->data,
2989 .owner = dba,
2990 .description = "COMMENT",
2991 .section = SECTION_NONE,
2992 .createStmt = dbQry->data,
2993 .deps = &dbDumpId,
2994 .nDeps = 1));
2997 else
2999 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
3000 dbCatId, 0, dbDumpId);
3003 /* Dump DB security label, if enabled */
3004 if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
3006 PGresult *shres;
3007 PQExpBuffer seclabelQry;
3009 seclabelQry = createPQExpBuffer();
3011 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
3012 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
3013 resetPQExpBuffer(seclabelQry);
3014 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
3015 if (seclabelQry->len > 0)
3016 ArchiveEntry(fout, nilCatalogId, createDumpId(),
3017 ARCHIVE_OPTS(.tag = labelq->data,
3018 .owner = dba,
3019 .description = "SECURITY LABEL",
3020 .section = SECTION_NONE,
3021 .createStmt = seclabelQry->data,
3022 .deps = &dbDumpId,
3023 .nDeps = 1));
3024 destroyPQExpBuffer(seclabelQry);
3025 PQclear(shres);
3029 * Dump ACL if any. Note that we do not support initial privileges
3030 * (pg_init_privs) on databases.
3032 dumpACL(fout, dbDumpId, InvalidDumpId, "DATABASE",
3033 qdatname, NULL, NULL,
3034 dba, datacl, rdatacl, "", "");
3037 * Now construct a DATABASE PROPERTIES archive entry to restore any
3038 * non-default database-level properties. (The reason this must be
3039 * separate is that we cannot put any additional commands into the TOC
3040 * entry that has CREATE DATABASE. pg_restore would execute such a group
3041 * in an implicit transaction block, and the backend won't allow CREATE
3042 * DATABASE in that context.)
3044 resetPQExpBuffer(creaQry);
3045 resetPQExpBuffer(delQry);
3047 if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
3048 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
3049 qdatname, datconnlimit);
3051 if (strcmp(datistemplate, "t") == 0)
3053 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
3054 qdatname);
3057 * The backend won't accept DROP DATABASE on a template database. We
3058 * can deal with that by removing the template marking before the DROP
3059 * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
3060 * since no such command is currently supported, fake it with a direct
3061 * UPDATE on pg_database.
3063 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
3064 "SET datistemplate = false WHERE datname = ");
3065 appendStringLiteralAH(delQry, datname, fout);
3066 appendPQExpBufferStr(delQry, ";\n");
3069 /* Add database-specific SET options */
3070 dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
3073 * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
3074 * entry, too, for lack of a better place.
3076 if (dopt->binary_upgrade)
3078 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
3079 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
3080 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
3081 "WHERE datname = ",
3082 frozenxid, minmxid);
3083 appendStringLiteralAH(creaQry, datname, fout);
3084 appendPQExpBufferStr(creaQry, ";\n");
3087 if (creaQry->len > 0)
3088 ArchiveEntry(fout, nilCatalogId, createDumpId(),
3089 ARCHIVE_OPTS(.tag = datname,
3090 .owner = dba,
3091 .description = "DATABASE PROPERTIES",
3092 .section = SECTION_PRE_DATA,
3093 .createStmt = creaQry->data,
3094 .dropStmt = delQry->data,
3095 .deps = &dbDumpId));
3098 * pg_largeobject comes from the old system intact, so set its
3099 * relfrozenxids and relminmxids.
3101 if (dopt->binary_upgrade)
3103 PGresult *lo_res;
3104 PQExpBuffer loFrozenQry = createPQExpBuffer();
3105 PQExpBuffer loOutQry = createPQExpBuffer();
3106 int i_relfrozenxid,
3107 i_relminmxid;
3110 * pg_largeobject
3112 if (fout->remoteVersion >= 90300)
3113 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
3114 "FROM pg_catalog.pg_class\n"
3115 "WHERE oid = %u;\n",
3116 LargeObjectRelationId);
3117 else
3118 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
3119 "FROM pg_catalog.pg_class\n"
3120 "WHERE oid = %u;\n",
3121 LargeObjectRelationId);
3123 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
3125 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
3126 i_relminmxid = PQfnumber(lo_res, "relminmxid");
3128 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
3129 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
3130 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
3131 "WHERE oid = %u;\n",
3132 atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
3133 atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
3134 LargeObjectRelationId);
3135 ArchiveEntry(fout, nilCatalogId, createDumpId(),
3136 ARCHIVE_OPTS(.tag = "pg_largeobject",
3137 .description = "pg_largeobject",
3138 .section = SECTION_PRE_DATA,
3139 .createStmt = loOutQry->data));
3141 PQclear(lo_res);
3143 destroyPQExpBuffer(loFrozenQry);
3144 destroyPQExpBuffer(loOutQry);
3147 PQclear(res);
3149 free(qdatname);
3150 destroyPQExpBuffer(dbQry);
3151 destroyPQExpBuffer(delQry);
3152 destroyPQExpBuffer(creaQry);
3153 destroyPQExpBuffer(labelq);
3157 * Collect any database-specific or role-and-database-specific SET options
3158 * for this database, and append them to outbuf.
3160 static void
3161 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
3162 const char *dbname, Oid dboid)
3164 PGconn *conn = GetConnection(AH);
3165 PQExpBuffer buf = createPQExpBuffer();
3166 PGresult *res;
3167 int count = 1;
3170 * First collect database-specific options. Pre-8.4 server versions lack
3171 * unnest(), so we do this the hard way by querying once per subscript.
3173 for (;;)
3175 if (AH->remoteVersion >= 90000)
3176 printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3177 "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3178 count, dboid);
3179 else
3180 printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3182 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3184 if (PQntuples(res) == 1 &&
3185 !PQgetisnull(res, 0, 0))
3187 makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3188 "DATABASE", dbname, NULL, NULL,
3189 outbuf);
3190 PQclear(res);
3191 count++;
3193 else
3195 PQclear(res);
3196 break;
3200 /* Now look for role-and-database-specific options */
3201 if (AH->remoteVersion >= 90000)
3203 /* Here we can assume we have unnest() */
3204 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3205 "FROM pg_db_role_setting s, pg_roles r "
3206 "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3207 dboid);
3209 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3211 if (PQntuples(res) > 0)
3213 int i;
3215 for (i = 0; i < PQntuples(res); i++)
3216 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3217 "ROLE", PQgetvalue(res, i, 0),
3218 "DATABASE", dbname,
3219 outbuf);
3222 PQclear(res);
3225 destroyPQExpBuffer(buf);
3229 * dumpEncoding: put the correct encoding into the archive
3231 static void
3232 dumpEncoding(Archive *AH)
3234 const char *encname = pg_encoding_to_char(AH->encoding);
3235 PQExpBuffer qry = createPQExpBuffer();
3237 pg_log_info("saving encoding = %s", encname);
3239 appendPQExpBufferStr(qry, "SET client_encoding = ");
3240 appendStringLiteralAH(qry, encname, AH);
3241 appendPQExpBufferStr(qry, ";\n");
3243 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3244 ARCHIVE_OPTS(.tag = "ENCODING",
3245 .description = "ENCODING",
3246 .section = SECTION_PRE_DATA,
3247 .createStmt = qry->data));
3249 destroyPQExpBuffer(qry);
3254 * dumpStdStrings: put the correct escape string behavior into the archive
3256 static void
3257 dumpStdStrings(Archive *AH)
3259 const char *stdstrings = AH->std_strings ? "on" : "off";
3260 PQExpBuffer qry = createPQExpBuffer();
3262 pg_log_info("saving standard_conforming_strings = %s",
3263 stdstrings);
3265 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3266 stdstrings);
3268 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3269 ARCHIVE_OPTS(.tag = "STDSTRINGS",
3270 .description = "STDSTRINGS",
3271 .section = SECTION_PRE_DATA,
3272 .createStmt = qry->data));
3274 destroyPQExpBuffer(qry);
3278 * dumpSearchPath: record the active search_path in the archive
3280 static void
3281 dumpSearchPath(Archive *AH)
3283 PQExpBuffer qry = createPQExpBuffer();
3284 PQExpBuffer path = createPQExpBuffer();
3285 PGresult *res;
3286 char **schemanames = NULL;
3287 int nschemanames = 0;
3288 int i;
3291 * We use the result of current_schemas(), not the search_path GUC,
3292 * because that might contain wildcards such as "$user", which won't
3293 * necessarily have the same value during restore. Also, this way avoids
3294 * listing schemas that may appear in search_path but not actually exist,
3295 * which seems like a prudent exclusion.
3297 res = ExecuteSqlQueryForSingleRow(AH,
3298 "SELECT pg_catalog.current_schemas(false)");
3300 if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3301 fatal("could not parse result of current_schemas()");
3304 * We use set_config(), not a simple "SET search_path" command, because
3305 * the latter has less-clean behavior if the search path is empty. While
3306 * that's likely to get fixed at some point, it seems like a good idea to
3307 * be as backwards-compatible as possible in what we put into archives.
3309 for (i = 0; i < nschemanames; i++)
3311 if (i > 0)
3312 appendPQExpBufferStr(path, ", ");
3313 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3316 appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3317 appendStringLiteralAH(qry, path->data, AH);
3318 appendPQExpBufferStr(qry, ", false);\n");
3320 pg_log_info("saving search_path = %s", path->data);
3322 ArchiveEntry(AH, nilCatalogId, createDumpId(),
3323 ARCHIVE_OPTS(.tag = "SEARCHPATH",
3324 .description = "SEARCHPATH",
3325 .section = SECTION_PRE_DATA,
3326 .createStmt = qry->data));
3328 /* Also save it in AH->searchpath, in case we're doing plain text dump */
3329 AH->searchpath = pg_strdup(qry->data);
3331 if (schemanames)
3332 free(schemanames);
3333 PQclear(res);
3334 destroyPQExpBuffer(qry);
3335 destroyPQExpBuffer(path);
3340 * getBlobs:
3341 * Collect schema-level data about large objects
3343 static void
3344 getBlobs(Archive *fout)
3346 DumpOptions *dopt = fout->dopt;
3347 PQExpBuffer blobQry = createPQExpBuffer();
3348 BlobInfo *binfo;
3349 DumpableObject *bdata;
3350 PGresult *res;
3351 int ntups;
3352 int i;
3353 int i_oid;
3354 int i_lomowner;
3355 int i_lomacl;
3356 int i_rlomacl;
3357 int i_initlomacl;
3358 int i_initrlomacl;
3360 pg_log_info("reading large objects");
3362 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3363 if (fout->remoteVersion >= 90600)
3365 PQExpBuffer acl_subquery = createPQExpBuffer();
3366 PQExpBuffer racl_subquery = createPQExpBuffer();
3367 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3368 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3370 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3371 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3372 dopt->binary_upgrade);
3374 appendPQExpBuffer(blobQry,
3375 "SELECT l.oid, (%s l.lomowner) AS rolname, "
3376 "%s AS lomacl, "
3377 "%s AS rlomacl, "
3378 "%s AS initlomacl, "
3379 "%s AS initrlomacl "
3380 "FROM pg_largeobject_metadata l "
3381 "LEFT JOIN pg_init_privs pip ON "
3382 "(l.oid = pip.objoid "
3383 "AND pip.classoid = 'pg_largeobject'::regclass "
3384 "AND pip.objsubid = 0) ",
3385 username_subquery,
3386 acl_subquery->data,
3387 racl_subquery->data,
3388 init_acl_subquery->data,
3389 init_racl_subquery->data);
3391 destroyPQExpBuffer(acl_subquery);
3392 destroyPQExpBuffer(racl_subquery);
3393 destroyPQExpBuffer(init_acl_subquery);
3394 destroyPQExpBuffer(init_racl_subquery);
3396 else if (fout->remoteVersion >= 90000)
3397 appendPQExpBuffer(blobQry,
3398 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3399 "NULL AS rlomacl, NULL AS initlomacl, "
3400 "NULL AS initrlomacl "
3401 " FROM pg_largeobject_metadata",
3402 username_subquery);
3403 else
3404 appendPQExpBufferStr(blobQry,
3405 "SELECT DISTINCT loid AS oid, "
3406 "NULL::name AS rolname, NULL::oid AS lomacl, "
3407 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3408 "NULL::oid AS initrlomacl "
3409 " FROM pg_largeobject");
3411 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3413 i_oid = PQfnumber(res, "oid");
3414 i_lomowner = PQfnumber(res, "rolname");
3415 i_lomacl = PQfnumber(res, "lomacl");
3416 i_rlomacl = PQfnumber(res, "rlomacl");
3417 i_initlomacl = PQfnumber(res, "initlomacl");
3418 i_initrlomacl = PQfnumber(res, "initrlomacl");
3420 ntups = PQntuples(res);
3423 * Each large object has its own BLOB archive entry.
3425 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3427 for (i = 0; i < ntups; i++)
3429 binfo[i].dobj.objType = DO_BLOB;
3430 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3431 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3432 AssignDumpId(&binfo[i].dobj);
3434 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3435 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3436 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3437 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3438 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3439 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3441 if (PQgetisnull(res, i, i_lomacl) &&
3442 PQgetisnull(res, i, i_rlomacl) &&
3443 PQgetisnull(res, i, i_initlomacl) &&
3444 PQgetisnull(res, i, i_initrlomacl))
3445 binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3448 * In binary-upgrade mode for blobs, we do *not* dump out the blob
3449 * data, as it will be copied by pg_upgrade, which simply copies the
3450 * pg_largeobject table. We *do* however dump out anything but the
3451 * data, as pg_upgrade copies just pg_largeobject, but not
3452 * pg_largeobject_metadata, after the dump is restored.
3454 if (dopt->binary_upgrade)
3455 binfo[i].dobj.dump &= ~DUMP_COMPONENT_DATA;
3459 * If we have any large objects, a "BLOBS" archive entry is needed. This
3460 * is just a placeholder for sorting; it carries no data now.
3462 if (ntups > 0)
3464 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3465 bdata->objType = DO_BLOB_DATA;
3466 bdata->catId = nilCatalogId;
3467 AssignDumpId(bdata);
3468 bdata->name = pg_strdup("BLOBS");
3471 PQclear(res);
3472 destroyPQExpBuffer(blobQry);
3476 * dumpBlob
3478 * dump the definition (metadata) of the given large object
3480 static void
3481 dumpBlob(Archive *fout, BlobInfo *binfo)
3483 PQExpBuffer cquery = createPQExpBuffer();
3484 PQExpBuffer dquery = createPQExpBuffer();
3486 appendPQExpBuffer(cquery,
3487 "SELECT pg_catalog.lo_create('%s');\n",
3488 binfo->dobj.name);
3490 appendPQExpBuffer(dquery,
3491 "SELECT pg_catalog.lo_unlink('%s');\n",
3492 binfo->dobj.name);
3494 if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3495 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3496 ARCHIVE_OPTS(.tag = binfo->dobj.name,
3497 .owner = binfo->rolname,
3498 .description = "BLOB",
3499 .section = SECTION_PRE_DATA,
3500 .createStmt = cquery->data,
3501 .dropStmt = dquery->data));
3503 /* Dump comment if any */
3504 if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3505 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3506 NULL, binfo->rolname,
3507 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3509 /* Dump security label if any */
3510 if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3511 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3512 NULL, binfo->rolname,
3513 binfo->dobj.catId, 0, binfo->dobj.dumpId);
3515 /* Dump ACL if any */
3516 if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3517 dumpACL(fout, binfo->dobj.dumpId, InvalidDumpId, "LARGE OBJECT",
3518 binfo->dobj.name, NULL,
3519 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3520 binfo->initblobacl, binfo->initrblobacl);
3522 destroyPQExpBuffer(cquery);
3523 destroyPQExpBuffer(dquery);
3527 * dumpBlobs:
3528 * dump the data contents of all large objects
3530 static int
3531 dumpBlobs(Archive *fout, void *arg)
3533 const char *blobQry;
3534 const char *blobFetchQry;
3535 PGconn *conn = GetConnection(fout);
3536 PGresult *res;
3537 char buf[LOBBUFSIZE];
3538 int ntups;
3539 int i;
3540 int cnt;
3542 pg_log_info("saving large objects");
3545 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3546 * the already-in-memory dumpable objects instead...
3548 if (fout->remoteVersion >= 90000)
3549 blobQry =
3550 "DECLARE bloboid CURSOR FOR "
3551 "SELECT oid FROM pg_largeobject_metadata ORDER BY 1";
3552 else
3553 blobQry =
3554 "DECLARE bloboid CURSOR FOR "
3555 "SELECT DISTINCT loid FROM pg_largeobject ORDER BY 1";
3557 ExecuteSqlStatement(fout, blobQry);
3559 /* Command to fetch from cursor */
3560 blobFetchQry = "FETCH 1000 IN bloboid";
3564 /* Do a fetch */
3565 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3567 /* Process the tuples, if any */
3568 ntups = PQntuples(res);
3569 for (i = 0; i < ntups; i++)
3571 Oid blobOid;
3572 int loFd;
3574 blobOid = atooid(PQgetvalue(res, i, 0));
3575 /* Open the BLOB */
3576 loFd = lo_open(conn, blobOid, INV_READ);
3577 if (loFd == -1)
3578 fatal("could not open large object %u: %s",
3579 blobOid, PQerrorMessage(conn));
3581 StartBlob(fout, blobOid);
3583 /* Now read it in chunks, sending data to archive */
3586 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3587 if (cnt < 0)
3588 fatal("error reading large object %u: %s",
3589 blobOid, PQerrorMessage(conn));
3591 WriteData(fout, buf, cnt);
3592 } while (cnt > 0);
3594 lo_close(conn, loFd);
3596 EndBlob(fout, blobOid);
3599 PQclear(res);
3600 } while (ntups > 0);
3602 return 1;
3606 * getPolicies
3607 * get information about all RLS policies on dumpable tables.
3609 void
3610 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3612 PQExpBuffer query;
3613 PQExpBuffer tbloids;
3614 PGresult *res;
3615 PolicyInfo *polinfo;
3616 int i_oid;
3617 int i_tableoid;
3618 int i_polrelid;
3619 int i_polname;
3620 int i_polcmd;
3621 int i_polpermissive;
3622 int i_polroles;
3623 int i_polqual;
3624 int i_polwithcheck;
3625 int i,
3627 ntups;
3629 /* No policies before 9.5 */
3630 if (fout->remoteVersion < 90500)
3631 return;
3633 query = createPQExpBuffer();
3634 tbloids = createPQExpBuffer();
3637 * Identify tables of interest, and check which ones have RLS enabled.
3639 appendPQExpBufferChar(tbloids, '{');
3640 for (i = 0; i < numTables; i++)
3642 TableInfo *tbinfo = &tblinfo[i];
3644 /* Ignore row security on tables not to be dumped */
3645 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3646 continue;
3648 /* It can't have RLS or policies if it's not a table */
3649 if (tbinfo->relkind != RELKIND_RELATION &&
3650 tbinfo->relkind != RELKIND_PARTITIONED_TABLE)
3651 continue;
3653 /* Add it to the list of table OIDs to be probed below */
3654 if (tbloids->len > 1) /* do we have more than the '{'? */
3655 appendPQExpBufferChar(tbloids, ',');
3656 appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
3658 /* Is RLS enabled? (That's separate from whether it has policies) */
3659 if (tbinfo->rowsec)
3662 * We represent RLS being enabled on a table by creating a
3663 * PolicyInfo object with null polname.
3665 * Note: use tableoid 0 so that this object won't be mistaken for
3666 * something that pg_depend entries apply to.
3668 polinfo = pg_malloc(sizeof(PolicyInfo));
3669 polinfo->dobj.objType = DO_POLICY;
3670 polinfo->dobj.catId.tableoid = 0;
3671 polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3672 AssignDumpId(&polinfo->dobj);
3673 polinfo->dobj.namespace = tbinfo->dobj.namespace;
3674 polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3675 polinfo->poltable = tbinfo;
3676 polinfo->polname = NULL;
3677 polinfo->polcmd = '\0';
3678 polinfo->polpermissive = 0;
3679 polinfo->polroles = NULL;
3680 polinfo->polqual = NULL;
3681 polinfo->polwithcheck = NULL;
3684 appendPQExpBufferChar(tbloids, '}');
3687 * Now, read all RLS policies belonging to the tables of interest, and
3688 * create PolicyInfo objects for them. (Note that we must filter the
3689 * results server-side not locally, because we dare not apply pg_get_expr
3690 * to tables we don't have lock on.)
3692 pg_log_info("reading row-level security policies");
3694 printfPQExpBuffer(query,
3695 "SELECT pol.oid, pol.tableoid, pol.polrelid, pol.polname, pol.polcmd, ");
3696 if (fout->remoteVersion >= 100000)
3697 appendPQExpBuffer(query, "pol.polpermissive, ");
3698 else
3699 appendPQExpBuffer(query, "'t' as polpermissive, ");
3700 appendPQExpBuffer(query,
3701 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3702 " 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, "
3703 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3704 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3705 "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
3706 "JOIN pg_catalog.pg_policy pol ON (src.tbloid = pol.polrelid)",
3707 tbloids->data);
3709 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3711 ntups = PQntuples(res);
3712 if (ntups > 0)
3714 i_oid = PQfnumber(res, "oid");
3715 i_tableoid = PQfnumber(res, "tableoid");
3716 i_polrelid = PQfnumber(res, "polrelid");
3717 i_polname = PQfnumber(res, "polname");
3718 i_polcmd = PQfnumber(res, "polcmd");
3719 i_polpermissive = PQfnumber(res, "polpermissive");
3720 i_polroles = PQfnumber(res, "polroles");
3721 i_polqual = PQfnumber(res, "polqual");
3722 i_polwithcheck = PQfnumber(res, "polwithcheck");
3724 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3726 for (j = 0; j < ntups; j++)
3728 Oid polrelid = atooid(PQgetvalue(res, j, i_polrelid));
3729 TableInfo *tbinfo = findTableByOid(polrelid);
3731 polinfo[j].dobj.objType = DO_POLICY;
3732 polinfo[j].dobj.catId.tableoid =
3733 atooid(PQgetvalue(res, j, i_tableoid));
3734 polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3735 AssignDumpId(&polinfo[j].dobj);
3736 polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3737 polinfo[j].poltable = tbinfo;
3738 polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3739 polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3741 polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3742 polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3744 if (PQgetisnull(res, j, i_polroles))
3745 polinfo[j].polroles = NULL;
3746 else
3747 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3749 if (PQgetisnull(res, j, i_polqual))
3750 polinfo[j].polqual = NULL;
3751 else
3752 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3754 if (PQgetisnull(res, j, i_polwithcheck))
3755 polinfo[j].polwithcheck = NULL;
3756 else
3757 polinfo[j].polwithcheck
3758 = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3762 PQclear(res);
3764 destroyPQExpBuffer(query);
3765 destroyPQExpBuffer(tbloids);
3769 * dumpPolicy
3770 * dump the definition of the given policy
3772 static void
3773 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3775 DumpOptions *dopt = fout->dopt;
3776 TableInfo *tbinfo = polinfo->poltable;
3777 PQExpBuffer query;
3778 PQExpBuffer delqry;
3779 PQExpBuffer polprefix;
3780 char *qtabname;
3781 const char *cmd;
3782 char *tag;
3784 if (dopt->dataOnly)
3785 return;
3788 * If polname is NULL, then this record is just indicating that ROW LEVEL
3789 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3790 * ROW LEVEL SECURITY.
3792 if (polinfo->polname == NULL)
3794 query = createPQExpBuffer();
3796 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3797 fmtQualifiedDumpable(tbinfo));
3800 * We must emit the ROW SECURITY object's dependency on its table
3801 * explicitly, because it will not match anything in pg_depend (unlike
3802 * the case for other PolicyInfo objects).
3804 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3805 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3806 ARCHIVE_OPTS(.tag = polinfo->dobj.name,
3807 .namespace = polinfo->dobj.namespace->dobj.name,
3808 .owner = tbinfo->rolname,
3809 .description = "ROW SECURITY",
3810 .section = SECTION_POST_DATA,
3811 .createStmt = query->data,
3812 .deps = &(tbinfo->dobj.dumpId),
3813 .nDeps = 1));
3815 destroyPQExpBuffer(query);
3816 return;
3819 if (polinfo->polcmd == '*')
3820 cmd = "";
3821 else if (polinfo->polcmd == 'r')
3822 cmd = " FOR SELECT";
3823 else if (polinfo->polcmd == 'a')
3824 cmd = " FOR INSERT";
3825 else if (polinfo->polcmd == 'w')
3826 cmd = " FOR UPDATE";
3827 else if (polinfo->polcmd == 'd')
3828 cmd = " FOR DELETE";
3829 else
3831 pg_log_error("unexpected policy command type: %c",
3832 polinfo->polcmd);
3833 exit_nicely(1);
3836 query = createPQExpBuffer();
3837 delqry = createPQExpBuffer();
3838 polprefix = createPQExpBuffer();
3840 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
3842 appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3844 appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3845 !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3847 if (polinfo->polroles != NULL)
3848 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3850 if (polinfo->polqual != NULL)
3851 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3853 if (polinfo->polwithcheck != NULL)
3854 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3856 appendPQExpBuffer(query, ";\n");
3858 appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3859 appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3861 appendPQExpBuffer(polprefix, "POLICY %s ON",
3862 fmtId(polinfo->polname));
3864 tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3866 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3867 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3868 ARCHIVE_OPTS(.tag = tag,
3869 .namespace = polinfo->dobj.namespace->dobj.name,
3870 .owner = tbinfo->rolname,
3871 .description = "POLICY",
3872 .section = SECTION_POST_DATA,
3873 .createStmt = query->data,
3874 .dropStmt = delqry->data));
3876 if (polinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3877 dumpComment(fout, polprefix->data, qtabname,
3878 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
3879 polinfo->dobj.catId, 0, polinfo->dobj.dumpId);
3881 free(tag);
3882 destroyPQExpBuffer(query);
3883 destroyPQExpBuffer(delqry);
3884 destroyPQExpBuffer(polprefix);
3885 free(qtabname);
3889 * getPublications
3890 * get information about publications
3892 PublicationInfo *
3893 getPublications(Archive *fout, int *numPublications)
3895 DumpOptions *dopt = fout->dopt;
3896 PQExpBuffer query;
3897 PGresult *res;
3898 PublicationInfo *pubinfo;
3899 int i_tableoid;
3900 int i_oid;
3901 int i_pubname;
3902 int i_rolname;
3903 int i_puballtables;
3904 int i_pubinsert;
3905 int i_pubupdate;
3906 int i_pubdelete;
3907 int i_pubtruncate;
3908 int i,
3909 ntups;
3911 if (dopt->no_publications || fout->remoteVersion < 100000)
3913 *numPublications = 0;
3914 return NULL;
3917 query = createPQExpBuffer();
3919 resetPQExpBuffer(query);
3921 /* Get the publications. */
3922 if (fout->remoteVersion >= 110000)
3923 appendPQExpBuffer(query,
3924 "SELECT p.tableoid, p.oid, p.pubname, "
3925 "(%s p.pubowner) AS rolname, "
3926 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3927 "FROM pg_publication p",
3928 username_subquery);
3929 else
3930 appendPQExpBuffer(query,
3931 "SELECT p.tableoid, p.oid, p.pubname, "
3932 "(%s p.pubowner) AS rolname, "
3933 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3934 "FROM pg_publication p",
3935 username_subquery);
3937 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3939 ntups = PQntuples(res);
3941 i_tableoid = PQfnumber(res, "tableoid");
3942 i_oid = PQfnumber(res, "oid");
3943 i_pubname = PQfnumber(res, "pubname");
3944 i_rolname = PQfnumber(res, "rolname");
3945 i_puballtables = PQfnumber(res, "puballtables");
3946 i_pubinsert = PQfnumber(res, "pubinsert");
3947 i_pubupdate = PQfnumber(res, "pubupdate");
3948 i_pubdelete = PQfnumber(res, "pubdelete");
3949 i_pubtruncate = PQfnumber(res, "pubtruncate");
3951 pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3953 for (i = 0; i < ntups; i++)
3955 pubinfo[i].dobj.objType = DO_PUBLICATION;
3956 pubinfo[i].dobj.catId.tableoid =
3957 atooid(PQgetvalue(res, i, i_tableoid));
3958 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3959 AssignDumpId(&pubinfo[i].dobj);
3960 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3961 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3962 pubinfo[i].puballtables =
3963 (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3964 pubinfo[i].pubinsert =
3965 (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3966 pubinfo[i].pubupdate =
3967 (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3968 pubinfo[i].pubdelete =
3969 (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3970 pubinfo[i].pubtruncate =
3971 (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
3973 if (strlen(pubinfo[i].rolname) == 0)
3974 pg_log_warning("owner of publication \"%s\" appears to be invalid",
3975 pubinfo[i].dobj.name);
3977 /* Decide whether we want to dump it */
3978 selectDumpableObject(&(pubinfo[i].dobj), fout);
3980 PQclear(res);
3982 destroyPQExpBuffer(query);
3984 *numPublications = ntups;
3985 return pubinfo;
3989 * dumpPublication
3990 * dump the definition of the given publication
3992 static void
3993 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3995 PQExpBuffer delq;
3996 PQExpBuffer query;
3997 char *qpubname;
3998 bool first = true;
4000 if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4001 return;
4003 delq = createPQExpBuffer();
4004 query = createPQExpBuffer();
4006 qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
4008 appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
4009 qpubname);
4011 appendPQExpBuffer(query, "CREATE PUBLICATION %s",
4012 qpubname);
4014 if (pubinfo->puballtables)
4015 appendPQExpBufferStr(query, " FOR ALL TABLES");
4017 appendPQExpBufferStr(query, " WITH (publish = '");
4018 if (pubinfo->pubinsert)
4020 appendPQExpBufferStr(query, "insert");
4021 first = false;
4024 if (pubinfo->pubupdate)
4026 if (!first)
4027 appendPQExpBufferStr(query, ", ");
4029 appendPQExpBufferStr(query, "update");
4030 first = false;
4033 if (pubinfo->pubdelete)
4035 if (!first)
4036 appendPQExpBufferStr(query, ", ");
4038 appendPQExpBufferStr(query, "delete");
4039 first = false;
4042 if (pubinfo->pubtruncate)
4044 if (!first)
4045 appendPQExpBufferStr(query, ", ");
4047 appendPQExpBufferStr(query, "truncate");
4048 first = false;
4051 appendPQExpBufferStr(query, "');\n");
4053 ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
4054 ARCHIVE_OPTS(.tag = pubinfo->dobj.name,
4055 .owner = pubinfo->rolname,
4056 .description = "PUBLICATION",
4057 .section = SECTION_POST_DATA,
4058 .createStmt = query->data,
4059 .dropStmt = delq->data));
4061 if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4062 dumpComment(fout, "PUBLICATION", qpubname,
4063 NULL, pubinfo->rolname,
4064 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
4066 if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4067 dumpSecLabel(fout, "PUBLICATION", qpubname,
4068 NULL, pubinfo->rolname,
4069 pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
4071 destroyPQExpBuffer(delq);
4072 destroyPQExpBuffer(query);
4073 free(qpubname);
4077 * getPublicationTables
4078 * get information about publication membership for dumpable tables.
4080 void
4081 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
4083 PQExpBuffer query;
4084 PGresult *res;
4085 PublicationRelInfo *pubrinfo;
4086 DumpOptions *dopt = fout->dopt;
4087 int i_tableoid;
4088 int i_oid;
4089 int i_prpubid;
4090 int i_prrelid;
4091 int i,
4093 ntups;
4095 if (dopt->no_publications || fout->remoteVersion < 100000)
4096 return;
4098 query = createPQExpBuffer();
4100 /* Collect all publication membership info. */
4101 appendPQExpBufferStr(query,
4102 "SELECT tableoid, oid, prpubid, prrelid "
4103 "FROM pg_catalog.pg_publication_rel");
4104 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4106 ntups = PQntuples(res);
4108 i_tableoid = PQfnumber(res, "tableoid");
4109 i_oid = PQfnumber(res, "oid");
4110 i_prpubid = PQfnumber(res, "prpubid");
4111 i_prrelid = PQfnumber(res, "prrelid");
4113 /* this allocation may be more than we need */
4114 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
4115 j = 0;
4117 for (i = 0; i < ntups; i++)
4119 Oid prpubid = atooid(PQgetvalue(res, i, i_prpubid));
4120 Oid prrelid = atooid(PQgetvalue(res, i, i_prrelid));
4121 PublicationInfo *pubinfo;
4122 TableInfo *tbinfo;
4125 * Ignore any entries for which we aren't interested in either the
4126 * publication or the rel.
4128 pubinfo = findPublicationByOid(prpubid);
4129 if (pubinfo == NULL)
4130 continue;
4131 tbinfo = findTableByOid(prrelid);
4132 if (tbinfo == NULL)
4133 continue;
4136 * Ignore publication membership of tables whose definitions are not
4137 * to be dumped.
4139 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4140 continue;
4142 /* OK, make a DumpableObject for this relationship */
4143 pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
4144 pubrinfo[j].dobj.catId.tableoid =
4145 atooid(PQgetvalue(res, i, i_tableoid));
4146 pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4147 AssignDumpId(&pubrinfo[j].dobj);
4148 pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4149 pubrinfo[j].dobj.name = tbinfo->dobj.name;
4150 pubrinfo[j].publication = pubinfo;
4151 pubrinfo[j].pubtable = tbinfo;
4153 /* Decide whether we want to dump it */
4154 selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
4156 j++;
4159 PQclear(res);
4160 destroyPQExpBuffer(query);
4164 * dumpPublicationTable
4165 * dump the definition of the given publication table mapping
4167 static void
4168 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
4170 PublicationInfo *pubinfo = pubrinfo->publication;
4171 TableInfo *tbinfo = pubrinfo->pubtable;
4172 PQExpBuffer query;
4173 char *tag;
4175 if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4176 return;
4178 tag = psprintf("%s %s", pubinfo->dobj.name, tbinfo->dobj.name);
4180 query = createPQExpBuffer();
4182 appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
4183 fmtId(pubinfo->dobj.name));
4184 appendPQExpBuffer(query, " %s;\n",
4185 fmtQualifiedDumpable(tbinfo));
4188 * There is no point in creating a drop query as the drop is done by table
4189 * drop. (If you think to change this, see also _printTocEntry().)
4190 * Although this object doesn't really have ownership as such, set the
4191 * owner field anyway to ensure that the command is run by the correct
4192 * role at restore time.
4194 ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4195 ARCHIVE_OPTS(.tag = tag,
4196 .namespace = tbinfo->dobj.namespace->dobj.name,
4197 .owner = pubinfo->rolname,
4198 .description = "PUBLICATION TABLE",
4199 .section = SECTION_POST_DATA,
4200 .createStmt = query->data));
4202 free(tag);
4203 destroyPQExpBuffer(query);
4207 * Is the currently connected user a superuser?
4209 static bool
4210 is_superuser(Archive *fout)
4212 ArchiveHandle *AH = (ArchiveHandle *) fout;
4213 const char *val;
4215 val = PQparameterStatus(AH->connection, "is_superuser");
4217 if (val && strcmp(val, "on") == 0)
4218 return true;
4220 return false;
4224 * getSubscriptions
4225 * get information about subscriptions
4227 void
4228 getSubscriptions(Archive *fout)
4230 DumpOptions *dopt = fout->dopt;
4231 PQExpBuffer query;
4232 PGresult *res;
4233 SubscriptionInfo *subinfo;
4234 int i_tableoid;
4235 int i_oid;
4236 int i_subname;
4237 int i_rolname;
4238 int i_subconninfo;
4239 int i_subslotname;
4240 int i_subsynccommit;
4241 int i_subpublications;
4242 int i,
4243 ntups;
4245 if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4246 return;
4248 if (!is_superuser(fout))
4250 int n;
4252 res = ExecuteSqlQuery(fout,
4253 "SELECT count(*) FROM pg_subscription "
4254 "WHERE subdbid = (SELECT oid FROM pg_database"
4255 " WHERE datname = current_database())",
4256 PGRES_TUPLES_OK);
4257 n = atoi(PQgetvalue(res, 0, 0));
4258 if (n > 0)
4259 pg_log_warning("subscriptions not dumped because current user is not a superuser");
4260 PQclear(res);
4261 return;
4264 query = createPQExpBuffer();
4266 resetPQExpBuffer(query);
4268 /* Get the subscriptions in current database. */
4269 appendPQExpBuffer(query,
4270 "SELECT s.tableoid, s.oid, s.subname,"
4271 "(%s s.subowner) AS rolname, "
4272 " s.subconninfo, s.subslotname, s.subsynccommit, "
4273 " s.subpublications "
4274 "FROM pg_subscription s "
4275 "WHERE s.subdbid = (SELECT oid FROM pg_database"
4276 " WHERE datname = current_database())",
4277 username_subquery);
4278 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4280 ntups = PQntuples(res);
4282 i_tableoid = PQfnumber(res, "tableoid");
4283 i_oid = PQfnumber(res, "oid");
4284 i_subname = PQfnumber(res, "subname");
4285 i_rolname = PQfnumber(res, "rolname");
4286 i_subconninfo = PQfnumber(res, "subconninfo");
4287 i_subslotname = PQfnumber(res, "subslotname");
4288 i_subsynccommit = PQfnumber(res, "subsynccommit");
4289 i_subpublications = PQfnumber(res, "subpublications");
4291 subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4293 for (i = 0; i < ntups; i++)
4295 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4296 subinfo[i].dobj.catId.tableoid =
4297 atooid(PQgetvalue(res, i, i_tableoid));
4298 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4299 AssignDumpId(&subinfo[i].dobj);
4300 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4301 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4302 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4303 if (PQgetisnull(res, i, i_subslotname))
4304 subinfo[i].subslotname = NULL;
4305 else
4306 subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4307 subinfo[i].subsynccommit =
4308 pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4309 subinfo[i].subpublications =
4310 pg_strdup(PQgetvalue(res, i, i_subpublications));
4312 if (strlen(subinfo[i].rolname) == 0)
4313 pg_log_warning("owner of subscription \"%s\" appears to be invalid",
4314 subinfo[i].dobj.name);
4316 /* Decide whether we want to dump it */
4317 selectDumpableObject(&(subinfo[i].dobj), fout);
4319 PQclear(res);
4321 destroyPQExpBuffer(query);
4325 * dumpSubscription
4326 * dump the definition of the given subscription
4328 static void
4329 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4331 PQExpBuffer delq;
4332 PQExpBuffer query;
4333 PQExpBuffer publications;
4334 char *qsubname;
4335 char **pubnames = NULL;
4336 int npubnames = 0;
4337 int i;
4339 if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4340 return;
4342 delq = createPQExpBuffer();
4343 query = createPQExpBuffer();
4345 qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4347 appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4348 qsubname);
4350 appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4351 qsubname);
4352 appendStringLiteralAH(query, subinfo->subconninfo, fout);
4354 /* Build list of quoted publications and append them to query. */
4355 if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4357 pg_log_warning("could not parse subpublications array");
4358 if (pubnames)
4359 free(pubnames);
4360 pubnames = NULL;
4361 npubnames = 0;
4364 publications = createPQExpBuffer();
4365 for (i = 0; i < npubnames; i++)
4367 if (i > 0)
4368 appendPQExpBufferStr(publications, ", ");
4370 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4373 appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4374 if (subinfo->subslotname)
4375 appendStringLiteralAH(query, subinfo->subslotname, fout);
4376 else
4377 appendPQExpBufferStr(query, "NONE");
4379 if (strcmp(subinfo->subsynccommit, "off") != 0)
4380 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4382 appendPQExpBufferStr(query, ");\n");
4384 ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4385 ARCHIVE_OPTS(.tag = subinfo->dobj.name,
4386 .owner = subinfo->rolname,
4387 .description = "SUBSCRIPTION",
4388 .section = SECTION_POST_DATA,
4389 .createStmt = query->data,
4390 .dropStmt = delq->data));
4392 if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4393 dumpComment(fout, "SUBSCRIPTION", qsubname,
4394 NULL, subinfo->rolname,
4395 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4397 if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4398 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4399 NULL, subinfo->rolname,
4400 subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4402 destroyPQExpBuffer(publications);
4403 if (pubnames)
4404 free(pubnames);
4406 destroyPQExpBuffer(delq);
4407 destroyPQExpBuffer(query);
4408 free(qsubname);
4412 * Given a "create query", append as many ALTER ... DEPENDS ON EXTENSION as
4413 * the object needs.
4415 static void
4416 append_depends_on_extension(Archive *fout,
4417 PQExpBuffer create,
4418 DumpableObject *dobj,
4419 const char *catalog,
4420 const char *keyword,
4421 const char *objname)
4423 if (dobj->depends_on_ext)
4425 char *nm;
4426 PGresult *res;
4427 PQExpBuffer query;
4428 int ntups;
4429 int i_extname;
4430 int i;
4432 /* dodge fmtId() non-reentrancy */
4433 nm = pg_strdup(objname);
4435 query = createPQExpBuffer();
4436 appendPQExpBuffer(query,
4437 "SELECT e.extname "
4438 "FROM pg_catalog.pg_depend d, pg_catalog.pg_extension e "
4439 "WHERE d.refobjid = e.oid AND classid = '%s'::pg_catalog.regclass "
4440 "AND objid = '%u'::pg_catalog.oid AND deptype = 'x' "
4441 "AND refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass",
4442 catalog,
4443 dobj->catId.oid);
4444 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4445 ntups = PQntuples(res);
4446 i_extname = PQfnumber(res, "extname");
4447 for (i = 0; i < ntups; i++)
4449 appendPQExpBuffer(create, "ALTER %s %s DEPENDS ON EXTENSION %s;\n",
4450 keyword, nm,
4451 fmtId(PQgetvalue(res, i, i_extname)));
4454 PQclear(res);
4455 destroyPQExpBuffer(query);
4456 pg_free(nm);
4461 static void
4462 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4463 PQExpBuffer upgrade_buffer,
4464 Oid pg_type_oid,
4465 bool force_array_type)
4467 PQExpBuffer upgrade_query = createPQExpBuffer();
4468 PGresult *res;
4469 Oid pg_type_array_oid;
4471 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4472 appendPQExpBuffer(upgrade_buffer,
4473 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4474 pg_type_oid);
4476 /* we only support old >= 8.3 for binary upgrades */
4477 appendPQExpBuffer(upgrade_query,
4478 "SELECT typarray "
4479 "FROM pg_catalog.pg_type "
4480 "WHERE oid = '%u'::pg_catalog.oid;",
4481 pg_type_oid);
4483 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4485 pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4487 PQclear(res);
4489 if (!OidIsValid(pg_type_array_oid) && force_array_type)
4492 * If the old version didn't assign an array type, but the new version
4493 * does, we must select an unused type OID to assign. This currently
4494 * only happens for domains, when upgrading pre-v11 to v11 and up.
4496 * Note: local state here is kind of ugly, but we must have some,
4497 * since we mustn't choose the same unused OID more than once.
4499 static Oid next_possible_free_oid = FirstNormalObjectId;
4500 bool is_dup;
4504 ++next_possible_free_oid;
4505 printfPQExpBuffer(upgrade_query,
4506 "SELECT EXISTS(SELECT 1 "
4507 "FROM pg_catalog.pg_type "
4508 "WHERE oid = '%u'::pg_catalog.oid);",
4509 next_possible_free_oid);
4510 res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4511 is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4512 PQclear(res);
4513 } while (is_dup);
4515 pg_type_array_oid = next_possible_free_oid;
4518 if (OidIsValid(pg_type_array_oid))
4520 appendPQExpBufferStr(upgrade_buffer,
4521 "\n-- For binary upgrade, must preserve pg_type array oid\n");
4522 appendPQExpBuffer(upgrade_buffer,
4523 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4524 pg_type_array_oid);
4527 destroyPQExpBuffer(upgrade_query);
4530 static bool
4531 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4532 PQExpBuffer upgrade_buffer,
4533 Oid pg_rel_oid)
4535 PQExpBuffer upgrade_query = createPQExpBuffer();
4536 PGresult *upgrade_res;
4537 Oid pg_type_oid;
4538 bool toast_set = false;
4541 * We only support old >= 8.3 for binary upgrades.
4543 * We purposefully ignore toast OIDs for partitioned tables; the reason is
4544 * that versions 10 and 11 have them, but 12 does not, so emitting them
4545 * causes the upgrade to fail.
4547 appendPQExpBuffer(upgrade_query,
4548 "SELECT c.reltype AS crel, t.reltype AS trel "
4549 "FROM pg_catalog.pg_class c "
4550 "LEFT JOIN pg_catalog.pg_class t ON "
4551 " (c.reltoastrelid = t.oid AND c.relkind <> '%c') "
4552 "WHERE c.oid = '%u'::pg_catalog.oid;",
4553 RELKIND_PARTITIONED_TABLE, pg_rel_oid);
4555 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4557 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4559 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4560 pg_type_oid, false);
4562 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4564 /* Toast tables do not have pg_type array rows */
4565 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4566 PQfnumber(upgrade_res, "trel")));
4568 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4569 appendPQExpBuffer(upgrade_buffer,
4570 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4571 pg_type_toast_oid);
4573 toast_set = true;
4576 PQclear(upgrade_res);
4577 destroyPQExpBuffer(upgrade_query);
4579 return toast_set;
4582 static void
4583 binary_upgrade_set_pg_class_oids(Archive *fout,
4584 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4585 bool is_index)
4587 PQExpBuffer upgrade_query = createPQExpBuffer();
4588 PGresult *upgrade_res;
4589 Oid pg_class_reltoastrelid;
4590 Oid pg_index_indexrelid;
4592 appendPQExpBuffer(upgrade_query,
4593 "SELECT c.reltoastrelid, i.indexrelid "
4594 "FROM pg_catalog.pg_class c LEFT JOIN "
4595 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4596 "WHERE c.oid = '%u'::pg_catalog.oid;",
4597 pg_class_oid);
4599 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4601 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4602 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4604 appendPQExpBufferStr(upgrade_buffer,
4605 "\n-- For binary upgrade, must preserve pg_class oids\n");
4607 if (!is_index)
4609 appendPQExpBuffer(upgrade_buffer,
4610 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4611 pg_class_oid);
4612 /* only tables have toast tables, not indexes */
4613 if (OidIsValid(pg_class_reltoastrelid))
4616 * One complexity is that the table definition might not require
4617 * the creation of a TOAST table, and the TOAST table might have
4618 * been created long after table creation, when the table was
4619 * loaded with wide data. By setting the TOAST oid we force
4620 * creation of the TOAST heap and TOAST index by the backend so we
4621 * can cleanly copy the files during binary upgrade.
4624 appendPQExpBuffer(upgrade_buffer,
4625 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4626 pg_class_reltoastrelid);
4628 /* every toast table has an index */
4629 appendPQExpBuffer(upgrade_buffer,
4630 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4631 pg_index_indexrelid);
4634 else
4635 appendPQExpBuffer(upgrade_buffer,
4636 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4637 pg_class_oid);
4639 appendPQExpBufferChar(upgrade_buffer, '\n');
4641 PQclear(upgrade_res);
4642 destroyPQExpBuffer(upgrade_query);
4646 * If the DumpableObject is a member of an extension, add a suitable
4647 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4649 * For somewhat historical reasons, objname should already be quoted,
4650 * but not objnamespace (if any).
4652 static void
4653 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4654 DumpableObject *dobj,
4655 const char *objtype,
4656 const char *objname,
4657 const char *objnamespace)
4659 DumpableObject *extobj = NULL;
4660 int i;
4662 if (!dobj->ext_member)
4663 return;
4666 * Find the parent extension. We could avoid this search if we wanted to
4667 * add a link field to DumpableObject, but the space costs of that would
4668 * be considerable. We assume that member objects could only have a
4669 * direct dependency on their own extension, not any others.
4671 for (i = 0; i < dobj->nDeps; i++)
4673 extobj = findObjectByDumpId(dobj->dependencies[i]);
4674 if (extobj && extobj->objType == DO_EXTENSION)
4675 break;
4676 extobj = NULL;
4678 if (extobj == NULL)
4679 fatal("could not find parent extension for %s %s",
4680 objtype, objname);
4682 appendPQExpBufferStr(upgrade_buffer,
4683 "\n-- For binary upgrade, handle extension membership the hard way\n");
4684 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4685 fmtId(extobj->name),
4686 objtype);
4687 if (objnamespace && *objnamespace)
4688 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4689 appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4693 * getNamespaces:
4694 * read all namespaces in the system catalogs and return them in the
4695 * NamespaceInfo* structure
4697 * numNamespaces is set to the number of namespaces read in
4699 NamespaceInfo *
4700 getNamespaces(Archive *fout, int *numNamespaces)
4702 DumpOptions *dopt = fout->dopt;
4703 PGresult *res;
4704 int ntups;
4705 int i;
4706 PQExpBuffer query;
4707 NamespaceInfo *nsinfo;
4708 int i_tableoid;
4709 int i_oid;
4710 int i_nspname;
4711 int i_rolname;
4712 int i_nspacl;
4713 int i_rnspacl;
4714 int i_initnspacl;
4715 int i_initrnspacl;
4717 query = createPQExpBuffer();
4720 * we fetch all namespaces including system ones, so that every object we
4721 * read in can be linked to a containing namespace.
4723 if (fout->remoteVersion >= 90600)
4725 PQExpBuffer acl_subquery = createPQExpBuffer();
4726 PQExpBuffer racl_subquery = createPQExpBuffer();
4727 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4728 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4730 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4731 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4732 dopt->binary_upgrade);
4734 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4735 "(%s nspowner) AS rolname, "
4736 "%s as nspacl, "
4737 "%s as rnspacl, "
4738 "%s as initnspacl, "
4739 "%s as initrnspacl "
4740 "FROM pg_namespace n "
4741 "LEFT JOIN pg_init_privs pip "
4742 "ON (n.oid = pip.objoid "
4743 "AND pip.classoid = 'pg_namespace'::regclass "
4744 "AND pip.objsubid = 0",
4745 username_subquery,
4746 acl_subquery->data,
4747 racl_subquery->data,
4748 init_acl_subquery->data,
4749 init_racl_subquery->data);
4751 appendPQExpBuffer(query, ") ");
4753 destroyPQExpBuffer(acl_subquery);
4754 destroyPQExpBuffer(racl_subquery);
4755 destroyPQExpBuffer(init_acl_subquery);
4756 destroyPQExpBuffer(init_racl_subquery);
4758 else
4759 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4760 "(%s nspowner) AS rolname, "
4761 "nspacl, NULL as rnspacl, "
4762 "NULL AS initnspacl, NULL as initrnspacl "
4763 "FROM pg_namespace",
4764 username_subquery);
4766 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4768 ntups = PQntuples(res);
4770 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4772 i_tableoid = PQfnumber(res, "tableoid");
4773 i_oid = PQfnumber(res, "oid");
4774 i_nspname = PQfnumber(res, "nspname");
4775 i_rolname = PQfnumber(res, "rolname");
4776 i_nspacl = PQfnumber(res, "nspacl");
4777 i_rnspacl = PQfnumber(res, "rnspacl");
4778 i_initnspacl = PQfnumber(res, "initnspacl");
4779 i_initrnspacl = PQfnumber(res, "initrnspacl");
4781 for (i = 0; i < ntups; i++)
4783 nsinfo[i].dobj.objType = DO_NAMESPACE;
4784 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4785 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4786 AssignDumpId(&nsinfo[i].dobj);
4787 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4788 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4789 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4790 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4791 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4792 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4794 /* Decide whether to dump this namespace */
4795 selectDumpableNamespace(&nsinfo[i], fout);
4798 * Do not try to dump ACL if the ACL is empty or the default.
4800 * This is useful because, for some schemas/objects, the only
4801 * component we are going to try and dump is the ACL and if we can
4802 * remove that then 'dump' goes to zero/false and we don't consider
4803 * this object for dumping at all later on.
4805 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4806 PQgetisnull(res, i, i_initnspacl) &&
4807 PQgetisnull(res, i, i_initrnspacl))
4808 nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4810 if (strlen(nsinfo[i].rolname) == 0)
4811 pg_log_warning("owner of schema \"%s\" appears to be invalid",
4812 nsinfo[i].dobj.name);
4815 PQclear(res);
4816 destroyPQExpBuffer(query);
4818 *numNamespaces = ntups;
4820 return nsinfo;
4824 * findNamespace:
4825 * given a namespace OID, look up the info read by getNamespaces
4827 static NamespaceInfo *
4828 findNamespace(Archive *fout, Oid nsoid)
4830 NamespaceInfo *nsinfo;
4832 nsinfo = findNamespaceByOid(nsoid);
4833 if (nsinfo == NULL)
4834 fatal("schema with OID %u does not exist", nsoid);
4835 return nsinfo;
4839 * getExtensions:
4840 * read all extensions in the system catalogs and return them in the
4841 * ExtensionInfo* structure
4843 * numExtensions is set to the number of extensions read in
4845 ExtensionInfo *
4846 getExtensions(Archive *fout, int *numExtensions)
4848 DumpOptions *dopt = fout->dopt;
4849 PGresult *res;
4850 int ntups;
4851 int i;
4852 PQExpBuffer query;
4853 ExtensionInfo *extinfo;
4854 int i_tableoid;
4855 int i_oid;
4856 int i_extname;
4857 int i_nspname;
4858 int i_extrelocatable;
4859 int i_extversion;
4860 int i_extconfig;
4861 int i_extcondition;
4864 * Before 9.1, there are no extensions.
4866 if (fout->remoteVersion < 90100)
4868 *numExtensions = 0;
4869 return NULL;
4872 query = createPQExpBuffer();
4874 appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4875 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4876 "FROM pg_extension x "
4877 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4879 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4881 ntups = PQntuples(res);
4883 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4885 i_tableoid = PQfnumber(res, "tableoid");
4886 i_oid = PQfnumber(res, "oid");
4887 i_extname = PQfnumber(res, "extname");
4888 i_nspname = PQfnumber(res, "nspname");
4889 i_extrelocatable = PQfnumber(res, "extrelocatable");
4890 i_extversion = PQfnumber(res, "extversion");
4891 i_extconfig = PQfnumber(res, "extconfig");
4892 i_extcondition = PQfnumber(res, "extcondition");
4894 for (i = 0; i < ntups; i++)
4896 extinfo[i].dobj.objType = DO_EXTENSION;
4897 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4898 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4899 AssignDumpId(&extinfo[i].dobj);
4900 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4901 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4902 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4903 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4904 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4905 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4907 /* Decide whether we want to dump it */
4908 selectDumpableExtension(&(extinfo[i]), dopt);
4911 PQclear(res);
4912 destroyPQExpBuffer(query);
4914 *numExtensions = ntups;
4916 return extinfo;
4920 * getTypes:
4921 * read all types in the system catalogs and return them in the
4922 * TypeInfo* structure
4924 * numTypes is set to the number of types read in
4926 * NB: this must run after getFuncs() because we assume we can do
4927 * findFuncByOid().
4929 TypeInfo *
4930 getTypes(Archive *fout, int *numTypes)
4932 DumpOptions *dopt = fout->dopt;
4933 PGresult *res;
4934 int ntups;
4935 int i;
4936 PQExpBuffer query = createPQExpBuffer();
4937 TypeInfo *tyinfo;
4938 ShellTypeInfo *stinfo;
4939 int i_tableoid;
4940 int i_oid;
4941 int i_typname;
4942 int i_typnamespace;
4943 int i_typacl;
4944 int i_rtypacl;
4945 int i_inittypacl;
4946 int i_initrtypacl;
4947 int i_rolname;
4948 int i_typelem;
4949 int i_typrelid;
4950 int i_typrelkind;
4951 int i_typtype;
4952 int i_typisdefined;
4953 int i_isarray;
4956 * we include even the built-in types because those may be used as array
4957 * elements by user-defined types
4959 * we filter out the built-in types when we dump out the types
4961 * same approach for undefined (shell) types and array types
4963 * Note: as of 8.3 we can reliably detect whether a type is an
4964 * auto-generated array type by checking the element type's typarray.
4965 * (Before that the test is capable of generating false positives.) We
4966 * still check for name beginning with '_', though, so as to avoid the
4967 * cost of the subselect probe for all standard types. This would have to
4968 * be revisited if the backend ever allows renaming of array types.
4971 if (fout->remoteVersion >= 90600)
4973 PQExpBuffer acl_subquery = createPQExpBuffer();
4974 PQExpBuffer racl_subquery = createPQExpBuffer();
4975 PQExpBuffer initacl_subquery = createPQExpBuffer();
4976 PQExpBuffer initracl_subquery = createPQExpBuffer();
4978 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4979 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4980 dopt->binary_upgrade);
4982 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4983 "t.typnamespace, "
4984 "%s AS typacl, "
4985 "%s AS rtypacl, "
4986 "%s AS inittypacl, "
4987 "%s AS initrtypacl, "
4988 "(%s t.typowner) AS rolname, "
4989 "t.typelem, t.typrelid, "
4990 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4991 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4992 "t.typtype, t.typisdefined, "
4993 "t.typname[0] = '_' AND t.typelem != 0 AND "
4994 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4995 "FROM pg_type t "
4996 "LEFT JOIN pg_init_privs pip ON "
4997 "(t.oid = pip.objoid "
4998 "AND pip.classoid = 'pg_type'::regclass "
4999 "AND pip.objsubid = 0) ",
5000 acl_subquery->data,
5001 racl_subquery->data,
5002 initacl_subquery->data,
5003 initracl_subquery->data,
5004 username_subquery);
5006 destroyPQExpBuffer(acl_subquery);
5007 destroyPQExpBuffer(racl_subquery);
5008 destroyPQExpBuffer(initacl_subquery);
5009 destroyPQExpBuffer(initracl_subquery);
5011 else if (fout->remoteVersion >= 90200)
5013 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
5014 "typnamespace, typacl, NULL as rtypacl, "
5015 "NULL AS inittypacl, NULL AS initrtypacl, "
5016 "(%s typowner) AS rolname, "
5017 "typelem, typrelid, "
5018 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5019 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5020 "typtype, typisdefined, "
5021 "typname[0] = '_' AND typelem != 0 AND "
5022 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
5023 "FROM pg_type",
5024 username_subquery);
5026 else if (fout->remoteVersion >= 80300)
5028 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
5029 "typnamespace, NULL AS typacl, NULL as rtypacl, "
5030 "NULL AS inittypacl, NULL AS initrtypacl, "
5031 "(%s typowner) AS rolname, "
5032 "typelem, typrelid, "
5033 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5034 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5035 "typtype, typisdefined, "
5036 "typname[0] = '_' AND typelem != 0 AND "
5037 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
5038 "FROM pg_type",
5039 username_subquery);
5041 else
5043 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
5044 "typnamespace, NULL AS typacl, NULL as rtypacl, "
5045 "NULL AS inittypacl, NULL AS initrtypacl, "
5046 "(%s typowner) AS rolname, "
5047 "typelem, typrelid, "
5048 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5049 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5050 "typtype, typisdefined, "
5051 "typname[0] = '_' AND typelem != 0 AS isarray "
5052 "FROM pg_type",
5053 username_subquery);
5056 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5058 ntups = PQntuples(res);
5060 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
5062 i_tableoid = PQfnumber(res, "tableoid");
5063 i_oid = PQfnumber(res, "oid");
5064 i_typname = PQfnumber(res, "typname");
5065 i_typnamespace = PQfnumber(res, "typnamespace");
5066 i_typacl = PQfnumber(res, "typacl");
5067 i_rtypacl = PQfnumber(res, "rtypacl");
5068 i_inittypacl = PQfnumber(res, "inittypacl");
5069 i_initrtypacl = PQfnumber(res, "initrtypacl");
5070 i_rolname = PQfnumber(res, "rolname");
5071 i_typelem = PQfnumber(res, "typelem");
5072 i_typrelid = PQfnumber(res, "typrelid");
5073 i_typrelkind = PQfnumber(res, "typrelkind");
5074 i_typtype = PQfnumber(res, "typtype");
5075 i_typisdefined = PQfnumber(res, "typisdefined");
5076 i_isarray = PQfnumber(res, "isarray");
5078 for (i = 0; i < ntups; i++)
5080 tyinfo[i].dobj.objType = DO_TYPE;
5081 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5082 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5083 AssignDumpId(&tyinfo[i].dobj);
5084 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
5085 tyinfo[i].dobj.namespace =
5086 findNamespace(fout,
5087 atooid(PQgetvalue(res, i, i_typnamespace)));
5088 tyinfo[i].ftypname = NULL; /* may get filled later */
5089 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5090 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
5091 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
5092 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
5093 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
5094 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
5095 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
5096 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
5097 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
5098 tyinfo[i].shellType = NULL;
5100 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
5101 tyinfo[i].isDefined = true;
5102 else
5103 tyinfo[i].isDefined = false;
5105 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
5106 tyinfo[i].isArray = true;
5107 else
5108 tyinfo[i].isArray = false;
5110 /* Decide whether we want to dump it */
5111 selectDumpableType(&tyinfo[i], fout);
5113 /* Do not try to dump ACL if no ACL exists. */
5114 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
5115 PQgetisnull(res, i, i_inittypacl) &&
5116 PQgetisnull(res, i, i_initrtypacl))
5117 tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5120 * If it's a domain, fetch info about its constraints, if any
5122 tyinfo[i].nDomChecks = 0;
5123 tyinfo[i].domChecks = NULL;
5124 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
5125 tyinfo[i].typtype == TYPTYPE_DOMAIN)
5126 getDomainConstraints(fout, &(tyinfo[i]));
5129 * If it's a base type, make a DumpableObject representing a shell
5130 * definition of the type. We will need to dump that ahead of the I/O
5131 * functions for the type. Similarly, range types need a shell
5132 * definition in case they have a canonicalize function.
5134 * Note: the shell type doesn't have a catId. You might think it
5135 * should copy the base type's catId, but then it might capture the
5136 * pg_depend entries for the type, which we don't want.
5138 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
5139 (tyinfo[i].typtype == TYPTYPE_BASE ||
5140 tyinfo[i].typtype == TYPTYPE_RANGE))
5142 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
5143 stinfo->dobj.objType = DO_SHELL_TYPE;
5144 stinfo->dobj.catId = nilCatalogId;
5145 AssignDumpId(&stinfo->dobj);
5146 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
5147 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
5148 stinfo->baseType = &(tyinfo[i]);
5149 tyinfo[i].shellType = stinfo;
5152 * Initially mark the shell type as not to be dumped. We'll only
5153 * dump it if the I/O or canonicalize functions need to be dumped;
5154 * this is taken care of while sorting dependencies.
5156 stinfo->dobj.dump = DUMP_COMPONENT_NONE;
5159 if (strlen(tyinfo[i].rolname) == 0)
5160 pg_log_warning("owner of data type \"%s\" appears to be invalid",
5161 tyinfo[i].dobj.name);
5164 *numTypes = ntups;
5166 PQclear(res);
5168 destroyPQExpBuffer(query);
5170 return tyinfo;
5174 * getOperators:
5175 * read all operators in the system catalogs and return them in the
5176 * OprInfo* structure
5178 * numOprs is set to the number of operators read in
5180 OprInfo *
5181 getOperators(Archive *fout, int *numOprs)
5183 PGresult *res;
5184 int ntups;
5185 int i;
5186 PQExpBuffer query = createPQExpBuffer();
5187 OprInfo *oprinfo;
5188 int i_tableoid;
5189 int i_oid;
5190 int i_oprname;
5191 int i_oprnamespace;
5192 int i_rolname;
5193 int i_oprkind;
5194 int i_oprcode;
5197 * find all operators, including builtin operators; we filter out
5198 * system-defined operators at dump-out time.
5201 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
5202 "oprnamespace, "
5203 "(%s oprowner) AS rolname, "
5204 "oprkind, "
5205 "oprcode::oid AS oprcode "
5206 "FROM pg_operator",
5207 username_subquery);
5209 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5211 ntups = PQntuples(res);
5212 *numOprs = ntups;
5214 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
5216 i_tableoid = PQfnumber(res, "tableoid");
5217 i_oid = PQfnumber(res, "oid");
5218 i_oprname = PQfnumber(res, "oprname");
5219 i_oprnamespace = PQfnumber(res, "oprnamespace");
5220 i_rolname = PQfnumber(res, "rolname");
5221 i_oprkind = PQfnumber(res, "oprkind");
5222 i_oprcode = PQfnumber(res, "oprcode");
5224 for (i = 0; i < ntups; i++)
5226 oprinfo[i].dobj.objType = DO_OPERATOR;
5227 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5228 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5229 AssignDumpId(&oprinfo[i].dobj);
5230 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
5231 oprinfo[i].dobj.namespace =
5232 findNamespace(fout,
5233 atooid(PQgetvalue(res, i, i_oprnamespace)));
5234 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5235 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
5236 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
5238 /* Decide whether we want to dump it */
5239 selectDumpableObject(&(oprinfo[i].dobj), fout);
5241 /* Operators do not currently have ACLs. */
5242 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5244 if (strlen(oprinfo[i].rolname) == 0)
5245 pg_log_warning("owner of operator \"%s\" appears to be invalid",
5246 oprinfo[i].dobj.name);
5249 PQclear(res);
5251 destroyPQExpBuffer(query);
5253 return oprinfo;
5257 * getCollations:
5258 * read all collations in the system catalogs and return them in the
5259 * CollInfo* structure
5261 * numCollations is set to the number of collations read in
5263 CollInfo *
5264 getCollations(Archive *fout, int *numCollations)
5266 PGresult *res;
5267 int ntups;
5268 int i;
5269 PQExpBuffer query;
5270 CollInfo *collinfo;
5271 int i_tableoid;
5272 int i_oid;
5273 int i_collname;
5274 int i_collnamespace;
5275 int i_rolname;
5277 /* Collations didn't exist pre-9.1 */
5278 if (fout->remoteVersion < 90100)
5280 *numCollations = 0;
5281 return NULL;
5284 query = createPQExpBuffer();
5287 * find all collations, including builtin collations; we filter out
5288 * system-defined collations at dump-out time.
5291 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5292 "collnamespace, "
5293 "(%s collowner) AS rolname "
5294 "FROM pg_collation",
5295 username_subquery);
5297 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5299 ntups = PQntuples(res);
5300 *numCollations = ntups;
5302 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5304 i_tableoid = PQfnumber(res, "tableoid");
5305 i_oid = PQfnumber(res, "oid");
5306 i_collname = PQfnumber(res, "collname");
5307 i_collnamespace = PQfnumber(res, "collnamespace");
5308 i_rolname = PQfnumber(res, "rolname");
5310 for (i = 0; i < ntups; i++)
5312 collinfo[i].dobj.objType = DO_COLLATION;
5313 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5314 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5315 AssignDumpId(&collinfo[i].dobj);
5316 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5317 collinfo[i].dobj.namespace =
5318 findNamespace(fout,
5319 atooid(PQgetvalue(res, i, i_collnamespace)));
5320 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5322 /* Decide whether we want to dump it */
5323 selectDumpableObject(&(collinfo[i].dobj), fout);
5325 /* Collations do not currently have ACLs. */
5326 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5329 PQclear(res);
5331 destroyPQExpBuffer(query);
5333 return collinfo;
5337 * getConversions:
5338 * read all conversions in the system catalogs and return them in the
5339 * ConvInfo* structure
5341 * numConversions is set to the number of conversions read in
5343 ConvInfo *
5344 getConversions(Archive *fout, int *numConversions)
5346 PGresult *res;
5347 int ntups;
5348 int i;
5349 PQExpBuffer query;
5350 ConvInfo *convinfo;
5351 int i_tableoid;
5352 int i_oid;
5353 int i_conname;
5354 int i_connamespace;
5355 int i_rolname;
5357 query = createPQExpBuffer();
5360 * find all conversions, including builtin conversions; we filter out
5361 * system-defined conversions at dump-out time.
5364 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5365 "connamespace, "
5366 "(%s conowner) AS rolname "
5367 "FROM pg_conversion",
5368 username_subquery);
5370 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5372 ntups = PQntuples(res);
5373 *numConversions = ntups;
5375 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5377 i_tableoid = PQfnumber(res, "tableoid");
5378 i_oid = PQfnumber(res, "oid");
5379 i_conname = PQfnumber(res, "conname");
5380 i_connamespace = PQfnumber(res, "connamespace");
5381 i_rolname = PQfnumber(res, "rolname");
5383 for (i = 0; i < ntups; i++)
5385 convinfo[i].dobj.objType = DO_CONVERSION;
5386 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5387 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5388 AssignDumpId(&convinfo[i].dobj);
5389 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5390 convinfo[i].dobj.namespace =
5391 findNamespace(fout,
5392 atooid(PQgetvalue(res, i, i_connamespace)));
5393 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5395 /* Decide whether we want to dump it */
5396 selectDumpableObject(&(convinfo[i].dobj), fout);
5398 /* Conversions do not currently have ACLs. */
5399 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5402 PQclear(res);
5404 destroyPQExpBuffer(query);
5406 return convinfo;
5410 * getAccessMethods:
5411 * read all user-defined access methods in the system catalogs and return
5412 * them in the AccessMethodInfo* structure
5414 * numAccessMethods is set to the number of access methods read in
5416 AccessMethodInfo *
5417 getAccessMethods(Archive *fout, int *numAccessMethods)
5419 PGresult *res;
5420 int ntups;
5421 int i;
5422 PQExpBuffer query;
5423 AccessMethodInfo *aminfo;
5424 int i_tableoid;
5425 int i_oid;
5426 int i_amname;
5427 int i_amhandler;
5428 int i_amtype;
5430 /* Before 9.6, there are no user-defined access methods */
5431 if (fout->remoteVersion < 90600)
5433 *numAccessMethods = 0;
5434 return NULL;
5437 query = createPQExpBuffer();
5439 /* Select all access methods from pg_am table */
5440 appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5441 "amhandler::pg_catalog.regproc AS amhandler "
5442 "FROM pg_am");
5444 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5446 ntups = PQntuples(res);
5447 *numAccessMethods = ntups;
5449 aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5451 i_tableoid = PQfnumber(res, "tableoid");
5452 i_oid = PQfnumber(res, "oid");
5453 i_amname = PQfnumber(res, "amname");
5454 i_amhandler = PQfnumber(res, "amhandler");
5455 i_amtype = PQfnumber(res, "amtype");
5457 for (i = 0; i < ntups; i++)
5459 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5460 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5461 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5462 AssignDumpId(&aminfo[i].dobj);
5463 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5464 aminfo[i].dobj.namespace = NULL;
5465 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5466 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5468 /* Decide whether we want to dump it */
5469 selectDumpableAccessMethod(&(aminfo[i]), fout);
5471 /* Access methods do not currently have ACLs. */
5472 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5475 PQclear(res);
5477 destroyPQExpBuffer(query);
5479 return aminfo;
5484 * getOpclasses:
5485 * read all opclasses in the system catalogs and return them in the
5486 * OpclassInfo* structure
5488 * numOpclasses is set to the number of opclasses read in
5490 OpclassInfo *
5491 getOpclasses(Archive *fout, int *numOpclasses)
5493 PGresult *res;
5494 int ntups;
5495 int i;
5496 PQExpBuffer query = createPQExpBuffer();
5497 OpclassInfo *opcinfo;
5498 int i_tableoid;
5499 int i_oid;
5500 int i_opcname;
5501 int i_opcnamespace;
5502 int i_rolname;
5505 * find all opclasses, including builtin opclasses; we filter out
5506 * system-defined opclasses at dump-out time.
5509 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5510 "opcnamespace, "
5511 "(%s opcowner) AS rolname "
5512 "FROM pg_opclass",
5513 username_subquery);
5515 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5517 ntups = PQntuples(res);
5518 *numOpclasses = ntups;
5520 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5522 i_tableoid = PQfnumber(res, "tableoid");
5523 i_oid = PQfnumber(res, "oid");
5524 i_opcname = PQfnumber(res, "opcname");
5525 i_opcnamespace = PQfnumber(res, "opcnamespace");
5526 i_rolname = PQfnumber(res, "rolname");
5528 for (i = 0; i < ntups; i++)
5530 opcinfo[i].dobj.objType = DO_OPCLASS;
5531 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5532 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5533 AssignDumpId(&opcinfo[i].dobj);
5534 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5535 opcinfo[i].dobj.namespace =
5536 findNamespace(fout,
5537 atooid(PQgetvalue(res, i, i_opcnamespace)));
5538 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5540 /* Decide whether we want to dump it */
5541 selectDumpableObject(&(opcinfo[i].dobj), fout);
5543 /* Op Classes do not currently have ACLs. */
5544 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5546 if (strlen(opcinfo[i].rolname) == 0)
5547 pg_log_warning("owner of operator class \"%s\" appears to be invalid",
5548 opcinfo[i].dobj.name);
5551 PQclear(res);
5553 destroyPQExpBuffer(query);
5555 return opcinfo;
5559 * getOpfamilies:
5560 * read all opfamilies in the system catalogs and return them in the
5561 * OpfamilyInfo* structure
5563 * numOpfamilies is set to the number of opfamilies read in
5565 OpfamilyInfo *
5566 getOpfamilies(Archive *fout, int *numOpfamilies)
5568 PGresult *res;
5569 int ntups;
5570 int i;
5571 PQExpBuffer query;
5572 OpfamilyInfo *opfinfo;
5573 int i_tableoid;
5574 int i_oid;
5575 int i_opfname;
5576 int i_opfnamespace;
5577 int i_rolname;
5579 /* Before 8.3, there is no separate concept of opfamilies */
5580 if (fout->remoteVersion < 80300)
5582 *numOpfamilies = 0;
5583 return NULL;
5586 query = createPQExpBuffer();
5589 * find all opfamilies, including builtin opfamilies; we filter out
5590 * system-defined opfamilies at dump-out time.
5593 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5594 "opfnamespace, "
5595 "(%s opfowner) AS rolname "
5596 "FROM pg_opfamily",
5597 username_subquery);
5599 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5601 ntups = PQntuples(res);
5602 *numOpfamilies = ntups;
5604 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5606 i_tableoid = PQfnumber(res, "tableoid");
5607 i_oid = PQfnumber(res, "oid");
5608 i_opfname = PQfnumber(res, "opfname");
5609 i_opfnamespace = PQfnumber(res, "opfnamespace");
5610 i_rolname = PQfnumber(res, "rolname");
5612 for (i = 0; i < ntups; i++)
5614 opfinfo[i].dobj.objType = DO_OPFAMILY;
5615 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5616 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5617 AssignDumpId(&opfinfo[i].dobj);
5618 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5619 opfinfo[i].dobj.namespace =
5620 findNamespace(fout,
5621 atooid(PQgetvalue(res, i, i_opfnamespace)));
5622 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5624 /* Decide whether we want to dump it */
5625 selectDumpableObject(&(opfinfo[i].dobj), fout);
5627 /* Extensions do not currently have ACLs. */
5628 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5630 if (strlen(opfinfo[i].rolname) == 0)
5631 pg_log_warning("owner of operator family \"%s\" appears to be invalid",
5632 opfinfo[i].dobj.name);
5635 PQclear(res);
5637 destroyPQExpBuffer(query);
5639 return opfinfo;
5643 * getAggregates:
5644 * read all the user-defined aggregates in the system catalogs and
5645 * return them in the AggInfo* structure
5647 * numAggs is set to the number of aggregates read in
5649 AggInfo *
5650 getAggregates(Archive *fout, int *numAggs)
5652 DumpOptions *dopt = fout->dopt;
5653 PGresult *res;
5654 int ntups;
5655 int i;
5656 PQExpBuffer query = createPQExpBuffer();
5657 AggInfo *agginfo;
5658 int i_tableoid;
5659 int i_oid;
5660 int i_aggname;
5661 int i_aggnamespace;
5662 int i_pronargs;
5663 int i_proargtypes;
5664 int i_rolname;
5665 int i_aggacl;
5666 int i_raggacl;
5667 int i_initaggacl;
5668 int i_initraggacl;
5671 * Find all interesting aggregates. See comment in getFuncs() for the
5672 * rationale behind the filtering logic.
5674 if (fout->remoteVersion >= 90600)
5676 PQExpBuffer acl_subquery = createPQExpBuffer();
5677 PQExpBuffer racl_subquery = createPQExpBuffer();
5678 PQExpBuffer initacl_subquery = createPQExpBuffer();
5679 PQExpBuffer initracl_subquery = createPQExpBuffer();
5680 const char *agg_check;
5682 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5683 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5684 dopt->binary_upgrade);
5686 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5687 : "p.proisagg");
5689 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5690 "p.proname AS aggname, "
5691 "p.pronamespace AS aggnamespace, "
5692 "p.pronargs, p.proargtypes, "
5693 "(%s p.proowner) AS rolname, "
5694 "%s AS aggacl, "
5695 "%s AS raggacl, "
5696 "%s AS initaggacl, "
5697 "%s AS initraggacl "
5698 "FROM pg_proc p "
5699 "LEFT JOIN pg_init_privs pip ON "
5700 "(p.oid = pip.objoid "
5701 "AND pip.classoid = 'pg_proc'::regclass "
5702 "AND pip.objsubid = 0) "
5703 "WHERE %s AND ("
5704 "p.pronamespace != "
5705 "(SELECT oid FROM pg_namespace "
5706 "WHERE nspname = 'pg_catalog') OR "
5707 "p.proacl IS DISTINCT FROM pip.initprivs",
5708 username_subquery,
5709 acl_subquery->data,
5710 racl_subquery->data,
5711 initacl_subquery->data,
5712 initracl_subquery->data,
5713 agg_check);
5714 if (dopt->binary_upgrade)
5715 appendPQExpBufferStr(query,
5716 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5717 "classid = 'pg_proc'::regclass AND "
5718 "objid = p.oid AND "
5719 "refclassid = 'pg_extension'::regclass AND "
5720 "deptype = 'e')");
5721 appendPQExpBufferChar(query, ')');
5723 destroyPQExpBuffer(acl_subquery);
5724 destroyPQExpBuffer(racl_subquery);
5725 destroyPQExpBuffer(initacl_subquery);
5726 destroyPQExpBuffer(initracl_subquery);
5728 else if (fout->remoteVersion >= 80200)
5730 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5731 "pronamespace AS aggnamespace, "
5732 "pronargs, proargtypes, "
5733 "(%s proowner) AS rolname, "
5734 "proacl AS aggacl, "
5735 "NULL AS raggacl, "
5736 "NULL AS initaggacl, NULL AS initraggacl "
5737 "FROM pg_proc p "
5738 "WHERE proisagg AND ("
5739 "pronamespace != "
5740 "(SELECT oid FROM pg_namespace "
5741 "WHERE nspname = 'pg_catalog')",
5742 username_subquery);
5743 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5744 appendPQExpBufferStr(query,
5745 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5746 "classid = 'pg_proc'::regclass AND "
5747 "objid = p.oid AND "
5748 "refclassid = 'pg_extension'::regclass AND "
5749 "deptype = 'e')");
5750 appendPQExpBufferChar(query, ')');
5752 else
5754 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5755 "pronamespace AS aggnamespace, "
5756 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5757 "proargtypes, "
5758 "(%s proowner) AS rolname, "
5759 "proacl AS aggacl, "
5760 "NULL AS raggacl, "
5761 "NULL AS initaggacl, NULL AS initraggacl "
5762 "FROM pg_proc "
5763 "WHERE proisagg "
5764 "AND pronamespace != "
5765 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5766 username_subquery);
5769 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5771 ntups = PQntuples(res);
5772 *numAggs = ntups;
5774 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5776 i_tableoid = PQfnumber(res, "tableoid");
5777 i_oid = PQfnumber(res, "oid");
5778 i_aggname = PQfnumber(res, "aggname");
5779 i_aggnamespace = PQfnumber(res, "aggnamespace");
5780 i_pronargs = PQfnumber(res, "pronargs");
5781 i_proargtypes = PQfnumber(res, "proargtypes");
5782 i_rolname = PQfnumber(res, "rolname");
5783 i_aggacl = PQfnumber(res, "aggacl");
5784 i_raggacl = PQfnumber(res, "raggacl");
5785 i_initaggacl = PQfnumber(res, "initaggacl");
5786 i_initraggacl = PQfnumber(res, "initraggacl");
5788 for (i = 0; i < ntups; i++)
5790 agginfo[i].aggfn.dobj.objType = DO_AGG;
5791 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5792 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5793 AssignDumpId(&agginfo[i].aggfn.dobj);
5794 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5795 agginfo[i].aggfn.dobj.namespace =
5796 findNamespace(fout,
5797 atooid(PQgetvalue(res, i, i_aggnamespace)));
5798 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5799 if (strlen(agginfo[i].aggfn.rolname) == 0)
5800 pg_log_warning("owner of aggregate function \"%s\" appears to be invalid",
5801 agginfo[i].aggfn.dobj.name);
5802 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5803 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
5804 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5805 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5806 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5807 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5808 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5809 if (agginfo[i].aggfn.nargs == 0)
5810 agginfo[i].aggfn.argtypes = NULL;
5811 else
5813 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5814 parseOidArray(PQgetvalue(res, i, i_proargtypes),
5815 agginfo[i].aggfn.argtypes,
5816 agginfo[i].aggfn.nargs);
5819 /* Decide whether we want to dump it */
5820 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5822 /* Do not try to dump ACL if no ACL exists. */
5823 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5824 PQgetisnull(res, i, i_initaggacl) &&
5825 PQgetisnull(res, i, i_initraggacl))
5826 agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5829 PQclear(res);
5831 destroyPQExpBuffer(query);
5833 return agginfo;
5837 * getFuncs:
5838 * read all the user-defined functions in the system catalogs and
5839 * return them in the FuncInfo* structure
5841 * numFuncs is set to the number of functions read in
5843 FuncInfo *
5844 getFuncs(Archive *fout, int *numFuncs)
5846 DumpOptions *dopt = fout->dopt;
5847 PGresult *res;
5848 int ntups;
5849 int i;
5850 PQExpBuffer query = createPQExpBuffer();
5851 FuncInfo *finfo;
5852 int i_tableoid;
5853 int i_oid;
5854 int i_proname;
5855 int i_pronamespace;
5856 int i_rolname;
5857 int i_prolang;
5858 int i_pronargs;
5859 int i_proargtypes;
5860 int i_prorettype;
5861 int i_proacl;
5862 int i_rproacl;
5863 int i_initproacl;
5864 int i_initrproacl;
5867 * Find all interesting functions. This is a bit complicated:
5869 * 1. Always exclude aggregates; those are handled elsewhere.
5871 * 2. Always exclude functions that are internally dependent on something
5872 * else, since presumably those will be created as a result of creating
5873 * the something else. This currently acts only to suppress constructor
5874 * functions for range types (so we only need it in 9.2 and up). Note
5875 * this is OK only because the constructors don't have any dependencies
5876 * the range type doesn't have; otherwise we might not get creation
5877 * ordering correct.
5879 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5880 * they're members of extensions and we are in binary-upgrade mode then
5881 * include them, since we want to dump extension members individually in
5882 * that mode. Also, if they are used by casts or transforms then we need
5883 * to gather the information about them, though they won't be dumped if
5884 * they are built-in. Also, in 9.6 and up, include functions in
5885 * pg_catalog if they have an ACL different from what's shown in
5886 * pg_init_privs.
5888 if (fout->remoteVersion >= 90600)
5890 PQExpBuffer acl_subquery = createPQExpBuffer();
5891 PQExpBuffer racl_subquery = createPQExpBuffer();
5892 PQExpBuffer initacl_subquery = createPQExpBuffer();
5893 PQExpBuffer initracl_subquery = createPQExpBuffer();
5894 const char *not_agg_check;
5896 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5897 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5898 dopt->binary_upgrade);
5900 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5901 : "NOT p.proisagg");
5903 appendPQExpBuffer(query,
5904 "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5905 "p.pronargs, p.proargtypes, p.prorettype, "
5906 "%s AS proacl, "
5907 "%s AS rproacl, "
5908 "%s AS initproacl, "
5909 "%s AS initrproacl, "
5910 "p.pronamespace, "
5911 "(%s p.proowner) AS rolname "
5912 "FROM pg_proc p "
5913 "LEFT JOIN pg_init_privs pip ON "
5914 "(p.oid = pip.objoid "
5915 "AND pip.classoid = 'pg_proc'::regclass "
5916 "AND pip.objsubid = 0) "
5917 "WHERE %s"
5918 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5919 "WHERE classid = 'pg_proc'::regclass AND "
5920 "objid = p.oid AND deptype = 'i')"
5921 "\n AND ("
5922 "\n pronamespace != "
5923 "(SELECT oid FROM pg_namespace "
5924 "WHERE nspname = 'pg_catalog')"
5925 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5926 "\n WHERE pg_cast.oid > %u "
5927 "\n AND p.oid = pg_cast.castfunc)"
5928 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5929 "\n WHERE pg_transform.oid > %u AND "
5930 "\n (p.oid = pg_transform.trffromsql"
5931 "\n OR p.oid = pg_transform.trftosql))",
5932 acl_subquery->data,
5933 racl_subquery->data,
5934 initacl_subquery->data,
5935 initracl_subquery->data,
5936 username_subquery,
5937 not_agg_check,
5938 g_last_builtin_oid,
5939 g_last_builtin_oid);
5940 if (dopt->binary_upgrade)
5941 appendPQExpBufferStr(query,
5942 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5943 "classid = 'pg_proc'::regclass AND "
5944 "objid = p.oid AND "
5945 "refclassid = 'pg_extension'::regclass AND "
5946 "deptype = 'e')");
5947 appendPQExpBufferStr(query,
5948 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5949 appendPQExpBufferChar(query, ')');
5951 destroyPQExpBuffer(acl_subquery);
5952 destroyPQExpBuffer(racl_subquery);
5953 destroyPQExpBuffer(initacl_subquery);
5954 destroyPQExpBuffer(initracl_subquery);
5956 else
5958 appendPQExpBuffer(query,
5959 "SELECT tableoid, oid, proname, prolang, "
5960 "pronargs, proargtypes, prorettype, proacl, "
5961 "NULL as rproacl, "
5962 "NULL as initproacl, NULL AS initrproacl, "
5963 "pronamespace, "
5964 "(%s proowner) AS rolname "
5965 "FROM pg_proc p "
5966 "WHERE NOT proisagg",
5967 username_subquery);
5968 if (fout->remoteVersion >= 90200)
5969 appendPQExpBufferStr(query,
5970 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5971 "WHERE classid = 'pg_proc'::regclass AND "
5972 "objid = p.oid AND deptype = 'i')");
5973 appendPQExpBuffer(query,
5974 "\n AND ("
5975 "\n pronamespace != "
5976 "(SELECT oid FROM pg_namespace "
5977 "WHERE nspname = 'pg_catalog')"
5978 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5979 "\n WHERE pg_cast.oid > '%u'::oid"
5980 "\n AND p.oid = pg_cast.castfunc)",
5981 g_last_builtin_oid);
5983 if (fout->remoteVersion >= 90500)
5984 appendPQExpBuffer(query,
5985 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5986 "\n WHERE pg_transform.oid > '%u'::oid"
5987 "\n AND (p.oid = pg_transform.trffromsql"
5988 "\n OR p.oid = pg_transform.trftosql))",
5989 g_last_builtin_oid);
5991 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5992 appendPQExpBufferStr(query,
5993 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5994 "classid = 'pg_proc'::regclass AND "
5995 "objid = p.oid AND "
5996 "refclassid = 'pg_extension'::regclass AND "
5997 "deptype = 'e')");
5998 appendPQExpBufferChar(query, ')');
6001 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6003 ntups = PQntuples(res);
6005 *numFuncs = ntups;
6007 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
6009 i_tableoid = PQfnumber(res, "tableoid");
6010 i_oid = PQfnumber(res, "oid");
6011 i_proname = PQfnumber(res, "proname");
6012 i_pronamespace = PQfnumber(res, "pronamespace");
6013 i_rolname = PQfnumber(res, "rolname");
6014 i_prolang = PQfnumber(res, "prolang");
6015 i_pronargs = PQfnumber(res, "pronargs");
6016 i_proargtypes = PQfnumber(res, "proargtypes");
6017 i_prorettype = PQfnumber(res, "prorettype");
6018 i_proacl = PQfnumber(res, "proacl");
6019 i_rproacl = PQfnumber(res, "rproacl");
6020 i_initproacl = PQfnumber(res, "initproacl");
6021 i_initrproacl = PQfnumber(res, "initrproacl");
6023 for (i = 0; i < ntups; i++)
6025 finfo[i].dobj.objType = DO_FUNC;
6026 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6027 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6028 AssignDumpId(&finfo[i].dobj);
6029 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
6030 finfo[i].dobj.namespace =
6031 findNamespace(fout,
6032 atooid(PQgetvalue(res, i, i_pronamespace)));
6033 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6034 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
6035 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
6036 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
6037 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
6038 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
6039 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
6040 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
6041 if (finfo[i].nargs == 0)
6042 finfo[i].argtypes = NULL;
6043 else
6045 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
6046 parseOidArray(PQgetvalue(res, i, i_proargtypes),
6047 finfo[i].argtypes, finfo[i].nargs);
6050 /* Decide whether we want to dump it */
6051 selectDumpableObject(&(finfo[i].dobj), fout);
6053 /* Do not try to dump ACL if no ACL exists. */
6054 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
6055 PQgetisnull(res, i, i_initproacl) &&
6056 PQgetisnull(res, i, i_initrproacl))
6057 finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6059 if (strlen(finfo[i].rolname) == 0)
6060 pg_log_warning("owner of function \"%s\" appears to be invalid",
6061 finfo[i].dobj.name);
6064 PQclear(res);
6066 destroyPQExpBuffer(query);
6068 return finfo;
6072 * getTables
6073 * read all the tables (no indexes)
6074 * in the system catalogs return them in the TableInfo* structure
6076 * numTables is set to the number of tables read in
6078 TableInfo *
6079 getTables(Archive *fout, int *numTables)
6081 DumpOptions *dopt = fout->dopt;
6082 PGresult *res;
6083 int ntups;
6084 int i;
6085 PQExpBuffer query = createPQExpBuffer();
6086 TableInfo *tblinfo;
6087 int i_reltableoid;
6088 int i_reloid;
6089 int i_relname;
6090 int i_relnamespace;
6091 int i_relkind;
6092 int i_relacl;
6093 int i_rrelacl;
6094 int i_initrelacl;
6095 int i_initrrelacl;
6096 int i_rolname;
6097 int i_relchecks;
6098 int i_relhastriggers;
6099 int i_relhasindex;
6100 int i_relhasrules;
6101 int i_relrowsec;
6102 int i_relforcerowsec;
6103 int i_relhasoids;
6104 int i_relfrozenxid;
6105 int i_relminmxid;
6106 int i_toastoid;
6107 int i_toastfrozenxid;
6108 int i_toastminmxid;
6109 int i_relpersistence;
6110 int i_relispopulated;
6111 int i_relreplident;
6112 int i_owning_tab;
6113 int i_owning_col;
6114 int i_reltablespace;
6115 int i_reloptions;
6116 int i_checkoption;
6117 int i_toastreloptions;
6118 int i_reloftype;
6119 int i_relpages;
6120 int i_is_identity_sequence;
6121 int i_changed_acl;
6122 int i_ispartition;
6123 int i_amname;
6126 * Find all the tables and table-like objects.
6128 * We must fetch all tables in this phase because otherwise we cannot
6129 * correctly identify inherited columns, owned sequences, etc.
6131 * We include system catalogs, so that we can work if a user table is
6132 * defined to inherit from a system catalog (pretty weird, but...)
6134 * We ignore relations that are not ordinary tables, sequences, views,
6135 * materialized views, composite types, or foreign tables.
6137 * Composite-type table entries won't be dumped as such, but we have to
6138 * make a DumpableObject for them so that we can track dependencies of the
6139 * composite type (pg_depend entries for columns of the composite type
6140 * link to the pg_class entry not the pg_type entry).
6142 * Note: in this phase we should collect only a minimal amount of
6143 * information about each table, basically just enough to decide if it is
6144 * interesting. In particular, since we do not yet have lock on any user
6145 * table, we MUST NOT invoke any server-side data collection functions
6146 * (for instance, pg_get_partkeydef()). Those are likely to fail or give
6147 * wrong answers if any concurrent DDL is happening.
6149 * We purposefully ignore toast OIDs for partitioned tables; the reason is
6150 * that versions 10 and 11 have them, but 12 does not, so emitting them
6151 * causes the upgrade to fail.
6154 if (fout->remoteVersion >= 90600)
6156 char *ispartition = "false";
6157 char *relhasoids = "c.relhasoids";
6159 PQExpBuffer acl_subquery = createPQExpBuffer();
6160 PQExpBuffer racl_subquery = createPQExpBuffer();
6161 PQExpBuffer initacl_subquery = createPQExpBuffer();
6162 PQExpBuffer initracl_subquery = createPQExpBuffer();
6164 PQExpBuffer attacl_subquery = createPQExpBuffer();
6165 PQExpBuffer attracl_subquery = createPQExpBuffer();
6166 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
6167 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
6170 * Collect the information about any partitioned tables, which were
6171 * added in PG10.
6173 if (fout->remoteVersion >= 100000)
6174 ispartition = "c.relispartition";
6176 /* In PG12 upwards WITH OIDS does not exist anymore. */
6177 if (fout->remoteVersion >= 120000)
6178 relhasoids = "'f'::bool";
6181 * Left join to pick up dependency info linking sequences to their
6182 * owning column, if any (note this dependency is AUTO as of 8.2)
6184 * Left join to detect if any privileges are still as-set-at-init, in
6185 * which case we won't dump out ACL commands for those.
6188 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
6189 initracl_subquery, "c.relacl", "c.relowner",
6190 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
6191 " THEN 's' ELSE 'r' END::\"char\"",
6192 dopt->binary_upgrade);
6194 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
6195 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
6196 dopt->binary_upgrade);
6198 appendPQExpBuffer(query,
6199 "SELECT c.tableoid, c.oid, c.relname, "
6200 "%s AS relacl, %s as rrelacl, "
6201 "%s AS initrelacl, %s as initrrelacl, "
6202 "c.relkind, c.relnamespace, "
6203 "(%s c.relowner) AS rolname, "
6204 "c.relchecks, c.relhastriggers, "
6205 "c.relhasindex, c.relhasrules, %s AS relhasoids, "
6206 "c.relrowsecurity, c.relforcerowsecurity, "
6207 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6208 "tc.relfrozenxid AS tfrozenxid, "
6209 "tc.relminmxid AS tminmxid, "
6210 "c.relpersistence, c.relispopulated, "
6211 "c.relreplident, c.relpages, am.amname, "
6212 "c.reloftype, "
6213 "d.refobjid AS owning_tab, "
6214 "d.refobjsubid AS owning_col, "
6215 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6216 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6217 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6218 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6219 "tc.reloptions AS toast_reloptions, "
6220 "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, "
6221 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
6222 "(c.oid = pip.objoid "
6223 "AND pip.classoid = 'pg_class'::regclass "
6224 "AND pip.objsubid = at.attnum)"
6225 "WHERE at.attrelid = c.oid AND ("
6226 "%s IS NOT NULL "
6227 "OR %s IS NOT NULL "
6228 "OR %s IS NOT NULL "
6229 "OR %s IS NOT NULL"
6230 "))"
6231 "AS changed_acl, "
6232 "%s AS ispartition "
6233 "FROM pg_class c "
6234 "LEFT JOIN pg_depend d ON "
6235 "(c.relkind = '%c' AND "
6236 "d.classid = c.tableoid AND d.objid = c.oid AND "
6237 "d.objsubid = 0 AND "
6238 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
6239 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid AND c.relkind <> '%c') "
6240 "LEFT JOIN pg_am am ON (c.relam = am.oid) "
6241 "LEFT JOIN pg_init_privs pip ON "
6242 "(c.oid = pip.objoid "
6243 "AND pip.classoid = 'pg_class'::regclass "
6244 "AND pip.objsubid = 0) "
6245 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
6246 "ORDER BY c.oid",
6247 acl_subquery->data,
6248 racl_subquery->data,
6249 initacl_subquery->data,
6250 initracl_subquery->data,
6251 username_subquery,
6252 relhasoids,
6253 RELKIND_SEQUENCE,
6254 attacl_subquery->data,
6255 attracl_subquery->data,
6256 attinitacl_subquery->data,
6257 attinitracl_subquery->data,
6258 ispartition,
6259 RELKIND_SEQUENCE,
6260 RELKIND_PARTITIONED_TABLE,
6261 RELKIND_RELATION, RELKIND_SEQUENCE,
6262 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6263 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
6264 RELKIND_PARTITIONED_TABLE);
6266 destroyPQExpBuffer(acl_subquery);
6267 destroyPQExpBuffer(racl_subquery);
6268 destroyPQExpBuffer(initacl_subquery);
6269 destroyPQExpBuffer(initracl_subquery);
6271 destroyPQExpBuffer(attacl_subquery);
6272 destroyPQExpBuffer(attracl_subquery);
6273 destroyPQExpBuffer(attinitacl_subquery);
6274 destroyPQExpBuffer(attinitracl_subquery);
6276 else if (fout->remoteVersion >= 90500)
6279 * Left join to pick up dependency info linking sequences to their
6280 * owning column, if any (note this dependency is AUTO as of 8.2)
6282 appendPQExpBuffer(query,
6283 "SELECT c.tableoid, c.oid, c.relname, "
6284 "c.relacl, NULL as rrelacl, "
6285 "NULL AS initrelacl, NULL AS initrrelacl, "
6286 "c.relkind, "
6287 "c.relnamespace, "
6288 "(%s c.relowner) AS rolname, "
6289 "c.relchecks, c.relhastriggers, "
6290 "c.relhasindex, c.relhasrules, c.relhasoids, "
6291 "c.relrowsecurity, c.relforcerowsecurity, "
6292 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6293 "tc.relfrozenxid AS tfrozenxid, "
6294 "tc.relminmxid AS tminmxid, "
6295 "c.relpersistence, c.relispopulated, "
6296 "c.relreplident, c.relpages, "
6297 "NULL AS amname, "
6298 "c.reloftype, "
6299 "d.refobjid AS owning_tab, "
6300 "d.refobjsubid AS owning_col, "
6301 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6302 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6303 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6304 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6305 "tc.reloptions AS toast_reloptions, "
6306 "NULL AS changed_acl, "
6307 "false AS ispartition "
6308 "FROM pg_class c "
6309 "LEFT JOIN pg_depend d ON "
6310 "(c.relkind = '%c' AND "
6311 "d.classid = c.tableoid AND d.objid = c.oid AND "
6312 "d.objsubid = 0 AND "
6313 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6314 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6315 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6316 "ORDER BY c.oid",
6317 username_subquery,
6318 RELKIND_SEQUENCE,
6319 RELKIND_RELATION, RELKIND_SEQUENCE,
6320 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6321 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6323 else if (fout->remoteVersion >= 90400)
6326 * Left join to pick up dependency info linking sequences to their
6327 * owning column, if any (note this dependency is AUTO as of 8.2)
6329 appendPQExpBuffer(query,
6330 "SELECT c.tableoid, c.oid, c.relname, "
6331 "c.relacl, NULL as rrelacl, "
6332 "NULL AS initrelacl, NULL AS initrrelacl, "
6333 "c.relkind, "
6334 "c.relnamespace, "
6335 "(%s c.relowner) AS rolname, "
6336 "c.relchecks, c.relhastriggers, "
6337 "c.relhasindex, c.relhasrules, c.relhasoids, "
6338 "'f'::bool AS relrowsecurity, "
6339 "'f'::bool AS relforcerowsecurity, "
6340 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6341 "tc.relfrozenxid AS tfrozenxid, "
6342 "tc.relminmxid AS tminmxid, "
6343 "c.relpersistence, c.relispopulated, "
6344 "c.relreplident, c.relpages, "
6345 "NULL AS amname, "
6346 "c.reloftype, "
6347 "d.refobjid AS owning_tab, "
6348 "d.refobjsubid AS owning_col, "
6349 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6350 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6351 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6352 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6353 "tc.reloptions AS toast_reloptions, "
6354 "NULL AS changed_acl, "
6355 "false AS ispartition "
6356 "FROM pg_class c "
6357 "LEFT JOIN pg_depend d ON "
6358 "(c.relkind = '%c' AND "
6359 "d.classid = c.tableoid AND d.objid = c.oid AND "
6360 "d.objsubid = 0 AND "
6361 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6362 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6363 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6364 "ORDER BY c.oid",
6365 username_subquery,
6366 RELKIND_SEQUENCE,
6367 RELKIND_RELATION, RELKIND_SEQUENCE,
6368 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6369 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6371 else if (fout->remoteVersion >= 90300)
6374 * Left join to pick up dependency info linking sequences to their
6375 * owning column, if any (note this dependency is AUTO as of 8.2)
6377 appendPQExpBuffer(query,
6378 "SELECT c.tableoid, c.oid, c.relname, "
6379 "c.relacl, NULL as rrelacl, "
6380 "NULL AS initrelacl, NULL AS initrrelacl, "
6381 "c.relkind, "
6382 "c.relnamespace, "
6383 "(%s c.relowner) AS rolname, "
6384 "c.relchecks, c.relhastriggers, "
6385 "c.relhasindex, c.relhasrules, c.relhasoids, "
6386 "'f'::bool AS relrowsecurity, "
6387 "'f'::bool AS relforcerowsecurity, "
6388 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6389 "tc.relfrozenxid AS tfrozenxid, "
6390 "tc.relminmxid AS tminmxid, "
6391 "c.relpersistence, c.relispopulated, "
6392 "'d' AS relreplident, c.relpages, "
6393 "NULL AS amname, "
6394 "c.reloftype, "
6395 "d.refobjid AS owning_tab, "
6396 "d.refobjsubid AS owning_col, "
6397 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6398 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6399 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6400 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6401 "tc.reloptions AS toast_reloptions, "
6402 "NULL AS changed_acl, "
6403 "false AS ispartition "
6404 "FROM pg_class c "
6405 "LEFT JOIN pg_depend d ON "
6406 "(c.relkind = '%c' AND "
6407 "d.classid = c.tableoid AND d.objid = c.oid AND "
6408 "d.objsubid = 0 AND "
6409 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6410 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6411 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6412 "ORDER BY c.oid",
6413 username_subquery,
6414 RELKIND_SEQUENCE,
6415 RELKIND_RELATION, RELKIND_SEQUENCE,
6416 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6417 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6419 else if (fout->remoteVersion >= 90100)
6422 * Left join to pick up dependency info linking sequences to their
6423 * owning column, if any (note this dependency is AUTO as of 8.2)
6425 appendPQExpBuffer(query,
6426 "SELECT c.tableoid, c.oid, c.relname, "
6427 "c.relacl, NULL as rrelacl, "
6428 "NULL AS initrelacl, NULL AS initrrelacl, "
6429 "c.relkind, "
6430 "c.relnamespace, "
6431 "(%s c.relowner) AS rolname, "
6432 "c.relchecks, c.relhastriggers, "
6433 "c.relhasindex, c.relhasrules, c.relhasoids, "
6434 "'f'::bool AS relrowsecurity, "
6435 "'f'::bool AS relforcerowsecurity, "
6436 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6437 "tc.relfrozenxid AS tfrozenxid, "
6438 "0 AS tminmxid, "
6439 "c.relpersistence, 't' as relispopulated, "
6440 "'d' AS relreplident, c.relpages, "
6441 "NULL AS amname, "
6442 "c.reloftype, "
6443 "d.refobjid AS owning_tab, "
6444 "d.refobjsubid AS owning_col, "
6445 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6446 "c.reloptions AS reloptions, "
6447 "tc.reloptions AS toast_reloptions, "
6448 "NULL AS changed_acl, "
6449 "false AS ispartition "
6450 "FROM pg_class c "
6451 "LEFT JOIN pg_depend d ON "
6452 "(c.relkind = '%c' AND "
6453 "d.classid = c.tableoid AND d.objid = c.oid AND "
6454 "d.objsubid = 0 AND "
6455 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6456 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6457 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6458 "ORDER BY c.oid",
6459 username_subquery,
6460 RELKIND_SEQUENCE,
6461 RELKIND_RELATION, RELKIND_SEQUENCE,
6462 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6463 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6465 else if (fout->remoteVersion >= 90000)
6468 * Left join to pick up dependency info linking sequences to their
6469 * owning column, if any (note this dependency is AUTO as of 8.2)
6471 appendPQExpBuffer(query,
6472 "SELECT c.tableoid, c.oid, c.relname, "
6473 "c.relacl, NULL as rrelacl, "
6474 "NULL AS initrelacl, NULL AS initrrelacl, "
6475 "c.relkind, "
6476 "c.relnamespace, "
6477 "(%s c.relowner) AS rolname, "
6478 "c.relchecks, c.relhastriggers, "
6479 "c.relhasindex, c.relhasrules, c.relhasoids, "
6480 "'f'::bool AS relrowsecurity, "
6481 "'f'::bool AS relforcerowsecurity, "
6482 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6483 "tc.relfrozenxid AS tfrozenxid, "
6484 "0 AS tminmxid, "
6485 "'p' AS relpersistence, 't' as relispopulated, "
6486 "'d' AS relreplident, c.relpages, "
6487 "NULL AS amname, "
6488 "c.reloftype, "
6489 "d.refobjid AS owning_tab, "
6490 "d.refobjsubid AS owning_col, "
6491 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6492 "c.reloptions AS reloptions, "
6493 "tc.reloptions AS toast_reloptions, "
6494 "NULL AS changed_acl, "
6495 "false AS ispartition "
6496 "FROM pg_class c "
6497 "LEFT JOIN pg_depend d ON "
6498 "(c.relkind = '%c' AND "
6499 "d.classid = c.tableoid AND d.objid = c.oid AND "
6500 "d.objsubid = 0 AND "
6501 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6502 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6503 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6504 "ORDER BY c.oid",
6505 username_subquery,
6506 RELKIND_SEQUENCE,
6507 RELKIND_RELATION, RELKIND_SEQUENCE,
6508 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6510 else if (fout->remoteVersion >= 80400)
6513 * Left join to pick up dependency info linking sequences to their
6514 * owning column, if any (note this dependency is AUTO as of 8.2)
6516 appendPQExpBuffer(query,
6517 "SELECT c.tableoid, c.oid, c.relname, "
6518 "c.relacl, NULL as rrelacl, "
6519 "NULL AS initrelacl, NULL AS initrrelacl, "
6520 "c.relkind, "
6521 "c.relnamespace, "
6522 "(%s c.relowner) AS rolname, "
6523 "c.relchecks, c.relhastriggers, "
6524 "c.relhasindex, c.relhasrules, c.relhasoids, "
6525 "'f'::bool AS relrowsecurity, "
6526 "'f'::bool AS relforcerowsecurity, "
6527 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6528 "tc.relfrozenxid AS tfrozenxid, "
6529 "0 AS tminmxid, "
6530 "'p' AS relpersistence, 't' as relispopulated, "
6531 "'d' AS relreplident, c.relpages, "
6532 "NULL AS amname, "
6533 "0 AS reloftype, "
6534 "d.refobjid AS owning_tab, "
6535 "d.refobjsubid AS owning_col, "
6536 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6537 "c.reloptions AS reloptions, "
6538 "tc.reloptions AS toast_reloptions, "
6539 "NULL AS changed_acl, "
6540 "false AS ispartition "
6541 "FROM pg_class c "
6542 "LEFT JOIN pg_depend d ON "
6543 "(c.relkind = '%c' AND "
6544 "d.classid = c.tableoid AND d.objid = c.oid AND "
6545 "d.objsubid = 0 AND "
6546 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6547 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6548 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6549 "ORDER BY c.oid",
6550 username_subquery,
6551 RELKIND_SEQUENCE,
6552 RELKIND_RELATION, RELKIND_SEQUENCE,
6553 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6555 else if (fout->remoteVersion >= 80200)
6558 * Left join to pick up dependency info linking sequences to their
6559 * owning column, if any (note this dependency is AUTO as of 8.2)
6561 appendPQExpBuffer(query,
6562 "SELECT c.tableoid, c.oid, c.relname, "
6563 "c.relacl, NULL as rrelacl, "
6564 "NULL AS initrelacl, NULL AS initrrelacl, "
6565 "c.relkind, "
6566 "c.relnamespace, "
6567 "(%s c.relowner) AS rolname, "
6568 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6569 "c.relhasindex, c.relhasrules, c.relhasoids, "
6570 "'f'::bool AS relrowsecurity, "
6571 "'f'::bool AS relforcerowsecurity, "
6572 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6573 "tc.relfrozenxid AS tfrozenxid, "
6574 "0 AS tminmxid, "
6575 "'p' AS relpersistence, 't' as relispopulated, "
6576 "'d' AS relreplident, c.relpages, "
6577 "NULL AS amname, "
6578 "0 AS reloftype, "
6579 "d.refobjid AS owning_tab, "
6580 "d.refobjsubid AS owning_col, "
6581 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6582 "c.reloptions AS reloptions, "
6583 "NULL AS toast_reloptions, "
6584 "NULL AS changed_acl, "
6585 "false AS ispartition "
6586 "FROM pg_class c "
6587 "LEFT JOIN pg_depend d ON "
6588 "(c.relkind = '%c' AND "
6589 "d.classid = c.tableoid AND d.objid = c.oid AND "
6590 "d.objsubid = 0 AND "
6591 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6592 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6593 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6594 "ORDER BY c.oid",
6595 username_subquery,
6596 RELKIND_SEQUENCE,
6597 RELKIND_RELATION, RELKIND_SEQUENCE,
6598 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6600 else
6603 * Left join to pick up dependency info linking sequences to their
6604 * owning column, if any
6606 appendPQExpBuffer(query,
6607 "SELECT c.tableoid, c.oid, relname, "
6608 "relacl, NULL as rrelacl, "
6609 "NULL AS initrelacl, NULL AS initrrelacl, "
6610 "relkind, relnamespace, "
6611 "(%s relowner) AS rolname, "
6612 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6613 "relhasindex, relhasrules, relhasoids, "
6614 "'f'::bool AS relrowsecurity, "
6615 "'f'::bool AS relforcerowsecurity, "
6616 "0 AS relfrozenxid, 0 AS relminmxid,"
6617 "0 AS toid, "
6618 "0 AS tfrozenxid, 0 AS tminmxid,"
6619 "'p' AS relpersistence, 't' as relispopulated, "
6620 "'d' AS relreplident, relpages, "
6621 "NULL AS amname, "
6622 "0 AS reloftype, "
6623 "d.refobjid AS owning_tab, "
6624 "d.refobjsubid AS owning_col, "
6625 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6626 "NULL AS reloptions, "
6627 "NULL AS toast_reloptions, "
6628 "NULL AS changed_acl, "
6629 "false AS ispartition "
6630 "FROM pg_class c "
6631 "LEFT JOIN pg_depend d ON "
6632 "(c.relkind = '%c' AND "
6633 "d.classid = c.tableoid AND d.objid = c.oid AND "
6634 "d.objsubid = 0 AND "
6635 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6636 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6637 "ORDER BY c.oid",
6638 username_subquery,
6639 RELKIND_SEQUENCE,
6640 RELKIND_RELATION, RELKIND_SEQUENCE,
6641 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6644 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6646 ntups = PQntuples(res);
6648 *numTables = ntups;
6651 * Extract data from result and lock dumpable tables. We do the locking
6652 * before anything else, to minimize the window wherein a table could
6653 * disappear under us.
6655 * Note that we have to save info about all tables here, even when dumping
6656 * only one, because we don't yet know which tables might be inheritance
6657 * ancestors of the target table.
6659 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6661 i_reltableoid = PQfnumber(res, "tableoid");
6662 i_reloid = PQfnumber(res, "oid");
6663 i_relname = PQfnumber(res, "relname");
6664 i_relnamespace = PQfnumber(res, "relnamespace");
6665 i_relacl = PQfnumber(res, "relacl");
6666 i_rrelacl = PQfnumber(res, "rrelacl");
6667 i_initrelacl = PQfnumber(res, "initrelacl");
6668 i_initrrelacl = PQfnumber(res, "initrrelacl");
6669 i_relkind = PQfnumber(res, "relkind");
6670 i_rolname = PQfnumber(res, "rolname");
6671 i_relchecks = PQfnumber(res, "relchecks");
6672 i_relhastriggers = PQfnumber(res, "relhastriggers");
6673 i_relhasindex = PQfnumber(res, "relhasindex");
6674 i_relhasrules = PQfnumber(res, "relhasrules");
6675 i_relrowsec = PQfnumber(res, "relrowsecurity");
6676 i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6677 i_relhasoids = PQfnumber(res, "relhasoids");
6678 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6679 i_relminmxid = PQfnumber(res, "relminmxid");
6680 i_toastoid = PQfnumber(res, "toid");
6681 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6682 i_toastminmxid = PQfnumber(res, "tminmxid");
6683 i_relpersistence = PQfnumber(res, "relpersistence");
6684 i_relispopulated = PQfnumber(res, "relispopulated");
6685 i_relreplident = PQfnumber(res, "relreplident");
6686 i_relpages = PQfnumber(res, "relpages");
6687 i_owning_tab = PQfnumber(res, "owning_tab");
6688 i_owning_col = PQfnumber(res, "owning_col");
6689 i_reltablespace = PQfnumber(res, "reltablespace");
6690 i_reloptions = PQfnumber(res, "reloptions");
6691 i_checkoption = PQfnumber(res, "checkoption");
6692 i_toastreloptions = PQfnumber(res, "toast_reloptions");
6693 i_reloftype = PQfnumber(res, "reloftype");
6694 i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6695 i_changed_acl = PQfnumber(res, "changed_acl");
6696 i_ispartition = PQfnumber(res, "ispartition");
6697 i_amname = PQfnumber(res, "amname");
6699 if (dopt->lockWaitTimeout)
6702 * Arrange to fail instead of waiting forever for a table lock.
6704 * NB: this coding assumes that the only queries issued within the
6705 * following loop are LOCK TABLEs; else the timeout may be undesirably
6706 * applied to other things too.
6708 resetPQExpBuffer(query);
6709 appendPQExpBufferStr(query, "SET statement_timeout = ");
6710 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6711 ExecuteSqlStatement(fout, query->data);
6714 for (i = 0; i < ntups; i++)
6716 tblinfo[i].dobj.objType = DO_TABLE;
6717 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6718 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6719 AssignDumpId(&tblinfo[i].dobj);
6720 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6721 tblinfo[i].dobj.namespace =
6722 findNamespace(fout,
6723 atooid(PQgetvalue(res, i, i_relnamespace)));
6724 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6725 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6726 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6727 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6728 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6729 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6730 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6731 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6732 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6733 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6734 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6735 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6736 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6737 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6738 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6739 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6740 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6741 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6742 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6743 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6744 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6745 tblinfo[i].reloftype = atooid(PQgetvalue(res, i, i_reloftype));
6746 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6747 if (PQgetisnull(res, i, i_owning_tab))
6749 tblinfo[i].owning_tab = InvalidOid;
6750 tblinfo[i].owning_col = 0;
6752 else
6754 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6755 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6757 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6758 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6759 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6760 tblinfo[i].checkoption = NULL;
6761 else
6762 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6763 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6764 if (PQgetisnull(res, i, i_amname))
6765 tblinfo[i].amname = NULL;
6766 else
6767 tblinfo[i].amname = pg_strdup(PQgetvalue(res, i, i_amname));
6769 /* other fields were zeroed above */
6772 * Decide whether we want to dump this table.
6774 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6775 tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6776 else
6777 selectDumpableTable(&tblinfo[i], fout);
6780 * If the table-level and all column-level ACLs for this table are
6781 * unchanged, then we don't need to worry about including the ACLs for
6782 * this table. If any column-level ACLs have been changed, the
6783 * 'changed_acl' column from the query will indicate that.
6785 * This can result in a significant performance improvement in cases
6786 * where we are only looking to dump out the ACL (eg: pg_catalog).
6788 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6789 PQgetisnull(res, i, i_initrelacl) &&
6790 PQgetisnull(res, i, i_initrrelacl) &&
6791 strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6792 tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6794 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6795 tblinfo[i].dummy_view = false; /* might get set during sort */
6796 tblinfo[i].postponed_def = false; /* might get set during sort */
6798 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6799 strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6801 /* Partition? */
6802 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6805 * Read-lock target tables to make sure they aren't DROPPED or altered
6806 * in schema before we get around to dumping them.
6808 * Note that we don't explicitly lock parents of the target tables; we
6809 * assume our lock on the child is enough to prevent schema
6810 * alterations to parent tables.
6812 * NOTE: it'd be kinda nice to lock other relations too, not only
6813 * plain or partitioned tables, but the backend doesn't presently
6814 * allow that.
6816 * We only need to lock the table for certain components; see
6817 * pg_dump.h
6819 if (tblinfo[i].dobj.dump &&
6820 (tblinfo[i].relkind == RELKIND_RELATION ||
6821 tblinfo[i].relkind == RELKIND_PARTITIONED_TABLE) &&
6822 (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6824 resetPQExpBuffer(query);
6825 appendPQExpBuffer(query,
6826 "LOCK TABLE %s IN ACCESS SHARE MODE",
6827 fmtQualifiedDumpable(&tblinfo[i]));
6828 ExecuteSqlStatement(fout, query->data);
6831 /* Emit notice if join for owner failed */
6832 if (strlen(tblinfo[i].rolname) == 0)
6833 pg_log_warning("owner of table \"%s\" appears to be invalid",
6834 tblinfo[i].dobj.name);
6837 if (dopt->lockWaitTimeout)
6839 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6842 PQclear(res);
6844 destroyPQExpBuffer(query);
6846 return tblinfo;
6850 * getOwnedSeqs
6851 * identify owned sequences and mark them as dumpable if owning table is
6853 * We used to do this in getTables(), but it's better to do it after the
6854 * index used by findTableByOid() has been set up.
6856 void
6857 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6859 int i;
6862 * Force sequences that are "owned" by table columns to be dumped whenever
6863 * their owning table is being dumped.
6865 for (i = 0; i < numTables; i++)
6867 TableInfo *seqinfo = &tblinfo[i];
6868 TableInfo *owning_tab;
6870 if (!OidIsValid(seqinfo->owning_tab))
6871 continue; /* not an owned sequence */
6873 owning_tab = findTableByOid(seqinfo->owning_tab);
6874 if (owning_tab == NULL)
6875 fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
6876 seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6879 * Only dump identity sequences if we're going to dump the table that
6880 * it belongs to.
6882 if (owning_tab->dobj.dump == DUMP_COMPONENT_NONE &&
6883 seqinfo->is_identity_sequence)
6885 seqinfo->dobj.dump = DUMP_COMPONENT_NONE;
6886 continue;
6890 * Otherwise we need to dump the components that are being dumped for
6891 * the table and any components which the sequence is explicitly
6892 * marked with.
6894 * We can't simply use the set of components which are being dumped
6895 * for the table as the table might be in an extension (and only the
6896 * non-extension components, eg: ACLs if changed, security labels, and
6897 * policies, are being dumped) while the sequence is not (and
6898 * therefore the definition and other components should also be
6899 * dumped).
6901 * If the sequence is part of the extension then it should be properly
6902 * marked by checkExtensionMembership() and this will be a no-op as
6903 * the table will be equivalently marked.
6905 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6907 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6908 seqinfo->interesting = true;
6913 * getInherits
6914 * read all the inheritance information
6915 * from the system catalogs return them in the InhInfo* structure
6917 * numInherits is set to the number of pairs read in
6919 InhInfo *
6920 getInherits(Archive *fout, int *numInherits)
6922 PGresult *res;
6923 int ntups;
6924 int i;
6925 PQExpBuffer query = createPQExpBuffer();
6926 InhInfo *inhinfo;
6928 int i_inhrelid;
6929 int i_inhparent;
6932 * Find all the inheritance information, excluding implicit inheritance
6933 * via partitioning. We handle that case using getPartitions(), because
6934 * we want more information about partitions than just the parent-child
6935 * relationship.
6937 appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6939 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6941 ntups = PQntuples(res);
6943 *numInherits = ntups;
6945 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6947 i_inhrelid = PQfnumber(res, "inhrelid");
6948 i_inhparent = PQfnumber(res, "inhparent");
6950 for (i = 0; i < ntups; i++)
6952 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6953 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6956 PQclear(res);
6958 destroyPQExpBuffer(query);
6960 return inhinfo;
6964 * getPartitioningInfo
6965 * get information about partitioning
6967 * For the most part, we only collect partitioning info about tables we
6968 * intend to dump. However, this function has to consider all partitioned
6969 * tables in the database, because we need to know about parents of partitions
6970 * we are going to dump even if the parents themselves won't be dumped.
6972 * Specifically, what we need to know is whether each partitioned table
6973 * has an "unsafe" partitioning scheme that requires us to force
6974 * load-via-partition-root mode for its children. Currently the only case
6975 * for which we force that is hash partitioning on enum columns, since the
6976 * hash codes depend on enum value OIDs which won't be replicated across
6977 * dump-and-reload. There are other cases in which load-via-partition-root
6978 * might be necessary, but we expect users to cope with them.
6980 void
6981 getPartitioningInfo(Archive *fout)
6983 PQExpBuffer query;
6984 PGresult *res;
6985 int ntups;
6987 /* hash partitioning didn't exist before v11 */
6988 if (fout->remoteVersion < 110000)
6989 return;
6990 /* needn't bother if schema-only dump */
6991 if (fout->dopt->schemaOnly)
6992 return;
6994 query = createPQExpBuffer();
6997 * Unsafe partitioning schemes are exactly those for which hash enum_ops
6998 * appears among the partition opclasses. We needn't check partstrat.
7000 * Note that this query may well retrieve info about tables we aren't
7001 * going to dump and hence have no lock on. That's okay since we need not
7002 * invoke any unsafe server-side functions.
7004 appendPQExpBufferStr(query,
7005 "SELECT partrelid FROM pg_partitioned_table WHERE\n"
7006 "(SELECT c.oid FROM pg_opclass c JOIN pg_am a "
7007 "ON c.opcmethod = a.oid\n"
7008 "WHERE opcname = 'enum_ops' "
7009 "AND opcnamespace = 'pg_catalog'::regnamespace "
7010 "AND amname = 'hash') = ANY(partclass)");
7012 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7014 ntups = PQntuples(res);
7016 for (int i = 0; i < ntups; i++)
7018 Oid tabrelid = atooid(PQgetvalue(res, i, 0));
7019 TableInfo *tbinfo;
7021 tbinfo = findTableByOid(tabrelid);
7022 if (tbinfo == NULL)
7023 fatal("failed sanity check, table OID %u appearing in pg_partitioned_table not found",
7024 tabrelid);
7025 tbinfo->unsafe_partitions = true;
7028 PQclear(res);
7030 destroyPQExpBuffer(query);
7034 * getIndexes
7035 * get information about every index on a dumpable table
7037 * Note: index data is not returned directly to the caller, but it
7038 * does get entered into the DumpableObject tables.
7040 void
7041 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
7043 int i,
7045 PQExpBuffer query = createPQExpBuffer();
7046 PGresult *res;
7047 IndxInfo *indxinfo;
7048 ConstraintInfo *constrinfo;
7049 int i_tableoid,
7050 i_oid,
7051 i_indexname,
7052 i_parentidx,
7053 i_indexdef,
7054 i_indnkeyatts,
7055 i_indnatts,
7056 i_indkey,
7057 i_indisclustered,
7058 i_indisreplident,
7059 i_contype,
7060 i_conname,
7061 i_condeferrable,
7062 i_condeferred,
7063 i_contableoid,
7064 i_conoid,
7065 i_condef,
7066 i_tablespace,
7067 i_indreloptions,
7068 i_indstatcols,
7069 i_indstatvals;
7070 int ntups;
7072 for (i = 0; i < numTables; i++)
7074 TableInfo *tbinfo = &tblinfo[i];
7076 if (!tbinfo->hasindex)
7077 continue;
7080 * Ignore indexes of tables whose definitions are not to be dumped.
7082 * We also need indexes on partitioned tables which have partitions to
7083 * be dumped, in order to dump the indexes on the partitions.
7085 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
7086 !tbinfo->interesting)
7087 continue;
7089 pg_log_info("reading indexes for table \"%s.%s\"",
7090 tbinfo->dobj.namespace->dobj.name,
7091 tbinfo->dobj.name);
7094 * The point of the messy-looking outer join is to find a constraint
7095 * that is related by an internal dependency link to the index. If we
7096 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
7097 * assume an index won't have more than one internal dependency.
7099 * As of 9.0 we don't need to look at pg_depend but can check for a
7100 * match to pg_constraint.conindid. The check on conrelid is
7101 * redundant but useful because that column is indexed while conindid
7102 * is not.
7104 resetPQExpBuffer(query);
7105 if (fout->remoteVersion >= 110000)
7107 appendPQExpBuffer(query,
7108 "SELECT t.tableoid, t.oid, "
7109 "t.relname AS indexname, "
7110 "inh.inhparent AS parentidx, "
7111 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7112 "i.indnkeyatts AS indnkeyatts, "
7113 "i.indnatts AS indnatts, "
7114 "i.indkey, i.indisclustered, "
7115 "i.indisreplident, "
7116 "c.contype, c.conname, "
7117 "c.condeferrable, c.condeferred, "
7118 "c.tableoid AS contableoid, "
7119 "c.oid AS conoid, "
7120 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7121 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7122 "t.reloptions AS indreloptions, "
7123 "(SELECT pg_catalog.array_agg(attnum ORDER BY attnum) "
7124 " FROM pg_catalog.pg_attribute "
7125 " WHERE attrelid = i.indexrelid AND "
7126 " attstattarget >= 0) AS indstatcols,"
7127 "(SELECT pg_catalog.array_agg(attstattarget ORDER BY attnum) "
7128 " FROM pg_catalog.pg_attribute "
7129 " WHERE attrelid = i.indexrelid AND "
7130 " attstattarget >= 0) AS indstatvals "
7131 "FROM pg_catalog.pg_index i "
7132 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7133 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
7134 "LEFT JOIN pg_catalog.pg_constraint c "
7135 "ON (i.indrelid = c.conrelid AND "
7136 "i.indexrelid = c.conindid AND "
7137 "c.contype IN ('p','u','x')) "
7138 "LEFT JOIN pg_catalog.pg_inherits inh "
7139 "ON (inh.inhrelid = indexrelid) "
7140 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7141 "AND (i.indisvalid OR t2.relkind = 'p') "
7142 "AND i.indisready "
7143 "ORDER BY indexname",
7144 tbinfo->dobj.catId.oid);
7146 else if (fout->remoteVersion >= 90400)
7149 * the test on indisready is necessary in 9.2, and harmless in
7150 * earlier/later versions
7152 appendPQExpBuffer(query,
7153 "SELECT t.tableoid, t.oid, "
7154 "t.relname AS indexname, "
7155 "0 AS parentidx, "
7156 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7157 "i.indnatts AS indnkeyatts, "
7158 "i.indnatts AS indnatts, "
7159 "i.indkey, i.indisclustered, "
7160 "i.indisreplident, "
7161 "c.contype, c.conname, "
7162 "c.condeferrable, c.condeferred, "
7163 "c.tableoid AS contableoid, "
7164 "c.oid AS conoid, "
7165 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7166 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7167 "t.reloptions AS indreloptions, "
7168 "'' AS indstatcols, "
7169 "'' AS indstatvals "
7170 "FROM pg_catalog.pg_index i "
7171 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7172 "LEFT JOIN pg_catalog.pg_constraint c "
7173 "ON (i.indrelid = c.conrelid AND "
7174 "i.indexrelid = c.conindid AND "
7175 "c.contype IN ('p','u','x')) "
7176 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7177 "AND i.indisvalid AND i.indisready "
7178 "ORDER BY indexname",
7179 tbinfo->dobj.catId.oid);
7181 else if (fout->remoteVersion >= 90000)
7184 * the test on indisready is necessary in 9.2, and harmless in
7185 * earlier/later versions
7187 appendPQExpBuffer(query,
7188 "SELECT t.tableoid, t.oid, "
7189 "t.relname AS indexname, "
7190 "0 AS parentidx, "
7191 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7192 "i.indnatts AS indnkeyatts, "
7193 "i.indnatts AS indnatts, "
7194 "i.indkey, i.indisclustered, "
7195 "false AS indisreplident, "
7196 "c.contype, c.conname, "
7197 "c.condeferrable, c.condeferred, "
7198 "c.tableoid AS contableoid, "
7199 "c.oid AS conoid, "
7200 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7201 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7202 "t.reloptions AS indreloptions, "
7203 "'' AS indstatcols, "
7204 "'' AS indstatvals "
7205 "FROM pg_catalog.pg_index i "
7206 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7207 "LEFT JOIN pg_catalog.pg_constraint c "
7208 "ON (i.indrelid = c.conrelid AND "
7209 "i.indexrelid = c.conindid AND "
7210 "c.contype IN ('p','u','x')) "
7211 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7212 "AND i.indisvalid AND i.indisready "
7213 "ORDER BY indexname",
7214 tbinfo->dobj.catId.oid);
7216 else if (fout->remoteVersion >= 80200)
7218 appendPQExpBuffer(query,
7219 "SELECT t.tableoid, t.oid, "
7220 "t.relname AS indexname, "
7221 "0 AS parentidx, "
7222 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7223 "i.indnatts AS indnkeyatts, "
7224 "i.indnatts AS indnatts, "
7225 "i.indkey, i.indisclustered, "
7226 "false AS indisreplident, "
7227 "c.contype, c.conname, "
7228 "c.condeferrable, c.condeferred, "
7229 "c.tableoid AS contableoid, "
7230 "c.oid AS conoid, "
7231 "null AS condef, "
7232 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7233 "t.reloptions AS indreloptions, "
7234 "'' AS indstatcols, "
7235 "'' AS indstatvals "
7236 "FROM pg_catalog.pg_index i "
7237 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7238 "LEFT JOIN pg_catalog.pg_depend d "
7239 "ON (d.classid = t.tableoid "
7240 "AND d.objid = t.oid "
7241 "AND d.deptype = 'i') "
7242 "LEFT JOIN pg_catalog.pg_constraint c "
7243 "ON (d.refclassid = c.tableoid "
7244 "AND d.refobjid = c.oid) "
7245 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7246 "AND i.indisvalid "
7247 "ORDER BY indexname",
7248 tbinfo->dobj.catId.oid);
7250 else
7252 appendPQExpBuffer(query,
7253 "SELECT t.tableoid, t.oid, "
7254 "t.relname AS indexname, "
7255 "0 AS parentidx, "
7256 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7257 "t.relnatts AS indnkeyatts, "
7258 "t.relnatts AS indnatts, "
7259 "i.indkey, i.indisclustered, "
7260 "false AS indisreplident, "
7261 "c.contype, c.conname, "
7262 "c.condeferrable, c.condeferred, "
7263 "c.tableoid AS contableoid, "
7264 "c.oid AS conoid, "
7265 "null AS condef, "
7266 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7267 "null AS indreloptions, "
7268 "'' AS indstatcols, "
7269 "'' AS indstatvals "
7270 "FROM pg_catalog.pg_index i "
7271 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7272 "LEFT JOIN pg_catalog.pg_depend d "
7273 "ON (d.classid = t.tableoid "
7274 "AND d.objid = t.oid "
7275 "AND d.deptype = 'i') "
7276 "LEFT JOIN pg_catalog.pg_constraint c "
7277 "ON (d.refclassid = c.tableoid "
7278 "AND d.refobjid = c.oid) "
7279 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7280 "ORDER BY indexname",
7281 tbinfo->dobj.catId.oid);
7284 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7286 ntups = PQntuples(res);
7288 i_tableoid = PQfnumber(res, "tableoid");
7289 i_oid = PQfnumber(res, "oid");
7290 i_indexname = PQfnumber(res, "indexname");
7291 i_parentidx = PQfnumber(res, "parentidx");
7292 i_indexdef = PQfnumber(res, "indexdef");
7293 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
7294 i_indnatts = PQfnumber(res, "indnatts");
7295 i_indkey = PQfnumber(res, "indkey");
7296 i_indisclustered = PQfnumber(res, "indisclustered");
7297 i_indisreplident = PQfnumber(res, "indisreplident");
7298 i_contype = PQfnumber(res, "contype");
7299 i_conname = PQfnumber(res, "conname");
7300 i_condeferrable = PQfnumber(res, "condeferrable");
7301 i_condeferred = PQfnumber(res, "condeferred");
7302 i_contableoid = PQfnumber(res, "contableoid");
7303 i_conoid = PQfnumber(res, "conoid");
7304 i_condef = PQfnumber(res, "condef");
7305 i_tablespace = PQfnumber(res, "tablespace");
7306 i_indreloptions = PQfnumber(res, "indreloptions");
7307 i_indstatcols = PQfnumber(res, "indstatcols");
7308 i_indstatvals = PQfnumber(res, "indstatvals");
7310 tbinfo->indexes = indxinfo =
7311 (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
7312 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7313 tbinfo->numIndexes = ntups;
7315 for (j = 0; j < ntups; j++)
7317 char contype;
7319 indxinfo[j].dobj.objType = DO_INDEX;
7320 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7321 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7322 AssignDumpId(&indxinfo[j].dobj);
7323 indxinfo[j].dobj.dump = tbinfo->dobj.dump;
7324 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
7325 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7326 indxinfo[j].indextable = tbinfo;
7327 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
7328 indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
7329 indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
7330 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
7331 indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
7332 indxinfo[j].indstatcols = pg_strdup(PQgetvalue(res, j, i_indstatcols));
7333 indxinfo[j].indstatvals = pg_strdup(PQgetvalue(res, j, i_indstatvals));
7334 indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
7335 parseOidArray(PQgetvalue(res, j, i_indkey),
7336 indxinfo[j].indkeys, indxinfo[j].indnattrs);
7337 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
7338 indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
7339 indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
7340 indxinfo[j].partattaches = (SimplePtrList) { NULL, NULL };
7341 contype = *(PQgetvalue(res, j, i_contype));
7343 if (contype == 'p' || contype == 'u' || contype == 'x')
7346 * If we found a constraint matching the index, create an
7347 * entry for it.
7349 constrinfo[j].dobj.objType = DO_CONSTRAINT;
7350 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7351 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7352 AssignDumpId(&constrinfo[j].dobj);
7353 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
7354 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7355 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7356 constrinfo[j].contable = tbinfo;
7357 constrinfo[j].condomain = NULL;
7358 constrinfo[j].contype = contype;
7359 if (contype == 'x')
7360 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7361 else
7362 constrinfo[j].condef = NULL;
7363 constrinfo[j].confrelid = InvalidOid;
7364 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7365 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7366 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7367 constrinfo[j].conislocal = true;
7368 constrinfo[j].separate = true;
7370 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7372 else
7374 /* Plain secondary index */
7375 indxinfo[j].indexconstraint = 0;
7379 PQclear(res);
7382 destroyPQExpBuffer(query);
7386 * getExtendedStatistics
7387 * get information about extended-statistics objects.
7389 * Note: extended statistics data is not returned directly to the caller, but
7390 * it does get entered into the DumpableObject tables.
7392 void
7393 getExtendedStatistics(Archive *fout)
7395 PQExpBuffer query;
7396 PGresult *res;
7397 StatsExtInfo *statsextinfo;
7398 int ntups;
7399 int i_tableoid;
7400 int i_oid;
7401 int i_stxname;
7402 int i_stxnamespace;
7403 int i_rolname;
7404 int i_stxrelid;
7405 int i;
7407 /* Extended statistics were new in v10 */
7408 if (fout->remoteVersion < 100000)
7409 return;
7411 query = createPQExpBuffer();
7413 appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7414 "stxnamespace, (%s stxowner) AS rolname, stxrelid "
7415 "FROM pg_catalog.pg_statistic_ext",
7416 username_subquery);
7418 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7420 ntups = PQntuples(res);
7422 i_tableoid = PQfnumber(res, "tableoid");
7423 i_oid = PQfnumber(res, "oid");
7424 i_stxname = PQfnumber(res, "stxname");
7425 i_stxnamespace = PQfnumber(res, "stxnamespace");
7426 i_rolname = PQfnumber(res, "rolname");
7427 i_stxrelid = PQfnumber(res, "stxrelid");
7429 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7431 for (i = 0; i < ntups; i++)
7433 statsextinfo[i].dobj.objType = DO_STATSEXT;
7434 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7435 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7436 AssignDumpId(&statsextinfo[i].dobj);
7437 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7438 statsextinfo[i].dobj.namespace =
7439 findNamespace(fout,
7440 atooid(PQgetvalue(res, i, i_stxnamespace)));
7441 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7442 statsextinfo[i].stattable =
7443 findTableByOid(atooid(PQgetvalue(res, i, i_stxrelid)));
7445 /* Decide whether we want to dump it */
7446 selectDumpableStatisticsObject(&(statsextinfo[i]), fout);
7448 /* Stats objects do not currently have ACLs. */
7449 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7452 PQclear(res);
7453 destroyPQExpBuffer(query);
7457 * getConstraints
7459 * Get info about constraints on dumpable tables.
7461 * Currently handles foreign keys only.
7462 * Unique and primary key constraints are handled with indexes,
7463 * while check constraints are processed in getTableAttrs().
7465 void
7466 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7468 int i,
7470 ConstraintInfo *constrinfo;
7471 PQExpBuffer query;
7472 PGresult *res;
7473 int i_contableoid,
7474 i_conoid,
7475 i_conname,
7476 i_confrelid,
7477 i_conindid,
7478 i_condef;
7479 int ntups;
7481 query = createPQExpBuffer();
7483 for (i = 0; i < numTables; i++)
7485 TableInfo *tbinfo = &tblinfo[i];
7488 * For partitioned tables, foreign keys have no triggers so they must
7489 * be included anyway in case some foreign keys are defined.
7491 if ((!tbinfo->hastriggers &&
7492 tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7493 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7494 continue;
7496 pg_log_info("reading foreign key constraints for table \"%s.%s\"",
7497 tbinfo->dobj.namespace->dobj.name,
7498 tbinfo->dobj.name);
7500 resetPQExpBuffer(query);
7501 if (fout->remoteVersion >= 110000)
7502 appendPQExpBuffer(query,
7503 "SELECT tableoid, oid, conname, confrelid, conindid, "
7504 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7505 "FROM pg_catalog.pg_constraint "
7506 "WHERE conrelid = '%u'::pg_catalog.oid "
7507 "AND conparentid = 0 "
7508 "AND contype = 'f'",
7509 tbinfo->dobj.catId.oid);
7510 else
7511 appendPQExpBuffer(query,
7512 "SELECT tableoid, oid, conname, confrelid, 0 as conindid, "
7513 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7514 "FROM pg_catalog.pg_constraint "
7515 "WHERE conrelid = '%u'::pg_catalog.oid "
7516 "AND contype = 'f'",
7517 tbinfo->dobj.catId.oid);
7518 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7520 ntups = PQntuples(res);
7522 i_contableoid = PQfnumber(res, "tableoid");
7523 i_conoid = PQfnumber(res, "oid");
7524 i_conname = PQfnumber(res, "conname");
7525 i_confrelid = PQfnumber(res, "confrelid");
7526 i_conindid = PQfnumber(res, "conindid");
7527 i_condef = PQfnumber(res, "condef");
7529 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7531 for (j = 0; j < ntups; j++)
7533 TableInfo *reftable;
7535 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7536 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7537 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7538 AssignDumpId(&constrinfo[j].dobj);
7539 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7540 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7541 constrinfo[j].contable = tbinfo;
7542 constrinfo[j].condomain = NULL;
7543 constrinfo[j].contype = 'f';
7544 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7545 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7546 constrinfo[j].conindex = 0;
7547 constrinfo[j].condeferrable = false;
7548 constrinfo[j].condeferred = false;
7549 constrinfo[j].conislocal = true;
7550 constrinfo[j].separate = true;
7553 * Restoring an FK that points to a partitioned table requires
7554 * that all partition indexes have been attached beforehand.
7555 * Ensure that happens by making the constraint depend on each
7556 * index partition attach object.
7558 reftable = findTableByOid(constrinfo[j].confrelid);
7559 if (reftable && reftable->relkind == RELKIND_PARTITIONED_TABLE)
7561 Oid indexOid = atooid(PQgetvalue(res, j, i_conindid));
7563 if (indexOid != InvalidOid)
7565 for (int k = 0; k < reftable->numIndexes; k++)
7567 IndxInfo *refidx;
7569 /* not our index? */
7570 if (reftable->indexes[k].dobj.catId.oid != indexOid)
7571 continue;
7573 refidx = &reftable->indexes[k];
7574 addConstrChildIdxDeps(&constrinfo[j].dobj, refidx);
7575 break;
7581 PQclear(res);
7584 destroyPQExpBuffer(query);
7588 * addConstrChildIdxDeps
7590 * Recursive subroutine for getConstraints
7592 * Given an object representing a foreign key constraint and an index on the
7593 * partitioned table it references, mark the constraint object as dependent
7594 * on each partition, recursing to children until all leaves are found.
7595 * This ensures that the FK is not restored until the index is fully marked
7596 * valid.
7598 static void
7599 addConstrChildIdxDeps(DumpableObject *dobj, IndxInfo *refidx)
7601 SimplePtrListCell *cell;
7603 Assert(dobj->objType == DO_FK_CONSTRAINT);
7605 for (cell = refidx->partattaches.head; cell; cell = cell->next)
7607 DumpableObject *childobj = (DumpableObject *) cell->ptr;
7608 IndexAttachInfo *attach;
7610 addObjectDependency(dobj, childobj->dumpId);
7612 attach = (IndexAttachInfo *) childobj;
7613 if (attach->partitionIdx->partattaches.head != NULL)
7614 addConstrChildIdxDeps(dobj, attach->partitionIdx);
7619 * getDomainConstraints
7621 * Get info about constraints on a domain.
7623 static void
7624 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7626 int i;
7627 ConstraintInfo *constrinfo;
7628 PQExpBuffer query;
7629 PGresult *res;
7630 int i_tableoid,
7631 i_oid,
7632 i_conname,
7633 i_consrc;
7634 int ntups;
7636 query = createPQExpBuffer();
7638 if (fout->remoteVersion >= 90100)
7639 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7640 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7641 "convalidated "
7642 "FROM pg_catalog.pg_constraint "
7643 "WHERE contypid = '%u'::pg_catalog.oid "
7644 "ORDER BY conname",
7645 tyinfo->dobj.catId.oid);
7647 else
7648 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7649 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7650 "true as convalidated "
7651 "FROM pg_catalog.pg_constraint "
7652 "WHERE contypid = '%u'::pg_catalog.oid "
7653 "ORDER BY conname",
7654 tyinfo->dobj.catId.oid);
7656 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7658 ntups = PQntuples(res);
7660 i_tableoid = PQfnumber(res, "tableoid");
7661 i_oid = PQfnumber(res, "oid");
7662 i_conname = PQfnumber(res, "conname");
7663 i_consrc = PQfnumber(res, "consrc");
7665 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7667 tyinfo->nDomChecks = ntups;
7668 tyinfo->domChecks = constrinfo;
7670 for (i = 0; i < ntups; i++)
7672 bool validated = PQgetvalue(res, i, 4)[0] == 't';
7674 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7675 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7676 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7677 AssignDumpId(&constrinfo[i].dobj);
7678 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7679 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7680 constrinfo[i].contable = NULL;
7681 constrinfo[i].condomain = tyinfo;
7682 constrinfo[i].contype = 'c';
7683 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7684 constrinfo[i].confrelid = InvalidOid;
7685 constrinfo[i].conindex = 0;
7686 constrinfo[i].condeferrable = false;
7687 constrinfo[i].condeferred = false;
7688 constrinfo[i].conislocal = true;
7690 constrinfo[i].separate = !validated;
7693 * Make the domain depend on the constraint, ensuring it won't be
7694 * output till any constraint dependencies are OK. If the constraint
7695 * has not been validated, it's going to be dumped after the domain
7696 * anyway, so this doesn't matter.
7698 if (validated)
7699 addObjectDependency(&tyinfo->dobj,
7700 constrinfo[i].dobj.dumpId);
7703 PQclear(res);
7705 destroyPQExpBuffer(query);
7709 * getRules
7710 * get basic information about every rule in the system
7712 * numRules is set to the number of rules read in
7714 RuleInfo *
7715 getRules(Archive *fout, int *numRules)
7717 PGresult *res;
7718 int ntups;
7719 int i;
7720 PQExpBuffer query = createPQExpBuffer();
7721 RuleInfo *ruleinfo;
7722 int i_tableoid;
7723 int i_oid;
7724 int i_rulename;
7725 int i_ruletable;
7726 int i_ev_type;
7727 int i_is_instead;
7728 int i_ev_enabled;
7730 if (fout->remoteVersion >= 80300)
7732 appendPQExpBufferStr(query, "SELECT "
7733 "tableoid, oid, rulename, "
7734 "ev_class AS ruletable, ev_type, is_instead, "
7735 "ev_enabled "
7736 "FROM pg_rewrite "
7737 "ORDER BY oid");
7739 else
7741 appendPQExpBufferStr(query, "SELECT "
7742 "tableoid, oid, rulename, "
7743 "ev_class AS ruletable, ev_type, is_instead, "
7744 "'O'::char AS ev_enabled "
7745 "FROM pg_rewrite "
7746 "ORDER BY oid");
7749 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7751 ntups = PQntuples(res);
7753 *numRules = ntups;
7755 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7757 i_tableoid = PQfnumber(res, "tableoid");
7758 i_oid = PQfnumber(res, "oid");
7759 i_rulename = PQfnumber(res, "rulename");
7760 i_ruletable = PQfnumber(res, "ruletable");
7761 i_ev_type = PQfnumber(res, "ev_type");
7762 i_is_instead = PQfnumber(res, "is_instead");
7763 i_ev_enabled = PQfnumber(res, "ev_enabled");
7765 for (i = 0; i < ntups; i++)
7767 Oid ruletableoid;
7769 ruleinfo[i].dobj.objType = DO_RULE;
7770 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7771 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7772 AssignDumpId(&ruleinfo[i].dobj);
7773 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7774 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7775 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7776 if (ruleinfo[i].ruletable == NULL)
7777 fatal("failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found",
7778 ruletableoid, ruleinfo[i].dobj.catId.oid);
7779 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7780 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7781 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7782 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7783 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7784 if (ruleinfo[i].ruletable)
7787 * If the table is a view or materialized view, force its ON
7788 * SELECT rule to be sorted before the view itself --- this
7789 * ensures that any dependencies for the rule affect the table's
7790 * positioning. Other rules are forced to appear after their
7791 * table.
7793 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7794 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7795 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7797 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7798 ruleinfo[i].dobj.dumpId);
7799 /* We'll merge the rule into CREATE VIEW, if possible */
7800 ruleinfo[i].separate = false;
7802 else
7804 addObjectDependency(&ruleinfo[i].dobj,
7805 ruleinfo[i].ruletable->dobj.dumpId);
7806 ruleinfo[i].separate = true;
7809 else
7810 ruleinfo[i].separate = true;
7813 PQclear(res);
7815 destroyPQExpBuffer(query);
7817 return ruleinfo;
7821 * getTriggers
7822 * get information about every trigger on a dumpable table
7824 * Note: trigger data is not returned directly to the caller, but it
7825 * does get entered into the DumpableObject tables.
7827 void
7828 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7830 int i,
7832 PQExpBuffer query = createPQExpBuffer();
7833 PGresult *res;
7834 TriggerInfo *tginfo;
7835 int i_tableoid,
7836 i_oid,
7837 i_tgname,
7838 i_tgfname,
7839 i_tgtype,
7840 i_tgnargs,
7841 i_tgargs,
7842 i_tgisconstraint,
7843 i_tgconstrname,
7844 i_tgconstrrelid,
7845 i_tgconstrrelname,
7846 i_tgenabled,
7847 i_tgisinternal,
7848 i_tgdeferrable,
7849 i_tginitdeferred,
7850 i_tgdef;
7851 int ntups;
7853 for (i = 0; i < numTables; i++)
7855 TableInfo *tbinfo = &tblinfo[i];
7857 if (!tbinfo->hastriggers ||
7858 !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7859 continue;
7861 pg_log_info("reading triggers for table \"%s.%s\"",
7862 tbinfo->dobj.namespace->dobj.name,
7863 tbinfo->dobj.name);
7865 resetPQExpBuffer(query);
7866 if (fout->remoteVersion >= 130000)
7869 * NB: think not to use pretty=true in pg_get_triggerdef. It
7870 * could result in non-forward-compatible dumps of WHEN clauses
7871 * due to under-parenthesization.
7873 * NB: We need to see tgisinternal triggers in partitions, in case
7874 * the tgenabled flag has been changed from the parent.
7876 appendPQExpBuffer(query,
7877 "SELECT t.tgname, "
7878 "t.tgfoid::pg_catalog.regproc AS tgfname, "
7879 "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
7880 "t.tgenabled, t.tableoid, t.oid, t.tgisinternal "
7881 "FROM pg_catalog.pg_trigger t "
7882 "LEFT JOIN pg_catalog.pg_trigger u ON u.oid = t.tgparentid "
7883 "WHERE t.tgrelid = '%u'::pg_catalog.oid "
7884 "AND (NOT t.tgisinternal OR t.tgenabled != u.tgenabled)",
7885 tbinfo->dobj.catId.oid);
7887 else if (fout->remoteVersion >= 110000)
7890 * NB: We need to see tgisinternal triggers in partitions, in case
7891 * the tgenabled flag has been changed from the parent. No
7892 * tgparentid in version 11-12, so we have to match them via
7893 * pg_depend.
7895 * See above about pretty=true in pg_get_triggerdef.
7897 appendPQExpBuffer(query,
7898 "SELECT t.tgname, "
7899 "t.tgfoid::pg_catalog.regproc AS tgfname, "
7900 "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
7901 "t.tgenabled, t.tableoid, t.oid, t.tgisinternal "
7902 "FROM pg_catalog.pg_trigger t "
7903 "LEFT JOIN pg_catalog.pg_depend AS d ON "
7904 " d.classid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
7905 " d.refclassid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
7906 " d.objid = t.oid "
7907 "LEFT JOIN pg_catalog.pg_trigger AS pt ON pt.oid = refobjid "
7908 "WHERE t.tgrelid = '%u'::pg_catalog.oid "
7909 "AND (NOT t.tgisinternal%s)",
7910 tbinfo->dobj.catId.oid,
7911 tbinfo->ispartition ?
7912 " OR t.tgenabled != pt.tgenabled" : "");
7914 else if (fout->remoteVersion >= 90000)
7916 /* See above about pretty=true in pg_get_triggerdef */
7917 appendPQExpBuffer(query,
7918 "SELECT t.tgname, "
7919 "t.tgfoid::pg_catalog.regproc AS tgfname, "
7920 "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
7921 "t.tgenabled, false as tgisinternal, "
7922 "t.tableoid, t.oid "
7923 "FROM pg_catalog.pg_trigger t "
7924 "WHERE tgrelid = '%u'::pg_catalog.oid "
7925 "AND NOT tgisinternal",
7926 tbinfo->dobj.catId.oid);
7928 else if (fout->remoteVersion >= 80300)
7931 * We ignore triggers that are tied to a foreign-key constraint
7933 appendPQExpBuffer(query,
7934 "SELECT tgname, "
7935 "tgfoid::pg_catalog.regproc AS tgfname, "
7936 "tgtype, tgnargs, tgargs, tgenabled, "
7937 "false as tgisinternal, "
7938 "tgisconstraint, tgconstrname, tgdeferrable, "
7939 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7940 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7941 "FROM pg_catalog.pg_trigger t "
7942 "WHERE tgrelid = '%u'::pg_catalog.oid "
7943 "AND tgconstraint = 0",
7944 tbinfo->dobj.catId.oid);
7946 else
7949 * We ignore triggers that are tied to a foreign-key constraint,
7950 * but in these versions we have to grovel through pg_constraint
7951 * to find out
7953 appendPQExpBuffer(query,
7954 "SELECT tgname, "
7955 "tgfoid::pg_catalog.regproc AS tgfname, "
7956 "tgtype, tgnargs, tgargs, tgenabled, "
7957 "false as tgisinternal, "
7958 "tgisconstraint, tgconstrname, tgdeferrable, "
7959 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7960 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7961 "FROM pg_catalog.pg_trigger t "
7962 "WHERE tgrelid = '%u'::pg_catalog.oid "
7963 "AND (NOT tgisconstraint "
7964 " OR NOT EXISTS"
7965 " (SELECT 1 FROM pg_catalog.pg_depend d "
7966 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7967 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7968 tbinfo->dobj.catId.oid);
7971 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7973 ntups = PQntuples(res);
7975 i_tableoid = PQfnumber(res, "tableoid");
7976 i_oid = PQfnumber(res, "oid");
7977 i_tgname = PQfnumber(res, "tgname");
7978 i_tgfname = PQfnumber(res, "tgfname");
7979 i_tgtype = PQfnumber(res, "tgtype");
7980 i_tgnargs = PQfnumber(res, "tgnargs");
7981 i_tgargs = PQfnumber(res, "tgargs");
7982 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7983 i_tgconstrname = PQfnumber(res, "tgconstrname");
7984 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7985 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7986 i_tgenabled = PQfnumber(res, "tgenabled");
7987 i_tgisinternal = PQfnumber(res, "tgisinternal");
7988 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7989 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7990 i_tgdef = PQfnumber(res, "tgdef");
7992 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7994 tbinfo->numTriggers = ntups;
7995 tbinfo->triggers = tginfo;
7997 for (j = 0; j < ntups; j++)
7999 tginfo[j].dobj.objType = DO_TRIGGER;
8000 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
8001 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
8002 AssignDumpId(&tginfo[j].dobj);
8003 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
8004 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
8005 tginfo[j].tgtable = tbinfo;
8006 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
8007 tginfo[j].tgisinternal = *(PQgetvalue(res, j, i_tgisinternal)) == 't';
8008 if (i_tgdef >= 0)
8010 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
8012 /* remaining fields are not valid if we have tgdef */
8013 tginfo[j].tgfname = NULL;
8014 tginfo[j].tgtype = 0;
8015 tginfo[j].tgnargs = 0;
8016 tginfo[j].tgargs = NULL;
8017 tginfo[j].tgisconstraint = false;
8018 tginfo[j].tgdeferrable = false;
8019 tginfo[j].tginitdeferred = false;
8020 tginfo[j].tgconstrname = NULL;
8021 tginfo[j].tgconstrrelid = InvalidOid;
8022 tginfo[j].tgconstrrelname = NULL;
8024 else
8026 tginfo[j].tgdef = NULL;
8028 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
8029 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
8030 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
8031 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
8032 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
8033 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
8034 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
8036 if (tginfo[j].tgisconstraint)
8038 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
8039 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
8040 if (OidIsValid(tginfo[j].tgconstrrelid))
8042 if (PQgetisnull(res, j, i_tgconstrrelname))
8043 fatal("query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)",
8044 tginfo[j].dobj.name,
8045 tbinfo->dobj.name,
8046 tginfo[j].tgconstrrelid);
8047 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
8049 else
8050 tginfo[j].tgconstrrelname = NULL;
8052 else
8054 tginfo[j].tgconstrname = NULL;
8055 tginfo[j].tgconstrrelid = InvalidOid;
8056 tginfo[j].tgconstrrelname = NULL;
8061 PQclear(res);
8064 destroyPQExpBuffer(query);
8068 * getEventTriggers
8069 * get information about event triggers
8071 EventTriggerInfo *
8072 getEventTriggers(Archive *fout, int *numEventTriggers)
8074 int i;
8075 PQExpBuffer query;
8076 PGresult *res;
8077 EventTriggerInfo *evtinfo;
8078 int i_tableoid,
8079 i_oid,
8080 i_evtname,
8081 i_evtevent,
8082 i_evtowner,
8083 i_evttags,
8084 i_evtfname,
8085 i_evtenabled;
8086 int ntups;
8088 /* Before 9.3, there are no event triggers */
8089 if (fout->remoteVersion < 90300)
8091 *numEventTriggers = 0;
8092 return NULL;
8095 query = createPQExpBuffer();
8097 appendPQExpBuffer(query,
8098 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
8099 "evtevent, (%s evtowner) AS evtowner, "
8100 "array_to_string(array("
8101 "select quote_literal(x) "
8102 " from unnest(evttags) as t(x)), ', ') as evttags, "
8103 "e.evtfoid::regproc as evtfname "
8104 "FROM pg_event_trigger e "
8105 "ORDER BY e.oid",
8106 username_subquery);
8108 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8110 ntups = PQntuples(res);
8112 *numEventTriggers = ntups;
8114 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
8116 i_tableoid = PQfnumber(res, "tableoid");
8117 i_oid = PQfnumber(res, "oid");
8118 i_evtname = PQfnumber(res, "evtname");
8119 i_evtevent = PQfnumber(res, "evtevent");
8120 i_evtowner = PQfnumber(res, "evtowner");
8121 i_evttags = PQfnumber(res, "evttags");
8122 i_evtfname = PQfnumber(res, "evtfname");
8123 i_evtenabled = PQfnumber(res, "evtenabled");
8125 for (i = 0; i < ntups; i++)
8127 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
8128 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8129 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8130 AssignDumpId(&evtinfo[i].dobj);
8131 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
8132 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
8133 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
8134 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
8135 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
8136 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
8137 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
8139 /* Decide whether we want to dump it */
8140 selectDumpableObject(&(evtinfo[i].dobj), fout);
8142 /* Event Triggers do not currently have ACLs. */
8143 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8146 PQclear(res);
8148 destroyPQExpBuffer(query);
8150 return evtinfo;
8154 * getProcLangs
8155 * get basic information about every procedural language in the system
8157 * numProcLangs is set to the number of langs read in
8159 * NB: this must run after getFuncs() because we assume we can do
8160 * findFuncByOid().
8162 ProcLangInfo *
8163 getProcLangs(Archive *fout, int *numProcLangs)
8165 DumpOptions *dopt = fout->dopt;
8166 PGresult *res;
8167 int ntups;
8168 int i;
8169 PQExpBuffer query = createPQExpBuffer();
8170 ProcLangInfo *planginfo;
8171 int i_tableoid;
8172 int i_oid;
8173 int i_lanname;
8174 int i_lanpltrusted;
8175 int i_lanplcallfoid;
8176 int i_laninline;
8177 int i_lanvalidator;
8178 int i_lanacl;
8179 int i_rlanacl;
8180 int i_initlanacl;
8181 int i_initrlanacl;
8182 int i_lanowner;
8184 if (fout->remoteVersion >= 90600)
8186 PQExpBuffer acl_subquery = createPQExpBuffer();
8187 PQExpBuffer racl_subquery = createPQExpBuffer();
8188 PQExpBuffer initacl_subquery = createPQExpBuffer();
8189 PQExpBuffer initracl_subquery = createPQExpBuffer();
8191 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8192 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
8193 dopt->binary_upgrade);
8195 /* pg_language has a laninline column */
8196 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
8197 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
8198 "l.laninline, l.lanvalidator, "
8199 "%s AS lanacl, "
8200 "%s AS rlanacl, "
8201 "%s AS initlanacl, "
8202 "%s AS initrlanacl, "
8203 "(%s l.lanowner) AS lanowner "
8204 "FROM pg_language l "
8205 "LEFT JOIN pg_init_privs pip ON "
8206 "(l.oid = pip.objoid "
8207 "AND pip.classoid = 'pg_language'::regclass "
8208 "AND pip.objsubid = 0) "
8209 "WHERE l.lanispl "
8210 "ORDER BY l.oid",
8211 acl_subquery->data,
8212 racl_subquery->data,
8213 initacl_subquery->data,
8214 initracl_subquery->data,
8215 username_subquery);
8217 destroyPQExpBuffer(acl_subquery);
8218 destroyPQExpBuffer(racl_subquery);
8219 destroyPQExpBuffer(initacl_subquery);
8220 destroyPQExpBuffer(initracl_subquery);
8222 else if (fout->remoteVersion >= 90000)
8224 /* pg_language has a laninline column */
8225 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8226 "lanname, lanpltrusted, lanplcallfoid, "
8227 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
8228 "NULL AS initlanacl, NULL AS initrlanacl, "
8229 "(%s lanowner) AS lanowner "
8230 "FROM pg_language "
8231 "WHERE lanispl "
8232 "ORDER BY oid",
8233 username_subquery);
8235 else if (fout->remoteVersion >= 80300)
8237 /* pg_language has a lanowner column */
8238 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8239 "lanname, lanpltrusted, lanplcallfoid, "
8240 "0 AS laninline, lanvalidator, lanacl, "
8241 "NULL AS rlanacl, "
8242 "NULL AS initlanacl, NULL AS initrlanacl, "
8243 "(%s lanowner) AS lanowner "
8244 "FROM pg_language "
8245 "WHERE lanispl "
8246 "ORDER BY oid",
8247 username_subquery);
8249 else if (fout->remoteVersion >= 80100)
8251 /* Languages are owned by the bootstrap superuser, OID 10 */
8252 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8253 "lanname, lanpltrusted, lanplcallfoid, "
8254 "0 AS laninline, lanvalidator, lanacl, "
8255 "NULL AS rlanacl, "
8256 "NULL AS initlanacl, NULL AS initrlanacl, "
8257 "(%s '10') AS lanowner "
8258 "FROM pg_language "
8259 "WHERE lanispl "
8260 "ORDER BY oid",
8261 username_subquery);
8263 else
8265 /* Languages are owned by the bootstrap superuser, sysid 1 */
8266 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8267 "lanname, lanpltrusted, lanplcallfoid, "
8268 "0 AS laninline, lanvalidator, lanacl, "
8269 "NULL AS rlanacl, "
8270 "NULL AS initlanacl, NULL AS initrlanacl, "
8271 "(%s '1') AS lanowner "
8272 "FROM pg_language "
8273 "WHERE lanispl "
8274 "ORDER BY oid",
8275 username_subquery);
8278 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8280 ntups = PQntuples(res);
8282 *numProcLangs = ntups;
8284 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
8286 i_tableoid = PQfnumber(res, "tableoid");
8287 i_oid = PQfnumber(res, "oid");
8288 i_lanname = PQfnumber(res, "lanname");
8289 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
8290 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
8291 i_laninline = PQfnumber(res, "laninline");
8292 i_lanvalidator = PQfnumber(res, "lanvalidator");
8293 i_lanacl = PQfnumber(res, "lanacl");
8294 i_rlanacl = PQfnumber(res, "rlanacl");
8295 i_initlanacl = PQfnumber(res, "initlanacl");
8296 i_initrlanacl = PQfnumber(res, "initrlanacl");
8297 i_lanowner = PQfnumber(res, "lanowner");
8299 for (i = 0; i < ntups; i++)
8301 planginfo[i].dobj.objType = DO_PROCLANG;
8302 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8303 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8304 AssignDumpId(&planginfo[i].dobj);
8306 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
8307 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
8308 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
8309 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
8310 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
8311 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
8312 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
8313 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
8314 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
8315 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
8317 /* Decide whether we want to dump it */
8318 selectDumpableProcLang(&(planginfo[i]), fout);
8320 /* Do not try to dump ACL if no ACL exists. */
8321 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
8322 PQgetisnull(res, i, i_initlanacl) &&
8323 PQgetisnull(res, i, i_initrlanacl))
8324 planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8327 PQclear(res);
8329 destroyPQExpBuffer(query);
8331 return planginfo;
8335 * getCasts
8336 * get basic information about every cast in the system
8338 * numCasts is set to the number of casts read in
8340 CastInfo *
8341 getCasts(Archive *fout, int *numCasts)
8343 PGresult *res;
8344 int ntups;
8345 int i;
8346 PQExpBuffer query = createPQExpBuffer();
8347 CastInfo *castinfo;
8348 int i_tableoid;
8349 int i_oid;
8350 int i_castsource;
8351 int i_casttarget;
8352 int i_castfunc;
8353 int i_castcontext;
8354 int i_castmethod;
8356 if (fout->remoteVersion >= 80400)
8358 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8359 "castsource, casttarget, castfunc, castcontext, "
8360 "castmethod "
8361 "FROM pg_cast ORDER BY 3,4");
8363 else
8365 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8366 "castsource, casttarget, castfunc, castcontext, "
8367 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
8368 "FROM pg_cast ORDER BY 3,4");
8371 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8373 ntups = PQntuples(res);
8375 *numCasts = ntups;
8377 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
8379 i_tableoid = PQfnumber(res, "tableoid");
8380 i_oid = PQfnumber(res, "oid");
8381 i_castsource = PQfnumber(res, "castsource");
8382 i_casttarget = PQfnumber(res, "casttarget");
8383 i_castfunc = PQfnumber(res, "castfunc");
8384 i_castcontext = PQfnumber(res, "castcontext");
8385 i_castmethod = PQfnumber(res, "castmethod");
8387 for (i = 0; i < ntups; i++)
8389 PQExpBufferData namebuf;
8390 TypeInfo *sTypeInfo;
8391 TypeInfo *tTypeInfo;
8393 castinfo[i].dobj.objType = DO_CAST;
8394 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8395 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8396 AssignDumpId(&castinfo[i].dobj);
8397 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
8398 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
8399 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
8400 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
8401 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
8404 * Try to name cast as concatenation of typnames. This is only used
8405 * for purposes of sorting. If we fail to find either type, the name
8406 * will be an empty string.
8408 initPQExpBuffer(&namebuf);
8409 sTypeInfo = findTypeByOid(castinfo[i].castsource);
8410 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
8411 if (sTypeInfo && tTypeInfo)
8412 appendPQExpBuffer(&namebuf, "%s %s",
8413 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
8414 castinfo[i].dobj.name = namebuf.data;
8416 /* Decide whether we want to dump it */
8417 selectDumpableCast(&(castinfo[i]), fout);
8419 /* Casts do not currently have ACLs. */
8420 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8423 PQclear(res);
8425 destroyPQExpBuffer(query);
8427 return castinfo;
8430 static char *
8431 get_language_name(Archive *fout, Oid langid)
8433 PQExpBuffer query;
8434 PGresult *res;
8435 char *lanname;
8437 query = createPQExpBuffer();
8438 appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
8439 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8440 lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
8441 destroyPQExpBuffer(query);
8442 PQclear(res);
8444 return lanname;
8448 * getTransforms
8449 * get basic information about every transform in the system
8451 * numTransforms is set to the number of transforms read in
8453 TransformInfo *
8454 getTransforms(Archive *fout, int *numTransforms)
8456 PGresult *res;
8457 int ntups;
8458 int i;
8459 PQExpBuffer query;
8460 TransformInfo *transforminfo;
8461 int i_tableoid;
8462 int i_oid;
8463 int i_trftype;
8464 int i_trflang;
8465 int i_trffromsql;
8466 int i_trftosql;
8468 /* Transforms didn't exist pre-9.5 */
8469 if (fout->remoteVersion < 90500)
8471 *numTransforms = 0;
8472 return NULL;
8475 query = createPQExpBuffer();
8477 appendPQExpBuffer(query, "SELECT tableoid, oid, "
8478 "trftype, trflang, trffromsql::oid, trftosql::oid "
8479 "FROM pg_transform "
8480 "ORDER BY 3,4");
8482 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8484 ntups = PQntuples(res);
8486 *numTransforms = ntups;
8488 transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8490 i_tableoid = PQfnumber(res, "tableoid");
8491 i_oid = PQfnumber(res, "oid");
8492 i_trftype = PQfnumber(res, "trftype");
8493 i_trflang = PQfnumber(res, "trflang");
8494 i_trffromsql = PQfnumber(res, "trffromsql");
8495 i_trftosql = PQfnumber(res, "trftosql");
8497 for (i = 0; i < ntups; i++)
8499 PQExpBufferData namebuf;
8500 TypeInfo *typeInfo;
8501 char *lanname;
8503 transforminfo[i].dobj.objType = DO_TRANSFORM;
8504 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8505 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8506 AssignDumpId(&transforminfo[i].dobj);
8507 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8508 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8509 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8510 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8513 * Try to name transform as concatenation of type and language name.
8514 * This is only used for purposes of sorting. If we fail to find
8515 * either, the name will be an empty string.
8517 initPQExpBuffer(&namebuf);
8518 typeInfo = findTypeByOid(transforminfo[i].trftype);
8519 lanname = get_language_name(fout, transforminfo[i].trflang);
8520 if (typeInfo && lanname)
8521 appendPQExpBuffer(&namebuf, "%s %s",
8522 typeInfo->dobj.name, lanname);
8523 transforminfo[i].dobj.name = namebuf.data;
8524 free(lanname);
8526 /* Decide whether we want to dump it */
8527 selectDumpableObject(&(transforminfo[i].dobj), fout);
8530 PQclear(res);
8532 destroyPQExpBuffer(query);
8534 return transforminfo;
8538 * getTableAttrs -
8539 * for each interesting table, read info about its attributes
8540 * (names, types, default values, CHECK constraints, etc)
8542 * This is implemented in a very inefficient way right now, looping
8543 * through the tblinfo and doing a join per table to find the attrs and their
8544 * types. However, because we want type names and so forth to be named
8545 * relative to the schema of each table, we couldn't do it in just one
8546 * query. (Maybe one query per schema?)
8548 * modifies tblinfo
8550 void
8551 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8553 DumpOptions *dopt = fout->dopt;
8554 int i,
8556 PQExpBuffer q = createPQExpBuffer();
8557 int i_attnum;
8558 int i_attname;
8559 int i_atttypname;
8560 int i_atttypmod;
8561 int i_attstattarget;
8562 int i_attstorage;
8563 int i_typstorage;
8564 int i_attnotnull;
8565 int i_atthasdef;
8566 int i_attidentity;
8567 int i_attgenerated;
8568 int i_attisdropped;
8569 int i_attlen;
8570 int i_attalign;
8571 int i_attislocal;
8572 int i_attoptions;
8573 int i_attcollation;
8574 int i_attfdwoptions;
8575 int i_attmissingval;
8576 PGresult *res;
8577 int ntups;
8578 bool hasdefaults;
8580 for (i = 0; i < numTables; i++)
8582 TableInfo *tbinfo = &tblinfo[i];
8584 /* Don't bother to collect info for sequences */
8585 if (tbinfo->relkind == RELKIND_SEQUENCE)
8586 continue;
8588 /* Don't bother with uninteresting tables, either */
8589 if (!tbinfo->interesting)
8590 continue;
8592 /* find all the user attributes and their types */
8595 * we must read the attribute names in attribute number order! because
8596 * we will use the attnum to index into the attnames array later.
8598 pg_log_info("finding the columns and types of table \"%s.%s\"",
8599 tbinfo->dobj.namespace->dobj.name,
8600 tbinfo->dobj.name);
8602 resetPQExpBuffer(q);
8604 appendPQExpBuffer(q,
8605 "SELECT\n"
8606 "a.attnum,\n"
8607 "a.attname,\n"
8608 "a.atttypmod,\n"
8609 "a.attstattarget,\n"
8610 "a.attstorage,\n"
8611 "t.typstorage,\n"
8612 "a.attnotnull,\n"
8613 "a.atthasdef,\n"
8614 "a.attisdropped,\n"
8615 "a.attlen,\n"
8616 "a.attalign,\n"
8617 "a.attislocal,\n"
8618 "pg_catalog.format_type(t.oid, a.atttypmod) AS atttypname,\n");
8620 if (fout->remoteVersion >= 120000)
8621 appendPQExpBuffer(q,
8622 "a.attgenerated,\n");
8623 else
8624 appendPQExpBuffer(q,
8625 "'' AS attgenerated,\n");
8627 if (fout->remoteVersion >= 110000)
8628 appendPQExpBuffer(q,
8629 "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8630 "THEN a.attmissingval ELSE null END AS attmissingval,\n");
8631 else
8632 appendPQExpBuffer(q,
8633 "NULL AS attmissingval,\n");
8635 if (fout->remoteVersion >= 100000)
8636 appendPQExpBuffer(q,
8637 "a.attidentity,\n");
8638 else
8639 appendPQExpBuffer(q,
8640 "'' AS attidentity,\n");
8642 if (fout->remoteVersion >= 90200)
8643 appendPQExpBuffer(q,
8644 "pg_catalog.array_to_string(ARRAY("
8645 "SELECT pg_catalog.quote_ident(option_name) || "
8646 "' ' || pg_catalog.quote_literal(option_value) "
8647 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8648 "ORDER BY option_name"
8649 "), E',\n ') AS attfdwoptions,\n");
8650 else
8651 appendPQExpBuffer(q,
8652 "'' AS attfdwoptions,\n");
8654 if (fout->remoteVersion >= 90100)
8657 * Since we only want to dump COLLATE clauses for attributes whose
8658 * collation is different from their type's default, we use a CASE
8659 * here to suppress uninteresting attcollations cheaply.
8661 appendPQExpBuffer(q,
8662 "CASE WHEN a.attcollation <> t.typcollation "
8663 "THEN a.attcollation ELSE 0 END AS attcollation,\n");
8665 else
8666 appendPQExpBuffer(q,
8667 "0 AS attcollation,\n");
8669 if (fout->remoteVersion >= 90000)
8670 appendPQExpBuffer(q,
8671 "array_to_string(a.attoptions, ', ') AS attoptions\n");
8672 else
8673 appendPQExpBuffer(q,
8674 "'' AS attoptions\n");
8676 /* need left join here to not fail on dropped columns ... */
8677 appendPQExpBuffer(q,
8678 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8679 "ON a.atttypid = t.oid\n"
8680 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8681 "AND a.attnum > 0::pg_catalog.int2\n"
8682 "ORDER BY a.attnum",
8683 tbinfo->dobj.catId.oid);
8685 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8687 ntups = PQntuples(res);
8689 i_attnum = PQfnumber(res, "attnum");
8690 i_attname = PQfnumber(res, "attname");
8691 i_atttypname = PQfnumber(res, "atttypname");
8692 i_atttypmod = PQfnumber(res, "atttypmod");
8693 i_attstattarget = PQfnumber(res, "attstattarget");
8694 i_attstorage = PQfnumber(res, "attstorage");
8695 i_typstorage = PQfnumber(res, "typstorage");
8696 i_attnotnull = PQfnumber(res, "attnotnull");
8697 i_atthasdef = PQfnumber(res, "atthasdef");
8698 i_attidentity = PQfnumber(res, "attidentity");
8699 i_attgenerated = PQfnumber(res, "attgenerated");
8700 i_attisdropped = PQfnumber(res, "attisdropped");
8701 i_attlen = PQfnumber(res, "attlen");
8702 i_attalign = PQfnumber(res, "attalign");
8703 i_attislocal = PQfnumber(res, "attislocal");
8704 i_attoptions = PQfnumber(res, "attoptions");
8705 i_attcollation = PQfnumber(res, "attcollation");
8706 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8707 i_attmissingval = PQfnumber(res, "attmissingval");
8709 tbinfo->numatts = ntups;
8710 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8711 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8712 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8713 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8714 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8715 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8716 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8717 tbinfo->attgenerated = (char *) pg_malloc(ntups * sizeof(char));
8718 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8719 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8720 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8721 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8722 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8723 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8724 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8725 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8726 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8727 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8728 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8729 hasdefaults = false;
8731 for (j = 0; j < ntups; j++)
8733 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8734 fatal("invalid column numbering in table \"%s\"",
8735 tbinfo->dobj.name);
8736 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8737 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8738 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8739 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8740 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8741 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8742 tbinfo->attidentity[j] = *(PQgetvalue(res, j, i_attidentity));
8743 tbinfo->attgenerated[j] = *(PQgetvalue(res, j, i_attgenerated));
8744 tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8745 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8746 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8747 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8748 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8749 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8750 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8751 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8752 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8753 tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8754 tbinfo->attrdefs[j] = NULL; /* fix below */
8755 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8756 hasdefaults = true;
8757 /* these flags will be set in flagInhAttrs() */
8758 tbinfo->inhNotNull[j] = false;
8761 PQclear(res);
8764 * Get info about column defaults
8766 if (hasdefaults)
8768 AttrDefInfo *attrdefs;
8769 int numDefaults;
8771 pg_log_info("finding default expressions of table \"%s.%s\"",
8772 tbinfo->dobj.namespace->dobj.name,
8773 tbinfo->dobj.name);
8775 printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8776 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8777 "FROM pg_catalog.pg_attrdef "
8778 "WHERE adrelid = '%u'::pg_catalog.oid",
8779 tbinfo->dobj.catId.oid);
8781 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8783 numDefaults = PQntuples(res);
8784 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8786 for (j = 0; j < numDefaults; j++)
8788 int adnum;
8790 adnum = atoi(PQgetvalue(res, j, 2));
8792 if (adnum <= 0 || adnum > ntups)
8793 fatal("invalid adnum value %d for table \"%s\"",
8794 adnum, tbinfo->dobj.name);
8797 * dropped columns shouldn't have defaults, but just in case,
8798 * ignore 'em
8800 if (tbinfo->attisdropped[adnum - 1])
8801 continue;
8803 attrdefs[j].dobj.objType = DO_ATTRDEF;
8804 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8805 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8806 AssignDumpId(&attrdefs[j].dobj);
8807 attrdefs[j].adtable = tbinfo;
8808 attrdefs[j].adnum = adnum;
8809 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8811 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8812 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8814 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8817 * Figure out whether the default/generation expression should
8818 * be dumped as part of the main CREATE TABLE (or similar)
8819 * command or as a separate ALTER TABLE (or similar) command.
8820 * The preference is to put it into the CREATE command, but in
8821 * some cases that's not possible.
8823 if (tbinfo->attgenerated[adnum - 1])
8826 * Column generation expressions cannot be dumped
8827 * separately, because there is no syntax for it. The
8828 * !shouldPrintColumn case below will be tempted to set
8829 * them to separate if they are attached to an inherited
8830 * column without a local definition, but that would be
8831 * wrong and unnecessary, because generation expressions
8832 * are always inherited, so there is no need to set them
8833 * again in child tables, and there is no syntax for it
8834 * either. By setting separate to false here we prevent
8835 * the "default" from being processed as its own dumpable
8836 * object, and flagInhAttrs() will remove it from the
8837 * table when it detects that it belongs to an inherited
8838 * column.
8840 attrdefs[j].separate = false;
8842 else if (tbinfo->relkind == RELKIND_VIEW)
8845 * Defaults on a VIEW must always be dumped as separate
8846 * ALTER TABLE commands.
8848 attrdefs[j].separate = true;
8850 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8852 /* column will be suppressed, print default separately */
8853 attrdefs[j].separate = true;
8855 else
8857 attrdefs[j].separate = false;
8860 if (!attrdefs[j].separate)
8863 * Mark the default as needing to appear before the table,
8864 * so that any dependencies it has must be emitted before
8865 * the CREATE TABLE. If this is not possible, we'll
8866 * change to "separate" mode while sorting dependencies.
8868 addObjectDependency(&tbinfo->dobj,
8869 attrdefs[j].dobj.dumpId);
8872 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8874 PQclear(res);
8878 * Get info about table CHECK constraints
8880 if (tbinfo->ncheck > 0)
8882 ConstraintInfo *constrs;
8883 int numConstrs;
8885 pg_log_info("finding check constraints for table \"%s.%s\"",
8886 tbinfo->dobj.namespace->dobj.name,
8887 tbinfo->dobj.name);
8889 resetPQExpBuffer(q);
8890 if (fout->remoteVersion >= 90200)
8893 * convalidated is new in 9.2 (actually, it is there in 9.1,
8894 * but it wasn't ever false for check constraints until 9.2).
8896 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8897 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8898 "conislocal, convalidated "
8899 "FROM pg_catalog.pg_constraint "
8900 "WHERE conrelid = '%u'::pg_catalog.oid "
8901 " AND contype = 'c' "
8902 "ORDER BY conname",
8903 tbinfo->dobj.catId.oid);
8905 else if (fout->remoteVersion >= 80400)
8907 /* conislocal is new in 8.4 */
8908 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8909 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8910 "conislocal, true AS convalidated "
8911 "FROM pg_catalog.pg_constraint "
8912 "WHERE conrelid = '%u'::pg_catalog.oid "
8913 " AND contype = 'c' "
8914 "ORDER BY conname",
8915 tbinfo->dobj.catId.oid);
8917 else
8919 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8920 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8921 "true AS conislocal, true AS convalidated "
8922 "FROM pg_catalog.pg_constraint "
8923 "WHERE conrelid = '%u'::pg_catalog.oid "
8924 " AND contype = 'c' "
8925 "ORDER BY conname",
8926 tbinfo->dobj.catId.oid);
8929 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8931 numConstrs = PQntuples(res);
8932 if (numConstrs != tbinfo->ncheck)
8934 pg_log_error(ngettext("expected %d check constraint on table \"%s\" but found %d",
8935 "expected %d check constraints on table \"%s\" but found %d",
8936 tbinfo->ncheck),
8937 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8938 pg_log_error("(The system catalogs might be corrupted.)");
8939 exit_nicely(1);
8942 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8943 tbinfo->checkexprs = constrs;
8945 for (j = 0; j < numConstrs; j++)
8947 bool validated = PQgetvalue(res, j, 5)[0] == 't';
8949 constrs[j].dobj.objType = DO_CONSTRAINT;
8950 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8951 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8952 AssignDumpId(&constrs[j].dobj);
8953 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8954 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8955 constrs[j].contable = tbinfo;
8956 constrs[j].condomain = NULL;
8957 constrs[j].contype = 'c';
8958 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8959 constrs[j].confrelid = InvalidOid;
8960 constrs[j].conindex = 0;
8961 constrs[j].condeferrable = false;
8962 constrs[j].condeferred = false;
8963 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8966 * An unvalidated constraint needs to be dumped separately, so
8967 * that potentially-violating existing data is loaded before
8968 * the constraint.
8970 constrs[j].separate = !validated;
8972 constrs[j].dobj.dump = tbinfo->dobj.dump;
8975 * Mark the constraint as needing to appear before the table
8976 * --- this is so that any other dependencies of the
8977 * constraint will be emitted before we try to create the
8978 * table. If the constraint is to be dumped separately, it
8979 * will be dumped after data is loaded anyway, so don't do it.
8980 * (There's an automatic dependency in the opposite direction
8981 * anyway, so don't need to add one manually here.)
8983 if (!constrs[j].separate)
8984 addObjectDependency(&tbinfo->dobj,
8985 constrs[j].dobj.dumpId);
8988 * If the constraint is inherited, this will be detected later
8989 * (in pre-8.4 databases). We also detect later if the
8990 * constraint must be split out from the table definition.
8993 PQclear(res);
8997 destroyPQExpBuffer(q);
9001 * Test whether a column should be printed as part of table's CREATE TABLE.
9002 * Column number is zero-based.
9004 * Normally this is always true, but it's false for dropped columns, as well
9005 * as those that were inherited without any local definition. (If we print
9006 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
9007 * For partitions, it's always true, because we want the partitions to be
9008 * created independently and ATTACH PARTITION used afterwards.
9010 * In binary_upgrade mode, we must print all columns and fix the attislocal/
9011 * attisdropped state later, so as to keep control of the physical column
9012 * order.
9014 * This function exists because there are scattered nonobvious places that
9015 * must be kept in sync with this decision.
9017 bool
9018 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
9020 if (dopt->binary_upgrade)
9021 return true;
9022 if (tbinfo->attisdropped[colno])
9023 return false;
9024 return (tbinfo->attislocal[colno] || tbinfo->ispartition);
9029 * getTSParsers:
9030 * read all text search parsers in the system catalogs and return them
9031 * in the TSParserInfo* structure
9033 * numTSParsers is set to the number of parsers read in
9035 TSParserInfo *
9036 getTSParsers(Archive *fout, int *numTSParsers)
9038 PGresult *res;
9039 int ntups;
9040 int i;
9041 PQExpBuffer query;
9042 TSParserInfo *prsinfo;
9043 int i_tableoid;
9044 int i_oid;
9045 int i_prsname;
9046 int i_prsnamespace;
9047 int i_prsstart;
9048 int i_prstoken;
9049 int i_prsend;
9050 int i_prsheadline;
9051 int i_prslextype;
9053 /* Before 8.3, there is no built-in text search support */
9054 if (fout->remoteVersion < 80300)
9056 *numTSParsers = 0;
9057 return NULL;
9060 query = createPQExpBuffer();
9063 * find all text search objects, including builtin ones; we filter out
9064 * system-defined objects at dump-out time.
9067 appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
9068 "prsstart::oid, prstoken::oid, "
9069 "prsend::oid, prsheadline::oid, prslextype::oid "
9070 "FROM pg_ts_parser");
9072 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9074 ntups = PQntuples(res);
9075 *numTSParsers = ntups;
9077 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
9079 i_tableoid = PQfnumber(res, "tableoid");
9080 i_oid = PQfnumber(res, "oid");
9081 i_prsname = PQfnumber(res, "prsname");
9082 i_prsnamespace = PQfnumber(res, "prsnamespace");
9083 i_prsstart = PQfnumber(res, "prsstart");
9084 i_prstoken = PQfnumber(res, "prstoken");
9085 i_prsend = PQfnumber(res, "prsend");
9086 i_prsheadline = PQfnumber(res, "prsheadline");
9087 i_prslextype = PQfnumber(res, "prslextype");
9089 for (i = 0; i < ntups; i++)
9091 prsinfo[i].dobj.objType = DO_TSPARSER;
9092 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9093 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9094 AssignDumpId(&prsinfo[i].dobj);
9095 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
9096 prsinfo[i].dobj.namespace =
9097 findNamespace(fout,
9098 atooid(PQgetvalue(res, i, i_prsnamespace)));
9099 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
9100 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
9101 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
9102 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
9103 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
9105 /* Decide whether we want to dump it */
9106 selectDumpableObject(&(prsinfo[i].dobj), fout);
9108 /* Text Search Parsers do not currently have ACLs. */
9109 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9112 PQclear(res);
9114 destroyPQExpBuffer(query);
9116 return prsinfo;
9120 * getTSDictionaries:
9121 * read all text search dictionaries in the system catalogs and return them
9122 * in the TSDictInfo* structure
9124 * numTSDicts is set to the number of dictionaries read in
9126 TSDictInfo *
9127 getTSDictionaries(Archive *fout, int *numTSDicts)
9129 PGresult *res;
9130 int ntups;
9131 int i;
9132 PQExpBuffer query;
9133 TSDictInfo *dictinfo;
9134 int i_tableoid;
9135 int i_oid;
9136 int i_dictname;
9137 int i_dictnamespace;
9138 int i_rolname;
9139 int i_dicttemplate;
9140 int i_dictinitoption;
9142 /* Before 8.3, there is no built-in text search support */
9143 if (fout->remoteVersion < 80300)
9145 *numTSDicts = 0;
9146 return NULL;
9149 query = createPQExpBuffer();
9151 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
9152 "dictnamespace, (%s dictowner) AS rolname, "
9153 "dicttemplate, dictinitoption "
9154 "FROM pg_ts_dict",
9155 username_subquery);
9157 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9159 ntups = PQntuples(res);
9160 *numTSDicts = ntups;
9162 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
9164 i_tableoid = PQfnumber(res, "tableoid");
9165 i_oid = PQfnumber(res, "oid");
9166 i_dictname = PQfnumber(res, "dictname");
9167 i_dictnamespace = PQfnumber(res, "dictnamespace");
9168 i_rolname = PQfnumber(res, "rolname");
9169 i_dictinitoption = PQfnumber(res, "dictinitoption");
9170 i_dicttemplate = PQfnumber(res, "dicttemplate");
9172 for (i = 0; i < ntups; i++)
9174 dictinfo[i].dobj.objType = DO_TSDICT;
9175 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9176 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9177 AssignDumpId(&dictinfo[i].dobj);
9178 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
9179 dictinfo[i].dobj.namespace =
9180 findNamespace(fout,
9181 atooid(PQgetvalue(res, i, i_dictnamespace)));
9182 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9183 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
9184 if (PQgetisnull(res, i, i_dictinitoption))
9185 dictinfo[i].dictinitoption = NULL;
9186 else
9187 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
9189 /* Decide whether we want to dump it */
9190 selectDumpableObject(&(dictinfo[i].dobj), fout);
9192 /* Text Search Dictionaries do not currently have ACLs. */
9193 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9196 PQclear(res);
9198 destroyPQExpBuffer(query);
9200 return dictinfo;
9204 * getTSTemplates:
9205 * read all text search templates in the system catalogs and return them
9206 * in the TSTemplateInfo* structure
9208 * numTSTemplates is set to the number of templates read in
9210 TSTemplateInfo *
9211 getTSTemplates(Archive *fout, int *numTSTemplates)
9213 PGresult *res;
9214 int ntups;
9215 int i;
9216 PQExpBuffer query;
9217 TSTemplateInfo *tmplinfo;
9218 int i_tableoid;
9219 int i_oid;
9220 int i_tmplname;
9221 int i_tmplnamespace;
9222 int i_tmplinit;
9223 int i_tmpllexize;
9225 /* Before 8.3, there is no built-in text search support */
9226 if (fout->remoteVersion < 80300)
9228 *numTSTemplates = 0;
9229 return NULL;
9232 query = createPQExpBuffer();
9234 appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
9235 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
9236 "FROM pg_ts_template");
9238 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9240 ntups = PQntuples(res);
9241 *numTSTemplates = ntups;
9243 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
9245 i_tableoid = PQfnumber(res, "tableoid");
9246 i_oid = PQfnumber(res, "oid");
9247 i_tmplname = PQfnumber(res, "tmplname");
9248 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
9249 i_tmplinit = PQfnumber(res, "tmplinit");
9250 i_tmpllexize = PQfnumber(res, "tmpllexize");
9252 for (i = 0; i < ntups; i++)
9254 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
9255 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9256 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9257 AssignDumpId(&tmplinfo[i].dobj);
9258 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
9259 tmplinfo[i].dobj.namespace =
9260 findNamespace(fout,
9261 atooid(PQgetvalue(res, i, i_tmplnamespace)));
9262 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
9263 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
9265 /* Decide whether we want to dump it */
9266 selectDumpableObject(&(tmplinfo[i].dobj), fout);
9268 /* Text Search Templates do not currently have ACLs. */
9269 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9272 PQclear(res);
9274 destroyPQExpBuffer(query);
9276 return tmplinfo;
9280 * getTSConfigurations:
9281 * read all text search configurations in the system catalogs and return
9282 * them in the TSConfigInfo* structure
9284 * numTSConfigs is set to the number of configurations read in
9286 TSConfigInfo *
9287 getTSConfigurations(Archive *fout, int *numTSConfigs)
9289 PGresult *res;
9290 int ntups;
9291 int i;
9292 PQExpBuffer query;
9293 TSConfigInfo *cfginfo;
9294 int i_tableoid;
9295 int i_oid;
9296 int i_cfgname;
9297 int i_cfgnamespace;
9298 int i_rolname;
9299 int i_cfgparser;
9301 /* Before 8.3, there is no built-in text search support */
9302 if (fout->remoteVersion < 80300)
9304 *numTSConfigs = 0;
9305 return NULL;
9308 query = createPQExpBuffer();
9310 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
9311 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
9312 "FROM pg_ts_config",
9313 username_subquery);
9315 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9317 ntups = PQntuples(res);
9318 *numTSConfigs = ntups;
9320 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
9322 i_tableoid = PQfnumber(res, "tableoid");
9323 i_oid = PQfnumber(res, "oid");
9324 i_cfgname = PQfnumber(res, "cfgname");
9325 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
9326 i_rolname = PQfnumber(res, "rolname");
9327 i_cfgparser = PQfnumber(res, "cfgparser");
9329 for (i = 0; i < ntups; i++)
9331 cfginfo[i].dobj.objType = DO_TSCONFIG;
9332 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9333 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9334 AssignDumpId(&cfginfo[i].dobj);
9335 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
9336 cfginfo[i].dobj.namespace =
9337 findNamespace(fout,
9338 atooid(PQgetvalue(res, i, i_cfgnamespace)));
9339 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9340 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
9342 /* Decide whether we want to dump it */
9343 selectDumpableObject(&(cfginfo[i].dobj), fout);
9345 /* Text Search Configurations do not currently have ACLs. */
9346 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9349 PQclear(res);
9351 destroyPQExpBuffer(query);
9353 return cfginfo;
9357 * getForeignDataWrappers:
9358 * read all foreign-data wrappers in the system catalogs and return
9359 * them in the FdwInfo* structure
9361 * numForeignDataWrappers is set to the number of fdws read in
9363 FdwInfo *
9364 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
9366 DumpOptions *dopt = fout->dopt;
9367 PGresult *res;
9368 int ntups;
9369 int i;
9370 PQExpBuffer query;
9371 FdwInfo *fdwinfo;
9372 int i_tableoid;
9373 int i_oid;
9374 int i_fdwname;
9375 int i_rolname;
9376 int i_fdwhandler;
9377 int i_fdwvalidator;
9378 int i_fdwacl;
9379 int i_rfdwacl;
9380 int i_initfdwacl;
9381 int i_initrfdwacl;
9382 int i_fdwoptions;
9384 /* Before 8.4, there are no foreign-data wrappers */
9385 if (fout->remoteVersion < 80400)
9387 *numForeignDataWrappers = 0;
9388 return NULL;
9391 query = createPQExpBuffer();
9393 if (fout->remoteVersion >= 90600)
9395 PQExpBuffer acl_subquery = createPQExpBuffer();
9396 PQExpBuffer racl_subquery = createPQExpBuffer();
9397 PQExpBuffer initacl_subquery = createPQExpBuffer();
9398 PQExpBuffer initracl_subquery = createPQExpBuffer();
9400 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9401 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
9402 dopt->binary_upgrade);
9404 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
9405 "(%s f.fdwowner) AS rolname, "
9406 "f.fdwhandler::pg_catalog.regproc, "
9407 "f.fdwvalidator::pg_catalog.regproc, "
9408 "%s AS fdwacl, "
9409 "%s AS rfdwacl, "
9410 "%s AS initfdwacl, "
9411 "%s AS initrfdwacl, "
9412 "array_to_string(ARRAY("
9413 "SELECT quote_ident(option_name) || ' ' || "
9414 "quote_literal(option_value) "
9415 "FROM pg_options_to_table(f.fdwoptions) "
9416 "ORDER BY option_name"
9417 "), E',\n ') AS fdwoptions "
9418 "FROM pg_foreign_data_wrapper f "
9419 "LEFT JOIN pg_init_privs pip ON "
9420 "(f.oid = pip.objoid "
9421 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
9422 "AND pip.objsubid = 0) ",
9423 username_subquery,
9424 acl_subquery->data,
9425 racl_subquery->data,
9426 initacl_subquery->data,
9427 initracl_subquery->data);
9429 destroyPQExpBuffer(acl_subquery);
9430 destroyPQExpBuffer(racl_subquery);
9431 destroyPQExpBuffer(initacl_subquery);
9432 destroyPQExpBuffer(initracl_subquery);
9434 else if (fout->remoteVersion >= 90100)
9436 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9437 "(%s fdwowner) AS rolname, "
9438 "fdwhandler::pg_catalog.regproc, "
9439 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9440 "NULL as rfdwacl, "
9441 "NULL as initfdwacl, NULL AS initrfdwacl, "
9442 "array_to_string(ARRAY("
9443 "SELECT quote_ident(option_name) || ' ' || "
9444 "quote_literal(option_value) "
9445 "FROM pg_options_to_table(fdwoptions) "
9446 "ORDER BY option_name"
9447 "), E',\n ') AS fdwoptions "
9448 "FROM pg_foreign_data_wrapper",
9449 username_subquery);
9451 else
9453 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9454 "(%s fdwowner) AS rolname, "
9455 "'-' AS fdwhandler, "
9456 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9457 "NULL as rfdwacl, "
9458 "NULL as initfdwacl, NULL AS initrfdwacl, "
9459 "array_to_string(ARRAY("
9460 "SELECT quote_ident(option_name) || ' ' || "
9461 "quote_literal(option_value) "
9462 "FROM pg_options_to_table(fdwoptions) "
9463 "ORDER BY option_name"
9464 "), E',\n ') AS fdwoptions "
9465 "FROM pg_foreign_data_wrapper",
9466 username_subquery);
9469 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9471 ntups = PQntuples(res);
9472 *numForeignDataWrappers = ntups;
9474 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9476 i_tableoid = PQfnumber(res, "tableoid");
9477 i_oid = PQfnumber(res, "oid");
9478 i_fdwname = PQfnumber(res, "fdwname");
9479 i_rolname = PQfnumber(res, "rolname");
9480 i_fdwhandler = PQfnumber(res, "fdwhandler");
9481 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9482 i_fdwacl = PQfnumber(res, "fdwacl");
9483 i_rfdwacl = PQfnumber(res, "rfdwacl");
9484 i_initfdwacl = PQfnumber(res, "initfdwacl");
9485 i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9486 i_fdwoptions = PQfnumber(res, "fdwoptions");
9488 for (i = 0; i < ntups; i++)
9490 fdwinfo[i].dobj.objType = DO_FDW;
9491 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9492 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9493 AssignDumpId(&fdwinfo[i].dobj);
9494 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9495 fdwinfo[i].dobj.namespace = NULL;
9496 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9497 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9498 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9499 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9500 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9501 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9502 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9503 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9505 /* Decide whether we want to dump it */
9506 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9508 /* Do not try to dump ACL if no ACL exists. */
9509 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9510 PQgetisnull(res, i, i_initfdwacl) &&
9511 PQgetisnull(res, i, i_initrfdwacl))
9512 fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9515 PQclear(res);
9517 destroyPQExpBuffer(query);
9519 return fdwinfo;
9523 * getForeignServers:
9524 * read all foreign servers in the system catalogs and return
9525 * them in the ForeignServerInfo * structure
9527 * numForeignServers is set to the number of servers read in
9529 ForeignServerInfo *
9530 getForeignServers(Archive *fout, int *numForeignServers)
9532 DumpOptions *dopt = fout->dopt;
9533 PGresult *res;
9534 int ntups;
9535 int i;
9536 PQExpBuffer query;
9537 ForeignServerInfo *srvinfo;
9538 int i_tableoid;
9539 int i_oid;
9540 int i_srvname;
9541 int i_rolname;
9542 int i_srvfdw;
9543 int i_srvtype;
9544 int i_srvversion;
9545 int i_srvacl;
9546 int i_rsrvacl;
9547 int i_initsrvacl;
9548 int i_initrsrvacl;
9549 int i_srvoptions;
9551 /* Before 8.4, there are no foreign servers */
9552 if (fout->remoteVersion < 80400)
9554 *numForeignServers = 0;
9555 return NULL;
9558 query = createPQExpBuffer();
9560 if (fout->remoteVersion >= 90600)
9562 PQExpBuffer acl_subquery = createPQExpBuffer();
9563 PQExpBuffer racl_subquery = createPQExpBuffer();
9564 PQExpBuffer initacl_subquery = createPQExpBuffer();
9565 PQExpBuffer initracl_subquery = createPQExpBuffer();
9567 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9568 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9569 dopt->binary_upgrade);
9571 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9572 "(%s f.srvowner) AS rolname, "
9573 "f.srvfdw, f.srvtype, f.srvversion, "
9574 "%s AS srvacl, "
9575 "%s AS rsrvacl, "
9576 "%s AS initsrvacl, "
9577 "%s AS initrsrvacl, "
9578 "array_to_string(ARRAY("
9579 "SELECT quote_ident(option_name) || ' ' || "
9580 "quote_literal(option_value) "
9581 "FROM pg_options_to_table(f.srvoptions) "
9582 "ORDER BY option_name"
9583 "), E',\n ') AS srvoptions "
9584 "FROM pg_foreign_server f "
9585 "LEFT JOIN pg_init_privs pip "
9586 "ON (f.oid = pip.objoid "
9587 "AND pip.classoid = 'pg_foreign_server'::regclass "
9588 "AND pip.objsubid = 0) ",
9589 username_subquery,
9590 acl_subquery->data,
9591 racl_subquery->data,
9592 initacl_subquery->data,
9593 initracl_subquery->data);
9595 destroyPQExpBuffer(acl_subquery);
9596 destroyPQExpBuffer(racl_subquery);
9597 destroyPQExpBuffer(initacl_subquery);
9598 destroyPQExpBuffer(initracl_subquery);
9600 else
9602 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9603 "(%s srvowner) AS rolname, "
9604 "srvfdw, srvtype, srvversion, srvacl, "
9605 "NULL AS rsrvacl, "
9606 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9607 "array_to_string(ARRAY("
9608 "SELECT quote_ident(option_name) || ' ' || "
9609 "quote_literal(option_value) "
9610 "FROM pg_options_to_table(srvoptions) "
9611 "ORDER BY option_name"
9612 "), E',\n ') AS srvoptions "
9613 "FROM pg_foreign_server",
9614 username_subquery);
9617 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9619 ntups = PQntuples(res);
9620 *numForeignServers = ntups;
9622 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9624 i_tableoid = PQfnumber(res, "tableoid");
9625 i_oid = PQfnumber(res, "oid");
9626 i_srvname = PQfnumber(res, "srvname");
9627 i_rolname = PQfnumber(res, "rolname");
9628 i_srvfdw = PQfnumber(res, "srvfdw");
9629 i_srvtype = PQfnumber(res, "srvtype");
9630 i_srvversion = PQfnumber(res, "srvversion");
9631 i_srvacl = PQfnumber(res, "srvacl");
9632 i_rsrvacl = PQfnumber(res, "rsrvacl");
9633 i_initsrvacl = PQfnumber(res, "initsrvacl");
9634 i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9635 i_srvoptions = PQfnumber(res, "srvoptions");
9637 for (i = 0; i < ntups; i++)
9639 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9640 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9641 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9642 AssignDumpId(&srvinfo[i].dobj);
9643 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9644 srvinfo[i].dobj.namespace = NULL;
9645 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9646 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9647 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9648 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9649 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9650 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9651 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9652 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9653 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9655 /* Decide whether we want to dump it */
9656 selectDumpableObject(&(srvinfo[i].dobj), fout);
9658 /* Do not try to dump ACL if no ACL exists. */
9659 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9660 PQgetisnull(res, i, i_initsrvacl) &&
9661 PQgetisnull(res, i, i_initrsrvacl))
9662 srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9665 PQclear(res);
9667 destroyPQExpBuffer(query);
9669 return srvinfo;
9673 * getDefaultACLs:
9674 * read all default ACL information in the system catalogs and return
9675 * them in the DefaultACLInfo structure
9677 * numDefaultACLs is set to the number of ACLs read in
9679 DefaultACLInfo *
9680 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9682 DumpOptions *dopt = fout->dopt;
9683 DefaultACLInfo *daclinfo;
9684 PQExpBuffer query;
9685 PGresult *res;
9686 int i_oid;
9687 int i_tableoid;
9688 int i_defaclrole;
9689 int i_defaclnamespace;
9690 int i_defaclobjtype;
9691 int i_defaclacl;
9692 int i_rdefaclacl;
9693 int i_initdefaclacl;
9694 int i_initrdefaclacl;
9695 int i,
9696 ntups;
9698 if (fout->remoteVersion < 90000)
9700 *numDefaultACLs = 0;
9701 return NULL;
9704 query = createPQExpBuffer();
9706 if (fout->remoteVersion >= 90600)
9708 PQExpBuffer acl_subquery = createPQExpBuffer();
9709 PQExpBuffer racl_subquery = createPQExpBuffer();
9710 PQExpBuffer initacl_subquery = createPQExpBuffer();
9711 PQExpBuffer initracl_subquery = createPQExpBuffer();
9714 * Global entries (with defaclnamespace=0) replace the hard-wired
9715 * default ACL for their object type. We should dump them as deltas
9716 * from the default ACL, since that will be used as a starting point
9717 * for interpreting the ALTER DEFAULT PRIVILEGES commands. On the
9718 * other hand, non-global entries can only add privileges not revoke
9719 * them. We must dump those as-is (i.e., as deltas from an empty
9720 * ACL). We implement that by passing NULL as the object type for
9721 * acldefault(), which works because acldefault() is STRICT.
9723 * We can use defaclobjtype as the object type for acldefault(),
9724 * except for the case of 'S' (DEFACLOBJ_SEQUENCE) which must be
9725 * converted to 's'.
9727 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9728 initracl_subquery, "defaclacl", "defaclrole",
9729 "CASE WHEN defaclnamespace = 0 THEN"
9730 " CASE WHEN defaclobjtype = 'S' THEN 's'::\"char\""
9731 " ELSE defaclobjtype END "
9732 "ELSE NULL END",
9733 dopt->binary_upgrade);
9735 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9736 "(%s d.defaclrole) AS defaclrole, "
9737 "d.defaclnamespace, "
9738 "d.defaclobjtype, "
9739 "%s AS defaclacl, "
9740 "%s AS rdefaclacl, "
9741 "%s AS initdefaclacl, "
9742 "%s AS initrdefaclacl "
9743 "FROM pg_default_acl d "
9744 "LEFT JOIN pg_init_privs pip ON "
9745 "(d.oid = pip.objoid "
9746 "AND pip.classoid = 'pg_default_acl'::regclass "
9747 "AND pip.objsubid = 0) ",
9748 username_subquery,
9749 acl_subquery->data,
9750 racl_subquery->data,
9751 initacl_subquery->data,
9752 initracl_subquery->data);
9754 destroyPQExpBuffer(acl_subquery);
9755 destroyPQExpBuffer(racl_subquery);
9756 destroyPQExpBuffer(initacl_subquery);
9757 destroyPQExpBuffer(initracl_subquery);
9759 else
9761 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9762 "(%s defaclrole) AS defaclrole, "
9763 "defaclnamespace, "
9764 "defaclobjtype, "
9765 "defaclacl, "
9766 "NULL AS rdefaclacl, "
9767 "NULL AS initdefaclacl, "
9768 "NULL AS initrdefaclacl "
9769 "FROM pg_default_acl",
9770 username_subquery);
9773 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9775 ntups = PQntuples(res);
9776 *numDefaultACLs = ntups;
9778 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9780 i_oid = PQfnumber(res, "oid");
9781 i_tableoid = PQfnumber(res, "tableoid");
9782 i_defaclrole = PQfnumber(res, "defaclrole");
9783 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9784 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9785 i_defaclacl = PQfnumber(res, "defaclacl");
9786 i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9787 i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9788 i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9790 for (i = 0; i < ntups; i++)
9792 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9794 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9795 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9796 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9797 AssignDumpId(&daclinfo[i].dobj);
9798 /* cheesy ... is it worth coming up with a better object name? */
9799 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9801 if (nspid != InvalidOid)
9802 daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9803 else
9804 daclinfo[i].dobj.namespace = NULL;
9806 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9807 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9808 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9809 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9810 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9811 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9813 /* Decide whether we want to dump it */
9814 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9817 PQclear(res);
9819 destroyPQExpBuffer(query);
9821 return daclinfo;
9825 * dumpComment --
9827 * This routine is used to dump any comments associated with the
9828 * object handed to this routine. The routine takes the object type
9829 * and object name (ready to print, except for schema decoration), plus
9830 * the namespace and owner of the object (for labeling the ArchiveEntry),
9831 * plus catalog ID and subid which are the lookup key for pg_description,
9832 * plus the dump ID for the object (for setting a dependency).
9833 * If a matching pg_description entry is found, it is dumped.
9835 * Note: in some cases, such as comments for triggers and rules, the "type"
9836 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9837 * but it doesn't seem worth complicating the API for all callers to make
9838 * it cleaner.
9840 * Note: although this routine takes a dumpId for dependency purposes,
9841 * that purpose is just to mark the dependency in the emitted dump file
9842 * for possible future use by pg_restore. We do NOT use it for determining
9843 * ordering of the comment in the dump file, because this routine is called
9844 * after dependency sorting occurs. This routine should be called just after
9845 * calling ArchiveEntry() for the specified object.
9847 static void
9848 dumpComment(Archive *fout, const char *type, const char *name,
9849 const char *namespace, const char *owner,
9850 CatalogId catalogId, int subid, DumpId dumpId)
9852 DumpOptions *dopt = fout->dopt;
9853 CommentItem *comments;
9854 int ncomments;
9856 /* do nothing, if --no-comments is supplied */
9857 if (dopt->no_comments)
9858 return;
9860 /* Comments are schema not data ... except blob comments are data */
9861 if (strcmp(type, "LARGE OBJECT") != 0)
9863 if (dopt->dataOnly)
9864 return;
9866 else
9868 /* We do dump blob comments in binary-upgrade mode */
9869 if (dopt->schemaOnly && !dopt->binary_upgrade)
9870 return;
9873 /* Search for comments associated with catalogId, using table */
9874 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9875 &comments);
9877 /* Is there one matching the subid? */
9878 while (ncomments > 0)
9880 if (comments->objsubid == subid)
9881 break;
9882 comments++;
9883 ncomments--;
9886 /* If a comment exists, build COMMENT ON statement */
9887 if (ncomments > 0)
9889 PQExpBuffer query = createPQExpBuffer();
9890 PQExpBuffer tag = createPQExpBuffer();
9892 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9893 if (namespace && *namespace)
9894 appendPQExpBuffer(query, "%s.", fmtId(namespace));
9895 appendPQExpBuffer(query, "%s IS ", name);
9896 appendStringLiteralAH(query, comments->descr, fout);
9897 appendPQExpBufferStr(query, ";\n");
9899 appendPQExpBuffer(tag, "%s %s", type, name);
9902 * We mark comments as SECTION_NONE because they really belong in the
9903 * same section as their parent, whether that is pre-data or
9904 * post-data.
9906 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9907 ARCHIVE_OPTS(.tag = tag->data,
9908 .namespace = namespace,
9909 .owner = owner,
9910 .description = "COMMENT",
9911 .section = SECTION_NONE,
9912 .createStmt = query->data,
9913 .deps = &dumpId,
9914 .nDeps = 1));
9916 destroyPQExpBuffer(query);
9917 destroyPQExpBuffer(tag);
9922 * dumpTableComment --
9924 * As above, but dump comments for both the specified table (or view)
9925 * and its columns.
9927 static void
9928 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9929 const char *reltypename)
9931 DumpOptions *dopt = fout->dopt;
9932 CommentItem *comments;
9933 int ncomments;
9934 PQExpBuffer query;
9935 PQExpBuffer tag;
9937 /* do nothing, if --no-comments is supplied */
9938 if (dopt->no_comments)
9939 return;
9941 /* Comments are SCHEMA not data */
9942 if (dopt->dataOnly)
9943 return;
9945 /* Search for comments associated with relation, using table */
9946 ncomments = findComments(fout,
9947 tbinfo->dobj.catId.tableoid,
9948 tbinfo->dobj.catId.oid,
9949 &comments);
9951 /* If comments exist, build COMMENT ON statements */
9952 if (ncomments <= 0)
9953 return;
9955 query = createPQExpBuffer();
9956 tag = createPQExpBuffer();
9958 while (ncomments > 0)
9960 const char *descr = comments->descr;
9961 int objsubid = comments->objsubid;
9963 if (objsubid == 0)
9965 resetPQExpBuffer(tag);
9966 appendPQExpBuffer(tag, "%s %s", reltypename,
9967 fmtId(tbinfo->dobj.name));
9969 resetPQExpBuffer(query);
9970 appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9971 fmtQualifiedDumpable(tbinfo));
9972 appendStringLiteralAH(query, descr, fout);
9973 appendPQExpBufferStr(query, ";\n");
9975 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9976 ARCHIVE_OPTS(.tag = tag->data,
9977 .namespace = tbinfo->dobj.namespace->dobj.name,
9978 .owner = tbinfo->rolname,
9979 .description = "COMMENT",
9980 .section = SECTION_NONE,
9981 .createStmt = query->data,
9982 .deps = &(tbinfo->dobj.dumpId),
9983 .nDeps = 1));
9985 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9987 resetPQExpBuffer(tag);
9988 appendPQExpBuffer(tag, "COLUMN %s.",
9989 fmtId(tbinfo->dobj.name));
9990 appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9992 resetPQExpBuffer(query);
9993 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9994 fmtQualifiedDumpable(tbinfo));
9995 appendPQExpBuffer(query, "%s IS ",
9996 fmtId(tbinfo->attnames[objsubid - 1]));
9997 appendStringLiteralAH(query, descr, fout);
9998 appendPQExpBufferStr(query, ";\n");
10000 ArchiveEntry(fout, nilCatalogId, createDumpId(),
10001 ARCHIVE_OPTS(.tag = tag->data,
10002 .namespace = tbinfo->dobj.namespace->dobj.name,
10003 .owner = tbinfo->rolname,
10004 .description = "COMMENT",
10005 .section = SECTION_NONE,
10006 .createStmt = query->data,
10007 .deps = &(tbinfo->dobj.dumpId),
10008 .nDeps = 1));
10011 comments++;
10012 ncomments--;
10015 destroyPQExpBuffer(query);
10016 destroyPQExpBuffer(tag);
10020 * findComments --
10022 * Find the comment(s), if any, associated with the given object. All the
10023 * objsubid values associated with the given classoid/objoid are found with
10024 * one search.
10026 static int
10027 findComments(Archive *fout, Oid classoid, Oid objoid,
10028 CommentItem **items)
10030 /* static storage for table of comments */
10031 static CommentItem *comments = NULL;
10032 static int ncomments = -1;
10034 CommentItem *middle = NULL;
10035 CommentItem *low;
10036 CommentItem *high;
10037 int nmatch;
10039 /* Get comments if we didn't already */
10040 if (ncomments < 0)
10041 ncomments = collectComments(fout, &comments);
10044 * Do binary search to find some item matching the object.
10046 low = &comments[0];
10047 high = &comments[ncomments - 1];
10048 while (low <= high)
10050 middle = low + (high - low) / 2;
10052 if (classoid < middle->classoid)
10053 high = middle - 1;
10054 else if (classoid > middle->classoid)
10055 low = middle + 1;
10056 else if (objoid < middle->objoid)
10057 high = middle - 1;
10058 else if (objoid > middle->objoid)
10059 low = middle + 1;
10060 else
10061 break; /* found a match */
10064 if (low > high) /* no matches */
10066 *items = NULL;
10067 return 0;
10071 * Now determine how many items match the object. The search loop
10072 * invariant still holds: only items between low and high inclusive could
10073 * match.
10075 nmatch = 1;
10076 while (middle > low)
10078 if (classoid != middle[-1].classoid ||
10079 objoid != middle[-1].objoid)
10080 break;
10081 middle--;
10082 nmatch++;
10085 *items = middle;
10087 middle += nmatch;
10088 while (middle <= high)
10090 if (classoid != middle->classoid ||
10091 objoid != middle->objoid)
10092 break;
10093 middle++;
10094 nmatch++;
10097 return nmatch;
10101 * collectComments --
10103 * Construct a table of all comments available for database objects.
10104 * We used to do per-object queries for the comments, but it's much faster
10105 * to pull them all over at once, and on most databases the memory cost
10106 * isn't high.
10108 * The table is sorted by classoid/objid/objsubid for speed in lookup.
10110 static int
10111 collectComments(Archive *fout, CommentItem **items)
10113 PGresult *res;
10114 PQExpBuffer query;
10115 int i_description;
10116 int i_classoid;
10117 int i_objoid;
10118 int i_objsubid;
10119 int ntups;
10120 int i;
10121 CommentItem *comments;
10123 query = createPQExpBuffer();
10125 appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
10126 "FROM pg_catalog.pg_description "
10127 "ORDER BY classoid, objoid, objsubid");
10129 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10131 /* Construct lookup table containing OIDs in numeric form */
10133 i_description = PQfnumber(res, "description");
10134 i_classoid = PQfnumber(res, "classoid");
10135 i_objoid = PQfnumber(res, "objoid");
10136 i_objsubid = PQfnumber(res, "objsubid");
10138 ntups = PQntuples(res);
10140 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
10142 for (i = 0; i < ntups; i++)
10144 comments[i].descr = PQgetvalue(res, i, i_description);
10145 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
10146 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
10147 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
10150 /* Do NOT free the PGresult since we are keeping pointers into it */
10151 destroyPQExpBuffer(query);
10153 *items = comments;
10154 return ntups;
10158 * dumpDumpableObject
10160 * This routine and its subsidiaries are responsible for creating
10161 * ArchiveEntries (TOC objects) for each object to be dumped.
10163 static void
10164 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
10166 switch (dobj->objType)
10168 case DO_NAMESPACE:
10169 dumpNamespace(fout, (NamespaceInfo *) dobj);
10170 break;
10171 case DO_EXTENSION:
10172 dumpExtension(fout, (ExtensionInfo *) dobj);
10173 break;
10174 case DO_TYPE:
10175 dumpType(fout, (TypeInfo *) dobj);
10176 break;
10177 case DO_SHELL_TYPE:
10178 dumpShellType(fout, (ShellTypeInfo *) dobj);
10179 break;
10180 case DO_FUNC:
10181 dumpFunc(fout, (FuncInfo *) dobj);
10182 break;
10183 case DO_AGG:
10184 dumpAgg(fout, (AggInfo *) dobj);
10185 break;
10186 case DO_OPERATOR:
10187 dumpOpr(fout, (OprInfo *) dobj);
10188 break;
10189 case DO_ACCESS_METHOD:
10190 dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
10191 break;
10192 case DO_OPCLASS:
10193 dumpOpclass(fout, (OpclassInfo *) dobj);
10194 break;
10195 case DO_OPFAMILY:
10196 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
10197 break;
10198 case DO_COLLATION:
10199 dumpCollation(fout, (CollInfo *) dobj);
10200 break;
10201 case DO_CONVERSION:
10202 dumpConversion(fout, (ConvInfo *) dobj);
10203 break;
10204 case DO_TABLE:
10205 dumpTable(fout, (TableInfo *) dobj);
10206 break;
10207 case DO_ATTRDEF:
10208 dumpAttrDef(fout, (AttrDefInfo *) dobj);
10209 break;
10210 case DO_INDEX:
10211 dumpIndex(fout, (IndxInfo *) dobj);
10212 break;
10213 case DO_INDEX_ATTACH:
10214 dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
10215 break;
10216 case DO_STATSEXT:
10217 dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
10218 break;
10219 case DO_REFRESH_MATVIEW:
10220 refreshMatViewData(fout, (TableDataInfo *) dobj);
10221 break;
10222 case DO_RULE:
10223 dumpRule(fout, (RuleInfo *) dobj);
10224 break;
10225 case DO_TRIGGER:
10226 dumpTrigger(fout, (TriggerInfo *) dobj);
10227 break;
10228 case DO_EVENT_TRIGGER:
10229 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
10230 break;
10231 case DO_CONSTRAINT:
10232 dumpConstraint(fout, (ConstraintInfo *) dobj);
10233 break;
10234 case DO_FK_CONSTRAINT:
10235 dumpConstraint(fout, (ConstraintInfo *) dobj);
10236 break;
10237 case DO_PROCLANG:
10238 dumpProcLang(fout, (ProcLangInfo *) dobj);
10239 break;
10240 case DO_CAST:
10241 dumpCast(fout, (CastInfo *) dobj);
10242 break;
10243 case DO_TRANSFORM:
10244 dumpTransform(fout, (TransformInfo *) dobj);
10245 break;
10246 case DO_SEQUENCE_SET:
10247 dumpSequenceData(fout, (TableDataInfo *) dobj);
10248 break;
10249 case DO_TABLE_DATA:
10250 dumpTableData(fout, (TableDataInfo *) dobj);
10251 break;
10252 case DO_DUMMY_TYPE:
10253 /* table rowtypes and array types are never dumped separately */
10254 break;
10255 case DO_TSPARSER:
10256 dumpTSParser(fout, (TSParserInfo *) dobj);
10257 break;
10258 case DO_TSDICT:
10259 dumpTSDictionary(fout, (TSDictInfo *) dobj);
10260 break;
10261 case DO_TSTEMPLATE:
10262 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
10263 break;
10264 case DO_TSCONFIG:
10265 dumpTSConfig(fout, (TSConfigInfo *) dobj);
10266 break;
10267 case DO_FDW:
10268 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
10269 break;
10270 case DO_FOREIGN_SERVER:
10271 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
10272 break;
10273 case DO_DEFAULT_ACL:
10274 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
10275 break;
10276 case DO_BLOB:
10277 dumpBlob(fout, (BlobInfo *) dobj);
10278 break;
10279 case DO_BLOB_DATA:
10280 if (dobj->dump & DUMP_COMPONENT_DATA)
10282 TocEntry *te;
10284 te = ArchiveEntry(fout, dobj->catId, dobj->dumpId,
10285 ARCHIVE_OPTS(.tag = dobj->name,
10286 .description = "BLOBS",
10287 .section = SECTION_DATA,
10288 .dumpFn = dumpBlobs));
10291 * Set the TocEntry's dataLength in case we are doing a
10292 * parallel dump and want to order dump jobs by table size.
10293 * (We need some size estimate for every TocEntry with a
10294 * DataDumper function.) We don't currently have any cheap
10295 * way to estimate the size of blobs, but it doesn't matter;
10296 * let's just set the size to a large value so parallel dumps
10297 * will launch this job first. If there's lots of blobs, we
10298 * win, and if there aren't, we don't lose much. (If you want
10299 * to improve on this, really what you should be thinking
10300 * about is allowing blob dumping to be parallelized, not just
10301 * getting a smarter estimate for the single TOC entry.)
10303 te->dataLength = MaxBlockNumber;
10305 break;
10306 case DO_POLICY:
10307 dumpPolicy(fout, (PolicyInfo *) dobj);
10308 break;
10309 case DO_PUBLICATION:
10310 dumpPublication(fout, (PublicationInfo *) dobj);
10311 break;
10312 case DO_PUBLICATION_REL:
10313 dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
10314 break;
10315 case DO_SUBSCRIPTION:
10316 dumpSubscription(fout, (SubscriptionInfo *) dobj);
10317 break;
10318 case DO_PRE_DATA_BOUNDARY:
10319 case DO_POST_DATA_BOUNDARY:
10320 /* never dumped, nothing to do */
10321 break;
10326 * dumpNamespace
10327 * writes out to fout the queries to recreate a user-defined namespace
10329 static void
10330 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
10332 DumpOptions *dopt = fout->dopt;
10333 PQExpBuffer q;
10334 PQExpBuffer delq;
10335 char *qnspname;
10337 /* Skip if not to be dumped */
10338 if (!nspinfo->dobj.dump || dopt->dataOnly)
10339 return;
10341 q = createPQExpBuffer();
10342 delq = createPQExpBuffer();
10344 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
10346 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
10348 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
10350 if (dopt->binary_upgrade)
10351 binary_upgrade_extension_member(q, &nspinfo->dobj,
10352 "SCHEMA", qnspname, NULL);
10354 if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10355 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
10356 ARCHIVE_OPTS(.tag = nspinfo->dobj.name,
10357 .owner = nspinfo->rolname,
10358 .description = "SCHEMA",
10359 .section = SECTION_PRE_DATA,
10360 .createStmt = q->data,
10361 .dropStmt = delq->data));
10363 /* Dump Schema Comments and Security Labels */
10364 if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10365 dumpComment(fout, "SCHEMA", qnspname,
10366 NULL, nspinfo->rolname,
10367 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
10369 if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10370 dumpSecLabel(fout, "SCHEMA", qnspname,
10371 NULL, nspinfo->rolname,
10372 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
10374 if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
10375 dumpACL(fout, nspinfo->dobj.dumpId, InvalidDumpId, "SCHEMA",
10376 qnspname, NULL, NULL,
10377 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
10378 nspinfo->initnspacl, nspinfo->initrnspacl);
10380 free(qnspname);
10382 destroyPQExpBuffer(q);
10383 destroyPQExpBuffer(delq);
10387 * dumpExtension
10388 * writes out to fout the queries to recreate an extension
10390 static void
10391 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
10393 DumpOptions *dopt = fout->dopt;
10394 PQExpBuffer q;
10395 PQExpBuffer delq;
10396 char *qextname;
10398 /* Skip if not to be dumped */
10399 if (!extinfo->dobj.dump || dopt->dataOnly)
10400 return;
10402 q = createPQExpBuffer();
10403 delq = createPQExpBuffer();
10405 qextname = pg_strdup(fmtId(extinfo->dobj.name));
10407 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
10409 if (!dopt->binary_upgrade)
10412 * In a regular dump, we simply create the extension, intentionally
10413 * not specifying a version, so that the destination installation's
10414 * default version is used.
10416 * Use of IF NOT EXISTS here is unlike our behavior for other object
10417 * types; but there are various scenarios in which it's convenient to
10418 * manually create the desired extension before restoring, so we
10419 * prefer to allow it to exist already.
10421 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
10422 qextname, fmtId(extinfo->namespace));
10424 else
10427 * In binary-upgrade mode, it's critical to reproduce the state of the
10428 * database exactly, so our procedure is to create an empty extension,
10429 * restore all the contained objects normally, and add them to the
10430 * extension one by one. This function performs just the first of
10431 * those steps. binary_upgrade_extension_member() takes care of
10432 * adding member objects as they're created.
10434 int i;
10435 int n;
10437 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
10440 * We unconditionally create the extension, so we must drop it if it
10441 * exists. This could happen if the user deleted 'plpgsql' and then
10442 * readded it, causing its oid to be greater than g_last_builtin_oid.
10444 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
10446 appendPQExpBufferStr(q,
10447 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
10448 appendStringLiteralAH(q, extinfo->dobj.name, fout);
10449 appendPQExpBufferStr(q, ", ");
10450 appendStringLiteralAH(q, extinfo->namespace, fout);
10451 appendPQExpBufferStr(q, ", ");
10452 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
10453 appendStringLiteralAH(q, extinfo->extversion, fout);
10454 appendPQExpBufferStr(q, ", ");
10457 * Note that we're pushing extconfig (an OID array) back into
10458 * pg_extension exactly as-is. This is OK because pg_class OIDs are
10459 * preserved in binary upgrade.
10461 if (strlen(extinfo->extconfig) > 2)
10462 appendStringLiteralAH(q, extinfo->extconfig, fout);
10463 else
10464 appendPQExpBufferStr(q, "NULL");
10465 appendPQExpBufferStr(q, ", ");
10466 if (strlen(extinfo->extcondition) > 2)
10467 appendStringLiteralAH(q, extinfo->extcondition, fout);
10468 else
10469 appendPQExpBufferStr(q, "NULL");
10470 appendPQExpBufferStr(q, ", ");
10471 appendPQExpBufferStr(q, "ARRAY[");
10472 n = 0;
10473 for (i = 0; i < extinfo->dobj.nDeps; i++)
10475 DumpableObject *extobj;
10477 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10478 if (extobj && extobj->objType == DO_EXTENSION)
10480 if (n++ > 0)
10481 appendPQExpBufferChar(q, ',');
10482 appendStringLiteralAH(q, extobj->name, fout);
10485 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10486 appendPQExpBufferStr(q, ");\n");
10489 if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10490 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10491 ARCHIVE_OPTS(.tag = extinfo->dobj.name,
10492 .description = "EXTENSION",
10493 .section = SECTION_PRE_DATA,
10494 .createStmt = q->data,
10495 .dropStmt = delq->data));
10497 /* Dump Extension Comments and Security Labels */
10498 if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10499 dumpComment(fout, "EXTENSION", qextname,
10500 NULL, "",
10501 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10503 if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10504 dumpSecLabel(fout, "EXTENSION", qextname,
10505 NULL, "",
10506 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10508 free(qextname);
10510 destroyPQExpBuffer(q);
10511 destroyPQExpBuffer(delq);
10515 * dumpType
10516 * writes out to fout the queries to recreate a user-defined type
10518 static void
10519 dumpType(Archive *fout, TypeInfo *tyinfo)
10521 DumpOptions *dopt = fout->dopt;
10523 /* Skip if not to be dumped */
10524 if (!tyinfo->dobj.dump || dopt->dataOnly)
10525 return;
10527 /* Dump out in proper style */
10528 if (tyinfo->typtype == TYPTYPE_BASE)
10529 dumpBaseType(fout, tyinfo);
10530 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10531 dumpDomain(fout, tyinfo);
10532 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10533 dumpCompositeType(fout, tyinfo);
10534 else if (tyinfo->typtype == TYPTYPE_ENUM)
10535 dumpEnumType(fout, tyinfo);
10536 else if (tyinfo->typtype == TYPTYPE_RANGE)
10537 dumpRangeType(fout, tyinfo);
10538 else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10539 dumpUndefinedType(fout, tyinfo);
10540 else
10541 pg_log_warning("typtype of data type \"%s\" appears to be invalid",
10542 tyinfo->dobj.name);
10546 * dumpEnumType
10547 * writes out to fout the queries to recreate a user-defined enum type
10549 static void
10550 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10552 DumpOptions *dopt = fout->dopt;
10553 PQExpBuffer q = createPQExpBuffer();
10554 PQExpBuffer delq = createPQExpBuffer();
10555 PQExpBuffer query = createPQExpBuffer();
10556 PGresult *res;
10557 int num,
10559 Oid enum_oid;
10560 char *qtypname;
10561 char *qualtypname;
10562 char *label;
10564 if (fout->remoteVersion >= 90100)
10565 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10566 "FROM pg_catalog.pg_enum "
10567 "WHERE enumtypid = '%u'"
10568 "ORDER BY enumsortorder",
10569 tyinfo->dobj.catId.oid);
10570 else
10571 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10572 "FROM pg_catalog.pg_enum "
10573 "WHERE enumtypid = '%u'"
10574 "ORDER BY oid",
10575 tyinfo->dobj.catId.oid);
10577 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10579 num = PQntuples(res);
10581 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10582 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10585 * CASCADE shouldn't be required here as for normal types since the I/O
10586 * functions are generic and do not get dropped.
10588 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10590 if (dopt->binary_upgrade)
10591 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10592 tyinfo->dobj.catId.oid,
10593 false);
10595 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10596 qualtypname);
10598 if (!dopt->binary_upgrade)
10600 /* Labels with server-assigned oids */
10601 for (i = 0; i < num; i++)
10603 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10604 if (i > 0)
10605 appendPQExpBufferChar(q, ',');
10606 appendPQExpBufferStr(q, "\n ");
10607 appendStringLiteralAH(q, label, fout);
10611 appendPQExpBufferStr(q, "\n);\n");
10613 if (dopt->binary_upgrade)
10615 /* Labels with dump-assigned (preserved) oids */
10616 for (i = 0; i < num; i++)
10618 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10619 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10621 if (i == 0)
10622 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10623 appendPQExpBuffer(q,
10624 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10625 enum_oid);
10626 appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10627 appendStringLiteralAH(q, label, fout);
10628 appendPQExpBufferStr(q, ";\n\n");
10632 if (dopt->binary_upgrade)
10633 binary_upgrade_extension_member(q, &tyinfo->dobj,
10634 "TYPE", qtypname,
10635 tyinfo->dobj.namespace->dobj.name);
10637 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10638 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10639 ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
10640 .namespace = tyinfo->dobj.namespace->dobj.name,
10641 .owner = tyinfo->rolname,
10642 .description = "TYPE",
10643 .section = SECTION_PRE_DATA,
10644 .createStmt = q->data,
10645 .dropStmt = delq->data));
10647 /* Dump Type Comments and Security Labels */
10648 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10649 dumpComment(fout, "TYPE", qtypname,
10650 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10651 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10653 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10654 dumpSecLabel(fout, "TYPE", qtypname,
10655 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10656 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10658 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10659 dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
10660 qtypname, NULL,
10661 tyinfo->dobj.namespace->dobj.name,
10662 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10663 tyinfo->inittypacl, tyinfo->initrtypacl);
10665 PQclear(res);
10666 destroyPQExpBuffer(q);
10667 destroyPQExpBuffer(delq);
10668 destroyPQExpBuffer(query);
10669 free(qtypname);
10670 free(qualtypname);
10674 * dumpRangeType
10675 * writes out to fout the queries to recreate a user-defined range type
10677 static void
10678 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10680 DumpOptions *dopt = fout->dopt;
10681 PQExpBuffer q = createPQExpBuffer();
10682 PQExpBuffer delq = createPQExpBuffer();
10683 PQExpBuffer query = createPQExpBuffer();
10684 PGresult *res;
10685 Oid collationOid;
10686 char *qtypname;
10687 char *qualtypname;
10688 char *procname;
10690 appendPQExpBuffer(query,
10691 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10692 "opc.opcname AS opcname, "
10693 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10694 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10695 "opc.opcdefault, "
10696 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10697 " ELSE rngcollation END AS collation, "
10698 "rngcanonical, rngsubdiff "
10699 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10700 " pg_catalog.pg_opclass opc "
10701 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10702 "rngtypid = '%u'",
10703 tyinfo->dobj.catId.oid);
10705 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10707 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10708 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10711 * CASCADE shouldn't be required here as for normal types since the I/O
10712 * functions are generic and do not get dropped.
10714 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10716 if (dopt->binary_upgrade)
10717 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10718 tyinfo->dobj.catId.oid,
10719 false);
10721 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10722 qualtypname);
10724 appendPQExpBuffer(q, "\n subtype = %s",
10725 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10727 /* print subtype_opclass only if not default for subtype */
10728 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10730 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10731 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10733 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
10734 fmtId(nspname));
10735 appendPQExpBufferStr(q, fmtId(opcname));
10738 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10739 if (OidIsValid(collationOid))
10741 CollInfo *coll = findCollationByOid(collationOid);
10743 if (coll)
10744 appendPQExpBuffer(q, ",\n collation = %s",
10745 fmtQualifiedDumpable(coll));
10748 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10749 if (strcmp(procname, "-") != 0)
10750 appendPQExpBuffer(q, ",\n canonical = %s", procname);
10752 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10753 if (strcmp(procname, "-") != 0)
10754 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
10756 appendPQExpBufferStr(q, "\n);\n");
10758 if (dopt->binary_upgrade)
10759 binary_upgrade_extension_member(q, &tyinfo->dobj,
10760 "TYPE", qtypname,
10761 tyinfo->dobj.namespace->dobj.name);
10763 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10764 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10765 ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
10766 .namespace = tyinfo->dobj.namespace->dobj.name,
10767 .owner = tyinfo->rolname,
10768 .description = "TYPE",
10769 .section = SECTION_PRE_DATA,
10770 .createStmt = q->data,
10771 .dropStmt = delq->data));
10773 /* Dump Type Comments and Security Labels */
10774 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10775 dumpComment(fout, "TYPE", qtypname,
10776 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10777 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10779 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10780 dumpSecLabel(fout, "TYPE", qtypname,
10781 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10782 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10784 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10785 dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
10786 qtypname, NULL,
10787 tyinfo->dobj.namespace->dobj.name,
10788 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10789 tyinfo->inittypacl, tyinfo->initrtypacl);
10791 PQclear(res);
10792 destroyPQExpBuffer(q);
10793 destroyPQExpBuffer(delq);
10794 destroyPQExpBuffer(query);
10795 free(qtypname);
10796 free(qualtypname);
10800 * dumpUndefinedType
10801 * writes out to fout the queries to recreate a !typisdefined type
10803 * This is a shell type, but we use different terminology to distinguish
10804 * this case from where we have to emit a shell type definition to break
10805 * circular dependencies. An undefined type shouldn't ever have anything
10806 * depending on it.
10808 static void
10809 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10811 DumpOptions *dopt = fout->dopt;
10812 PQExpBuffer q = createPQExpBuffer();
10813 PQExpBuffer delq = createPQExpBuffer();
10814 char *qtypname;
10815 char *qualtypname;
10817 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10818 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10820 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10822 if (dopt->binary_upgrade)
10823 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10824 tyinfo->dobj.catId.oid,
10825 false);
10827 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10828 qualtypname);
10830 if (dopt->binary_upgrade)
10831 binary_upgrade_extension_member(q, &tyinfo->dobj,
10832 "TYPE", qtypname,
10833 tyinfo->dobj.namespace->dobj.name);
10835 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10836 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10837 ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
10838 .namespace = tyinfo->dobj.namespace->dobj.name,
10839 .owner = tyinfo->rolname,
10840 .description = "TYPE",
10841 .section = SECTION_PRE_DATA,
10842 .createStmt = q->data,
10843 .dropStmt = delq->data));
10845 /* Dump Type Comments and Security Labels */
10846 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10847 dumpComment(fout, "TYPE", qtypname,
10848 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10849 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10851 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10852 dumpSecLabel(fout, "TYPE", qtypname,
10853 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10854 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10856 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10857 dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
10858 qtypname, NULL,
10859 tyinfo->dobj.namespace->dobj.name,
10860 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10861 tyinfo->inittypacl, tyinfo->initrtypacl);
10863 destroyPQExpBuffer(q);
10864 destroyPQExpBuffer(delq);
10865 free(qtypname);
10866 free(qualtypname);
10870 * dumpBaseType
10871 * writes out to fout the queries to recreate a user-defined base type
10873 static void
10874 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10876 DumpOptions *dopt = fout->dopt;
10877 PQExpBuffer q = createPQExpBuffer();
10878 PQExpBuffer delq = createPQExpBuffer();
10879 PQExpBuffer query = createPQExpBuffer();
10880 PGresult *res;
10881 char *qtypname;
10882 char *qualtypname;
10883 char *typlen;
10884 char *typinput;
10885 char *typoutput;
10886 char *typreceive;
10887 char *typsend;
10888 char *typmodin;
10889 char *typmodout;
10890 char *typanalyze;
10891 Oid typreceiveoid;
10892 Oid typsendoid;
10893 Oid typmodinoid;
10894 Oid typmodoutoid;
10895 Oid typanalyzeoid;
10896 char *typcategory;
10897 char *typispreferred;
10898 char *typdelim;
10899 char *typbyval;
10900 char *typalign;
10901 char *typstorage;
10902 char *typcollatable;
10903 char *typdefault;
10904 bool typdefault_is_literal = false;
10906 /* Fetch type-specific details */
10907 if (fout->remoteVersion >= 90100)
10909 appendPQExpBuffer(query, "SELECT typlen, "
10910 "typinput, typoutput, typreceive, typsend, "
10911 "typmodin, typmodout, typanalyze, "
10912 "typreceive::pg_catalog.oid AS typreceiveoid, "
10913 "typsend::pg_catalog.oid AS typsendoid, "
10914 "typmodin::pg_catalog.oid AS typmodinoid, "
10915 "typmodout::pg_catalog.oid AS typmodoutoid, "
10916 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10917 "typcategory, typispreferred, "
10918 "typdelim, typbyval, typalign, typstorage, "
10919 "(typcollation <> 0) AS typcollatable, "
10920 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10921 "FROM pg_catalog.pg_type "
10922 "WHERE oid = '%u'::pg_catalog.oid",
10923 tyinfo->dobj.catId.oid);
10925 else if (fout->remoteVersion >= 80400)
10927 appendPQExpBuffer(query, "SELECT typlen, "
10928 "typinput, typoutput, typreceive, typsend, "
10929 "typmodin, typmodout, typanalyze, "
10930 "typreceive::pg_catalog.oid AS typreceiveoid, "
10931 "typsend::pg_catalog.oid AS typsendoid, "
10932 "typmodin::pg_catalog.oid AS typmodinoid, "
10933 "typmodout::pg_catalog.oid AS typmodoutoid, "
10934 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10935 "typcategory, typispreferred, "
10936 "typdelim, typbyval, typalign, typstorage, "
10937 "false AS typcollatable, "
10938 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10939 "FROM pg_catalog.pg_type "
10940 "WHERE oid = '%u'::pg_catalog.oid",
10941 tyinfo->dobj.catId.oid);
10943 else if (fout->remoteVersion >= 80300)
10945 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10946 appendPQExpBuffer(query, "SELECT typlen, "
10947 "typinput, typoutput, typreceive, typsend, "
10948 "typmodin, typmodout, typanalyze, "
10949 "typreceive::pg_catalog.oid AS typreceiveoid, "
10950 "typsend::pg_catalog.oid AS typsendoid, "
10951 "typmodin::pg_catalog.oid AS typmodinoid, "
10952 "typmodout::pg_catalog.oid AS typmodoutoid, "
10953 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10954 "'U' AS typcategory, false AS typispreferred, "
10955 "typdelim, typbyval, typalign, typstorage, "
10956 "false AS typcollatable, "
10957 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10958 "FROM pg_catalog.pg_type "
10959 "WHERE oid = '%u'::pg_catalog.oid",
10960 tyinfo->dobj.catId.oid);
10962 else
10964 appendPQExpBuffer(query, "SELECT typlen, "
10965 "typinput, typoutput, typreceive, typsend, "
10966 "'-' AS typmodin, '-' AS typmodout, "
10967 "typanalyze, "
10968 "typreceive::pg_catalog.oid AS typreceiveoid, "
10969 "typsend::pg_catalog.oid AS typsendoid, "
10970 "0 AS typmodinoid, 0 AS typmodoutoid, "
10971 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10972 "'U' AS typcategory, false AS typispreferred, "
10973 "typdelim, typbyval, typalign, typstorage, "
10974 "false AS typcollatable, "
10975 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10976 "FROM pg_catalog.pg_type "
10977 "WHERE oid = '%u'::pg_catalog.oid",
10978 tyinfo->dobj.catId.oid);
10981 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10983 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10984 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10985 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10986 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10987 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10988 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10989 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10990 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10991 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10992 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10993 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10994 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10995 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10996 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10997 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10998 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10999 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
11000 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
11001 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
11002 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
11003 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
11004 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
11005 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
11007 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
11008 typdefault_is_literal = true; /* it needs quotes */
11010 else
11011 typdefault = NULL;
11013 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11014 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11017 * The reason we include CASCADE is that the circular dependency between
11018 * the type and its I/O functions makes it impossible to drop the type any
11019 * other way.
11021 appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
11024 * We might already have a shell type, but setting pg_type_oid is
11025 * harmless, and in any case we'd better set the array type OID.
11027 if (dopt->binary_upgrade)
11028 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11029 tyinfo->dobj.catId.oid,
11030 false);
11032 appendPQExpBuffer(q,
11033 "CREATE TYPE %s (\n"
11034 " INTERNALLENGTH = %s",
11035 qualtypname,
11036 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
11038 /* regproc result is sufficiently quoted already */
11039 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
11040 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
11041 if (OidIsValid(typreceiveoid))
11042 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
11043 if (OidIsValid(typsendoid))
11044 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
11045 if (OidIsValid(typmodinoid))
11046 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
11047 if (OidIsValid(typmodoutoid))
11048 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
11049 if (OidIsValid(typanalyzeoid))
11050 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
11052 if (strcmp(typcollatable, "t") == 0)
11053 appendPQExpBufferStr(q, ",\n COLLATABLE = true");
11055 if (typdefault != NULL)
11057 appendPQExpBufferStr(q, ",\n DEFAULT = ");
11058 if (typdefault_is_literal)
11059 appendStringLiteralAH(q, typdefault, fout);
11060 else
11061 appendPQExpBufferStr(q, typdefault);
11064 if (OidIsValid(tyinfo->typelem))
11065 appendPQExpBuffer(q, ",\n ELEMENT = %s",
11066 getFormattedTypeName(fout, tyinfo->typelem,
11067 zeroAsOpaque));
11069 if (strcmp(typcategory, "U") != 0)
11071 appendPQExpBufferStr(q, ",\n CATEGORY = ");
11072 appendStringLiteralAH(q, typcategory, fout);
11075 if (strcmp(typispreferred, "t") == 0)
11076 appendPQExpBufferStr(q, ",\n PREFERRED = true");
11078 if (typdelim && strcmp(typdelim, ",") != 0)
11080 appendPQExpBufferStr(q, ",\n DELIMITER = ");
11081 appendStringLiteralAH(q, typdelim, fout);
11084 if (strcmp(typalign, "c") == 0)
11085 appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
11086 else if (strcmp(typalign, "s") == 0)
11087 appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
11088 else if (strcmp(typalign, "i") == 0)
11089 appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
11090 else if (strcmp(typalign, "d") == 0)
11091 appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
11093 if (strcmp(typstorage, "p") == 0)
11094 appendPQExpBufferStr(q, ",\n STORAGE = plain");
11095 else if (strcmp(typstorage, "e") == 0)
11096 appendPQExpBufferStr(q, ",\n STORAGE = external");
11097 else if (strcmp(typstorage, "x") == 0)
11098 appendPQExpBufferStr(q, ",\n STORAGE = extended");
11099 else if (strcmp(typstorage, "m") == 0)
11100 appendPQExpBufferStr(q, ",\n STORAGE = main");
11102 if (strcmp(typbyval, "t") == 0)
11103 appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
11105 appendPQExpBufferStr(q, "\n);\n");
11107 if (dopt->binary_upgrade)
11108 binary_upgrade_extension_member(q, &tyinfo->dobj,
11109 "TYPE", qtypname,
11110 tyinfo->dobj.namespace->dobj.name);
11112 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11113 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11114 ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11115 .namespace = tyinfo->dobj.namespace->dobj.name,
11116 .owner = tyinfo->rolname,
11117 .description = "TYPE",
11118 .section = SECTION_PRE_DATA,
11119 .createStmt = q->data,
11120 .dropStmt = delq->data));
11122 /* Dump Type Comments and Security Labels */
11123 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11124 dumpComment(fout, "TYPE", qtypname,
11125 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11126 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11128 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11129 dumpSecLabel(fout, "TYPE", qtypname,
11130 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11131 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11133 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11134 dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11135 qtypname, NULL,
11136 tyinfo->dobj.namespace->dobj.name,
11137 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11138 tyinfo->inittypacl, tyinfo->initrtypacl);
11140 PQclear(res);
11141 destroyPQExpBuffer(q);
11142 destroyPQExpBuffer(delq);
11143 destroyPQExpBuffer(query);
11144 free(qtypname);
11145 free(qualtypname);
11149 * dumpDomain
11150 * writes out to fout the queries to recreate a user-defined domain
11152 static void
11153 dumpDomain(Archive *fout, TypeInfo *tyinfo)
11155 DumpOptions *dopt = fout->dopt;
11156 PQExpBuffer q = createPQExpBuffer();
11157 PQExpBuffer delq = createPQExpBuffer();
11158 PQExpBuffer query = createPQExpBuffer();
11159 PGresult *res;
11160 int i;
11161 char *qtypname;
11162 char *qualtypname;
11163 char *typnotnull;
11164 char *typdefn;
11165 char *typdefault;
11166 Oid typcollation;
11167 bool typdefault_is_literal = false;
11169 /* Fetch domain specific details */
11170 if (fout->remoteVersion >= 90100)
11172 /* typcollation is new in 9.1 */
11173 appendPQExpBuffer(query, "SELECT t.typnotnull, "
11174 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
11175 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
11176 "t.typdefault, "
11177 "CASE WHEN t.typcollation <> u.typcollation "
11178 "THEN t.typcollation ELSE 0 END AS typcollation "
11179 "FROM pg_catalog.pg_type t "
11180 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
11181 "WHERE t.oid = '%u'::pg_catalog.oid",
11182 tyinfo->dobj.catId.oid);
11184 else
11186 appendPQExpBuffer(query, "SELECT typnotnull, "
11187 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
11188 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
11189 "typdefault, 0 AS typcollation "
11190 "FROM pg_catalog.pg_type "
11191 "WHERE oid = '%u'::pg_catalog.oid",
11192 tyinfo->dobj.catId.oid);
11195 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11197 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
11198 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
11199 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
11200 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
11201 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
11203 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
11204 typdefault_is_literal = true; /* it needs quotes */
11206 else
11207 typdefault = NULL;
11208 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
11210 if (dopt->binary_upgrade)
11211 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11212 tyinfo->dobj.catId.oid,
11213 true); /* force array type */
11215 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11216 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11218 appendPQExpBuffer(q,
11219 "CREATE DOMAIN %s AS %s",
11220 qualtypname,
11221 typdefn);
11223 /* Print collation only if different from base type's collation */
11224 if (OidIsValid(typcollation))
11226 CollInfo *coll;
11228 coll = findCollationByOid(typcollation);
11229 if (coll)
11230 appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
11233 if (typnotnull[0] == 't')
11234 appendPQExpBufferStr(q, " NOT NULL");
11236 if (typdefault != NULL)
11238 appendPQExpBufferStr(q, " DEFAULT ");
11239 if (typdefault_is_literal)
11240 appendStringLiteralAH(q, typdefault, fout);
11241 else
11242 appendPQExpBufferStr(q, typdefault);
11245 PQclear(res);
11248 * Add any CHECK constraints for the domain
11250 for (i = 0; i < tyinfo->nDomChecks; i++)
11252 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
11254 if (!domcheck->separate)
11255 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
11256 fmtId(domcheck->dobj.name), domcheck->condef);
11259 appendPQExpBufferStr(q, ";\n");
11261 appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
11263 if (dopt->binary_upgrade)
11264 binary_upgrade_extension_member(q, &tyinfo->dobj,
11265 "DOMAIN", qtypname,
11266 tyinfo->dobj.namespace->dobj.name);
11268 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11269 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11270 ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11271 .namespace = tyinfo->dobj.namespace->dobj.name,
11272 .owner = tyinfo->rolname,
11273 .description = "DOMAIN",
11274 .section = SECTION_PRE_DATA,
11275 .createStmt = q->data,
11276 .dropStmt = delq->data));
11278 /* Dump Domain Comments and Security Labels */
11279 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11280 dumpComment(fout, "DOMAIN", qtypname,
11281 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11282 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11284 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11285 dumpSecLabel(fout, "DOMAIN", qtypname,
11286 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11287 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11289 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11290 dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11291 qtypname, NULL,
11292 tyinfo->dobj.namespace->dobj.name,
11293 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11294 tyinfo->inittypacl, tyinfo->initrtypacl);
11296 /* Dump any per-constraint comments */
11297 for (i = 0; i < tyinfo->nDomChecks; i++)
11299 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
11300 PQExpBuffer conprefix = createPQExpBuffer();
11302 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
11303 fmtId(domcheck->dobj.name));
11305 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11306 dumpComment(fout, conprefix->data, qtypname,
11307 tyinfo->dobj.namespace->dobj.name,
11308 tyinfo->rolname,
11309 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
11311 destroyPQExpBuffer(conprefix);
11314 destroyPQExpBuffer(q);
11315 destroyPQExpBuffer(delq);
11316 destroyPQExpBuffer(query);
11317 free(qtypname);
11318 free(qualtypname);
11322 * dumpCompositeType
11323 * writes out to fout the queries to recreate a user-defined stand-alone
11324 * composite type
11326 static void
11327 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
11329 DumpOptions *dopt = fout->dopt;
11330 PQExpBuffer q = createPQExpBuffer();
11331 PQExpBuffer dropped = createPQExpBuffer();
11332 PQExpBuffer delq = createPQExpBuffer();
11333 PQExpBuffer query = createPQExpBuffer();
11334 PGresult *res;
11335 char *qtypname;
11336 char *qualtypname;
11337 int ntups;
11338 int i_attname;
11339 int i_atttypdefn;
11340 int i_attlen;
11341 int i_attalign;
11342 int i_attisdropped;
11343 int i_attcollation;
11344 int i;
11345 int actual_atts;
11347 /* Fetch type specific details */
11348 if (fout->remoteVersion >= 90100)
11351 * attcollation is new in 9.1. Since we only want to dump COLLATE
11352 * clauses for attributes whose collation is different from their
11353 * type's default, we use a CASE here to suppress uninteresting
11354 * attcollations cheaply. atttypid will be 0 for dropped columns;
11355 * collation does not matter for those.
11357 appendPQExpBuffer(query, "SELECT a.attname, "
11358 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
11359 "a.attlen, a.attalign, a.attisdropped, "
11360 "CASE WHEN a.attcollation <> at.typcollation "
11361 "THEN a.attcollation ELSE 0 END AS attcollation "
11362 "FROM pg_catalog.pg_type ct "
11363 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
11364 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
11365 "WHERE ct.oid = '%u'::pg_catalog.oid "
11366 "ORDER BY a.attnum ",
11367 tyinfo->dobj.catId.oid);
11369 else
11372 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
11373 * should always be false.
11375 appendPQExpBuffer(query, "SELECT a.attname, "
11376 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
11377 "a.attlen, a.attalign, a.attisdropped, "
11378 "0 AS attcollation "
11379 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
11380 "WHERE ct.oid = '%u'::pg_catalog.oid "
11381 "AND a.attrelid = ct.typrelid "
11382 "ORDER BY a.attnum ",
11383 tyinfo->dobj.catId.oid);
11386 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11388 ntups = PQntuples(res);
11390 i_attname = PQfnumber(res, "attname");
11391 i_atttypdefn = PQfnumber(res, "atttypdefn");
11392 i_attlen = PQfnumber(res, "attlen");
11393 i_attalign = PQfnumber(res, "attalign");
11394 i_attisdropped = PQfnumber(res, "attisdropped");
11395 i_attcollation = PQfnumber(res, "attcollation");
11397 if (dopt->binary_upgrade)
11399 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11400 tyinfo->dobj.catId.oid,
11401 false);
11402 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
11405 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11406 qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11408 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
11409 qualtypname);
11411 actual_atts = 0;
11412 for (i = 0; i < ntups; i++)
11414 char *attname;
11415 char *atttypdefn;
11416 char *attlen;
11417 char *attalign;
11418 bool attisdropped;
11419 Oid attcollation;
11421 attname = PQgetvalue(res, i, i_attname);
11422 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
11423 attlen = PQgetvalue(res, i, i_attlen);
11424 attalign = PQgetvalue(res, i, i_attalign);
11425 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
11426 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
11428 if (attisdropped && !dopt->binary_upgrade)
11429 continue;
11431 /* Format properly if not first attr */
11432 if (actual_atts++ > 0)
11433 appendPQExpBufferChar(q, ',');
11434 appendPQExpBufferStr(q, "\n\t");
11436 if (!attisdropped)
11438 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
11440 /* Add collation if not default for the column type */
11441 if (OidIsValid(attcollation))
11443 CollInfo *coll;
11445 coll = findCollationByOid(attcollation);
11446 if (coll)
11447 appendPQExpBuffer(q, " COLLATE %s",
11448 fmtQualifiedDumpable(coll));
11451 else
11454 * This is a dropped attribute and we're in binary_upgrade mode.
11455 * Insert a placeholder for it in the CREATE TYPE command, and set
11456 * length and alignment with direct UPDATE to the catalogs
11457 * afterwards. See similar code in dumpTableSchema().
11459 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11461 /* stash separately for insertion after the CREATE TYPE */
11462 appendPQExpBufferStr(dropped,
11463 "\n-- For binary upgrade, recreate dropped column.\n");
11464 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11465 "SET attlen = %s, "
11466 "attalign = '%s', attbyval = false\n"
11467 "WHERE attname = ", attlen, attalign);
11468 appendStringLiteralAH(dropped, attname, fout);
11469 appendPQExpBufferStr(dropped, "\n AND attrelid = ");
11470 appendStringLiteralAH(dropped, qualtypname, fout);
11471 appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11473 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11474 qualtypname);
11475 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11476 fmtId(attname));
11479 appendPQExpBufferStr(q, "\n);\n");
11480 appendPQExpBufferStr(q, dropped->data);
11482 appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11484 if (dopt->binary_upgrade)
11485 binary_upgrade_extension_member(q, &tyinfo->dobj,
11486 "TYPE", qtypname,
11487 tyinfo->dobj.namespace->dobj.name);
11489 if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11490 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11491 ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11492 .namespace = tyinfo->dobj.namespace->dobj.name,
11493 .owner = tyinfo->rolname,
11494 .description = "TYPE",
11495 .section = SECTION_PRE_DATA,
11496 .createStmt = q->data,
11497 .dropStmt = delq->data));
11500 /* Dump Type Comments and Security Labels */
11501 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11502 dumpComment(fout, "TYPE", qtypname,
11503 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11504 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11506 if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11507 dumpSecLabel(fout, "TYPE", qtypname,
11508 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11509 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11511 if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11512 dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11513 qtypname, NULL,
11514 tyinfo->dobj.namespace->dobj.name,
11515 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11516 tyinfo->inittypacl, tyinfo->initrtypacl);
11518 PQclear(res);
11519 destroyPQExpBuffer(q);
11520 destroyPQExpBuffer(dropped);
11521 destroyPQExpBuffer(delq);
11522 destroyPQExpBuffer(query);
11523 free(qtypname);
11524 free(qualtypname);
11526 /* Dump any per-column comments */
11527 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11528 dumpCompositeTypeColComments(fout, tyinfo);
11532 * dumpCompositeTypeColComments
11533 * writes out to fout the queries to recreate comments on the columns of
11534 * a user-defined stand-alone composite type
11536 static void
11537 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11539 CommentItem *comments;
11540 int ncomments;
11541 PGresult *res;
11542 PQExpBuffer query;
11543 PQExpBuffer target;
11544 Oid pgClassOid;
11545 int i;
11546 int ntups;
11547 int i_attname;
11548 int i_attnum;
11550 /* do nothing, if --no-comments is supplied */
11551 if (fout->dopt->no_comments)
11552 return;
11554 query = createPQExpBuffer();
11556 appendPQExpBuffer(query,
11557 "SELECT c.tableoid, a.attname, a.attnum "
11558 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11559 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11560 " AND NOT a.attisdropped "
11561 "ORDER BY a.attnum ",
11562 tyinfo->typrelid);
11564 /* Fetch column attnames */
11565 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11567 ntups = PQntuples(res);
11568 if (ntups < 1)
11570 PQclear(res);
11571 destroyPQExpBuffer(query);
11572 return;
11575 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11577 /* Search for comments associated with type's pg_class OID */
11578 ncomments = findComments(fout,
11579 pgClassOid,
11580 tyinfo->typrelid,
11581 &comments);
11583 /* If no comments exist, we're done */
11584 if (ncomments <= 0)
11586 PQclear(res);
11587 destroyPQExpBuffer(query);
11588 return;
11591 /* Build COMMENT ON statements */
11592 target = createPQExpBuffer();
11594 i_attnum = PQfnumber(res, "attnum");
11595 i_attname = PQfnumber(res, "attname");
11596 while (ncomments > 0)
11598 const char *attname;
11600 attname = NULL;
11601 for (i = 0; i < ntups; i++)
11603 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11605 attname = PQgetvalue(res, i, i_attname);
11606 break;
11609 if (attname) /* just in case we don't find it */
11611 const char *descr = comments->descr;
11613 resetPQExpBuffer(target);
11614 appendPQExpBuffer(target, "COLUMN %s.",
11615 fmtId(tyinfo->dobj.name));
11616 appendPQExpBufferStr(target, fmtId(attname));
11618 resetPQExpBuffer(query);
11619 appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11620 fmtQualifiedDumpable(tyinfo));
11621 appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11622 appendStringLiteralAH(query, descr, fout);
11623 appendPQExpBufferStr(query, ";\n");
11625 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11626 ARCHIVE_OPTS(.tag = target->data,
11627 .namespace = tyinfo->dobj.namespace->dobj.name,
11628 .owner = tyinfo->rolname,
11629 .description = "COMMENT",
11630 .section = SECTION_NONE,
11631 .createStmt = query->data,
11632 .deps = &(tyinfo->dobj.dumpId),
11633 .nDeps = 1));
11636 comments++;
11637 ncomments--;
11640 PQclear(res);
11641 destroyPQExpBuffer(query);
11642 destroyPQExpBuffer(target);
11646 * dumpShellType
11647 * writes out to fout the queries to create a shell type
11649 * We dump a shell definition in advance of the I/O functions for the type.
11651 static void
11652 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11654 DumpOptions *dopt = fout->dopt;
11655 PQExpBuffer q;
11657 /* Skip if not to be dumped */
11658 if (!stinfo->dobj.dump || dopt->dataOnly)
11659 return;
11661 q = createPQExpBuffer();
11664 * Note the lack of a DROP command for the shell type; any required DROP
11665 * is driven off the base type entry, instead. This interacts with
11666 * _printTocEntry()'s use of the presence of a DROP command to decide
11667 * whether an entry needs an ALTER OWNER command. We don't want to alter
11668 * the shell type's owner immediately on creation; that should happen only
11669 * after it's filled in, otherwise the backend complains.
11672 if (dopt->binary_upgrade)
11673 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11674 stinfo->baseType->dobj.catId.oid,
11675 false);
11677 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11678 fmtQualifiedDumpable(stinfo));
11680 if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11681 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11682 ARCHIVE_OPTS(.tag = stinfo->dobj.name,
11683 .namespace = stinfo->dobj.namespace->dobj.name,
11684 .owner = stinfo->baseType->rolname,
11685 .description = "SHELL TYPE",
11686 .section = SECTION_PRE_DATA,
11687 .createStmt = q->data));
11689 destroyPQExpBuffer(q);
11693 * dumpProcLang
11694 * writes out to fout the queries to recreate a user-defined
11695 * procedural language
11697 static void
11698 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11700 DumpOptions *dopt = fout->dopt;
11701 PQExpBuffer defqry;
11702 PQExpBuffer delqry;
11703 bool useParams;
11704 char *qlanname;
11705 FuncInfo *funcInfo;
11706 FuncInfo *inlineInfo = NULL;
11707 FuncInfo *validatorInfo = NULL;
11709 /* Skip if not to be dumped */
11710 if (!plang->dobj.dump || dopt->dataOnly)
11711 return;
11714 * Try to find the support function(s). It is not an error if we don't
11715 * find them --- if the functions are in the pg_catalog schema, as is
11716 * standard in 8.1 and up, then we won't have loaded them. (In this case
11717 * we will emit a parameterless CREATE LANGUAGE command, which will
11718 * require PL template knowledge in the backend to reload.)
11721 funcInfo = findFuncByOid(plang->lanplcallfoid);
11722 if (funcInfo != NULL && !funcInfo->dobj.dump)
11723 funcInfo = NULL; /* treat not-dumped same as not-found */
11725 if (OidIsValid(plang->laninline))
11727 inlineInfo = findFuncByOid(plang->laninline);
11728 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11729 inlineInfo = NULL;
11732 if (OidIsValid(plang->lanvalidator))
11734 validatorInfo = findFuncByOid(plang->lanvalidator);
11735 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11736 validatorInfo = NULL;
11740 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11741 * with parameters. Otherwise, we'll write a parameterless command, which
11742 * will rely on data from pg_pltemplate.
11744 useParams = (funcInfo != NULL &&
11745 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11746 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11748 defqry = createPQExpBuffer();
11749 delqry = createPQExpBuffer();
11751 qlanname = pg_strdup(fmtId(plang->dobj.name));
11753 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11754 qlanname);
11756 if (useParams)
11758 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11759 plang->lanpltrusted ? "TRUSTED " : "",
11760 qlanname);
11761 appendPQExpBuffer(defqry, " HANDLER %s",
11762 fmtQualifiedDumpable(funcInfo));
11763 if (OidIsValid(plang->laninline))
11764 appendPQExpBuffer(defqry, " INLINE %s",
11765 fmtQualifiedDumpable(inlineInfo));
11766 if (OidIsValid(plang->lanvalidator))
11767 appendPQExpBuffer(defqry, " VALIDATOR %s",
11768 fmtQualifiedDumpable(validatorInfo));
11770 else
11773 * If not dumping parameters, then use CREATE OR REPLACE so that the
11774 * command will not fail if the language is preinstalled in the target
11775 * database. We restrict the use of REPLACE to this case so as to
11776 * eliminate the risk of replacing a language with incompatible
11777 * parameter settings: this command will only succeed at all if there
11778 * is a pg_pltemplate entry, and if there is one, the existing entry
11779 * must match it too.
11781 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11782 qlanname);
11784 appendPQExpBufferStr(defqry, ";\n");
11786 if (dopt->binary_upgrade)
11787 binary_upgrade_extension_member(defqry, &plang->dobj,
11788 "LANGUAGE", qlanname, NULL);
11790 if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11791 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11792 ARCHIVE_OPTS(.tag = plang->dobj.name,
11793 .owner = plang->lanowner,
11794 .description = "PROCEDURAL LANGUAGE",
11795 .section = SECTION_PRE_DATA,
11796 .createStmt = defqry->data,
11797 .dropStmt = delqry->data,
11800 /* Dump Proc Lang Comments and Security Labels */
11801 if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11802 dumpComment(fout, "LANGUAGE", qlanname,
11803 NULL, plang->lanowner,
11804 plang->dobj.catId, 0, plang->dobj.dumpId);
11806 if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11807 dumpSecLabel(fout, "LANGUAGE", qlanname,
11808 NULL, plang->lanowner,
11809 plang->dobj.catId, 0, plang->dobj.dumpId);
11811 if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11812 dumpACL(fout, plang->dobj.dumpId, InvalidDumpId, "LANGUAGE",
11813 qlanname, NULL, NULL,
11814 plang->lanowner, plang->lanacl, plang->rlanacl,
11815 plang->initlanacl, plang->initrlanacl);
11817 free(qlanname);
11819 destroyPQExpBuffer(defqry);
11820 destroyPQExpBuffer(delqry);
11824 * format_function_arguments: generate function name and argument list
11826 * This is used when we can rely on pg_get_function_arguments to format
11827 * the argument list. Note, however, that pg_get_function_arguments
11828 * does not special-case zero-argument aggregates.
11830 static char *
11831 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11833 PQExpBufferData fn;
11835 initPQExpBuffer(&fn);
11836 appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11837 if (is_agg && finfo->nargs == 0)
11838 appendPQExpBufferStr(&fn, "(*)");
11839 else
11840 appendPQExpBuffer(&fn, "(%s)", funcargs);
11841 return fn.data;
11845 * format_function_arguments_old: generate function name and argument list
11847 * The argument type names are qualified if needed. The function name
11848 * is never qualified.
11850 * This is used only with pre-8.4 servers, so we aren't expecting to see
11851 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11853 * Any or all of allargtypes, argmodes, argnames may be NULL.
11855 static char *
11856 format_function_arguments_old(Archive *fout,
11857 FuncInfo *finfo, int nallargs,
11858 char **allargtypes,
11859 char **argmodes,
11860 char **argnames)
11862 PQExpBufferData fn;
11863 int j;
11865 initPQExpBuffer(&fn);
11866 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11867 for (j = 0; j < nallargs; j++)
11869 Oid typid;
11870 const char *typname;
11871 const char *argmode;
11872 const char *argname;
11874 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11875 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11877 if (argmodes)
11879 switch (argmodes[j][0])
11881 case PROARGMODE_IN:
11882 argmode = "";
11883 break;
11884 case PROARGMODE_OUT:
11885 argmode = "OUT ";
11886 break;
11887 case PROARGMODE_INOUT:
11888 argmode = "INOUT ";
11889 break;
11890 default:
11891 pg_log_warning("bogus value in proargmodes array");
11892 argmode = "";
11893 break;
11896 else
11897 argmode = "";
11899 argname = argnames ? argnames[j] : (char *) NULL;
11900 if (argname && argname[0] == '\0')
11901 argname = NULL;
11903 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11904 (j > 0) ? ", " : "",
11905 argmode,
11906 argname ? fmtId(argname) : "",
11907 argname ? " " : "",
11908 typname);
11910 appendPQExpBufferChar(&fn, ')');
11911 return fn.data;
11915 * format_function_signature: generate function name and argument list
11917 * This is like format_function_arguments_old except that only a minimal
11918 * list of input argument types is generated; this is sufficient to
11919 * reference the function, but not to define it.
11921 * If honor_quotes is false then the function name is never quoted.
11922 * This is appropriate for use in TOC tags, but not in SQL commands.
11924 static char *
11925 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11927 PQExpBufferData fn;
11928 int j;
11930 initPQExpBuffer(&fn);
11931 if (honor_quotes)
11932 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11933 else
11934 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11935 for (j = 0; j < finfo->nargs; j++)
11937 if (j > 0)
11938 appendPQExpBufferStr(&fn, ", ");
11940 appendPQExpBufferStr(&fn,
11941 getFormattedTypeName(fout, finfo->argtypes[j],
11942 zeroAsOpaque));
11944 appendPQExpBufferChar(&fn, ')');
11945 return fn.data;
11950 * dumpFunc:
11951 * dump out one function
11953 static void
11954 dumpFunc(Archive *fout, FuncInfo *finfo)
11956 DumpOptions *dopt = fout->dopt;
11957 PQExpBuffer query;
11958 PQExpBuffer q;
11959 PQExpBuffer delqry;
11960 PQExpBuffer asPart;
11961 PGresult *res;
11962 char *funcsig; /* identity signature */
11963 char *funcfullsig = NULL; /* full signature */
11964 char *funcsig_tag;
11965 char *proretset;
11966 char *prosrc;
11967 char *probin;
11968 char *funcargs;
11969 char *funciargs;
11970 char *funcresult;
11971 char *proallargtypes;
11972 char *proargmodes;
11973 char *proargnames;
11974 char *protrftypes;
11975 char *prokind;
11976 char *provolatile;
11977 char *proisstrict;
11978 char *prosecdef;
11979 char *proleakproof;
11980 char *proconfig;
11981 char *procost;
11982 char *prorows;
11983 char *prosupport;
11984 char *proparallel;
11985 char *lanname;
11986 int nallargs;
11987 char **allargtypes = NULL;
11988 char **argmodes = NULL;
11989 char **argnames = NULL;
11990 char **configitems = NULL;
11991 int nconfigitems = 0;
11992 const char *keyword;
11993 int i;
11995 /* Skip if not to be dumped */
11996 if (!finfo->dobj.dump || dopt->dataOnly)
11997 return;
11999 query = createPQExpBuffer();
12000 q = createPQExpBuffer();
12001 delqry = createPQExpBuffer();
12002 asPart = createPQExpBuffer();
12004 /* Fetch function-specific details */
12005 if (fout->remoteVersion >= 120000)
12008 * prosupport was added in 12
12010 appendPQExpBuffer(query,
12011 "SELECT proretset, prosrc, probin, "
12012 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12013 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12014 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12015 "array_to_string(protrftypes, ' ') AS protrftypes, "
12016 "prokind, provolatile, proisstrict, prosecdef, "
12017 "proleakproof, proconfig, procost, prorows, "
12018 "prosupport, proparallel, "
12019 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12020 "FROM pg_catalog.pg_proc "
12021 "WHERE oid = '%u'::pg_catalog.oid",
12022 finfo->dobj.catId.oid);
12024 else if (fout->remoteVersion >= 110000)
12027 * prokind was added in 11
12029 appendPQExpBuffer(query,
12030 "SELECT proretset, prosrc, probin, "
12031 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12032 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12033 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12034 "array_to_string(protrftypes, ' ') AS protrftypes, "
12035 "prokind, provolatile, proisstrict, prosecdef, "
12036 "proleakproof, proconfig, procost, prorows, "
12037 "'-' AS prosupport, proparallel, "
12038 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12039 "FROM pg_catalog.pg_proc "
12040 "WHERE oid = '%u'::pg_catalog.oid",
12041 finfo->dobj.catId.oid);
12043 else if (fout->remoteVersion >= 90600)
12046 * proparallel was added in 9.6
12048 appendPQExpBuffer(query,
12049 "SELECT proretset, prosrc, probin, "
12050 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12051 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12052 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12053 "array_to_string(protrftypes, ' ') AS protrftypes, "
12054 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12055 "provolatile, proisstrict, prosecdef, "
12056 "proleakproof, proconfig, procost, prorows, "
12057 "'-' AS prosupport, proparallel, "
12058 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12059 "FROM pg_catalog.pg_proc "
12060 "WHERE oid = '%u'::pg_catalog.oid",
12061 finfo->dobj.catId.oid);
12063 else if (fout->remoteVersion >= 90500)
12066 * protrftypes was added in 9.5
12068 appendPQExpBuffer(query,
12069 "SELECT proretset, prosrc, probin, "
12070 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12071 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12072 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12073 "array_to_string(protrftypes, ' ') AS protrftypes, "
12074 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12075 "provolatile, proisstrict, prosecdef, "
12076 "proleakproof, proconfig, procost, prorows, "
12077 "'-' AS prosupport, "
12078 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12079 "FROM pg_catalog.pg_proc "
12080 "WHERE oid = '%u'::pg_catalog.oid",
12081 finfo->dobj.catId.oid);
12083 else if (fout->remoteVersion >= 90200)
12086 * proleakproof was added in 9.2
12088 appendPQExpBuffer(query,
12089 "SELECT proretset, prosrc, probin, "
12090 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12091 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12092 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12093 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12094 "provolatile, proisstrict, prosecdef, "
12095 "proleakproof, proconfig, procost, prorows, "
12096 "'-' AS prosupport, "
12097 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12098 "FROM pg_catalog.pg_proc "
12099 "WHERE oid = '%u'::pg_catalog.oid",
12100 finfo->dobj.catId.oid);
12102 else if (fout->remoteVersion >= 80400)
12105 * In 8.4 and up we rely on pg_get_function_arguments and
12106 * pg_get_function_result instead of examining proallargtypes etc.
12108 appendPQExpBuffer(query,
12109 "SELECT proretset, prosrc, probin, "
12110 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12111 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12112 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12113 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12114 "provolatile, proisstrict, prosecdef, "
12115 "false AS proleakproof, "
12116 " proconfig, procost, prorows, "
12117 "'-' AS prosupport, "
12118 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12119 "FROM pg_catalog.pg_proc "
12120 "WHERE oid = '%u'::pg_catalog.oid",
12121 finfo->dobj.catId.oid);
12123 else if (fout->remoteVersion >= 80300)
12125 appendPQExpBuffer(query,
12126 "SELECT proretset, prosrc, probin, "
12127 "proallargtypes, proargmodes, proargnames, "
12128 "'f' AS prokind, "
12129 "provolatile, proisstrict, prosecdef, "
12130 "false AS proleakproof, "
12131 "proconfig, procost, prorows, "
12132 "'-' AS prosupport, "
12133 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12134 "FROM pg_catalog.pg_proc "
12135 "WHERE oid = '%u'::pg_catalog.oid",
12136 finfo->dobj.catId.oid);
12138 else if (fout->remoteVersion >= 80100)
12140 appendPQExpBuffer(query,
12141 "SELECT proretset, prosrc, probin, "
12142 "proallargtypes, proargmodes, proargnames, "
12143 "'f' AS prokind, "
12144 "provolatile, proisstrict, prosecdef, "
12145 "false AS proleakproof, "
12146 "null AS proconfig, 0 AS procost, 0 AS prorows, "
12147 "'-' AS prosupport, "
12148 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12149 "FROM pg_catalog.pg_proc "
12150 "WHERE oid = '%u'::pg_catalog.oid",
12151 finfo->dobj.catId.oid);
12153 else
12155 appendPQExpBuffer(query,
12156 "SELECT proretset, prosrc, probin, "
12157 "null AS proallargtypes, "
12158 "null AS proargmodes, "
12159 "proargnames, "
12160 "'f' AS prokind, "
12161 "provolatile, proisstrict, prosecdef, "
12162 "false AS proleakproof, "
12163 "null AS proconfig, 0 AS procost, 0 AS prorows, "
12164 "'-' AS prosupport, "
12165 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12166 "FROM pg_catalog.pg_proc "
12167 "WHERE oid = '%u'::pg_catalog.oid",
12168 finfo->dobj.catId.oid);
12171 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12173 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
12174 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
12175 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
12176 if (fout->remoteVersion >= 80400)
12178 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
12179 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
12180 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
12181 proallargtypes = proargmodes = proargnames = NULL;
12183 else
12185 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
12186 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
12187 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
12188 funcargs = funciargs = funcresult = NULL;
12190 if (PQfnumber(res, "protrftypes") != -1)
12191 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
12192 else
12193 protrftypes = NULL;
12194 prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
12195 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
12196 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
12197 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
12198 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
12199 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
12200 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
12201 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
12202 prosupport = PQgetvalue(res, 0, PQfnumber(res, "prosupport"));
12204 if (PQfnumber(res, "proparallel") != -1)
12205 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
12206 else
12207 proparallel = NULL;
12209 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
12212 * See backend/commands/functioncmds.c for details of how the 'AS' clause
12213 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
12214 * versions would set it to "-". There are no known cases in which prosrc
12215 * is unused, so the tests below for "-" are probably useless.
12217 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
12219 appendPQExpBufferStr(asPart, "AS ");
12220 appendStringLiteralAH(asPart, probin, fout);
12221 if (strcmp(prosrc, "-") != 0)
12223 appendPQExpBufferStr(asPart, ", ");
12226 * where we have bin, use dollar quoting if allowed and src
12227 * contains quote or backslash; else use regular quoting.
12229 if (dopt->disable_dollar_quoting ||
12230 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
12231 appendStringLiteralAH(asPart, prosrc, fout);
12232 else
12233 appendStringLiteralDQ(asPart, prosrc, NULL);
12236 else
12238 if (strcmp(prosrc, "-") != 0)
12240 appendPQExpBufferStr(asPart, "AS ");
12241 /* with no bin, dollar quote src unconditionally if allowed */
12242 if (dopt->disable_dollar_quoting)
12243 appendStringLiteralAH(asPart, prosrc, fout);
12244 else
12245 appendStringLiteralDQ(asPart, prosrc, NULL);
12249 nallargs = finfo->nargs; /* unless we learn different from allargs */
12251 if (proallargtypes && *proallargtypes)
12253 int nitems = 0;
12255 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
12256 nitems < finfo->nargs)
12258 pg_log_warning("could not parse proallargtypes array");
12259 if (allargtypes)
12260 free(allargtypes);
12261 allargtypes = NULL;
12263 else
12264 nallargs = nitems;
12267 if (proargmodes && *proargmodes)
12269 int nitems = 0;
12271 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
12272 nitems != nallargs)
12274 pg_log_warning("could not parse proargmodes array");
12275 if (argmodes)
12276 free(argmodes);
12277 argmodes = NULL;
12281 if (proargnames && *proargnames)
12283 int nitems = 0;
12285 if (!parsePGArray(proargnames, &argnames, &nitems) ||
12286 nitems != nallargs)
12288 pg_log_warning("could not parse proargnames array");
12289 if (argnames)
12290 free(argnames);
12291 argnames = NULL;
12295 if (proconfig && *proconfig)
12297 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
12299 pg_log_warning("could not parse proconfig array");
12300 if (configitems)
12301 free(configitems);
12302 configitems = NULL;
12303 nconfigitems = 0;
12307 if (funcargs)
12309 /* 8.4 or later; we rely on server-side code for most of the work */
12310 funcfullsig = format_function_arguments(finfo, funcargs, false);
12311 funcsig = format_function_arguments(finfo, funciargs, false);
12313 else
12314 /* pre-8.4, do it ourselves */
12315 funcsig = format_function_arguments_old(fout,
12316 finfo, nallargs, allargtypes,
12317 argmodes, argnames);
12319 funcsig_tag = format_function_signature(fout, finfo, false);
12321 if (prokind[0] == PROKIND_PROCEDURE)
12322 keyword = "PROCEDURE";
12323 else
12324 keyword = "FUNCTION"; /* works for window functions too */
12326 appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
12327 keyword,
12328 fmtId(finfo->dobj.namespace->dobj.name),
12329 funcsig);
12331 appendPQExpBuffer(q, "CREATE %s %s.%s",
12332 keyword,
12333 fmtId(finfo->dobj.namespace->dobj.name),
12334 funcfullsig ? funcfullsig :
12335 funcsig);
12337 if (prokind[0] == PROKIND_PROCEDURE)
12338 /* no result type to output */ ;
12339 else if (funcresult)
12340 appendPQExpBuffer(q, " RETURNS %s", funcresult);
12341 else
12342 appendPQExpBuffer(q, " RETURNS %s%s",
12343 (proretset[0] == 't') ? "SETOF " : "",
12344 getFormattedTypeName(fout, finfo->prorettype,
12345 zeroAsOpaque));
12347 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
12349 if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
12351 Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
12352 int i;
12354 appendPQExpBufferStr(q, " TRANSFORM ");
12355 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
12356 for (i = 0; typeids[i]; i++)
12358 if (i != 0)
12359 appendPQExpBufferStr(q, ", ");
12360 appendPQExpBuffer(q, "FOR TYPE %s",
12361 getFormattedTypeName(fout, typeids[i], zeroAsNone));
12365 if (prokind[0] == PROKIND_WINDOW)
12366 appendPQExpBufferStr(q, " WINDOW");
12368 if (provolatile[0] != PROVOLATILE_VOLATILE)
12370 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
12371 appendPQExpBufferStr(q, " IMMUTABLE");
12372 else if (provolatile[0] == PROVOLATILE_STABLE)
12373 appendPQExpBufferStr(q, " STABLE");
12374 else if (provolatile[0] != PROVOLATILE_VOLATILE)
12375 fatal("unrecognized provolatile value for function \"%s\"",
12376 finfo->dobj.name);
12379 if (proisstrict[0] == 't')
12380 appendPQExpBufferStr(q, " STRICT");
12382 if (prosecdef[0] == 't')
12383 appendPQExpBufferStr(q, " SECURITY DEFINER");
12385 if (proleakproof[0] == 't')
12386 appendPQExpBufferStr(q, " LEAKPROOF");
12389 * COST and ROWS are emitted only if present and not default, so as not to
12390 * break backwards-compatibility of the dump without need. Keep this code
12391 * in sync with the defaults in functioncmds.c.
12393 if (strcmp(procost, "0") != 0)
12395 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
12397 /* default cost is 1 */
12398 if (strcmp(procost, "1") != 0)
12399 appendPQExpBuffer(q, " COST %s", procost);
12401 else
12403 /* default cost is 100 */
12404 if (strcmp(procost, "100") != 0)
12405 appendPQExpBuffer(q, " COST %s", procost);
12408 if (proretset[0] == 't' &&
12409 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
12410 appendPQExpBuffer(q, " ROWS %s", prorows);
12412 if (strcmp(prosupport, "-") != 0)
12414 /* We rely on regprocout to provide quoting and qualification */
12415 appendPQExpBuffer(q, " SUPPORT %s", prosupport);
12418 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
12420 if (proparallel[0] == PROPARALLEL_SAFE)
12421 appendPQExpBufferStr(q, " PARALLEL SAFE");
12422 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
12423 appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
12424 else if (proparallel[0] != PROPARALLEL_UNSAFE)
12425 fatal("unrecognized proparallel value for function \"%s\"",
12426 finfo->dobj.name);
12429 for (i = 0; i < nconfigitems; i++)
12431 /* we feel free to scribble on configitems[] here */
12432 char *configitem = configitems[i];
12433 char *pos;
12435 pos = strchr(configitem, '=');
12436 if (pos == NULL)
12437 continue;
12438 *pos++ = '\0';
12439 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
12442 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
12443 * by flatten_set_variable_args() before they were put into the
12444 * proconfig array. However, because the quoting rules used there
12445 * aren't exactly like SQL's, we have to break the list value apart
12446 * and then quote the elements as string literals. (The elements may
12447 * be double-quoted as-is, but we can't just feed them to the SQL
12448 * parser; it would do the wrong thing with elements that are
12449 * zero-length or longer than NAMEDATALEN.)
12451 * Variables that are not so marked should just be emitted as simple
12452 * string literals. If the variable is not known to
12453 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
12454 * to use GUC_LIST_QUOTE for extension variables.
12456 if (variable_is_guc_list_quote(configitem))
12458 char **namelist;
12459 char **nameptr;
12461 /* Parse string into list of identifiers */
12462 /* this shouldn't fail really */
12463 if (SplitGUCList(pos, ',', &namelist))
12465 for (nameptr = namelist; *nameptr; nameptr++)
12467 if (nameptr != namelist)
12468 appendPQExpBufferStr(q, ", ");
12469 appendStringLiteralAH(q, *nameptr, fout);
12472 pg_free(namelist);
12474 else
12475 appendStringLiteralAH(q, pos, fout);
12478 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
12480 append_depends_on_extension(fout, q, &finfo->dobj,
12481 "pg_catalog.pg_proc", keyword,
12482 psprintf("%s.%s",
12483 fmtId(finfo->dobj.namespace->dobj.name),
12484 funcsig));
12486 if (dopt->binary_upgrade)
12487 binary_upgrade_extension_member(q, &finfo->dobj,
12488 keyword, funcsig,
12489 finfo->dobj.namespace->dobj.name);
12491 if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12492 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12493 ARCHIVE_OPTS(.tag = funcsig_tag,
12494 .namespace = finfo->dobj.namespace->dobj.name,
12495 .owner = finfo->rolname,
12496 .description = keyword,
12497 .section = SECTION_PRE_DATA,
12498 .createStmt = q->data,
12499 .dropStmt = delqry->data));
12501 /* Dump Function Comments and Security Labels */
12502 if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12503 dumpComment(fout, keyword, funcsig,
12504 finfo->dobj.namespace->dobj.name, finfo->rolname,
12505 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12507 if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12508 dumpSecLabel(fout, keyword, funcsig,
12509 finfo->dobj.namespace->dobj.name, finfo->rolname,
12510 finfo->dobj.catId, 0, finfo->dobj.dumpId);
12512 if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12513 dumpACL(fout, finfo->dobj.dumpId, InvalidDumpId, keyword,
12514 funcsig, NULL,
12515 finfo->dobj.namespace->dobj.name,
12516 finfo->rolname, finfo->proacl, finfo->rproacl,
12517 finfo->initproacl, finfo->initrproacl);
12519 PQclear(res);
12521 destroyPQExpBuffer(query);
12522 destroyPQExpBuffer(q);
12523 destroyPQExpBuffer(delqry);
12524 destroyPQExpBuffer(asPart);
12525 free(funcsig);
12526 if (funcfullsig)
12527 free(funcfullsig);
12528 free(funcsig_tag);
12529 if (allargtypes)
12530 free(allargtypes);
12531 if (argmodes)
12532 free(argmodes);
12533 if (argnames)
12534 free(argnames);
12535 if (configitems)
12536 free(configitems);
12541 * Dump a user-defined cast
12543 static void
12544 dumpCast(Archive *fout, CastInfo *cast)
12546 DumpOptions *dopt = fout->dopt;
12547 PQExpBuffer defqry;
12548 PQExpBuffer delqry;
12549 PQExpBuffer labelq;
12550 PQExpBuffer castargs;
12551 FuncInfo *funcInfo = NULL;
12552 const char *sourceType;
12553 const char *targetType;
12555 /* Skip if not to be dumped */
12556 if (!cast->dobj.dump || dopt->dataOnly)
12557 return;
12559 /* Cannot dump if we don't have the cast function's info */
12560 if (OidIsValid(cast->castfunc))
12562 funcInfo = findFuncByOid(cast->castfunc);
12563 if (funcInfo == NULL)
12564 fatal("could not find function definition for function with OID %u",
12565 cast->castfunc);
12568 defqry = createPQExpBuffer();
12569 delqry = createPQExpBuffer();
12570 labelq = createPQExpBuffer();
12571 castargs = createPQExpBuffer();
12573 sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12574 targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12575 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12576 sourceType, targetType);
12578 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12579 sourceType, targetType);
12581 switch (cast->castmethod)
12583 case COERCION_METHOD_BINARY:
12584 appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12585 break;
12586 case COERCION_METHOD_INOUT:
12587 appendPQExpBufferStr(defqry, "WITH INOUT");
12588 break;
12589 case COERCION_METHOD_FUNCTION:
12590 if (funcInfo)
12592 char *fsig = format_function_signature(fout, funcInfo, true);
12595 * Always qualify the function name (format_function_signature
12596 * won't qualify it).
12598 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12599 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12600 free(fsig);
12602 else
12603 pg_log_warning("bogus value in pg_cast.castfunc or pg_cast.castmethod field");
12604 break;
12605 default:
12606 pg_log_warning("bogus value in pg_cast.castmethod field");
12609 if (cast->castcontext == 'a')
12610 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12611 else if (cast->castcontext == 'i')
12612 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12613 appendPQExpBufferStr(defqry, ";\n");
12615 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12616 sourceType, targetType);
12618 appendPQExpBuffer(castargs, "(%s AS %s)",
12619 sourceType, targetType);
12621 if (dopt->binary_upgrade)
12622 binary_upgrade_extension_member(defqry, &cast->dobj,
12623 "CAST", castargs->data, NULL);
12625 if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12626 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12627 ARCHIVE_OPTS(.tag = labelq->data,
12628 .description = "CAST",
12629 .section = SECTION_PRE_DATA,
12630 .createStmt = defqry->data,
12631 .dropStmt = delqry->data));
12633 /* Dump Cast Comments */
12634 if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12635 dumpComment(fout, "CAST", castargs->data,
12636 NULL, "",
12637 cast->dobj.catId, 0, cast->dobj.dumpId);
12639 destroyPQExpBuffer(defqry);
12640 destroyPQExpBuffer(delqry);
12641 destroyPQExpBuffer(labelq);
12642 destroyPQExpBuffer(castargs);
12646 * Dump a transform
12648 static void
12649 dumpTransform(Archive *fout, TransformInfo *transform)
12651 DumpOptions *dopt = fout->dopt;
12652 PQExpBuffer defqry;
12653 PQExpBuffer delqry;
12654 PQExpBuffer labelq;
12655 PQExpBuffer transformargs;
12656 FuncInfo *fromsqlFuncInfo = NULL;
12657 FuncInfo *tosqlFuncInfo = NULL;
12658 char *lanname;
12659 const char *transformType;
12661 /* Skip if not to be dumped */
12662 if (!transform->dobj.dump || dopt->dataOnly)
12663 return;
12665 /* Cannot dump if we don't have the transform functions' info */
12666 if (OidIsValid(transform->trffromsql))
12668 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12669 if (fromsqlFuncInfo == NULL)
12670 fatal("could not find function definition for function with OID %u",
12671 transform->trffromsql);
12673 if (OidIsValid(transform->trftosql))
12675 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12676 if (tosqlFuncInfo == NULL)
12677 fatal("could not find function definition for function with OID %u",
12678 transform->trftosql);
12681 defqry = createPQExpBuffer();
12682 delqry = createPQExpBuffer();
12683 labelq = createPQExpBuffer();
12684 transformargs = createPQExpBuffer();
12686 lanname = get_language_name(fout, transform->trflang);
12687 transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12689 appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12690 transformType, lanname);
12692 appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12693 transformType, lanname);
12695 if (!transform->trffromsql && !transform->trftosql)
12696 pg_log_warning("bogus transform definition, at least one of trffromsql and trftosql should be nonzero");
12698 if (transform->trffromsql)
12700 if (fromsqlFuncInfo)
12702 char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12705 * Always qualify the function name (format_function_signature
12706 * won't qualify it).
12708 appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12709 fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12710 free(fsig);
12712 else
12713 pg_log_warning("bogus value in pg_transform.trffromsql field");
12716 if (transform->trftosql)
12718 if (transform->trffromsql)
12719 appendPQExpBuffer(defqry, ", ");
12721 if (tosqlFuncInfo)
12723 char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12726 * Always qualify the function name (format_function_signature
12727 * won't qualify it).
12729 appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12730 fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12731 free(fsig);
12733 else
12734 pg_log_warning("bogus value in pg_transform.trftosql field");
12737 appendPQExpBuffer(defqry, ");\n");
12739 appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12740 transformType, lanname);
12742 appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12743 transformType, lanname);
12745 if (dopt->binary_upgrade)
12746 binary_upgrade_extension_member(defqry, &transform->dobj,
12747 "TRANSFORM", transformargs->data, NULL);
12749 if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12750 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12751 ARCHIVE_OPTS(.tag = labelq->data,
12752 .description = "TRANSFORM",
12753 .section = SECTION_PRE_DATA,
12754 .createStmt = defqry->data,
12755 .dropStmt = delqry->data,
12756 .deps = transform->dobj.dependencies,
12757 .nDeps = transform->dobj.nDeps));
12759 /* Dump Transform Comments */
12760 if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12761 dumpComment(fout, "TRANSFORM", transformargs->data,
12762 NULL, "",
12763 transform->dobj.catId, 0, transform->dobj.dumpId);
12765 free(lanname);
12766 destroyPQExpBuffer(defqry);
12767 destroyPQExpBuffer(delqry);
12768 destroyPQExpBuffer(labelq);
12769 destroyPQExpBuffer(transformargs);
12774 * dumpOpr
12775 * write out a single operator definition
12777 static void
12778 dumpOpr(Archive *fout, OprInfo *oprinfo)
12780 DumpOptions *dopt = fout->dopt;
12781 PQExpBuffer query;
12782 PQExpBuffer q;
12783 PQExpBuffer delq;
12784 PQExpBuffer oprid;
12785 PQExpBuffer details;
12786 PGresult *res;
12787 int i_oprkind;
12788 int i_oprcode;
12789 int i_oprleft;
12790 int i_oprright;
12791 int i_oprcom;
12792 int i_oprnegate;
12793 int i_oprrest;
12794 int i_oprjoin;
12795 int i_oprcanmerge;
12796 int i_oprcanhash;
12797 char *oprkind;
12798 char *oprcode;
12799 char *oprleft;
12800 char *oprright;
12801 char *oprcom;
12802 char *oprnegate;
12803 char *oprrest;
12804 char *oprjoin;
12805 char *oprcanmerge;
12806 char *oprcanhash;
12807 char *oprregproc;
12808 char *oprref;
12810 /* Skip if not to be dumped */
12811 if (!oprinfo->dobj.dump || dopt->dataOnly)
12812 return;
12815 * some operators are invalid because they were the result of user
12816 * defining operators before commutators exist
12818 if (!OidIsValid(oprinfo->oprcode))
12819 return;
12821 query = createPQExpBuffer();
12822 q = createPQExpBuffer();
12823 delq = createPQExpBuffer();
12824 oprid = createPQExpBuffer();
12825 details = createPQExpBuffer();
12827 if (fout->remoteVersion >= 80300)
12829 appendPQExpBuffer(query, "SELECT oprkind, "
12830 "oprcode::pg_catalog.regprocedure, "
12831 "oprleft::pg_catalog.regtype, "
12832 "oprright::pg_catalog.regtype, "
12833 "oprcom, "
12834 "oprnegate, "
12835 "oprrest::pg_catalog.regprocedure, "
12836 "oprjoin::pg_catalog.regprocedure, "
12837 "oprcanmerge, oprcanhash "
12838 "FROM pg_catalog.pg_operator "
12839 "WHERE oid = '%u'::pg_catalog.oid",
12840 oprinfo->dobj.catId.oid);
12842 else
12844 appendPQExpBuffer(query, "SELECT oprkind, "
12845 "oprcode::pg_catalog.regprocedure, "
12846 "oprleft::pg_catalog.regtype, "
12847 "oprright::pg_catalog.regtype, "
12848 "oprcom, "
12849 "oprnegate, "
12850 "oprrest::pg_catalog.regprocedure, "
12851 "oprjoin::pg_catalog.regprocedure, "
12852 "(oprlsortop != 0) AS oprcanmerge, "
12853 "oprcanhash "
12854 "FROM pg_catalog.pg_operator "
12855 "WHERE oid = '%u'::pg_catalog.oid",
12856 oprinfo->dobj.catId.oid);
12859 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12861 i_oprkind = PQfnumber(res, "oprkind");
12862 i_oprcode = PQfnumber(res, "oprcode");
12863 i_oprleft = PQfnumber(res, "oprleft");
12864 i_oprright = PQfnumber(res, "oprright");
12865 i_oprcom = PQfnumber(res, "oprcom");
12866 i_oprnegate = PQfnumber(res, "oprnegate");
12867 i_oprrest = PQfnumber(res, "oprrest");
12868 i_oprjoin = PQfnumber(res, "oprjoin");
12869 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12870 i_oprcanhash = PQfnumber(res, "oprcanhash");
12872 oprkind = PQgetvalue(res, 0, i_oprkind);
12873 oprcode = PQgetvalue(res, 0, i_oprcode);
12874 oprleft = PQgetvalue(res, 0, i_oprleft);
12875 oprright = PQgetvalue(res, 0, i_oprright);
12876 oprcom = PQgetvalue(res, 0, i_oprcom);
12877 oprnegate = PQgetvalue(res, 0, i_oprnegate);
12878 oprrest = PQgetvalue(res, 0, i_oprrest);
12879 oprjoin = PQgetvalue(res, 0, i_oprjoin);
12880 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12881 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12883 oprregproc = convertRegProcReference(fout, oprcode);
12884 if (oprregproc)
12886 appendPQExpBuffer(details, " FUNCTION = %s", oprregproc);
12887 free(oprregproc);
12890 appendPQExpBuffer(oprid, "%s (",
12891 oprinfo->dobj.name);
12894 * right unary means there's a left arg and left unary means there's a
12895 * right arg
12897 if (strcmp(oprkind, "r") == 0 ||
12898 strcmp(oprkind, "b") == 0)
12900 appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
12901 appendPQExpBufferStr(oprid, oprleft);
12903 else
12904 appendPQExpBufferStr(oprid, "NONE");
12906 if (strcmp(oprkind, "l") == 0 ||
12907 strcmp(oprkind, "b") == 0)
12909 appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
12910 appendPQExpBuffer(oprid, ", %s)", oprright);
12912 else
12913 appendPQExpBufferStr(oprid, ", NONE)");
12915 oprref = getFormattedOperatorName(fout, oprcom);
12916 if (oprref)
12918 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
12919 free(oprref);
12922 oprref = getFormattedOperatorName(fout, oprnegate);
12923 if (oprref)
12925 appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
12926 free(oprref);
12929 if (strcmp(oprcanmerge, "t") == 0)
12930 appendPQExpBufferStr(details, ",\n MERGES");
12932 if (strcmp(oprcanhash, "t") == 0)
12933 appendPQExpBufferStr(details, ",\n HASHES");
12935 oprregproc = convertRegProcReference(fout, oprrest);
12936 if (oprregproc)
12938 appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
12939 free(oprregproc);
12942 oprregproc = convertRegProcReference(fout, oprjoin);
12943 if (oprregproc)
12945 appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
12946 free(oprregproc);
12949 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12950 fmtId(oprinfo->dobj.namespace->dobj.name),
12951 oprid->data);
12953 appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12954 fmtId(oprinfo->dobj.namespace->dobj.name),
12955 oprinfo->dobj.name, details->data);
12957 if (dopt->binary_upgrade)
12958 binary_upgrade_extension_member(q, &oprinfo->dobj,
12959 "OPERATOR", oprid->data,
12960 oprinfo->dobj.namespace->dobj.name);
12962 if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12963 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12964 ARCHIVE_OPTS(.tag = oprinfo->dobj.name,
12965 .namespace = oprinfo->dobj.namespace->dobj.name,
12966 .owner = oprinfo->rolname,
12967 .description = "OPERATOR",
12968 .section = SECTION_PRE_DATA,
12969 .createStmt = q->data,
12970 .dropStmt = delq->data));
12972 /* Dump Operator Comments */
12973 if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12974 dumpComment(fout, "OPERATOR", oprid->data,
12975 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12976 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12978 PQclear(res);
12980 destroyPQExpBuffer(query);
12981 destroyPQExpBuffer(q);
12982 destroyPQExpBuffer(delq);
12983 destroyPQExpBuffer(oprid);
12984 destroyPQExpBuffer(details);
12988 * Convert a function reference obtained from pg_operator
12990 * Returns allocated string of what to print, or NULL if function references
12991 * is InvalidOid. Returned string is expected to be free'd by the caller.
12993 * The input is a REGPROCEDURE display; we have to strip the argument-types
12994 * part.
12996 static char *
12997 convertRegProcReference(Archive *fout, const char *proc)
12999 char *name;
13000 char *paren;
13001 bool inquote;
13003 /* In all cases "-" means a null reference */
13004 if (strcmp(proc, "-") == 0)
13005 return NULL;
13007 name = pg_strdup(proc);
13008 /* find non-double-quoted left paren */
13009 inquote = false;
13010 for (paren = name; *paren; paren++)
13012 if (*paren == '(' && !inquote)
13014 *paren = '\0';
13015 break;
13017 if (*paren == '"')
13018 inquote = !inquote;
13020 return name;
13024 * getFormattedOperatorName - retrieve the operator name for the
13025 * given operator OID (presented in string form).
13027 * Returns an allocated string, or NULL if the given OID is invalid.
13028 * Caller is responsible for free'ing result string.
13030 * What we produce has the format "OPERATOR(schema.oprname)". This is only
13031 * useful in commands where the operator's argument types can be inferred from
13032 * context. We always schema-qualify the name, though. The predecessor to
13033 * this code tried to skip the schema qualification if possible, but that led
13034 * to wrong results in corner cases, such as if an operator and its negator
13035 * are in different schemas.
13037 static char *
13038 getFormattedOperatorName(Archive *fout, const char *oproid)
13040 OprInfo *oprInfo;
13042 /* In all cases "0" means a null reference */
13043 if (strcmp(oproid, "0") == 0)
13044 return NULL;
13046 oprInfo = findOprByOid(atooid(oproid));
13047 if (oprInfo == NULL)
13049 pg_log_warning("could not find operator with OID %s",
13050 oproid);
13051 return NULL;
13054 return psprintf("OPERATOR(%s.%s)",
13055 fmtId(oprInfo->dobj.namespace->dobj.name),
13056 oprInfo->dobj.name);
13060 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
13062 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
13063 * argument lists of these functions are predetermined. Note that the
13064 * caller should ensure we are in the proper schema, because the results
13065 * are search path dependent!
13067 static char *
13068 convertTSFunction(Archive *fout, Oid funcOid)
13070 char *result;
13071 char query[128];
13072 PGresult *res;
13074 snprintf(query, sizeof(query),
13075 "SELECT '%u'::pg_catalog.regproc", funcOid);
13076 res = ExecuteSqlQueryForSingleRow(fout, query);
13078 result = pg_strdup(PQgetvalue(res, 0, 0));
13080 PQclear(res);
13082 return result;
13086 * dumpAccessMethod
13087 * write out a single access method definition
13089 static void
13090 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
13092 DumpOptions *dopt = fout->dopt;
13093 PQExpBuffer q;
13094 PQExpBuffer delq;
13095 char *qamname;
13097 /* Skip if not to be dumped */
13098 if (!aminfo->dobj.dump || dopt->dataOnly)
13099 return;
13101 q = createPQExpBuffer();
13102 delq = createPQExpBuffer();
13104 qamname = pg_strdup(fmtId(aminfo->dobj.name));
13106 appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
13108 switch (aminfo->amtype)
13110 case AMTYPE_INDEX:
13111 appendPQExpBuffer(q, "TYPE INDEX ");
13112 break;
13113 case AMTYPE_TABLE:
13114 appendPQExpBuffer(q, "TYPE TABLE ");
13115 break;
13116 default:
13117 pg_log_warning("invalid type \"%c\" of access method \"%s\"",
13118 aminfo->amtype, qamname);
13119 destroyPQExpBuffer(q);
13120 destroyPQExpBuffer(delq);
13121 free(qamname);
13122 return;
13125 appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
13127 appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
13128 qamname);
13130 if (dopt->binary_upgrade)
13131 binary_upgrade_extension_member(q, &aminfo->dobj,
13132 "ACCESS METHOD", qamname, NULL);
13134 if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13135 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
13136 ARCHIVE_OPTS(.tag = aminfo->dobj.name,
13137 .description = "ACCESS METHOD",
13138 .section = SECTION_PRE_DATA,
13139 .createStmt = q->data,
13140 .dropStmt = delq->data));
13142 /* Dump Access Method Comments */
13143 if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13144 dumpComment(fout, "ACCESS METHOD", qamname,
13145 NULL, "",
13146 aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
13148 destroyPQExpBuffer(q);
13149 destroyPQExpBuffer(delq);
13150 free(qamname);
13154 * dumpOpclass
13155 * write out a single operator class definition
13157 static void
13158 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
13160 DumpOptions *dopt = fout->dopt;
13161 PQExpBuffer query;
13162 PQExpBuffer q;
13163 PQExpBuffer delq;
13164 PQExpBuffer nameusing;
13165 PGresult *res;
13166 int ntups;
13167 int i_opcintype;
13168 int i_opckeytype;
13169 int i_opcdefault;
13170 int i_opcfamily;
13171 int i_opcfamilyname;
13172 int i_opcfamilynsp;
13173 int i_amname;
13174 int i_amopstrategy;
13175 int i_amopreqcheck;
13176 int i_amopopr;
13177 int i_sortfamily;
13178 int i_sortfamilynsp;
13179 int i_amprocnum;
13180 int i_amproc;
13181 int i_amproclefttype;
13182 int i_amprocrighttype;
13183 char *opcintype;
13184 char *opckeytype;
13185 char *opcdefault;
13186 char *opcfamily;
13187 char *opcfamilyname;
13188 char *opcfamilynsp;
13189 char *amname;
13190 char *amopstrategy;
13191 char *amopreqcheck;
13192 char *amopopr;
13193 char *sortfamily;
13194 char *sortfamilynsp;
13195 char *amprocnum;
13196 char *amproc;
13197 char *amproclefttype;
13198 char *amprocrighttype;
13199 bool needComma;
13200 int i;
13202 /* Skip if not to be dumped */
13203 if (!opcinfo->dobj.dump || dopt->dataOnly)
13204 return;
13206 query = createPQExpBuffer();
13207 q = createPQExpBuffer();
13208 delq = createPQExpBuffer();
13209 nameusing = createPQExpBuffer();
13211 /* Get additional fields from the pg_opclass row */
13212 if (fout->remoteVersion >= 80300)
13214 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
13215 "opckeytype::pg_catalog.regtype, "
13216 "opcdefault, opcfamily, "
13217 "opfname AS opcfamilyname, "
13218 "nspname AS opcfamilynsp, "
13219 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
13220 "FROM pg_catalog.pg_opclass c "
13221 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
13222 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13223 "WHERE c.oid = '%u'::pg_catalog.oid",
13224 opcinfo->dobj.catId.oid);
13226 else
13228 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
13229 "opckeytype::pg_catalog.regtype, "
13230 "opcdefault, NULL AS opcfamily, "
13231 "NULL AS opcfamilyname, "
13232 "NULL AS opcfamilynsp, "
13233 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
13234 "FROM pg_catalog.pg_opclass "
13235 "WHERE oid = '%u'::pg_catalog.oid",
13236 opcinfo->dobj.catId.oid);
13239 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13241 i_opcintype = PQfnumber(res, "opcintype");
13242 i_opckeytype = PQfnumber(res, "opckeytype");
13243 i_opcdefault = PQfnumber(res, "opcdefault");
13244 i_opcfamily = PQfnumber(res, "opcfamily");
13245 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
13246 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
13247 i_amname = PQfnumber(res, "amname");
13249 /* opcintype may still be needed after we PQclear res */
13250 opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
13251 opckeytype = PQgetvalue(res, 0, i_opckeytype);
13252 opcdefault = PQgetvalue(res, 0, i_opcdefault);
13253 /* opcfamily will still be needed after we PQclear res */
13254 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
13255 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
13256 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
13257 /* amname will still be needed after we PQclear res */
13258 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13260 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
13261 fmtQualifiedDumpable(opcinfo));
13262 appendPQExpBuffer(delq, " USING %s;\n",
13263 fmtId(amname));
13265 /* Build the fixed portion of the CREATE command */
13266 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
13267 fmtQualifiedDumpable(opcinfo));
13268 if (strcmp(opcdefault, "t") == 0)
13269 appendPQExpBufferStr(q, "DEFAULT ");
13270 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
13271 opcintype,
13272 fmtId(amname));
13273 if (strlen(opcfamilyname) > 0)
13275 appendPQExpBufferStr(q, " FAMILY ");
13276 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
13277 appendPQExpBufferStr(q, fmtId(opcfamilyname));
13279 appendPQExpBufferStr(q, " AS\n ");
13281 needComma = false;
13283 if (strcmp(opckeytype, "-") != 0)
13285 appendPQExpBuffer(q, "STORAGE %s",
13286 opckeytype);
13287 needComma = true;
13290 PQclear(res);
13293 * Now fetch and print the OPERATOR entries (pg_amop rows).
13295 * Print only those opfamily members that are tied to the opclass by
13296 * pg_depend entries.
13298 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13299 * older server's opclass in which it is used. This is to avoid
13300 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13301 * older server and then reload into that old version. This can go away
13302 * once 8.3 is so old as to not be of interest to anyone.
13304 resetPQExpBuffer(query);
13306 if (fout->remoteVersion >= 90100)
13308 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13309 "amopopr::pg_catalog.regoperator, "
13310 "opfname AS sortfamily, "
13311 "nspname AS sortfamilynsp "
13312 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13313 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13314 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13315 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13316 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13317 "AND refobjid = '%u'::pg_catalog.oid "
13318 "AND amopfamily = '%s'::pg_catalog.oid "
13319 "ORDER BY amopstrategy",
13320 opcinfo->dobj.catId.oid,
13321 opcfamily);
13323 else if (fout->remoteVersion >= 80400)
13325 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13326 "amopopr::pg_catalog.regoperator, "
13327 "NULL AS sortfamily, "
13328 "NULL AS sortfamilynsp "
13329 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13330 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13331 "AND refobjid = '%u'::pg_catalog.oid "
13332 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13333 "AND objid = ao.oid "
13334 "ORDER BY amopstrategy",
13335 opcinfo->dobj.catId.oid);
13337 else if (fout->remoteVersion >= 80300)
13339 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13340 "amopopr::pg_catalog.regoperator, "
13341 "NULL AS sortfamily, "
13342 "NULL AS sortfamilynsp "
13343 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13344 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13345 "AND refobjid = '%u'::pg_catalog.oid "
13346 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13347 "AND objid = ao.oid "
13348 "ORDER BY amopstrategy",
13349 opcinfo->dobj.catId.oid);
13351 else
13354 * Here, we print all entries since there are no opfamilies and hence
13355 * no loose operators to worry about.
13357 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13358 "amopopr::pg_catalog.regoperator, "
13359 "NULL AS sortfamily, "
13360 "NULL AS sortfamilynsp "
13361 "FROM pg_catalog.pg_amop "
13362 "WHERE amopclaid = '%u'::pg_catalog.oid "
13363 "ORDER BY amopstrategy",
13364 opcinfo->dobj.catId.oid);
13367 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13369 ntups = PQntuples(res);
13371 i_amopstrategy = PQfnumber(res, "amopstrategy");
13372 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
13373 i_amopopr = PQfnumber(res, "amopopr");
13374 i_sortfamily = PQfnumber(res, "sortfamily");
13375 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
13377 for (i = 0; i < ntups; i++)
13379 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
13380 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
13381 amopopr = PQgetvalue(res, i, i_amopopr);
13382 sortfamily = PQgetvalue(res, i, i_sortfamily);
13383 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
13385 if (needComma)
13386 appendPQExpBufferStr(q, " ,\n ");
13388 appendPQExpBuffer(q, "OPERATOR %s %s",
13389 amopstrategy, amopopr);
13391 if (strlen(sortfamily) > 0)
13393 appendPQExpBufferStr(q, " FOR ORDER BY ");
13394 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13395 appendPQExpBufferStr(q, fmtId(sortfamily));
13398 if (strcmp(amopreqcheck, "t") == 0)
13399 appendPQExpBufferStr(q, " RECHECK");
13401 needComma = true;
13404 PQclear(res);
13407 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13409 * Print only those opfamily members that are tied to the opclass by
13410 * pg_depend entries.
13412 * We print the amproclefttype/amprocrighttype even though in most cases
13413 * the backend could deduce the right values, because of the corner case
13414 * of a btree sort support function for a cross-type comparison. That's
13415 * only allowed in 9.2 and later, but for simplicity print them in all
13416 * versions that have the columns.
13418 resetPQExpBuffer(query);
13420 if (fout->remoteVersion >= 80300)
13422 appendPQExpBuffer(query, "SELECT amprocnum, "
13423 "amproc::pg_catalog.regprocedure, "
13424 "amproclefttype::pg_catalog.regtype, "
13425 "amprocrighttype::pg_catalog.regtype "
13426 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13427 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13428 "AND refobjid = '%u'::pg_catalog.oid "
13429 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13430 "AND objid = ap.oid "
13431 "ORDER BY amprocnum",
13432 opcinfo->dobj.catId.oid);
13434 else
13436 appendPQExpBuffer(query, "SELECT amprocnum, "
13437 "amproc::pg_catalog.regprocedure, "
13438 "'' AS amproclefttype, "
13439 "'' AS amprocrighttype "
13440 "FROM pg_catalog.pg_amproc "
13441 "WHERE amopclaid = '%u'::pg_catalog.oid "
13442 "ORDER BY amprocnum",
13443 opcinfo->dobj.catId.oid);
13446 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13448 ntups = PQntuples(res);
13450 i_amprocnum = PQfnumber(res, "amprocnum");
13451 i_amproc = PQfnumber(res, "amproc");
13452 i_amproclefttype = PQfnumber(res, "amproclefttype");
13453 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
13455 for (i = 0; i < ntups; i++)
13457 amprocnum = PQgetvalue(res, i, i_amprocnum);
13458 amproc = PQgetvalue(res, i, i_amproc);
13459 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
13460 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
13462 if (needComma)
13463 appendPQExpBufferStr(q, " ,\n ");
13465 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
13467 if (*amproclefttype && *amprocrighttype)
13468 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13470 appendPQExpBuffer(q, " %s", amproc);
13472 needComma = true;
13475 PQclear(res);
13478 * If needComma is still false it means we haven't added anything after
13479 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13480 * clause with the same datatype. This isn't sanctioned by the
13481 * documentation, but actually DefineOpClass will treat it as a no-op.
13483 if (!needComma)
13484 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13486 appendPQExpBufferStr(q, ";\n");
13488 appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13489 appendPQExpBuffer(nameusing, " USING %s",
13490 fmtId(amname));
13492 if (dopt->binary_upgrade)
13493 binary_upgrade_extension_member(q, &opcinfo->dobj,
13494 "OPERATOR CLASS", nameusing->data,
13495 opcinfo->dobj.namespace->dobj.name);
13497 if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13498 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13499 ARCHIVE_OPTS(.tag = opcinfo->dobj.name,
13500 .namespace = opcinfo->dobj.namespace->dobj.name,
13501 .owner = opcinfo->rolname,
13502 .description = "OPERATOR CLASS",
13503 .section = SECTION_PRE_DATA,
13504 .createStmt = q->data,
13505 .dropStmt = delq->data));
13507 /* Dump Operator Class Comments */
13508 if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13509 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13510 opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13511 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13513 free(opcintype);
13514 free(opcfamily);
13515 free(amname);
13516 destroyPQExpBuffer(query);
13517 destroyPQExpBuffer(q);
13518 destroyPQExpBuffer(delq);
13519 destroyPQExpBuffer(nameusing);
13523 * dumpOpfamily
13524 * write out a single operator family definition
13526 * Note: this also dumps any "loose" operator members that aren't bound to a
13527 * specific opclass within the opfamily.
13529 static void
13530 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13532 DumpOptions *dopt = fout->dopt;
13533 PQExpBuffer query;
13534 PQExpBuffer q;
13535 PQExpBuffer delq;
13536 PQExpBuffer nameusing;
13537 PGresult *res;
13538 PGresult *res_ops;
13539 PGresult *res_procs;
13540 int ntups;
13541 int i_amname;
13542 int i_amopstrategy;
13543 int i_amopreqcheck;
13544 int i_amopopr;
13545 int i_sortfamily;
13546 int i_sortfamilynsp;
13547 int i_amprocnum;
13548 int i_amproc;
13549 int i_amproclefttype;
13550 int i_amprocrighttype;
13551 char *amname;
13552 char *amopstrategy;
13553 char *amopreqcheck;
13554 char *amopopr;
13555 char *sortfamily;
13556 char *sortfamilynsp;
13557 char *amprocnum;
13558 char *amproc;
13559 char *amproclefttype;
13560 char *amprocrighttype;
13561 bool needComma;
13562 int i;
13564 /* Skip if not to be dumped */
13565 if (!opfinfo->dobj.dump || dopt->dataOnly)
13566 return;
13568 query = createPQExpBuffer();
13569 q = createPQExpBuffer();
13570 delq = createPQExpBuffer();
13571 nameusing = createPQExpBuffer();
13574 * Fetch only those opfamily members that are tied directly to the
13575 * opfamily by pg_depend entries.
13577 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13578 * older server's opclass in which it is used. This is to avoid
13579 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13580 * older server and then reload into that old version. This can go away
13581 * once 8.3 is so old as to not be of interest to anyone.
13583 if (fout->remoteVersion >= 90100)
13585 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13586 "amopopr::pg_catalog.regoperator, "
13587 "opfname AS sortfamily, "
13588 "nspname AS sortfamilynsp "
13589 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13590 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13591 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13592 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13593 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13594 "AND refobjid = '%u'::pg_catalog.oid "
13595 "AND amopfamily = '%u'::pg_catalog.oid "
13596 "ORDER BY amopstrategy",
13597 opfinfo->dobj.catId.oid,
13598 opfinfo->dobj.catId.oid);
13600 else if (fout->remoteVersion >= 80400)
13602 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13603 "amopopr::pg_catalog.regoperator, "
13604 "NULL AS sortfamily, "
13605 "NULL AS sortfamilynsp "
13606 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13607 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13608 "AND refobjid = '%u'::pg_catalog.oid "
13609 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13610 "AND objid = ao.oid "
13611 "ORDER BY amopstrategy",
13612 opfinfo->dobj.catId.oid);
13614 else
13616 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13617 "amopopr::pg_catalog.regoperator, "
13618 "NULL AS sortfamily, "
13619 "NULL AS sortfamilynsp "
13620 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13621 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13622 "AND refobjid = '%u'::pg_catalog.oid "
13623 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13624 "AND objid = ao.oid "
13625 "ORDER BY amopstrategy",
13626 opfinfo->dobj.catId.oid);
13629 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13631 resetPQExpBuffer(query);
13633 appendPQExpBuffer(query, "SELECT amprocnum, "
13634 "amproc::pg_catalog.regprocedure, "
13635 "amproclefttype::pg_catalog.regtype, "
13636 "amprocrighttype::pg_catalog.regtype "
13637 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13638 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13639 "AND refobjid = '%u'::pg_catalog.oid "
13640 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13641 "AND objid = ap.oid "
13642 "ORDER BY amprocnum",
13643 opfinfo->dobj.catId.oid);
13645 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13647 /* Get additional fields from the pg_opfamily row */
13648 resetPQExpBuffer(query);
13650 appendPQExpBuffer(query, "SELECT "
13651 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13652 "FROM pg_catalog.pg_opfamily "
13653 "WHERE oid = '%u'::pg_catalog.oid",
13654 opfinfo->dobj.catId.oid);
13656 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13658 i_amname = PQfnumber(res, "amname");
13660 /* amname will still be needed after we PQclear res */
13661 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13663 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13664 fmtQualifiedDumpable(opfinfo));
13665 appendPQExpBuffer(delq, " USING %s;\n",
13666 fmtId(amname));
13668 /* Build the fixed portion of the CREATE command */
13669 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13670 fmtQualifiedDumpable(opfinfo));
13671 appendPQExpBuffer(q, " USING %s;\n",
13672 fmtId(amname));
13674 PQclear(res);
13676 /* Do we need an ALTER to add loose members? */
13677 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13679 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13680 fmtQualifiedDumpable(opfinfo));
13681 appendPQExpBuffer(q, " USING %s ADD\n ",
13682 fmtId(amname));
13684 needComma = false;
13687 * Now fetch and print the OPERATOR entries (pg_amop rows).
13689 ntups = PQntuples(res_ops);
13691 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13692 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13693 i_amopopr = PQfnumber(res_ops, "amopopr");
13694 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13695 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13697 for (i = 0; i < ntups; i++)
13699 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13700 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13701 amopopr = PQgetvalue(res_ops, i, i_amopopr);
13702 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13703 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13705 if (needComma)
13706 appendPQExpBufferStr(q, " ,\n ");
13708 appendPQExpBuffer(q, "OPERATOR %s %s",
13709 amopstrategy, amopopr);
13711 if (strlen(sortfamily) > 0)
13713 appendPQExpBufferStr(q, " FOR ORDER BY ");
13714 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13715 appendPQExpBufferStr(q, fmtId(sortfamily));
13718 if (strcmp(amopreqcheck, "t") == 0)
13719 appendPQExpBufferStr(q, " RECHECK");
13721 needComma = true;
13725 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13727 ntups = PQntuples(res_procs);
13729 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13730 i_amproc = PQfnumber(res_procs, "amproc");
13731 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13732 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13734 for (i = 0; i < ntups; i++)
13736 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13737 amproc = PQgetvalue(res_procs, i, i_amproc);
13738 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13739 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13741 if (needComma)
13742 appendPQExpBufferStr(q, " ,\n ");
13744 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13745 amprocnum, amproclefttype, amprocrighttype,
13746 amproc);
13748 needComma = true;
13751 appendPQExpBufferStr(q, ";\n");
13754 appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13755 appendPQExpBuffer(nameusing, " USING %s",
13756 fmtId(amname));
13758 if (dopt->binary_upgrade)
13759 binary_upgrade_extension_member(q, &opfinfo->dobj,
13760 "OPERATOR FAMILY", nameusing->data,
13761 opfinfo->dobj.namespace->dobj.name);
13763 if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13764 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13765 ARCHIVE_OPTS(.tag = opfinfo->dobj.name,
13766 .namespace = opfinfo->dobj.namespace->dobj.name,
13767 .owner = opfinfo->rolname,
13768 .description = "OPERATOR FAMILY",
13769 .section = SECTION_PRE_DATA,
13770 .createStmt = q->data,
13771 .dropStmt = delq->data));
13773 /* Dump Operator Family Comments */
13774 if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13775 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13776 opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13777 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13779 free(amname);
13780 PQclear(res_ops);
13781 PQclear(res_procs);
13782 destroyPQExpBuffer(query);
13783 destroyPQExpBuffer(q);
13784 destroyPQExpBuffer(delq);
13785 destroyPQExpBuffer(nameusing);
13789 * dumpCollation
13790 * write out a single collation definition
13792 static void
13793 dumpCollation(Archive *fout, CollInfo *collinfo)
13795 DumpOptions *dopt = fout->dopt;
13796 PQExpBuffer query;
13797 PQExpBuffer q;
13798 PQExpBuffer delq;
13799 char *qcollname;
13800 PGresult *res;
13801 int i_collprovider;
13802 int i_collisdeterministic;
13803 int i_collcollate;
13804 int i_collctype;
13805 const char *collprovider;
13806 const char *collcollate;
13807 const char *collctype;
13809 /* Skip if not to be dumped */
13810 if (!collinfo->dobj.dump || dopt->dataOnly)
13811 return;
13813 query = createPQExpBuffer();
13814 q = createPQExpBuffer();
13815 delq = createPQExpBuffer();
13817 qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13819 /* Get collation-specific details */
13820 appendPQExpBuffer(query, "SELECT ");
13822 if (fout->remoteVersion >= 100000)
13823 appendPQExpBuffer(query,
13824 "collprovider, "
13825 "collversion, ");
13826 else
13827 appendPQExpBuffer(query,
13828 "'c' AS collprovider, "
13829 "NULL AS collversion, ");
13831 if (fout->remoteVersion >= 120000)
13832 appendPQExpBuffer(query,
13833 "collisdeterministic, ");
13834 else
13835 appendPQExpBuffer(query,
13836 "true AS collisdeterministic, ");
13838 appendPQExpBuffer(query,
13839 "collcollate, "
13840 "collctype "
13841 "FROM pg_catalog.pg_collation c "
13842 "WHERE c.oid = '%u'::pg_catalog.oid",
13843 collinfo->dobj.catId.oid);
13845 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13847 i_collprovider = PQfnumber(res, "collprovider");
13848 i_collisdeterministic = PQfnumber(res, "collisdeterministic");
13849 i_collcollate = PQfnumber(res, "collcollate");
13850 i_collctype = PQfnumber(res, "collctype");
13852 collprovider = PQgetvalue(res, 0, i_collprovider);
13853 collcollate = PQgetvalue(res, 0, i_collcollate);
13854 collctype = PQgetvalue(res, 0, i_collctype);
13856 appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13857 fmtQualifiedDumpable(collinfo));
13859 appendPQExpBuffer(q, "CREATE COLLATION %s (",
13860 fmtQualifiedDumpable(collinfo));
13862 appendPQExpBufferStr(q, "provider = ");
13863 if (collprovider[0] == 'c')
13864 appendPQExpBufferStr(q, "libc");
13865 else if (collprovider[0] == 'i')
13866 appendPQExpBufferStr(q, "icu");
13867 else if (collprovider[0] == 'd')
13868 /* to allow dumping pg_catalog; not accepted on input */
13869 appendPQExpBufferStr(q, "default");
13870 else
13871 fatal("unrecognized collation provider: %s",
13872 collprovider);
13874 if (strcmp(PQgetvalue(res, 0, i_collisdeterministic), "f") == 0)
13875 appendPQExpBufferStr(q, ", deterministic = false");
13877 if (strcmp(collcollate, collctype) == 0)
13879 appendPQExpBufferStr(q, ", locale = ");
13880 appendStringLiteralAH(q, collcollate, fout);
13882 else
13884 appendPQExpBufferStr(q, ", lc_collate = ");
13885 appendStringLiteralAH(q, collcollate, fout);
13886 appendPQExpBufferStr(q, ", lc_ctype = ");
13887 appendStringLiteralAH(q, collctype, fout);
13891 * For binary upgrade, carry over the collation version. For normal
13892 * dump/restore, omit the version, so that it is computed upon restore.
13894 if (dopt->binary_upgrade)
13896 int i_collversion;
13898 i_collversion = PQfnumber(res, "collversion");
13899 if (!PQgetisnull(res, 0, i_collversion))
13901 appendPQExpBufferStr(q, ", version = ");
13902 appendStringLiteralAH(q,
13903 PQgetvalue(res, 0, i_collversion),
13904 fout);
13908 appendPQExpBufferStr(q, ");\n");
13910 if (dopt->binary_upgrade)
13911 binary_upgrade_extension_member(q, &collinfo->dobj,
13912 "COLLATION", qcollname,
13913 collinfo->dobj.namespace->dobj.name);
13915 if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13916 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13917 ARCHIVE_OPTS(.tag = collinfo->dobj.name,
13918 .namespace = collinfo->dobj.namespace->dobj.name,
13919 .owner = collinfo->rolname,
13920 .description = "COLLATION",
13921 .section = SECTION_PRE_DATA,
13922 .createStmt = q->data,
13923 .dropStmt = delq->data));
13925 /* Dump Collation Comments */
13926 if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13927 dumpComment(fout, "COLLATION", qcollname,
13928 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13929 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13931 PQclear(res);
13933 destroyPQExpBuffer(query);
13934 destroyPQExpBuffer(q);
13935 destroyPQExpBuffer(delq);
13936 free(qcollname);
13940 * dumpConversion
13941 * write out a single conversion definition
13943 static void
13944 dumpConversion(Archive *fout, ConvInfo *convinfo)
13946 DumpOptions *dopt = fout->dopt;
13947 PQExpBuffer query;
13948 PQExpBuffer q;
13949 PQExpBuffer delq;
13950 char *qconvname;
13951 PGresult *res;
13952 int i_conforencoding;
13953 int i_contoencoding;
13954 int i_conproc;
13955 int i_condefault;
13956 const char *conforencoding;
13957 const char *contoencoding;
13958 const char *conproc;
13959 bool condefault;
13961 /* Skip if not to be dumped */
13962 if (!convinfo->dobj.dump || dopt->dataOnly)
13963 return;
13965 query = createPQExpBuffer();
13966 q = createPQExpBuffer();
13967 delq = createPQExpBuffer();
13969 qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13971 /* Get conversion-specific details */
13972 appendPQExpBuffer(query, "SELECT "
13973 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13974 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13975 "conproc, condefault "
13976 "FROM pg_catalog.pg_conversion c "
13977 "WHERE c.oid = '%u'::pg_catalog.oid",
13978 convinfo->dobj.catId.oid);
13980 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13982 i_conforencoding = PQfnumber(res, "conforencoding");
13983 i_contoencoding = PQfnumber(res, "contoencoding");
13984 i_conproc = PQfnumber(res, "conproc");
13985 i_condefault = PQfnumber(res, "condefault");
13987 conforencoding = PQgetvalue(res, 0, i_conforencoding);
13988 contoencoding = PQgetvalue(res, 0, i_contoencoding);
13989 conproc = PQgetvalue(res, 0, i_conproc);
13990 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13992 appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13993 fmtQualifiedDumpable(convinfo));
13995 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13996 (condefault) ? "DEFAULT " : "",
13997 fmtQualifiedDumpable(convinfo));
13998 appendStringLiteralAH(q, conforencoding, fout);
13999 appendPQExpBufferStr(q, " TO ");
14000 appendStringLiteralAH(q, contoencoding, fout);
14001 /* regproc output is already sufficiently quoted */
14002 appendPQExpBuffer(q, " FROM %s;\n", conproc);
14004 if (dopt->binary_upgrade)
14005 binary_upgrade_extension_member(q, &convinfo->dobj,
14006 "CONVERSION", qconvname,
14007 convinfo->dobj.namespace->dobj.name);
14009 if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14010 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
14011 ARCHIVE_OPTS(.tag = convinfo->dobj.name,
14012 .namespace = convinfo->dobj.namespace->dobj.name,
14013 .owner = convinfo->rolname,
14014 .description = "CONVERSION",
14015 .section = SECTION_PRE_DATA,
14016 .createStmt = q->data,
14017 .dropStmt = delq->data));
14019 /* Dump Conversion Comments */
14020 if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14021 dumpComment(fout, "CONVERSION", qconvname,
14022 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
14023 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
14025 PQclear(res);
14027 destroyPQExpBuffer(query);
14028 destroyPQExpBuffer(q);
14029 destroyPQExpBuffer(delq);
14030 free(qconvname);
14034 * format_aggregate_signature: generate aggregate name and argument list
14036 * The argument type names are qualified if needed. The aggregate name
14037 * is never qualified.
14039 static char *
14040 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
14042 PQExpBufferData buf;
14043 int j;
14045 initPQExpBuffer(&buf);
14046 if (honor_quotes)
14047 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
14048 else
14049 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
14051 if (agginfo->aggfn.nargs == 0)
14052 appendPQExpBuffer(&buf, "(*)");
14053 else
14055 appendPQExpBufferChar(&buf, '(');
14056 for (j = 0; j < agginfo->aggfn.nargs; j++)
14057 appendPQExpBuffer(&buf, "%s%s",
14058 (j > 0) ? ", " : "",
14059 getFormattedTypeName(fout,
14060 agginfo->aggfn.argtypes[j],
14061 zeroAsOpaque));
14062 appendPQExpBufferChar(&buf, ')');
14064 return buf.data;
14068 * dumpAgg
14069 * write out a single aggregate definition
14071 static void
14072 dumpAgg(Archive *fout, AggInfo *agginfo)
14074 DumpOptions *dopt = fout->dopt;
14075 PQExpBuffer query;
14076 PQExpBuffer q;
14077 PQExpBuffer delq;
14078 PQExpBuffer details;
14079 char *aggsig; /* identity signature */
14080 char *aggfullsig = NULL; /* full signature */
14081 char *aggsig_tag;
14082 PGresult *res;
14083 int i_aggtransfn;
14084 int i_aggfinalfn;
14085 int i_aggcombinefn;
14086 int i_aggserialfn;
14087 int i_aggdeserialfn;
14088 int i_aggmtransfn;
14089 int i_aggminvtransfn;
14090 int i_aggmfinalfn;
14091 int i_aggfinalextra;
14092 int i_aggmfinalextra;
14093 int i_aggfinalmodify;
14094 int i_aggmfinalmodify;
14095 int i_aggsortop;
14096 int i_aggkind;
14097 int i_aggtranstype;
14098 int i_aggtransspace;
14099 int i_aggmtranstype;
14100 int i_aggmtransspace;
14101 int i_agginitval;
14102 int i_aggminitval;
14103 int i_convertok;
14104 int i_proparallel;
14105 const char *aggtransfn;
14106 const char *aggfinalfn;
14107 const char *aggcombinefn;
14108 const char *aggserialfn;
14109 const char *aggdeserialfn;
14110 const char *aggmtransfn;
14111 const char *aggminvtransfn;
14112 const char *aggmfinalfn;
14113 bool aggfinalextra;
14114 bool aggmfinalextra;
14115 char aggfinalmodify;
14116 char aggmfinalmodify;
14117 const char *aggsortop;
14118 char *aggsortconvop;
14119 char aggkind;
14120 const char *aggtranstype;
14121 const char *aggtransspace;
14122 const char *aggmtranstype;
14123 const char *aggmtransspace;
14124 const char *agginitval;
14125 const char *aggminitval;
14126 bool convertok;
14127 const char *proparallel;
14128 char defaultfinalmodify;
14130 /* Skip if not to be dumped */
14131 if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
14132 return;
14134 query = createPQExpBuffer();
14135 q = createPQExpBuffer();
14136 delq = createPQExpBuffer();
14137 details = createPQExpBuffer();
14139 /* Get aggregate-specific details */
14140 if (fout->remoteVersion >= 110000)
14142 appendPQExpBuffer(query, "SELECT aggtransfn, "
14143 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14144 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
14145 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
14146 "aggfinalextra, aggmfinalextra, "
14147 "aggfinalmodify, aggmfinalmodify, "
14148 "aggsortop, "
14149 "aggkind, "
14150 "aggtransspace, agginitval, "
14151 "aggmtransspace, aggminitval, "
14152 "true AS convertok, "
14153 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14154 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
14155 "p.proparallel "
14156 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14157 "WHERE a.aggfnoid = p.oid "
14158 "AND p.oid = '%u'::pg_catalog.oid",
14159 agginfo->aggfn.dobj.catId.oid);
14161 else if (fout->remoteVersion >= 90600)
14163 appendPQExpBuffer(query, "SELECT aggtransfn, "
14164 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14165 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
14166 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
14167 "aggfinalextra, aggmfinalextra, "
14168 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14169 "aggsortop, "
14170 "aggkind, "
14171 "aggtransspace, agginitval, "
14172 "aggmtransspace, aggminitval, "
14173 "true AS convertok, "
14174 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14175 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
14176 "p.proparallel "
14177 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14178 "WHERE a.aggfnoid = p.oid "
14179 "AND p.oid = '%u'::pg_catalog.oid",
14180 agginfo->aggfn.dobj.catId.oid);
14182 else if (fout->remoteVersion >= 90400)
14184 appendPQExpBuffer(query, "SELECT aggtransfn, "
14185 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14186 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14187 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
14188 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
14189 "aggfinalextra, aggmfinalextra, "
14190 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14191 "aggsortop, "
14192 "aggkind, "
14193 "aggtransspace, agginitval, "
14194 "aggmtransspace, aggminitval, "
14195 "true AS convertok, "
14196 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14197 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
14198 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14199 "WHERE a.aggfnoid = p.oid "
14200 "AND p.oid = '%u'::pg_catalog.oid",
14201 agginfo->aggfn.dobj.catId.oid);
14203 else if (fout->remoteVersion >= 80400)
14205 appendPQExpBuffer(query, "SELECT aggtransfn, "
14206 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14207 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14208 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
14209 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
14210 "0 AS aggmtranstype, false AS aggfinalextra, "
14211 "false AS aggmfinalextra, "
14212 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14213 "aggsortop, "
14214 "'n' AS aggkind, "
14215 "0 AS aggtransspace, agginitval, "
14216 "0 AS aggmtransspace, NULL AS aggminitval, "
14217 "true AS convertok, "
14218 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14219 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
14220 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14221 "WHERE a.aggfnoid = p.oid "
14222 "AND p.oid = '%u'::pg_catalog.oid",
14223 agginfo->aggfn.dobj.catId.oid);
14225 else if (fout->remoteVersion >= 80100)
14227 appendPQExpBuffer(query, "SELECT aggtransfn, "
14228 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14229 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14230 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
14231 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
14232 "0 AS aggmtranstype, false AS aggfinalextra, "
14233 "false AS aggmfinalextra, "
14234 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14235 "aggsortop, "
14236 "'n' AS aggkind, "
14237 "0 AS aggtransspace, agginitval, "
14238 "0 AS aggmtransspace, NULL AS aggminitval, "
14239 "true AS convertok "
14240 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14241 "WHERE a.aggfnoid = p.oid "
14242 "AND p.oid = '%u'::pg_catalog.oid",
14243 agginfo->aggfn.dobj.catId.oid);
14245 else
14247 appendPQExpBuffer(query, "SELECT aggtransfn, "
14248 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14249 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14250 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
14251 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
14252 "0 AS aggmtranstype, false AS aggfinalextra, "
14253 "false AS aggmfinalextra, "
14254 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14255 "0 AS aggsortop, "
14256 "'n' AS aggkind, "
14257 "0 AS aggtransspace, agginitval, "
14258 "0 AS aggmtransspace, NULL AS aggminitval, "
14259 "true AS convertok "
14260 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14261 "WHERE a.aggfnoid = p.oid "
14262 "AND p.oid = '%u'::pg_catalog.oid",
14263 agginfo->aggfn.dobj.catId.oid);
14266 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14268 i_aggtransfn = PQfnumber(res, "aggtransfn");
14269 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
14270 i_aggcombinefn = PQfnumber(res, "aggcombinefn");
14271 i_aggserialfn = PQfnumber(res, "aggserialfn");
14272 i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
14273 i_aggmtransfn = PQfnumber(res, "aggmtransfn");
14274 i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
14275 i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
14276 i_aggfinalextra = PQfnumber(res, "aggfinalextra");
14277 i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
14278 i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
14279 i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
14280 i_aggsortop = PQfnumber(res, "aggsortop");
14281 i_aggkind = PQfnumber(res, "aggkind");
14282 i_aggtranstype = PQfnumber(res, "aggtranstype");
14283 i_aggtransspace = PQfnumber(res, "aggtransspace");
14284 i_aggmtranstype = PQfnumber(res, "aggmtranstype");
14285 i_aggmtransspace = PQfnumber(res, "aggmtransspace");
14286 i_agginitval = PQfnumber(res, "agginitval");
14287 i_aggminitval = PQfnumber(res, "aggminitval");
14288 i_convertok = PQfnumber(res, "convertok");
14289 i_proparallel = PQfnumber(res, "proparallel");
14291 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
14292 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
14293 aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
14294 aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
14295 aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
14296 aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
14297 aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
14298 aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
14299 aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
14300 aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
14301 aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
14302 aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
14303 aggsortop = PQgetvalue(res, 0, i_aggsortop);
14304 aggkind = PQgetvalue(res, 0, i_aggkind)[0];
14305 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
14306 aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
14307 aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
14308 aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
14309 agginitval = PQgetvalue(res, 0, i_agginitval);
14310 aggminitval = PQgetvalue(res, 0, i_aggminitval);
14311 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
14313 if (fout->remoteVersion >= 80400)
14315 /* 8.4 or later; we rely on server-side code for most of the work */
14316 char *funcargs;
14317 char *funciargs;
14319 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
14320 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
14321 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
14322 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
14324 else
14325 /* pre-8.4, do it ourselves */
14326 aggsig = format_aggregate_signature(agginfo, fout, true);
14328 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
14330 if (i_proparallel != -1)
14331 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
14332 else
14333 proparallel = NULL;
14335 if (!convertok)
14337 pg_log_warning("aggregate function %s could not be dumped correctly for this database version; ignored",
14338 aggsig);
14340 if (aggfullsig)
14341 free(aggfullsig);
14343 free(aggsig);
14345 return;
14348 /* identify default modify flag for aggkind (must match DefineAggregate) */
14349 defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
14350 /* replace omitted flags for old versions */
14351 if (aggfinalmodify == '0')
14352 aggfinalmodify = defaultfinalmodify;
14353 if (aggmfinalmodify == '0')
14354 aggmfinalmodify = defaultfinalmodify;
14356 /* regproc and regtype output is already sufficiently quoted */
14357 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
14358 aggtransfn, aggtranstype);
14360 if (strcmp(aggtransspace, "0") != 0)
14362 appendPQExpBuffer(details, ",\n SSPACE = %s",
14363 aggtransspace);
14366 if (!PQgetisnull(res, 0, i_agginitval))
14368 appendPQExpBufferStr(details, ",\n INITCOND = ");
14369 appendStringLiteralAH(details, agginitval, fout);
14372 if (strcmp(aggfinalfn, "-") != 0)
14374 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
14375 aggfinalfn);
14376 if (aggfinalextra)
14377 appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
14378 if (aggfinalmodify != defaultfinalmodify)
14380 switch (aggfinalmodify)
14382 case AGGMODIFY_READ_ONLY:
14383 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
14384 break;
14385 case AGGMODIFY_SHAREABLE:
14386 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
14387 break;
14388 case AGGMODIFY_READ_WRITE:
14389 appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
14390 break;
14391 default:
14392 fatal("unrecognized aggfinalmodify value for aggregate \"%s\"",
14393 agginfo->aggfn.dobj.name);
14394 break;
14399 if (strcmp(aggcombinefn, "-") != 0)
14400 appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
14402 if (strcmp(aggserialfn, "-") != 0)
14403 appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
14405 if (strcmp(aggdeserialfn, "-") != 0)
14406 appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
14408 if (strcmp(aggmtransfn, "-") != 0)
14410 appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
14411 aggmtransfn,
14412 aggminvtransfn,
14413 aggmtranstype);
14416 if (strcmp(aggmtransspace, "0") != 0)
14418 appendPQExpBuffer(details, ",\n MSSPACE = %s",
14419 aggmtransspace);
14422 if (!PQgetisnull(res, 0, i_aggminitval))
14424 appendPQExpBufferStr(details, ",\n MINITCOND = ");
14425 appendStringLiteralAH(details, aggminitval, fout);
14428 if (strcmp(aggmfinalfn, "-") != 0)
14430 appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
14431 aggmfinalfn);
14432 if (aggmfinalextra)
14433 appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
14434 if (aggmfinalmodify != defaultfinalmodify)
14436 switch (aggmfinalmodify)
14438 case AGGMODIFY_READ_ONLY:
14439 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
14440 break;
14441 case AGGMODIFY_SHAREABLE:
14442 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
14443 break;
14444 case AGGMODIFY_READ_WRITE:
14445 appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
14446 break;
14447 default:
14448 fatal("unrecognized aggmfinalmodify value for aggregate \"%s\"",
14449 agginfo->aggfn.dobj.name);
14450 break;
14455 aggsortconvop = getFormattedOperatorName(fout, aggsortop);
14456 if (aggsortconvop)
14458 appendPQExpBuffer(details, ",\n SORTOP = %s",
14459 aggsortconvop);
14460 free(aggsortconvop);
14463 if (aggkind == AGGKIND_HYPOTHETICAL)
14464 appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
14466 if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
14468 if (proparallel[0] == PROPARALLEL_SAFE)
14469 appendPQExpBufferStr(details, ",\n PARALLEL = safe");
14470 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14471 appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
14472 else if (proparallel[0] != PROPARALLEL_UNSAFE)
14473 fatal("unrecognized proparallel value for function \"%s\"",
14474 agginfo->aggfn.dobj.name);
14477 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14478 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14479 aggsig);
14481 appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14482 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14483 aggfullsig ? aggfullsig : aggsig, details->data);
14485 if (dopt->binary_upgrade)
14486 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14487 "AGGREGATE", aggsig,
14488 agginfo->aggfn.dobj.namespace->dobj.name);
14490 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14491 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14492 agginfo->aggfn.dobj.dumpId,
14493 ARCHIVE_OPTS(.tag = aggsig_tag,
14494 .namespace = agginfo->aggfn.dobj.namespace->dobj.name,
14495 .owner = agginfo->aggfn.rolname,
14496 .description = "AGGREGATE",
14497 .section = SECTION_PRE_DATA,
14498 .createStmt = q->data,
14499 .dropStmt = delq->data));
14501 /* Dump Aggregate Comments */
14502 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14503 dumpComment(fout, "AGGREGATE", aggsig,
14504 agginfo->aggfn.dobj.namespace->dobj.name,
14505 agginfo->aggfn.rolname,
14506 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14508 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14509 dumpSecLabel(fout, "AGGREGATE", aggsig,
14510 agginfo->aggfn.dobj.namespace->dobj.name,
14511 agginfo->aggfn.rolname,
14512 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14515 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14516 * command look like a function's GRANT; in particular this affects the
14517 * syntax for zero-argument aggregates and ordered-set aggregates.
14519 free(aggsig);
14521 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14523 if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14524 dumpACL(fout, agginfo->aggfn.dobj.dumpId, InvalidDumpId,
14525 "FUNCTION", aggsig, NULL,
14526 agginfo->aggfn.dobj.namespace->dobj.name,
14527 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14528 agginfo->aggfn.rproacl,
14529 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14531 free(aggsig);
14532 if (aggfullsig)
14533 free(aggfullsig);
14534 free(aggsig_tag);
14536 PQclear(res);
14538 destroyPQExpBuffer(query);
14539 destroyPQExpBuffer(q);
14540 destroyPQExpBuffer(delq);
14541 destroyPQExpBuffer(details);
14545 * dumpTSParser
14546 * write out a single text search parser
14548 static void
14549 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14551 DumpOptions *dopt = fout->dopt;
14552 PQExpBuffer q;
14553 PQExpBuffer delq;
14554 char *qprsname;
14556 /* Skip if not to be dumped */
14557 if (!prsinfo->dobj.dump || dopt->dataOnly)
14558 return;
14560 q = createPQExpBuffer();
14561 delq = createPQExpBuffer();
14563 qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14565 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14566 fmtQualifiedDumpable(prsinfo));
14568 appendPQExpBuffer(q, " START = %s,\n",
14569 convertTSFunction(fout, prsinfo->prsstart));
14570 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14571 convertTSFunction(fout, prsinfo->prstoken));
14572 appendPQExpBuffer(q, " END = %s,\n",
14573 convertTSFunction(fout, prsinfo->prsend));
14574 if (prsinfo->prsheadline != InvalidOid)
14575 appendPQExpBuffer(q, " HEADLINE = %s,\n",
14576 convertTSFunction(fout, prsinfo->prsheadline));
14577 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14578 convertTSFunction(fout, prsinfo->prslextype));
14580 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14581 fmtQualifiedDumpable(prsinfo));
14583 if (dopt->binary_upgrade)
14584 binary_upgrade_extension_member(q, &prsinfo->dobj,
14585 "TEXT SEARCH PARSER", qprsname,
14586 prsinfo->dobj.namespace->dobj.name);
14588 if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14589 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14590 ARCHIVE_OPTS(.tag = prsinfo->dobj.name,
14591 .namespace = prsinfo->dobj.namespace->dobj.name,
14592 .description = "TEXT SEARCH PARSER",
14593 .section = SECTION_PRE_DATA,
14594 .createStmt = q->data,
14595 .dropStmt = delq->data));
14597 /* Dump Parser Comments */
14598 if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14599 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14600 prsinfo->dobj.namespace->dobj.name, "",
14601 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14603 destroyPQExpBuffer(q);
14604 destroyPQExpBuffer(delq);
14605 free(qprsname);
14609 * dumpTSDictionary
14610 * write out a single text search dictionary
14612 static void
14613 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14615 DumpOptions *dopt = fout->dopt;
14616 PQExpBuffer q;
14617 PQExpBuffer delq;
14618 PQExpBuffer query;
14619 char *qdictname;
14620 PGresult *res;
14621 char *nspname;
14622 char *tmplname;
14624 /* Skip if not to be dumped */
14625 if (!dictinfo->dobj.dump || dopt->dataOnly)
14626 return;
14628 q = createPQExpBuffer();
14629 delq = createPQExpBuffer();
14630 query = createPQExpBuffer();
14632 qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14634 /* Fetch name and namespace of the dictionary's template */
14635 appendPQExpBuffer(query, "SELECT nspname, tmplname "
14636 "FROM pg_ts_template p, pg_namespace n "
14637 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14638 dictinfo->dicttemplate);
14639 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14640 nspname = PQgetvalue(res, 0, 0);
14641 tmplname = PQgetvalue(res, 0, 1);
14643 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14644 fmtQualifiedDumpable(dictinfo));
14646 appendPQExpBufferStr(q, " TEMPLATE = ");
14647 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14648 appendPQExpBufferStr(q, fmtId(tmplname));
14650 PQclear(res);
14652 /* the dictinitoption can be dumped straight into the command */
14653 if (dictinfo->dictinitoption)
14654 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14656 appendPQExpBufferStr(q, " );\n");
14658 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14659 fmtQualifiedDumpable(dictinfo));
14661 if (dopt->binary_upgrade)
14662 binary_upgrade_extension_member(q, &dictinfo->dobj,
14663 "TEXT SEARCH DICTIONARY", qdictname,
14664 dictinfo->dobj.namespace->dobj.name);
14666 if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14667 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14668 ARCHIVE_OPTS(.tag = dictinfo->dobj.name,
14669 .namespace = dictinfo->dobj.namespace->dobj.name,
14670 .owner = dictinfo->rolname,
14671 .description = "TEXT SEARCH DICTIONARY",
14672 .section = SECTION_PRE_DATA,
14673 .createStmt = q->data,
14674 .dropStmt = delq->data));
14676 /* Dump Dictionary Comments */
14677 if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14678 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14679 dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14680 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14682 destroyPQExpBuffer(q);
14683 destroyPQExpBuffer(delq);
14684 destroyPQExpBuffer(query);
14685 free(qdictname);
14689 * dumpTSTemplate
14690 * write out a single text search template
14692 static void
14693 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14695 DumpOptions *dopt = fout->dopt;
14696 PQExpBuffer q;
14697 PQExpBuffer delq;
14698 char *qtmplname;
14700 /* Skip if not to be dumped */
14701 if (!tmplinfo->dobj.dump || dopt->dataOnly)
14702 return;
14704 q = createPQExpBuffer();
14705 delq = createPQExpBuffer();
14707 qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14709 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14710 fmtQualifiedDumpable(tmplinfo));
14712 if (tmplinfo->tmplinit != InvalidOid)
14713 appendPQExpBuffer(q, " INIT = %s,\n",
14714 convertTSFunction(fout, tmplinfo->tmplinit));
14715 appendPQExpBuffer(q, " LEXIZE = %s );\n",
14716 convertTSFunction(fout, tmplinfo->tmpllexize));
14718 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14719 fmtQualifiedDumpable(tmplinfo));
14721 if (dopt->binary_upgrade)
14722 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14723 "TEXT SEARCH TEMPLATE", qtmplname,
14724 tmplinfo->dobj.namespace->dobj.name);
14726 if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14727 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14728 ARCHIVE_OPTS(.tag = tmplinfo->dobj.name,
14729 .namespace = tmplinfo->dobj.namespace->dobj.name,
14730 .description = "TEXT SEARCH TEMPLATE",
14731 .section = SECTION_PRE_DATA,
14732 .createStmt = q->data,
14733 .dropStmt = delq->data));
14735 /* Dump Template Comments */
14736 if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14737 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14738 tmplinfo->dobj.namespace->dobj.name, "",
14739 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14741 destroyPQExpBuffer(q);
14742 destroyPQExpBuffer(delq);
14743 free(qtmplname);
14747 * dumpTSConfig
14748 * write out a single text search configuration
14750 static void
14751 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14753 DumpOptions *dopt = fout->dopt;
14754 PQExpBuffer q;
14755 PQExpBuffer delq;
14756 PQExpBuffer query;
14757 char *qcfgname;
14758 PGresult *res;
14759 char *nspname;
14760 char *prsname;
14761 int ntups,
14763 int i_tokenname;
14764 int i_dictname;
14766 /* Skip if not to be dumped */
14767 if (!cfginfo->dobj.dump || dopt->dataOnly)
14768 return;
14770 q = createPQExpBuffer();
14771 delq = createPQExpBuffer();
14772 query = createPQExpBuffer();
14774 qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14776 /* Fetch name and namespace of the config's parser */
14777 appendPQExpBuffer(query, "SELECT nspname, prsname "
14778 "FROM pg_ts_parser p, pg_namespace n "
14779 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14780 cfginfo->cfgparser);
14781 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14782 nspname = PQgetvalue(res, 0, 0);
14783 prsname = PQgetvalue(res, 0, 1);
14785 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14786 fmtQualifiedDumpable(cfginfo));
14788 appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14789 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14791 PQclear(res);
14793 resetPQExpBuffer(query);
14794 appendPQExpBuffer(query,
14795 "SELECT\n"
14796 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14797 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14798 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14799 "FROM pg_catalog.pg_ts_config_map AS m\n"
14800 "WHERE m.mapcfg = '%u'\n"
14801 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14802 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14804 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14805 ntups = PQntuples(res);
14807 i_tokenname = PQfnumber(res, "tokenname");
14808 i_dictname = PQfnumber(res, "dictname");
14810 for (i = 0; i < ntups; i++)
14812 char *tokenname = PQgetvalue(res, i, i_tokenname);
14813 char *dictname = PQgetvalue(res, i, i_dictname);
14815 if (i == 0 ||
14816 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14818 /* starting a new token type, so start a new command */
14819 if (i > 0)
14820 appendPQExpBufferStr(q, ";\n");
14821 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14822 fmtQualifiedDumpable(cfginfo));
14823 /* tokenname needs quoting, dictname does NOT */
14824 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14825 fmtId(tokenname), dictname);
14827 else
14828 appendPQExpBuffer(q, ", %s", dictname);
14831 if (ntups > 0)
14832 appendPQExpBufferStr(q, ";\n");
14834 PQclear(res);
14836 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14837 fmtQualifiedDumpable(cfginfo));
14839 if (dopt->binary_upgrade)
14840 binary_upgrade_extension_member(q, &cfginfo->dobj,
14841 "TEXT SEARCH CONFIGURATION", qcfgname,
14842 cfginfo->dobj.namespace->dobj.name);
14844 if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14845 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14846 ARCHIVE_OPTS(.tag = cfginfo->dobj.name,
14847 .namespace = cfginfo->dobj.namespace->dobj.name,
14848 .owner = cfginfo->rolname,
14849 .description = "TEXT SEARCH CONFIGURATION",
14850 .section = SECTION_PRE_DATA,
14851 .createStmt = q->data,
14852 .dropStmt = delq->data));
14854 /* Dump Configuration Comments */
14855 if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14856 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14857 cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14858 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14860 destroyPQExpBuffer(q);
14861 destroyPQExpBuffer(delq);
14862 destroyPQExpBuffer(query);
14863 free(qcfgname);
14867 * dumpForeignDataWrapper
14868 * write out a single foreign-data wrapper definition
14870 static void
14871 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14873 DumpOptions *dopt = fout->dopt;
14874 PQExpBuffer q;
14875 PQExpBuffer delq;
14876 char *qfdwname;
14878 /* Skip if not to be dumped */
14879 if (!fdwinfo->dobj.dump || dopt->dataOnly)
14880 return;
14882 q = createPQExpBuffer();
14883 delq = createPQExpBuffer();
14885 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14887 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14888 qfdwname);
14890 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14891 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14893 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14894 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14896 if (strlen(fdwinfo->fdwoptions) > 0)
14897 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14899 appendPQExpBufferStr(q, ";\n");
14901 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14902 qfdwname);
14904 if (dopt->binary_upgrade)
14905 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14906 "FOREIGN DATA WRAPPER", qfdwname,
14907 NULL);
14909 if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14910 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14911 ARCHIVE_OPTS(.tag = fdwinfo->dobj.name,
14912 .owner = fdwinfo->rolname,
14913 .description = "FOREIGN DATA WRAPPER",
14914 .section = SECTION_PRE_DATA,
14915 .createStmt = q->data,
14916 .dropStmt = delq->data));
14918 /* Dump Foreign Data Wrapper Comments */
14919 if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14920 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14921 NULL, fdwinfo->rolname,
14922 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14924 /* Handle the ACL */
14925 if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14926 dumpACL(fout, fdwinfo->dobj.dumpId, InvalidDumpId,
14927 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14928 NULL, fdwinfo->rolname,
14929 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14930 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14932 free(qfdwname);
14934 destroyPQExpBuffer(q);
14935 destroyPQExpBuffer(delq);
14939 * dumpForeignServer
14940 * write out a foreign server definition
14942 static void
14943 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14945 DumpOptions *dopt = fout->dopt;
14946 PQExpBuffer q;
14947 PQExpBuffer delq;
14948 PQExpBuffer query;
14949 PGresult *res;
14950 char *qsrvname;
14951 char *fdwname;
14953 /* Skip if not to be dumped */
14954 if (!srvinfo->dobj.dump || dopt->dataOnly)
14955 return;
14957 q = createPQExpBuffer();
14958 delq = createPQExpBuffer();
14959 query = createPQExpBuffer();
14961 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14963 /* look up the foreign-data wrapper */
14964 appendPQExpBuffer(query, "SELECT fdwname "
14965 "FROM pg_foreign_data_wrapper w "
14966 "WHERE w.oid = '%u'",
14967 srvinfo->srvfdw);
14968 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14969 fdwname = PQgetvalue(res, 0, 0);
14971 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14972 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14974 appendPQExpBufferStr(q, " TYPE ");
14975 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14977 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14979 appendPQExpBufferStr(q, " VERSION ");
14980 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14983 appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14984 appendPQExpBufferStr(q, fmtId(fdwname));
14986 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14987 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14989 appendPQExpBufferStr(q, ";\n");
14991 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14992 qsrvname);
14994 if (dopt->binary_upgrade)
14995 binary_upgrade_extension_member(q, &srvinfo->dobj,
14996 "SERVER", qsrvname, NULL);
14998 if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14999 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
15000 ARCHIVE_OPTS(.tag = srvinfo->dobj.name,
15001 .owner = srvinfo->rolname,
15002 .description = "SERVER",
15003 .section = SECTION_PRE_DATA,
15004 .createStmt = q->data,
15005 .dropStmt = delq->data));
15007 /* Dump Foreign Server Comments */
15008 if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15009 dumpComment(fout, "SERVER", qsrvname,
15010 NULL, srvinfo->rolname,
15011 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
15013 /* Handle the ACL */
15014 if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
15015 dumpACL(fout, srvinfo->dobj.dumpId, InvalidDumpId,
15016 "FOREIGN SERVER", qsrvname, NULL,
15017 NULL, srvinfo->rolname,
15018 srvinfo->srvacl, srvinfo->rsrvacl,
15019 srvinfo->initsrvacl, srvinfo->initrsrvacl);
15021 /* Dump user mappings */
15022 if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
15023 dumpUserMappings(fout,
15024 srvinfo->dobj.name, NULL,
15025 srvinfo->rolname,
15026 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
15028 free(qsrvname);
15030 destroyPQExpBuffer(q);
15031 destroyPQExpBuffer(delq);
15032 destroyPQExpBuffer(query);
15036 * dumpUserMappings
15038 * This routine is used to dump any user mappings associated with the
15039 * server handed to this routine. Should be called after ArchiveEntry()
15040 * for the server.
15042 static void
15043 dumpUserMappings(Archive *fout,
15044 const char *servername, const char *namespace,
15045 const char *owner,
15046 CatalogId catalogId, DumpId dumpId)
15048 PQExpBuffer q;
15049 PQExpBuffer delq;
15050 PQExpBuffer query;
15051 PQExpBuffer tag;
15052 PGresult *res;
15053 int ntups;
15054 int i_usename;
15055 int i_umoptions;
15056 int i;
15058 q = createPQExpBuffer();
15059 tag = createPQExpBuffer();
15060 delq = createPQExpBuffer();
15061 query = createPQExpBuffer();
15064 * We read from the publicly accessible view pg_user_mappings, so as not
15065 * to fail if run by a non-superuser. Note that the view will show
15066 * umoptions as null if the user hasn't got privileges for the associated
15067 * server; this means that pg_dump will dump such a mapping, but with no
15068 * OPTIONS clause. A possible alternative is to skip such mappings
15069 * altogether, but it's not clear that that's an improvement.
15071 appendPQExpBuffer(query,
15072 "SELECT usename, "
15073 "array_to_string(ARRAY("
15074 "SELECT quote_ident(option_name) || ' ' || "
15075 "quote_literal(option_value) "
15076 "FROM pg_options_to_table(umoptions) "
15077 "ORDER BY option_name"
15078 "), E',\n ') AS umoptions "
15079 "FROM pg_user_mappings "
15080 "WHERE srvid = '%u' "
15081 "ORDER BY usename",
15082 catalogId.oid);
15084 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15086 ntups = PQntuples(res);
15087 i_usename = PQfnumber(res, "usename");
15088 i_umoptions = PQfnumber(res, "umoptions");
15090 for (i = 0; i < ntups; i++)
15092 char *usename;
15093 char *umoptions;
15095 usename = PQgetvalue(res, i, i_usename);
15096 umoptions = PQgetvalue(res, i, i_umoptions);
15098 resetPQExpBuffer(q);
15099 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
15100 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
15102 if (umoptions && strlen(umoptions) > 0)
15103 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
15105 appendPQExpBufferStr(q, ";\n");
15107 resetPQExpBuffer(delq);
15108 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
15109 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
15111 resetPQExpBuffer(tag);
15112 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
15113 usename, servername);
15115 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15116 ARCHIVE_OPTS(.tag = tag->data,
15117 .namespace = namespace,
15118 .owner = owner,
15119 .description = "USER MAPPING",
15120 .section = SECTION_PRE_DATA,
15121 .createStmt = q->data,
15122 .dropStmt = delq->data));
15125 PQclear(res);
15127 destroyPQExpBuffer(query);
15128 destroyPQExpBuffer(delq);
15129 destroyPQExpBuffer(tag);
15130 destroyPQExpBuffer(q);
15134 * Write out default privileges information
15136 static void
15137 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
15139 DumpOptions *dopt = fout->dopt;
15140 PQExpBuffer q;
15141 PQExpBuffer tag;
15142 const char *type;
15144 /* Skip if not to be dumped */
15145 if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
15146 return;
15148 q = createPQExpBuffer();
15149 tag = createPQExpBuffer();
15151 switch (daclinfo->defaclobjtype)
15153 case DEFACLOBJ_RELATION:
15154 type = "TABLES";
15155 break;
15156 case DEFACLOBJ_SEQUENCE:
15157 type = "SEQUENCES";
15158 break;
15159 case DEFACLOBJ_FUNCTION:
15160 type = "FUNCTIONS";
15161 break;
15162 case DEFACLOBJ_TYPE:
15163 type = "TYPES";
15164 break;
15165 case DEFACLOBJ_NAMESPACE:
15166 type = "SCHEMAS";
15167 break;
15168 default:
15169 /* shouldn't get here */
15170 fatal("unrecognized object type in default privileges: %d",
15171 (int) daclinfo->defaclobjtype);
15172 type = ""; /* keep compiler quiet */
15175 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
15177 /* build the actual command(s) for this tuple */
15178 if (!buildDefaultACLCommands(type,
15179 daclinfo->dobj.namespace != NULL ?
15180 daclinfo->dobj.namespace->dobj.name : NULL,
15181 daclinfo->defaclacl,
15182 daclinfo->rdefaclacl,
15183 daclinfo->initdefaclacl,
15184 daclinfo->initrdefaclacl,
15185 daclinfo->defaclrole,
15186 fout->remoteVersion,
15188 fatal("could not parse default ACL list (%s)",
15189 daclinfo->defaclacl);
15191 if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
15192 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
15193 ARCHIVE_OPTS(.tag = tag->data,
15194 .namespace = daclinfo->dobj.namespace ?
15195 daclinfo->dobj.namespace->dobj.name : NULL,
15196 .owner = daclinfo->defaclrole,
15197 .description = "DEFAULT ACL",
15198 .section = SECTION_POST_DATA,
15199 .createStmt = q->data));
15201 destroyPQExpBuffer(tag);
15202 destroyPQExpBuffer(q);
15205 /*----------
15206 * Write out grant/revoke information
15208 * 'objDumpId' is the dump ID of the underlying object.
15209 * 'altDumpId' can be a second dumpId that the ACL entry must also depend on,
15210 * or InvalidDumpId if there is no need for a second dependency.
15211 * 'type' must be one of
15212 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
15213 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
15214 * 'name' is the formatted name of the object. Must be quoted etc. already.
15215 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
15216 * (Currently we assume that subname is only provided for table columns.)
15217 * 'nspname' is the namespace the object is in (NULL if none).
15218 * 'owner' is the owner, NULL if there is no owner (for languages).
15219 * 'acls' contains the ACL string of the object from the appropriate system
15220 * catalog field; it will be passed to buildACLCommands for building the
15221 * appropriate GRANT commands.
15222 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
15223 * object; it will be passed to buildACLCommands for building the
15224 * appropriate REVOKE commands.
15225 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
15226 * privileges, to be recorded into pg_init_privs
15227 * 'initracls' In binary-upgrade mode, ACL string of the object's
15228 * revoked-from-default privileges, to be recorded into pg_init_privs
15230 * NB: initacls/initracls are needed because extensions can set privileges on
15231 * an object during the extension's script file and we record those into
15232 * pg_init_privs as that object's initial privileges.
15234 * Returns the dump ID assigned to the ACL TocEntry, or InvalidDumpId if
15235 * no ACL entry was created.
15236 *----------
15238 static DumpId
15239 dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId,
15240 const char *type, const char *name, const char *subname,
15241 const char *nspname, const char *owner,
15242 const char *acls, const char *racls,
15243 const char *initacls, const char *initracls)
15245 DumpId aclDumpId = InvalidDumpId;
15246 DumpOptions *dopt = fout->dopt;
15247 PQExpBuffer sql;
15249 /* Do nothing if ACL dump is not enabled */
15250 if (dopt->aclsSkip)
15251 return InvalidDumpId;
15253 /* --data-only skips ACLs *except* BLOB ACLs */
15254 if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
15255 return InvalidDumpId;
15257 sql = createPQExpBuffer();
15260 * Check to see if this object has had any initial ACLs included for it.
15261 * If so, we are in binary upgrade mode and these are the ACLs to turn
15262 * into GRANT and REVOKE statements to set and record the initial
15263 * privileges for an extension object. Let the backend know that these
15264 * are to be recorded by calling binary_upgrade_set_record_init_privs()
15265 * before and after.
15267 if (strlen(initacls) != 0 || strlen(initracls) != 0)
15269 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
15270 if (!buildACLCommands(name, subname, nspname, type,
15271 initacls, initracls, owner,
15272 "", fout->remoteVersion, sql))
15273 fatal("could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)",
15274 initacls, initracls, name, type);
15275 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
15278 if (!buildACLCommands(name, subname, nspname, type,
15279 acls, racls, owner,
15280 "", fout->remoteVersion, sql))
15281 fatal("could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)",
15282 acls, racls, name, type);
15284 if (sql->len > 0)
15286 PQExpBuffer tag = createPQExpBuffer();
15287 DumpId aclDeps[2];
15288 int nDeps = 0;
15290 if (subname)
15291 appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
15292 else
15293 appendPQExpBuffer(tag, "%s %s", type, name);
15295 aclDeps[nDeps++] = objDumpId;
15296 if (altDumpId != InvalidDumpId)
15297 aclDeps[nDeps++] = altDumpId;
15299 aclDumpId = createDumpId();
15301 ArchiveEntry(fout, nilCatalogId, aclDumpId,
15302 ARCHIVE_OPTS(.tag = tag->data,
15303 .namespace = nspname,
15304 .owner = owner,
15305 .description = "ACL",
15306 .section = SECTION_NONE,
15307 .createStmt = sql->data,
15308 .deps = aclDeps,
15309 .nDeps = nDeps));
15311 destroyPQExpBuffer(tag);
15314 destroyPQExpBuffer(sql);
15316 return aclDumpId;
15320 * dumpSecLabel
15322 * This routine is used to dump any security labels associated with the
15323 * object handed to this routine. The routine takes the object type
15324 * and object name (ready to print, except for schema decoration), plus
15325 * the namespace and owner of the object (for labeling the ArchiveEntry),
15326 * plus catalog ID and subid which are the lookup key for pg_seclabel,
15327 * plus the dump ID for the object (for setting a dependency).
15328 * If a matching pg_seclabel entry is found, it is dumped.
15330 * Note: although this routine takes a dumpId for dependency purposes,
15331 * that purpose is just to mark the dependency in the emitted dump file
15332 * for possible future use by pg_restore. We do NOT use it for determining
15333 * ordering of the label in the dump file, because this routine is called
15334 * after dependency sorting occurs. This routine should be called just after
15335 * calling ArchiveEntry() for the specified object.
15337 static void
15338 dumpSecLabel(Archive *fout, const char *type, const char *name,
15339 const char *namespace, const char *owner,
15340 CatalogId catalogId, int subid, DumpId dumpId)
15342 DumpOptions *dopt = fout->dopt;
15343 SecLabelItem *labels;
15344 int nlabels;
15345 int i;
15346 PQExpBuffer query;
15348 /* do nothing, if --no-security-labels is supplied */
15349 if (dopt->no_security_labels)
15350 return;
15352 /* Security labels are schema not data ... except blob labels are data */
15353 if (strcmp(type, "LARGE OBJECT") != 0)
15355 if (dopt->dataOnly)
15356 return;
15358 else
15360 /* We do dump blob security labels in binary-upgrade mode */
15361 if (dopt->schemaOnly && !dopt->binary_upgrade)
15362 return;
15365 /* Search for security labels associated with catalogId, using table */
15366 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
15368 query = createPQExpBuffer();
15370 for (i = 0; i < nlabels; i++)
15373 * Ignore label entries for which the subid doesn't match.
15375 if (labels[i].objsubid != subid)
15376 continue;
15378 appendPQExpBuffer(query,
15379 "SECURITY LABEL FOR %s ON %s ",
15380 fmtId(labels[i].provider), type);
15381 if (namespace && *namespace)
15382 appendPQExpBuffer(query, "%s.", fmtId(namespace));
15383 appendPQExpBuffer(query, "%s IS ", name);
15384 appendStringLiteralAH(query, labels[i].label, fout);
15385 appendPQExpBufferStr(query, ";\n");
15388 if (query->len > 0)
15390 PQExpBuffer tag = createPQExpBuffer();
15392 appendPQExpBuffer(tag, "%s %s", type, name);
15393 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15394 ARCHIVE_OPTS(.tag = tag->data,
15395 .namespace = namespace,
15396 .owner = owner,
15397 .description = "SECURITY LABEL",
15398 .section = SECTION_NONE,
15399 .createStmt = query->data,
15400 .deps = &dumpId,
15401 .nDeps = 1));
15402 destroyPQExpBuffer(tag);
15405 destroyPQExpBuffer(query);
15409 * dumpTableSecLabel
15411 * As above, but dump security label for both the specified table (or view)
15412 * and its columns.
15414 static void
15415 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
15417 DumpOptions *dopt = fout->dopt;
15418 SecLabelItem *labels;
15419 int nlabels;
15420 int i;
15421 PQExpBuffer query;
15422 PQExpBuffer target;
15424 /* do nothing, if --no-security-labels is supplied */
15425 if (dopt->no_security_labels)
15426 return;
15428 /* SecLabel are SCHEMA not data */
15429 if (dopt->dataOnly)
15430 return;
15432 /* Search for comments associated with relation, using table */
15433 nlabels = findSecLabels(fout,
15434 tbinfo->dobj.catId.tableoid,
15435 tbinfo->dobj.catId.oid,
15436 &labels);
15438 /* If security labels exist, build SECURITY LABEL statements */
15439 if (nlabels <= 0)
15440 return;
15442 query = createPQExpBuffer();
15443 target = createPQExpBuffer();
15445 for (i = 0; i < nlabels; i++)
15447 const char *colname;
15448 const char *provider = labels[i].provider;
15449 const char *label = labels[i].label;
15450 int objsubid = labels[i].objsubid;
15452 resetPQExpBuffer(target);
15453 if (objsubid == 0)
15455 appendPQExpBuffer(target, "%s %s", reltypename,
15456 fmtQualifiedDumpable(tbinfo));
15458 else
15460 colname = getAttrName(objsubid, tbinfo);
15461 /* first fmtXXX result must be consumed before calling again */
15462 appendPQExpBuffer(target, "COLUMN %s",
15463 fmtQualifiedDumpable(tbinfo));
15464 appendPQExpBuffer(target, ".%s", fmtId(colname));
15466 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
15467 fmtId(provider), target->data);
15468 appendStringLiteralAH(query, label, fout);
15469 appendPQExpBufferStr(query, ";\n");
15471 if (query->len > 0)
15473 resetPQExpBuffer(target);
15474 appendPQExpBuffer(target, "%s %s", reltypename,
15475 fmtId(tbinfo->dobj.name));
15476 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15477 ARCHIVE_OPTS(.tag = target->data,
15478 .namespace = tbinfo->dobj.namespace->dobj.name,
15479 .owner = tbinfo->rolname,
15480 .description = "SECURITY LABEL",
15481 .section = SECTION_NONE,
15482 .createStmt = query->data,
15483 .deps = &(tbinfo->dobj.dumpId),
15484 .nDeps = 1));
15486 destroyPQExpBuffer(query);
15487 destroyPQExpBuffer(target);
15491 * findSecLabels
15493 * Find the security label(s), if any, associated with the given object.
15494 * All the objsubid values associated with the given classoid/objoid are
15495 * found with one search.
15497 static int
15498 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15500 /* static storage for table of security labels */
15501 static SecLabelItem *labels = NULL;
15502 static int nlabels = -1;
15504 SecLabelItem *middle = NULL;
15505 SecLabelItem *low;
15506 SecLabelItem *high;
15507 int nmatch;
15509 /* Get security labels if we didn't already */
15510 if (nlabels < 0)
15511 nlabels = collectSecLabels(fout, &labels);
15513 if (nlabels <= 0) /* no labels, so no match is possible */
15515 *items = NULL;
15516 return 0;
15520 * Do binary search to find some item matching the object.
15522 low = &labels[0];
15523 high = &labels[nlabels - 1];
15524 while (low <= high)
15526 middle = low + (high - low) / 2;
15528 if (classoid < middle->classoid)
15529 high = middle - 1;
15530 else if (classoid > middle->classoid)
15531 low = middle + 1;
15532 else if (objoid < middle->objoid)
15533 high = middle - 1;
15534 else if (objoid > middle->objoid)
15535 low = middle + 1;
15536 else
15537 break; /* found a match */
15540 if (low > high) /* no matches */
15542 *items = NULL;
15543 return 0;
15547 * Now determine how many items match the object. The search loop
15548 * invariant still holds: only items between low and high inclusive could
15549 * match.
15551 nmatch = 1;
15552 while (middle > low)
15554 if (classoid != middle[-1].classoid ||
15555 objoid != middle[-1].objoid)
15556 break;
15557 middle--;
15558 nmatch++;
15561 *items = middle;
15563 middle += nmatch;
15564 while (middle <= high)
15566 if (classoid != middle->classoid ||
15567 objoid != middle->objoid)
15568 break;
15569 middle++;
15570 nmatch++;
15573 return nmatch;
15577 * collectSecLabels
15579 * Construct a table of all security labels available for database objects.
15580 * It's much faster to pull them all at once.
15582 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15584 static int
15585 collectSecLabels(Archive *fout, SecLabelItem **items)
15587 PGresult *res;
15588 PQExpBuffer query;
15589 int i_label;
15590 int i_provider;
15591 int i_classoid;
15592 int i_objoid;
15593 int i_objsubid;
15594 int ntups;
15595 int i;
15596 SecLabelItem *labels;
15598 query = createPQExpBuffer();
15600 appendPQExpBufferStr(query,
15601 "SELECT label, provider, classoid, objoid, objsubid "
15602 "FROM pg_catalog.pg_seclabel "
15603 "ORDER BY classoid, objoid, objsubid");
15605 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15607 /* Construct lookup table containing OIDs in numeric form */
15608 i_label = PQfnumber(res, "label");
15609 i_provider = PQfnumber(res, "provider");
15610 i_classoid = PQfnumber(res, "classoid");
15611 i_objoid = PQfnumber(res, "objoid");
15612 i_objsubid = PQfnumber(res, "objsubid");
15614 ntups = PQntuples(res);
15616 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15618 for (i = 0; i < ntups; i++)
15620 labels[i].label = PQgetvalue(res, i, i_label);
15621 labels[i].provider = PQgetvalue(res, i, i_provider);
15622 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15623 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15624 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15627 /* Do NOT free the PGresult since we are keeping pointers into it */
15628 destroyPQExpBuffer(query);
15630 *items = labels;
15631 return ntups;
15635 * dumpTable
15636 * write out to fout the declarations (not data) of a user-defined table
15638 static void
15639 dumpTable(Archive *fout, TableInfo *tbinfo)
15641 DumpOptions *dopt = fout->dopt;
15642 DumpId tableAclDumpId = InvalidDumpId;
15643 char *namecopy;
15646 * noop if we are not dumping anything about this table, or if we are
15647 * doing a data-only dump
15649 if (!tbinfo->dobj.dump || dopt->dataOnly)
15650 return;
15652 if (tbinfo->relkind == RELKIND_SEQUENCE)
15653 dumpSequence(fout, tbinfo);
15654 else
15655 dumpTableSchema(fout, tbinfo);
15657 /* Handle the ACL here */
15658 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15659 if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15661 const char *objtype =
15662 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15664 tableAclDumpId =
15665 dumpACL(fout, tbinfo->dobj.dumpId, InvalidDumpId,
15666 objtype, namecopy, NULL,
15667 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15668 tbinfo->relacl, tbinfo->rrelacl,
15669 tbinfo->initrelacl, tbinfo->initrrelacl);
15673 * Handle column ACLs, if any. Note: we pull these with a separate query
15674 * rather than trying to fetch them during getTableAttrs, so that we won't
15675 * miss ACLs on system columns.
15677 if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15679 PQExpBuffer query = createPQExpBuffer();
15680 PGresult *res;
15681 int i;
15683 if (fout->remoteVersion >= 90600)
15685 PQExpBuffer acl_subquery = createPQExpBuffer();
15686 PQExpBuffer racl_subquery = createPQExpBuffer();
15687 PQExpBuffer initacl_subquery = createPQExpBuffer();
15688 PQExpBuffer initracl_subquery = createPQExpBuffer();
15690 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15691 initracl_subquery, "at.attacl", "c.relowner", "'c'",
15692 dopt->binary_upgrade);
15694 appendPQExpBuffer(query,
15695 "SELECT at.attname, "
15696 "%s AS attacl, "
15697 "%s AS rattacl, "
15698 "%s AS initattacl, "
15699 "%s AS initrattacl "
15700 "FROM pg_catalog.pg_attribute at "
15701 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15702 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15703 "(at.attrelid = pip.objoid "
15704 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15705 "AND at.attnum = pip.objsubid) "
15706 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15707 "NOT at.attisdropped "
15708 "AND ("
15709 "%s IS NOT NULL OR "
15710 "%s IS NOT NULL OR "
15711 "%s IS NOT NULL OR "
15712 "%s IS NOT NULL)"
15713 "ORDER BY at.attnum",
15714 acl_subquery->data,
15715 racl_subquery->data,
15716 initacl_subquery->data,
15717 initracl_subquery->data,
15718 tbinfo->dobj.catId.oid,
15719 acl_subquery->data,
15720 racl_subquery->data,
15721 initacl_subquery->data,
15722 initracl_subquery->data);
15724 destroyPQExpBuffer(acl_subquery);
15725 destroyPQExpBuffer(racl_subquery);
15726 destroyPQExpBuffer(initacl_subquery);
15727 destroyPQExpBuffer(initracl_subquery);
15729 else
15731 appendPQExpBuffer(query,
15732 "SELECT attname, attacl, NULL as rattacl, "
15733 "NULL AS initattacl, NULL AS initrattacl "
15734 "FROM pg_catalog.pg_attribute "
15735 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15736 "AND attacl IS NOT NULL "
15737 "ORDER BY attnum",
15738 tbinfo->dobj.catId.oid);
15741 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15743 for (i = 0; i < PQntuples(res); i++)
15745 char *attname = PQgetvalue(res, i, 0);
15746 char *attacl = PQgetvalue(res, i, 1);
15747 char *rattacl = PQgetvalue(res, i, 2);
15748 char *initattacl = PQgetvalue(res, i, 3);
15749 char *initrattacl = PQgetvalue(res, i, 4);
15750 char *attnamecopy;
15752 attnamecopy = pg_strdup(fmtId(attname));
15755 * Column's GRANT type is always TABLE. Each column ACL depends
15756 * on the table-level ACL, since we can restore column ACLs in
15757 * parallel but the table-level ACL has to be done first.
15759 dumpACL(fout, tbinfo->dobj.dumpId, tableAclDumpId,
15760 "TABLE", namecopy, attnamecopy,
15761 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15762 attacl, rattacl, initattacl, initrattacl);
15763 free(attnamecopy);
15765 PQclear(res);
15766 destroyPQExpBuffer(query);
15769 free(namecopy);
15771 return;
15775 * Create the AS clause for a view or materialized view. The semicolon is
15776 * stripped because a materialized view must add a WITH NO DATA clause.
15778 * This returns a new buffer which must be freed by the caller.
15780 static PQExpBuffer
15781 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15783 PQExpBuffer query = createPQExpBuffer();
15784 PQExpBuffer result = createPQExpBuffer();
15785 PGresult *res;
15786 int len;
15788 /* Fetch the view definition */
15789 appendPQExpBuffer(query,
15790 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15791 tbinfo->dobj.catId.oid);
15793 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15795 if (PQntuples(res) != 1)
15797 if (PQntuples(res) < 1)
15798 fatal("query to obtain definition of view \"%s\" returned no data",
15799 tbinfo->dobj.name);
15800 else
15801 fatal("query to obtain definition of view \"%s\" returned more than one definition",
15802 tbinfo->dobj.name);
15805 len = PQgetlength(res, 0, 0);
15807 if (len == 0)
15808 fatal("definition of view \"%s\" appears to be empty (length zero)",
15809 tbinfo->dobj.name);
15811 /* Strip off the trailing semicolon so that other things may follow. */
15812 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15813 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15815 PQclear(res);
15816 destroyPQExpBuffer(query);
15818 return result;
15822 * Create a dummy AS clause for a view. This is used when the real view
15823 * definition has to be postponed because of circular dependencies.
15824 * We must duplicate the view's external properties -- column names and types
15825 * (including collation) -- so that it works for subsequent references.
15827 * This returns a new buffer which must be freed by the caller.
15829 static PQExpBuffer
15830 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15832 PQExpBuffer result = createPQExpBuffer();
15833 int j;
15835 appendPQExpBufferStr(result, "SELECT");
15837 for (j = 0; j < tbinfo->numatts; j++)
15839 if (j > 0)
15840 appendPQExpBufferChar(result, ',');
15841 appendPQExpBufferStr(result, "\n ");
15843 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15846 * Must add collation if not default for the type, because CREATE OR
15847 * REPLACE VIEW won't change it
15849 if (OidIsValid(tbinfo->attcollation[j]))
15851 CollInfo *coll;
15853 coll = findCollationByOid(tbinfo->attcollation[j]);
15854 if (coll)
15855 appendPQExpBuffer(result, " COLLATE %s",
15856 fmtQualifiedDumpable(coll));
15859 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15862 return result;
15866 * dumpTableSchema
15867 * write the declaration (not data) of one user-defined table or view
15869 static void
15870 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15872 DumpOptions *dopt = fout->dopt;
15873 PQExpBuffer q = createPQExpBuffer();
15874 PQExpBuffer delq = createPQExpBuffer();
15875 char *qrelname;
15876 char *qualrelname;
15877 int numParents;
15878 TableInfo **parents;
15879 int actual_atts; /* number of attrs in this CREATE statement */
15880 const char *reltypename;
15881 char *storage;
15882 int j,
15885 /* We had better have loaded per-column details about this table */
15886 Assert(tbinfo->interesting);
15888 qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15889 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15891 if (tbinfo->hasoids)
15892 pg_log_warning("WITH OIDS is not supported anymore (table \"%s\")",
15893 qrelname);
15895 if (dopt->binary_upgrade)
15896 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15897 tbinfo->dobj.catId.oid);
15899 /* Is it a table or a view? */
15900 if (tbinfo->relkind == RELKIND_VIEW)
15902 PQExpBuffer result;
15905 * Note: keep this code in sync with the is_view case in dumpRule()
15908 reltypename = "VIEW";
15910 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15912 if (dopt->binary_upgrade)
15913 binary_upgrade_set_pg_class_oids(fout, q,
15914 tbinfo->dobj.catId.oid, false);
15916 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15918 if (tbinfo->dummy_view)
15919 result = createDummyViewAsClause(fout, tbinfo);
15920 else
15922 if (nonemptyReloptions(tbinfo->reloptions))
15924 appendPQExpBufferStr(q, " WITH (");
15925 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15926 appendPQExpBufferChar(q, ')');
15928 result = createViewAsClause(fout, tbinfo);
15930 appendPQExpBuffer(q, " AS\n%s", result->data);
15931 destroyPQExpBuffer(result);
15933 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15934 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15935 appendPQExpBufferStr(q, ";\n");
15937 else
15939 char *partkeydef = NULL;
15940 char *ftoptions = NULL;
15941 char *srvname = NULL;
15944 * Set reltypename, and collect any relkind-specific data that we
15945 * didn't fetch during getTables().
15947 switch (tbinfo->relkind)
15949 case RELKIND_PARTITIONED_TABLE:
15951 PQExpBuffer query = createPQExpBuffer();
15952 PGresult *res;
15954 reltypename = "TABLE";
15956 /* retrieve partition key definition */
15957 appendPQExpBuffer(query,
15958 "SELECT pg_get_partkeydef('%u')",
15959 tbinfo->dobj.catId.oid);
15960 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15961 partkeydef = pg_strdup(PQgetvalue(res, 0, 0));
15962 PQclear(res);
15963 destroyPQExpBuffer(query);
15964 break;
15966 case RELKIND_FOREIGN_TABLE:
15968 PQExpBuffer query = createPQExpBuffer();
15969 PGresult *res;
15970 int i_srvname;
15971 int i_ftoptions;
15973 reltypename = "FOREIGN TABLE";
15975 /* retrieve name of foreign server and generic options */
15976 appendPQExpBuffer(query,
15977 "SELECT fs.srvname, "
15978 "pg_catalog.array_to_string(ARRAY("
15979 "SELECT pg_catalog.quote_ident(option_name) || "
15980 "' ' || pg_catalog.quote_literal(option_value) "
15981 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15982 "ORDER BY option_name"
15983 "), E',\n ') AS ftoptions "
15984 "FROM pg_catalog.pg_foreign_table ft "
15985 "JOIN pg_catalog.pg_foreign_server fs "
15986 "ON (fs.oid = ft.ftserver) "
15987 "WHERE ft.ftrelid = '%u'",
15988 tbinfo->dobj.catId.oid);
15989 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15990 i_srvname = PQfnumber(res, "srvname");
15991 i_ftoptions = PQfnumber(res, "ftoptions");
15992 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15993 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15994 PQclear(res);
15995 destroyPQExpBuffer(query);
15996 break;
15998 case RELKIND_MATVIEW:
15999 reltypename = "MATERIALIZED VIEW";
16000 break;
16001 default:
16002 reltypename = "TABLE";
16003 break;
16006 numParents = tbinfo->numParents;
16007 parents = tbinfo->parents;
16009 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
16011 if (dopt->binary_upgrade)
16012 binary_upgrade_set_pg_class_oids(fout, q,
16013 tbinfo->dobj.catId.oid, false);
16015 appendPQExpBuffer(q, "CREATE %s%s %s",
16016 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
16017 "UNLOGGED " : "",
16018 reltypename,
16019 qualrelname);
16022 * Attach to type, if reloftype; except in case of a binary upgrade,
16023 * we dump the table normally and attach it to the type afterward.
16025 if (OidIsValid(tbinfo->reloftype) && !dopt->binary_upgrade)
16026 appendPQExpBuffer(q, " OF %s",
16027 getFormattedTypeName(fout, tbinfo->reloftype,
16028 zeroAsOpaque));
16030 if (tbinfo->relkind != RELKIND_MATVIEW)
16032 /* Dump the attributes */
16033 actual_atts = 0;
16034 for (j = 0; j < tbinfo->numatts; j++)
16037 * Normally, dump if it's locally defined in this table, and
16038 * not dropped. But for binary upgrade, we'll dump all the
16039 * columns, and then fix up the dropped and nonlocal cases
16040 * below.
16042 if (shouldPrintColumn(dopt, tbinfo, j))
16044 bool print_default;
16045 bool print_notnull;
16048 * Default value --- suppress if to be printed separately.
16050 print_default = (tbinfo->attrdefs[j] != NULL &&
16051 !tbinfo->attrdefs[j]->separate);
16054 * Not Null constraint --- suppress if inherited, except
16055 * if partition, or in binary-upgrade case where that
16056 * won't work.
16058 print_notnull = (tbinfo->notnull[j] &&
16059 (!tbinfo->inhNotNull[j] ||
16060 tbinfo->ispartition || dopt->binary_upgrade));
16063 * Skip column if fully defined by reloftype, except in
16064 * binary upgrade
16066 if (OidIsValid(tbinfo->reloftype) &&
16067 !print_default && !print_notnull &&
16068 !dopt->binary_upgrade)
16069 continue;
16071 /* Format properly if not first attr */
16072 if (actual_atts == 0)
16073 appendPQExpBufferStr(q, " (");
16074 else
16075 appendPQExpBufferChar(q, ',');
16076 appendPQExpBufferStr(q, "\n ");
16077 actual_atts++;
16079 /* Attribute name */
16080 appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
16082 if (tbinfo->attisdropped[j])
16085 * ALTER TABLE DROP COLUMN clears
16086 * pg_attribute.atttypid, so we will not have gotten a
16087 * valid type name; insert INTEGER as a stopgap. We'll
16088 * clean things up later.
16090 appendPQExpBufferStr(q, " INTEGER /* dummy */");
16091 /* and skip to the next column */
16092 continue;
16096 * Attribute type; print it except when creating a typed
16097 * table ('OF type_name'), but in binary-upgrade mode,
16098 * print it in that case too.
16100 if (dopt->binary_upgrade || !OidIsValid(tbinfo->reloftype))
16102 appendPQExpBuffer(q, " %s",
16103 tbinfo->atttypnames[j]);
16106 if (print_default)
16108 if (tbinfo->attgenerated[j] == ATTRIBUTE_GENERATED_STORED)
16109 appendPQExpBuffer(q, " GENERATED ALWAYS AS (%s) STORED",
16110 tbinfo->attrdefs[j]->adef_expr);
16111 else
16112 appendPQExpBuffer(q, " DEFAULT %s",
16113 tbinfo->attrdefs[j]->adef_expr);
16117 if (print_notnull)
16118 appendPQExpBufferStr(q, " NOT NULL");
16120 /* Add collation if not default for the type */
16121 if (OidIsValid(tbinfo->attcollation[j]))
16123 CollInfo *coll;
16125 coll = findCollationByOid(tbinfo->attcollation[j]);
16126 if (coll)
16127 appendPQExpBuffer(q, " COLLATE %s",
16128 fmtQualifiedDumpable(coll));
16134 * Add non-inherited CHECK constraints, if any.
16136 * For partitions, we need to include check constraints even if
16137 * they're not defined locally, because the ALTER TABLE ATTACH
16138 * PARTITION that we'll emit later expects the constraint to be
16139 * there. (No need to fix conislocal: ATTACH PARTITION does that)
16141 for (j = 0; j < tbinfo->ncheck; j++)
16143 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16145 if (constr->separate ||
16146 (!constr->conislocal && !tbinfo->ispartition))
16147 continue;
16149 if (actual_atts == 0)
16150 appendPQExpBufferStr(q, " (\n ");
16151 else
16152 appendPQExpBufferStr(q, ",\n ");
16154 appendPQExpBuffer(q, "CONSTRAINT %s ",
16155 fmtId(constr->dobj.name));
16156 appendPQExpBufferStr(q, constr->condef);
16158 actual_atts++;
16161 if (actual_atts)
16162 appendPQExpBufferStr(q, "\n)");
16163 else if (!(OidIsValid(tbinfo->reloftype) && !dopt->binary_upgrade))
16166 * No attributes? we must have a parenthesized attribute list,
16167 * even though empty, when not using the OF TYPE syntax.
16169 appendPQExpBufferStr(q, " (\n)");
16173 * Emit the INHERITS clause (not for partitions), except in
16174 * binary-upgrade mode.
16176 if (numParents > 0 && !tbinfo->ispartition &&
16177 !dopt->binary_upgrade)
16179 appendPQExpBufferStr(q, "\nINHERITS (");
16180 for (k = 0; k < numParents; k++)
16182 TableInfo *parentRel = parents[k];
16184 if (k > 0)
16185 appendPQExpBufferStr(q, ", ");
16186 appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
16188 appendPQExpBufferChar(q, ')');
16191 if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
16192 appendPQExpBuffer(q, "\nPARTITION BY %s", partkeydef);
16194 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
16195 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
16198 if (nonemptyReloptions(tbinfo->reloptions) ||
16199 nonemptyReloptions(tbinfo->toast_reloptions))
16201 bool addcomma = false;
16203 appendPQExpBufferStr(q, "\nWITH (");
16204 if (nonemptyReloptions(tbinfo->reloptions))
16206 addcomma = true;
16207 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
16209 if (nonemptyReloptions(tbinfo->toast_reloptions))
16211 if (addcomma)
16212 appendPQExpBufferStr(q, ", ");
16213 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
16214 fout);
16216 appendPQExpBufferChar(q, ')');
16219 /* Dump generic options if any */
16220 if (ftoptions && ftoptions[0])
16221 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
16224 * For materialized views, create the AS clause just like a view. At
16225 * this point, we always mark the view as not populated.
16227 if (tbinfo->relkind == RELKIND_MATVIEW)
16229 PQExpBuffer result;
16231 result = createViewAsClause(fout, tbinfo);
16232 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
16233 result->data);
16234 destroyPQExpBuffer(result);
16236 else
16237 appendPQExpBufferStr(q, ";\n");
16239 /* Materialized views can depend on extensions */
16240 if (tbinfo->relkind == RELKIND_MATVIEW)
16241 append_depends_on_extension(fout, q, &tbinfo->dobj,
16242 "pg_catalog.pg_class",
16243 tbinfo->relkind == RELKIND_MATVIEW ?
16244 "MATERIALIZED VIEW" : "INDEX",
16245 qualrelname);
16248 * in binary upgrade mode, update the catalog with any missing values
16249 * that might be present.
16251 if (dopt->binary_upgrade)
16253 for (j = 0; j < tbinfo->numatts; j++)
16255 if (tbinfo->attmissingval[j][0] != '\0')
16257 appendPQExpBufferStr(q, "\n-- set missing value.\n");
16258 appendPQExpBufferStr(q,
16259 "SELECT pg_catalog.binary_upgrade_set_missing_value(");
16260 appendStringLiteralAH(q, qualrelname, fout);
16261 appendPQExpBufferStr(q, "::pg_catalog.regclass,");
16262 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16263 appendPQExpBufferStr(q, ",");
16264 appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
16265 appendPQExpBufferStr(q, ");\n\n");
16271 * To create binary-compatible heap files, we have to ensure the same
16272 * physical column order, including dropped columns, as in the
16273 * original. Therefore, we create dropped columns above and drop them
16274 * here, also updating their attlen/attalign values so that the
16275 * dropped column can be skipped properly. (We do not bother with
16276 * restoring the original attbyval setting.) Also, inheritance
16277 * relationships are set up by doing ALTER TABLE INHERIT rather than
16278 * using an INHERITS clause --- the latter would possibly mess up the
16279 * column order. That also means we have to take care about setting
16280 * attislocal correctly, plus fix up any inherited CHECK constraints.
16281 * Analogously, we set up typed tables using ALTER TABLE / OF here.
16283 * We process foreign and partitioned tables here, even though they
16284 * lack heap storage, because they can participate in inheritance
16285 * relationships and we want this stuff to be consistent across the
16286 * inheritance tree. We can exclude indexes, toast tables, sequences
16287 * and matviews, even though they have storage, because we don't
16288 * support altering or dropping columns in them, nor can they be part
16289 * of inheritance trees.
16291 if (dopt->binary_upgrade &&
16292 (tbinfo->relkind == RELKIND_RELATION ||
16293 tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
16294 tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
16296 for (j = 0; j < tbinfo->numatts; j++)
16298 if (tbinfo->attisdropped[j])
16300 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
16301 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
16302 "SET attlen = %d, "
16303 "attalign = '%c', attbyval = false\n"
16304 "WHERE attname = ",
16305 tbinfo->attlen[j],
16306 tbinfo->attalign[j]);
16307 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16308 appendPQExpBufferStr(q, "\n AND attrelid = ");
16309 appendStringLiteralAH(q, qualrelname, fout);
16310 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16312 if (tbinfo->relkind == RELKIND_RELATION ||
16313 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
16314 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16315 qualrelname);
16316 else
16317 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
16318 qualrelname);
16319 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
16320 fmtId(tbinfo->attnames[j]));
16322 else if (!tbinfo->attislocal[j])
16324 appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
16325 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
16326 "SET attislocal = false\n"
16327 "WHERE attname = ");
16328 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16329 appendPQExpBufferStr(q, "\n AND attrelid = ");
16330 appendStringLiteralAH(q, qualrelname, fout);
16331 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16336 * Add inherited CHECK constraints, if any.
16338 * For partitions, they were already dumped, and conislocal
16339 * doesn't need fixing.
16341 for (k = 0; k < tbinfo->ncheck; k++)
16343 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
16345 if (constr->separate || constr->conislocal || tbinfo->ispartition)
16346 continue;
16348 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
16349 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16350 qualrelname);
16351 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
16352 fmtId(constr->dobj.name));
16353 appendPQExpBuffer(q, "%s;\n", constr->condef);
16354 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
16355 "SET conislocal = false\n"
16356 "WHERE contype = 'c' AND conname = ");
16357 appendStringLiteralAH(q, constr->dobj.name, fout);
16358 appendPQExpBufferStr(q, "\n AND conrelid = ");
16359 appendStringLiteralAH(q, qualrelname, fout);
16360 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16363 if (numParents > 0 && !tbinfo->ispartition)
16365 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance this way.\n");
16366 for (k = 0; k < numParents; k++)
16368 TableInfo *parentRel = parents[k];
16370 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT %s;\n",
16371 qualrelname,
16372 fmtQualifiedDumpable(parentRel));
16376 if (OidIsValid(tbinfo->reloftype))
16378 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
16379 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
16380 qualrelname,
16381 getFormattedTypeName(fout, tbinfo->reloftype,
16382 zeroAsOpaque));
16387 * For partitioned tables, emit the ATTACH PARTITION clause. Note
16388 * that we always want to create partitions this way instead of using
16389 * CREATE TABLE .. PARTITION OF, mainly to preserve a possible column
16390 * layout discrepancy with the parent, but also to ensure it gets the
16391 * correct tablespace setting if it differs from the parent's.
16393 if (tbinfo->ispartition)
16395 PGresult *ares;
16396 char *partbound;
16397 PQExpBuffer q2;
16399 /* With partitions there can only be one parent */
16400 if (tbinfo->numParents != 1)
16401 fatal("invalid number of parents %d for table \"%s\"",
16402 tbinfo->numParents, tbinfo->dobj.name);
16404 q2 = createPQExpBuffer();
16406 /* Fetch the partition's partbound */
16407 appendPQExpBuffer(q2,
16408 "SELECT pg_get_expr(c.relpartbound, c.oid) "
16409 "FROM pg_class c "
16410 "WHERE c.oid = '%u'",
16411 tbinfo->dobj.catId.oid);
16412 ares = ExecuteSqlQueryForSingleRow(fout, q2->data);
16413 partbound = PQgetvalue(ares, 0, 0);
16415 /* Perform ALTER TABLE on the parent */
16416 appendPQExpBuffer(q,
16417 "ALTER TABLE ONLY %s ATTACH PARTITION %s %s;\n",
16418 fmtQualifiedDumpable(parents[0]),
16419 qualrelname, partbound);
16421 PQclear(ares);
16422 destroyPQExpBuffer(q2);
16426 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
16427 * relminmxid of all vacuumable relations. (While vacuum.c processes
16428 * TOAST tables semi-independently, here we see them only as children
16429 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
16430 * child toast table is handled below.)
16432 if (dopt->binary_upgrade &&
16433 (tbinfo->relkind == RELKIND_RELATION ||
16434 tbinfo->relkind == RELKIND_MATVIEW))
16436 appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
16437 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16438 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16439 "WHERE oid = ",
16440 tbinfo->frozenxid, tbinfo->minmxid);
16441 appendStringLiteralAH(q, qualrelname, fout);
16442 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16444 if (tbinfo->toast_oid)
16447 * The toast table will have the same OID at restore, so we
16448 * can safely target it by OID.
16450 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
16451 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16452 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16453 "WHERE oid = '%u';\n",
16454 tbinfo->toast_frozenxid,
16455 tbinfo->toast_minmxid, tbinfo->toast_oid);
16460 * In binary_upgrade mode, restore matviews' populated status by
16461 * poking pg_class directly. This is pretty ugly, but we can't use
16462 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
16463 * matview is not populated even though this matview is; in any case,
16464 * we want to transfer the matview's heap storage, not run REFRESH.
16466 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
16467 tbinfo->relispopulated)
16469 appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
16470 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
16471 "SET relispopulated = 't'\n"
16472 "WHERE oid = ");
16473 appendStringLiteralAH(q, qualrelname, fout);
16474 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16478 * Dump additional per-column properties that we can't handle in the
16479 * main CREATE TABLE command.
16481 for (j = 0; j < tbinfo->numatts; j++)
16483 /* None of this applies to dropped columns */
16484 if (tbinfo->attisdropped[j])
16485 continue;
16488 * If we didn't dump the column definition explicitly above, and
16489 * it is NOT NULL and did not inherit that property from a parent,
16490 * we have to mark it separately.
16492 if (!shouldPrintColumn(dopt, tbinfo, j) &&
16493 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
16495 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16496 qualrelname);
16497 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
16498 fmtId(tbinfo->attnames[j]));
16502 * Dump per-column statistics information. We only issue an ALTER
16503 * TABLE statement if the attstattarget entry for this column is
16504 * non-negative (i.e. it's not the default value)
16506 if (tbinfo->attstattarget[j] >= 0)
16508 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16509 qualrelname);
16510 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16511 fmtId(tbinfo->attnames[j]));
16512 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
16513 tbinfo->attstattarget[j]);
16517 * Dump per-column storage information. The statement is only
16518 * dumped if the storage has been changed from the type's default.
16520 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
16522 switch (tbinfo->attstorage[j])
16524 case 'p':
16525 storage = "PLAIN";
16526 break;
16527 case 'e':
16528 storage = "EXTERNAL";
16529 break;
16530 case 'm':
16531 storage = "MAIN";
16532 break;
16533 case 'x':
16534 storage = "EXTENDED";
16535 break;
16536 default:
16537 storage = NULL;
16541 * Only dump the statement if it's a storage type we recognize
16543 if (storage != NULL)
16545 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16546 qualrelname);
16547 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16548 fmtId(tbinfo->attnames[j]));
16549 appendPQExpBuffer(q, "SET STORAGE %s;\n",
16550 storage);
16555 * Dump per-column attributes.
16557 if (tbinfo->attoptions[j][0] != '\0')
16559 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16560 qualrelname);
16561 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16562 fmtId(tbinfo->attnames[j]));
16563 appendPQExpBuffer(q, "SET (%s);\n",
16564 tbinfo->attoptions[j]);
16568 * Dump per-column fdw options.
16570 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16571 tbinfo->attfdwoptions[j][0] != '\0')
16573 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16574 qualrelname);
16575 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16576 fmtId(tbinfo->attnames[j]));
16577 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
16578 tbinfo->attfdwoptions[j]);
16582 if (partkeydef)
16583 free(partkeydef);
16584 if (ftoptions)
16585 free(ftoptions);
16586 if (srvname)
16587 free(srvname);
16591 * dump properties we only have ALTER TABLE syntax for
16593 if ((tbinfo->relkind == RELKIND_RELATION ||
16594 tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16595 tbinfo->relkind == RELKIND_MATVIEW) &&
16596 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16598 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16600 /* nothing to do, will be set when the index is dumped */
16602 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16604 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16605 qualrelname);
16607 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16609 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16610 qualrelname);
16614 if (tbinfo->forcerowsec)
16615 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16616 qualrelname);
16618 if (dopt->binary_upgrade)
16619 binary_upgrade_extension_member(q, &tbinfo->dobj,
16620 reltypename, qrelname,
16621 tbinfo->dobj.namespace->dobj.name);
16623 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16625 char *tableam = NULL;
16627 if (tbinfo->relkind == RELKIND_RELATION ||
16628 tbinfo->relkind == RELKIND_MATVIEW)
16629 tableam = tbinfo->amname;
16631 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16632 ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
16633 .namespace = tbinfo->dobj.namespace->dobj.name,
16634 .tablespace = (tbinfo->relkind == RELKIND_VIEW) ?
16635 NULL : tbinfo->reltablespace,
16636 .tableam = tableam,
16637 .owner = tbinfo->rolname,
16638 .description = reltypename,
16639 .section = tbinfo->postponed_def ?
16640 SECTION_POST_DATA : SECTION_PRE_DATA,
16641 .createStmt = q->data,
16642 .dropStmt = delq->data));
16645 /* Dump Table Comments */
16646 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16647 dumpTableComment(fout, tbinfo, reltypename);
16649 /* Dump Table Security Labels */
16650 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16651 dumpTableSecLabel(fout, tbinfo, reltypename);
16653 /* Dump comments on inlined table constraints */
16654 for (j = 0; j < tbinfo->ncheck; j++)
16656 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16658 if (constr->separate || !constr->conislocal)
16659 continue;
16661 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16662 dumpTableConstraintComment(fout, constr);
16665 destroyPQExpBuffer(q);
16666 destroyPQExpBuffer(delq);
16667 free(qrelname);
16668 free(qualrelname);
16672 * dumpAttrDef --- dump an attribute's default-value declaration
16674 static void
16675 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16677 DumpOptions *dopt = fout->dopt;
16678 TableInfo *tbinfo = adinfo->adtable;
16679 int adnum = adinfo->adnum;
16680 PQExpBuffer q;
16681 PQExpBuffer delq;
16682 char *qualrelname;
16683 char *tag;
16685 /* Skip if table definition not to be dumped */
16686 if (!tbinfo->dobj.dump || dopt->dataOnly)
16687 return;
16689 /* Skip if not "separate"; it was dumped in the table's definition */
16690 if (!adinfo->separate)
16691 return;
16693 q = createPQExpBuffer();
16694 delq = createPQExpBuffer();
16696 qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16698 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16699 qualrelname);
16700 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16701 fmtId(tbinfo->attnames[adnum - 1]),
16702 adinfo->adef_expr);
16704 appendPQExpBuffer(delq, "ALTER TABLE %s ",
16705 qualrelname);
16706 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16707 fmtId(tbinfo->attnames[adnum - 1]));
16709 tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16711 if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16712 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16713 ARCHIVE_OPTS(.tag = tag,
16714 .namespace = tbinfo->dobj.namespace->dobj.name,
16715 .owner = tbinfo->rolname,
16716 .description = "DEFAULT",
16717 .section = SECTION_PRE_DATA,
16718 .createStmt = q->data,
16719 .dropStmt = delq->data));
16721 free(tag);
16722 destroyPQExpBuffer(q);
16723 destroyPQExpBuffer(delq);
16724 free(qualrelname);
16728 * getAttrName: extract the correct name for an attribute
16730 * The array tblInfo->attnames[] only provides names of user attributes;
16731 * if a system attribute number is supplied, we have to fake it.
16732 * We also do a little bit of bounds checking for safety's sake.
16734 static const char *
16735 getAttrName(int attrnum, TableInfo *tblInfo)
16737 if (attrnum > 0 && attrnum <= tblInfo->numatts)
16738 return tblInfo->attnames[attrnum - 1];
16739 switch (attrnum)
16741 case SelfItemPointerAttributeNumber:
16742 return "ctid";
16743 case MinTransactionIdAttributeNumber:
16744 return "xmin";
16745 case MinCommandIdAttributeNumber:
16746 return "cmin";
16747 case MaxTransactionIdAttributeNumber:
16748 return "xmax";
16749 case MaxCommandIdAttributeNumber:
16750 return "cmax";
16751 case TableOidAttributeNumber:
16752 return "tableoid";
16754 fatal("invalid column number %d for table \"%s\"",
16755 attrnum, tblInfo->dobj.name);
16756 return NULL; /* keep compiler quiet */
16760 * dumpIndex
16761 * write out to fout a user-defined index
16763 static void
16764 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16766 DumpOptions *dopt = fout->dopt;
16767 TableInfo *tbinfo = indxinfo->indextable;
16768 bool is_constraint = (indxinfo->indexconstraint != 0);
16769 PQExpBuffer q;
16770 PQExpBuffer delq;
16771 char *qindxname;
16772 char *qqindxname;
16774 if (dopt->dataOnly)
16775 return;
16777 q = createPQExpBuffer();
16778 delq = createPQExpBuffer();
16780 qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16781 qqindxname = pg_strdup(fmtQualifiedDumpable(indxinfo));
16784 * If there's an associated constraint, don't dump the index per se, but
16785 * do dump any comment for it. (This is safe because dependency ordering
16786 * will have ensured the constraint is emitted first.) Note that the
16787 * emitted comment has to be shown as depending on the constraint, not the
16788 * index, in such cases.
16790 if (!is_constraint)
16792 char *indstatcols = indxinfo->indstatcols;
16793 char *indstatvals = indxinfo->indstatvals;
16794 char **indstatcolsarray = NULL;
16795 char **indstatvalsarray = NULL;
16796 int nstatcols;
16797 int nstatvals;
16799 if (dopt->binary_upgrade)
16800 binary_upgrade_set_pg_class_oids(fout, q,
16801 indxinfo->dobj.catId.oid, true);
16803 /* Plain secondary index */
16804 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16807 * Append ALTER TABLE commands as needed to set properties that we
16808 * only have ALTER TABLE syntax for. Keep this in sync with the
16809 * similar code in dumpConstraint!
16812 /* If the index is clustered, we need to record that. */
16813 if (indxinfo->indisclustered)
16815 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16816 fmtQualifiedDumpable(tbinfo));
16817 /* index name is not qualified in this syntax */
16818 appendPQExpBuffer(q, " ON %s;\n",
16819 qindxname);
16823 * If the index has any statistics on some of its columns, generate
16824 * the associated ALTER INDEX queries.
16826 if (parsePGArray(indstatcols, &indstatcolsarray, &nstatcols) &&
16827 parsePGArray(indstatvals, &indstatvalsarray, &nstatvals) &&
16828 nstatcols == nstatvals)
16830 int j;
16832 for (j = 0; j < nstatcols; j++)
16834 appendPQExpBuffer(q, "ALTER INDEX %s ", qqindxname);
16837 * Note that this is a column number, so no quotes should be
16838 * used.
16840 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16841 indstatcolsarray[j]);
16842 appendPQExpBuffer(q, "SET STATISTICS %s;\n",
16843 indstatvalsarray[j]);
16847 /* Indexes can depend on extensions */
16848 append_depends_on_extension(fout, q, &indxinfo->dobj,
16849 "pg_catalog.pg_class",
16850 "INDEX", qqindxname);
16852 /* If the index defines identity, we need to record that. */
16853 if (indxinfo->indisreplident)
16855 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16856 fmtQualifiedDumpable(tbinfo));
16857 /* index name is not qualified in this syntax */
16858 appendPQExpBuffer(q, " INDEX %s;\n",
16859 qindxname);
16862 appendPQExpBuffer(delq, "DROP INDEX %s;\n", qqindxname);
16864 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16865 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16866 ARCHIVE_OPTS(.tag = indxinfo->dobj.name,
16867 .namespace = tbinfo->dobj.namespace->dobj.name,
16868 .tablespace = indxinfo->tablespace,
16869 .owner = tbinfo->rolname,
16870 .description = "INDEX",
16871 .section = SECTION_POST_DATA,
16872 .createStmt = q->data,
16873 .dropStmt = delq->data));
16875 if (indstatcolsarray)
16876 free(indstatcolsarray);
16877 if (indstatvalsarray)
16878 free(indstatvalsarray);
16881 /* Dump Index Comments */
16882 if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16883 dumpComment(fout, "INDEX", qindxname,
16884 tbinfo->dobj.namespace->dobj.name,
16885 tbinfo->rolname,
16886 indxinfo->dobj.catId, 0,
16887 is_constraint ? indxinfo->indexconstraint :
16888 indxinfo->dobj.dumpId);
16890 destroyPQExpBuffer(q);
16891 destroyPQExpBuffer(delq);
16892 free(qindxname);
16893 free(qqindxname);
16897 * dumpIndexAttach
16898 * write out to fout a partitioned-index attachment clause
16900 static void
16901 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16903 if (fout->dopt->dataOnly)
16904 return;
16906 if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16908 PQExpBuffer q = createPQExpBuffer();
16910 appendPQExpBuffer(q, "ALTER INDEX %s ",
16911 fmtQualifiedDumpable(attachinfo->parentIdx));
16912 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16913 fmtQualifiedDumpable(attachinfo->partitionIdx));
16916 * There is no point in creating a drop query as the drop is done by
16917 * index drop. (If you think to change this, see also
16918 * _printTocEntry().) Although this object doesn't really have
16919 * ownership as such, set the owner field anyway to ensure that the
16920 * command is run by the correct role at restore time.
16922 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16923 ARCHIVE_OPTS(.tag = attachinfo->dobj.name,
16924 .namespace = attachinfo->dobj.namespace->dobj.name,
16925 .owner = attachinfo->parentIdx->indextable->rolname,
16926 .description = "INDEX ATTACH",
16927 .section = SECTION_POST_DATA,
16928 .createStmt = q->data));
16930 destroyPQExpBuffer(q);
16935 * dumpStatisticsExt
16936 * write out to fout an extended statistics object
16938 static void
16939 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16941 DumpOptions *dopt = fout->dopt;
16942 PQExpBuffer q;
16943 PQExpBuffer delq;
16944 PQExpBuffer query;
16945 char *qstatsextname;
16946 PGresult *res;
16947 char *stxdef;
16949 /* Skip if not to be dumped */
16950 if (!statsextinfo->dobj.dump || dopt->dataOnly)
16951 return;
16953 q = createPQExpBuffer();
16954 delq = createPQExpBuffer();
16955 query = createPQExpBuffer();
16957 qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16959 appendPQExpBuffer(query, "SELECT "
16960 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16961 statsextinfo->dobj.catId.oid);
16963 res = ExecuteSqlQueryForSingleRow(fout, query->data);
16965 stxdef = PQgetvalue(res, 0, 0);
16967 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16968 appendPQExpBuffer(q, "%s;\n", stxdef);
16970 appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16971 fmtQualifiedDumpable(statsextinfo));
16973 if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16974 ArchiveEntry(fout, statsextinfo->dobj.catId,
16975 statsextinfo->dobj.dumpId,
16976 ARCHIVE_OPTS(.tag = statsextinfo->dobj.name,
16977 .namespace = statsextinfo->dobj.namespace->dobj.name,
16978 .owner = statsextinfo->rolname,
16979 .description = "STATISTICS",
16980 .section = SECTION_POST_DATA,
16981 .createStmt = q->data,
16982 .dropStmt = delq->data));
16984 /* Dump Statistics Comments */
16985 if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16986 dumpComment(fout, "STATISTICS", qstatsextname,
16987 statsextinfo->dobj.namespace->dobj.name,
16988 statsextinfo->rolname,
16989 statsextinfo->dobj.catId, 0,
16990 statsextinfo->dobj.dumpId);
16992 PQclear(res);
16993 destroyPQExpBuffer(q);
16994 destroyPQExpBuffer(delq);
16995 destroyPQExpBuffer(query);
16996 free(qstatsextname);
17000 * dumpConstraint
17001 * write out to fout a user-defined constraint
17003 static void
17004 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
17006 DumpOptions *dopt = fout->dopt;
17007 TableInfo *tbinfo = coninfo->contable;
17008 PQExpBuffer q;
17009 PQExpBuffer delq;
17010 char *tag = NULL;
17012 /* Skip if not to be dumped */
17013 if (!coninfo->dobj.dump || dopt->dataOnly)
17014 return;
17016 q = createPQExpBuffer();
17017 delq = createPQExpBuffer();
17019 if (coninfo->contype == 'p' ||
17020 coninfo->contype == 'u' ||
17021 coninfo->contype == 'x')
17023 /* Index-related constraint */
17024 IndxInfo *indxinfo;
17025 int k;
17027 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
17029 if (indxinfo == NULL)
17030 fatal("missing index for constraint \"%s\"",
17031 coninfo->dobj.name);
17033 if (dopt->binary_upgrade)
17034 binary_upgrade_set_pg_class_oids(fout, q,
17035 indxinfo->dobj.catId.oid, true);
17037 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
17038 fmtQualifiedDumpable(tbinfo));
17039 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
17040 fmtId(coninfo->dobj.name));
17042 if (coninfo->condef)
17044 /* pg_get_constraintdef should have provided everything */
17045 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
17047 else
17049 appendPQExpBuffer(q, "%s (",
17050 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
17051 for (k = 0; k < indxinfo->indnkeyattrs; k++)
17053 int indkey = (int) indxinfo->indkeys[k];
17054 const char *attname;
17056 if (indkey == InvalidAttrNumber)
17057 break;
17058 attname = getAttrName(indkey, tbinfo);
17060 appendPQExpBuffer(q, "%s%s",
17061 (k == 0) ? "" : ", ",
17062 fmtId(attname));
17065 if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
17066 appendPQExpBuffer(q, ") INCLUDE (");
17068 for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
17070 int indkey = (int) indxinfo->indkeys[k];
17071 const char *attname;
17073 if (indkey == InvalidAttrNumber)
17074 break;
17075 attname = getAttrName(indkey, tbinfo);
17077 appendPQExpBuffer(q, "%s%s",
17078 (k == indxinfo->indnkeyattrs) ? "" : ", ",
17079 fmtId(attname));
17082 appendPQExpBufferChar(q, ')');
17084 if (nonemptyReloptions(indxinfo->indreloptions))
17086 appendPQExpBufferStr(q, " WITH (");
17087 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
17088 appendPQExpBufferChar(q, ')');
17091 if (coninfo->condeferrable)
17093 appendPQExpBufferStr(q, " DEFERRABLE");
17094 if (coninfo->condeferred)
17095 appendPQExpBufferStr(q, " INITIALLY DEFERRED");
17098 appendPQExpBufferStr(q, ";\n");
17102 * Append ALTER TABLE commands as needed to set properties that we
17103 * only have ALTER TABLE syntax for. Keep this in sync with the
17104 * similar code in dumpIndex!
17107 /* If the index is clustered, we need to record that. */
17108 if (indxinfo->indisclustered)
17110 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
17111 fmtQualifiedDumpable(tbinfo));
17112 /* index name is not qualified in this syntax */
17113 appendPQExpBuffer(q, " ON %s;\n",
17114 fmtId(indxinfo->dobj.name));
17117 /* If the index defines identity, we need to record that. */
17118 if (indxinfo->indisreplident)
17120 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
17121 fmtQualifiedDumpable(tbinfo));
17122 /* index name is not qualified in this syntax */
17123 appendPQExpBuffer(q, " INDEX %s;\n",
17124 fmtId(indxinfo->dobj.name));
17127 /* Indexes can depend on extensions */
17128 append_depends_on_extension(fout, q, &indxinfo->dobj,
17129 "pg_catalog.pg_class", "INDEX",
17130 fmtQualifiedDumpable(indxinfo));
17132 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
17133 fmtQualifiedDumpable(tbinfo));
17134 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17135 fmtId(coninfo->dobj.name));
17137 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17139 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17140 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17141 ARCHIVE_OPTS(.tag = tag,
17142 .namespace = tbinfo->dobj.namespace->dobj.name,
17143 .tablespace = indxinfo->tablespace,
17144 .owner = tbinfo->rolname,
17145 .description = "CONSTRAINT",
17146 .section = SECTION_POST_DATA,
17147 .createStmt = q->data,
17148 .dropStmt = delq->data));
17150 else if (coninfo->contype == 'f')
17152 char *only;
17155 * Foreign keys on partitioned tables are always declared as
17156 * inheriting to partitions; for all other cases, emit them as
17157 * applying ONLY directly to the named table, because that's how they
17158 * work for regular inherited tables.
17160 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
17163 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
17164 * current table data is not processed
17166 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
17167 only, fmtQualifiedDumpable(tbinfo));
17168 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17169 fmtId(coninfo->dobj.name),
17170 coninfo->condef);
17172 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
17173 only, fmtQualifiedDumpable(tbinfo));
17174 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17175 fmtId(coninfo->dobj.name));
17177 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17179 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17180 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17181 ARCHIVE_OPTS(.tag = tag,
17182 .namespace = tbinfo->dobj.namespace->dobj.name,
17183 .owner = tbinfo->rolname,
17184 .description = "FK CONSTRAINT",
17185 .section = SECTION_POST_DATA,
17186 .createStmt = q->data,
17187 .dropStmt = delq->data));
17189 else if (coninfo->contype == 'c' && tbinfo)
17191 /* CHECK constraint on a table */
17193 /* Ignore if not to be dumped separately, or if it was inherited */
17194 if (coninfo->separate && coninfo->conislocal)
17196 /* not ONLY since we want it to propagate to children */
17197 appendPQExpBuffer(q, "ALTER TABLE %s\n",
17198 fmtQualifiedDumpable(tbinfo));
17199 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17200 fmtId(coninfo->dobj.name),
17201 coninfo->condef);
17203 appendPQExpBuffer(delq, "ALTER TABLE %s ",
17204 fmtQualifiedDumpable(tbinfo));
17205 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17206 fmtId(coninfo->dobj.name));
17208 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17210 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17211 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17212 ARCHIVE_OPTS(.tag = tag,
17213 .namespace = tbinfo->dobj.namespace->dobj.name,
17214 .owner = tbinfo->rolname,
17215 .description = "CHECK CONSTRAINT",
17216 .section = SECTION_POST_DATA,
17217 .createStmt = q->data,
17218 .dropStmt = delq->data));
17221 else if (coninfo->contype == 'c' && tbinfo == NULL)
17223 /* CHECK constraint on a domain */
17224 TypeInfo *tyinfo = coninfo->condomain;
17226 /* Ignore if not to be dumped separately */
17227 if (coninfo->separate)
17229 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
17230 fmtQualifiedDumpable(tyinfo));
17231 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17232 fmtId(coninfo->dobj.name),
17233 coninfo->condef);
17235 appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
17236 fmtQualifiedDumpable(tyinfo));
17237 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17238 fmtId(coninfo->dobj.name));
17240 tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
17242 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17243 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17244 ARCHIVE_OPTS(.tag = tag,
17245 .namespace = tyinfo->dobj.namespace->dobj.name,
17246 .owner = tyinfo->rolname,
17247 .description = "CHECK CONSTRAINT",
17248 .section = SECTION_POST_DATA,
17249 .createStmt = q->data,
17250 .dropStmt = delq->data));
17253 else
17255 fatal("unrecognized constraint type: %c",
17256 coninfo->contype);
17259 /* Dump Constraint Comments --- only works for table constraints */
17260 if (tbinfo && coninfo->separate &&
17261 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17262 dumpTableConstraintComment(fout, coninfo);
17264 free(tag);
17265 destroyPQExpBuffer(q);
17266 destroyPQExpBuffer(delq);
17270 * dumpTableConstraintComment --- dump a constraint's comment if any
17272 * This is split out because we need the function in two different places
17273 * depending on whether the constraint is dumped as part of CREATE TABLE
17274 * or as a separate ALTER command.
17276 static void
17277 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
17279 TableInfo *tbinfo = coninfo->contable;
17280 PQExpBuffer conprefix = createPQExpBuffer();
17281 char *qtabname;
17283 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17285 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
17286 fmtId(coninfo->dobj.name));
17288 if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17289 dumpComment(fout, conprefix->data, qtabname,
17290 tbinfo->dobj.namespace->dobj.name,
17291 tbinfo->rolname,
17292 coninfo->dobj.catId, 0,
17293 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
17295 destroyPQExpBuffer(conprefix);
17296 free(qtabname);
17300 * findLastBuiltinOid_V71 -
17302 * find the last built in oid
17304 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
17305 * pg_database entry for the current database. (Note: current_database()
17306 * requires 7.3; pg_dump requires 8.0 now.)
17308 static Oid
17309 findLastBuiltinOid_V71(Archive *fout)
17311 PGresult *res;
17312 Oid last_oid;
17314 res = ExecuteSqlQueryForSingleRow(fout,
17315 "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
17316 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
17317 PQclear(res);
17319 return last_oid;
17323 * dumpSequence
17324 * write the declaration (not data) of one user-defined sequence
17326 static void
17327 dumpSequence(Archive *fout, TableInfo *tbinfo)
17329 DumpOptions *dopt = fout->dopt;
17330 PGresult *res;
17331 char *startv,
17332 *incby,
17333 *maxv,
17334 *minv,
17335 *cache,
17336 *seqtype;
17337 bool cycled;
17338 bool is_ascending;
17339 int64 default_minv,
17340 default_maxv;
17341 char bufm[32],
17342 bufx[32];
17343 PQExpBuffer query = createPQExpBuffer();
17344 PQExpBuffer delqry = createPQExpBuffer();
17345 char *qseqname;
17347 qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
17349 if (fout->remoteVersion >= 100000)
17351 appendPQExpBuffer(query,
17352 "SELECT format_type(seqtypid, NULL), "
17353 "seqstart, seqincrement, "
17354 "seqmax, seqmin, "
17355 "seqcache, seqcycle "
17356 "FROM pg_catalog.pg_sequence "
17357 "WHERE seqrelid = '%u'::oid",
17358 tbinfo->dobj.catId.oid);
17360 else if (fout->remoteVersion >= 80400)
17363 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
17365 * Note: it might seem that 'bigint' potentially needs to be
17366 * schema-qualified, but actually that's a keyword.
17368 appendPQExpBuffer(query,
17369 "SELECT 'bigint' AS sequence_type, "
17370 "start_value, increment_by, max_value, min_value, "
17371 "cache_value, is_cycled FROM %s",
17372 fmtQualifiedDumpable(tbinfo));
17374 else
17376 appendPQExpBuffer(query,
17377 "SELECT 'bigint' AS sequence_type, "
17378 "0 AS start_value, increment_by, max_value, min_value, "
17379 "cache_value, is_cycled FROM %s",
17380 fmtQualifiedDumpable(tbinfo));
17383 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17385 if (PQntuples(res) != 1)
17387 pg_log_error(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17388 "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17389 PQntuples(res)),
17390 tbinfo->dobj.name, PQntuples(res));
17391 exit_nicely(1);
17394 seqtype = PQgetvalue(res, 0, 0);
17395 startv = PQgetvalue(res, 0, 1);
17396 incby = PQgetvalue(res, 0, 2);
17397 maxv = PQgetvalue(res, 0, 3);
17398 minv = PQgetvalue(res, 0, 4);
17399 cache = PQgetvalue(res, 0, 5);
17400 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
17402 /* Calculate default limits for a sequence of this type */
17403 is_ascending = (incby[0] != '-');
17404 if (strcmp(seqtype, "smallint") == 0)
17406 default_minv = is_ascending ? 1 : PG_INT16_MIN;
17407 default_maxv = is_ascending ? PG_INT16_MAX : -1;
17409 else if (strcmp(seqtype, "integer") == 0)
17411 default_minv = is_ascending ? 1 : PG_INT32_MIN;
17412 default_maxv = is_ascending ? PG_INT32_MAX : -1;
17414 else if (strcmp(seqtype, "bigint") == 0)
17416 default_minv = is_ascending ? 1 : PG_INT64_MIN;
17417 default_maxv = is_ascending ? PG_INT64_MAX : -1;
17419 else
17421 fatal("unrecognized sequence type: %s", seqtype);
17422 default_minv = default_maxv = 0; /* keep compiler quiet */
17426 * 64-bit strtol() isn't very portable, so convert the limits to strings
17427 * and compare that way.
17429 snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
17430 snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
17432 /* Don't print minv/maxv if they match the respective default limit */
17433 if (strcmp(minv, bufm) == 0)
17434 minv = NULL;
17435 if (strcmp(maxv, bufx) == 0)
17436 maxv = NULL;
17439 * Identity sequences are not to be dropped separately.
17441 if (!tbinfo->is_identity_sequence)
17443 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
17444 fmtQualifiedDumpable(tbinfo));
17447 resetPQExpBuffer(query);
17449 if (dopt->binary_upgrade)
17451 binary_upgrade_set_pg_class_oids(fout, query,
17452 tbinfo->dobj.catId.oid, false);
17453 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
17454 tbinfo->dobj.catId.oid);
17457 if (tbinfo->is_identity_sequence)
17459 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
17461 appendPQExpBuffer(query,
17462 "ALTER TABLE %s ",
17463 fmtQualifiedDumpable(owning_tab));
17464 appendPQExpBuffer(query,
17465 "ALTER COLUMN %s ADD GENERATED ",
17466 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17467 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
17468 appendPQExpBuffer(query, "ALWAYS");
17469 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
17470 appendPQExpBuffer(query, "BY DEFAULT");
17471 appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
17472 fmtQualifiedDumpable(tbinfo));
17474 else
17476 appendPQExpBuffer(query,
17477 "CREATE SEQUENCE %s\n",
17478 fmtQualifiedDumpable(tbinfo));
17480 if (strcmp(seqtype, "bigint") != 0)
17481 appendPQExpBuffer(query, " AS %s\n", seqtype);
17484 if (fout->remoteVersion >= 80400)
17485 appendPQExpBuffer(query, " START WITH %s\n", startv);
17487 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
17489 if (minv)
17490 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
17491 else
17492 appendPQExpBufferStr(query, " NO MINVALUE\n");
17494 if (maxv)
17495 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
17496 else
17497 appendPQExpBufferStr(query, " NO MAXVALUE\n");
17499 appendPQExpBuffer(query,
17500 " CACHE %s%s",
17501 cache, (cycled ? "\n CYCLE" : ""));
17503 if (tbinfo->is_identity_sequence)
17504 appendPQExpBufferStr(query, "\n);\n");
17505 else
17506 appendPQExpBufferStr(query, ";\n");
17508 /* binary_upgrade: no need to clear TOAST table oid */
17510 if (dopt->binary_upgrade)
17511 binary_upgrade_extension_member(query, &tbinfo->dobj,
17512 "SEQUENCE", qseqname,
17513 tbinfo->dobj.namespace->dobj.name);
17515 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17516 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
17517 ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17518 .namespace = tbinfo->dobj.namespace->dobj.name,
17519 .owner = tbinfo->rolname,
17520 .description = "SEQUENCE",
17521 .section = SECTION_PRE_DATA,
17522 .createStmt = query->data,
17523 .dropStmt = delqry->data));
17526 * If the sequence is owned by a table column, emit the ALTER for it as a
17527 * separate TOC entry immediately following the sequence's own entry. It's
17528 * OK to do this rather than using full sorting logic, because the
17529 * dependency that tells us it's owned will have forced the table to be
17530 * created first. We can't just include the ALTER in the TOC entry
17531 * because it will fail if we haven't reassigned the sequence owner to
17532 * match the table's owner.
17534 * We need not schema-qualify the table reference because both sequence
17535 * and table must be in the same schema.
17537 if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
17539 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
17541 if (owning_tab == NULL)
17542 fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
17543 tbinfo->owning_tab, tbinfo->dobj.catId.oid);
17545 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
17547 resetPQExpBuffer(query);
17548 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
17549 fmtQualifiedDumpable(tbinfo));
17550 appendPQExpBuffer(query, " OWNED BY %s",
17551 fmtQualifiedDumpable(owning_tab));
17552 appendPQExpBuffer(query, ".%s;\n",
17553 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17555 if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17556 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17557 ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17558 .namespace = tbinfo->dobj.namespace->dobj.name,
17559 .owner = tbinfo->rolname,
17560 .description = "SEQUENCE OWNED BY",
17561 .section = SECTION_PRE_DATA,
17562 .createStmt = query->data,
17563 .deps = &(tbinfo->dobj.dumpId),
17564 .nDeps = 1));
17568 /* Dump Sequence Comments and Security Labels */
17569 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17570 dumpComment(fout, "SEQUENCE", qseqname,
17571 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17572 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17574 if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
17575 dumpSecLabel(fout, "SEQUENCE", qseqname,
17576 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17577 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17579 PQclear(res);
17581 destroyPQExpBuffer(query);
17582 destroyPQExpBuffer(delqry);
17583 free(qseqname);
17587 * dumpSequenceData
17588 * write the data of one user-defined sequence
17590 static void
17591 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
17593 TableInfo *tbinfo = tdinfo->tdtable;
17594 PGresult *res;
17595 char *last;
17596 bool called;
17597 PQExpBuffer query = createPQExpBuffer();
17599 appendPQExpBuffer(query,
17600 "SELECT last_value, is_called FROM %s",
17601 fmtQualifiedDumpable(tbinfo));
17603 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17605 if (PQntuples(res) != 1)
17607 pg_log_error(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17608 "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17609 PQntuples(res)),
17610 tbinfo->dobj.name, PQntuples(res));
17611 exit_nicely(1);
17614 last = PQgetvalue(res, 0, 0);
17615 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17617 resetPQExpBuffer(query);
17618 appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17619 appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
17620 appendPQExpBuffer(query, ", %s, %s);\n",
17621 last, (called ? "true" : "false"));
17623 if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17624 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17625 ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17626 .namespace = tbinfo->dobj.namespace->dobj.name,
17627 .owner = tbinfo->rolname,
17628 .description = "SEQUENCE SET",
17629 .section = SECTION_DATA,
17630 .createStmt = query->data,
17631 .deps = &(tbinfo->dobj.dumpId),
17632 .nDeps = 1));
17634 PQclear(res);
17636 destroyPQExpBuffer(query);
17640 * dumpTrigger
17641 * write the declaration of one user-defined table trigger
17643 static void
17644 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17646 DumpOptions *dopt = fout->dopt;
17647 TableInfo *tbinfo = tginfo->tgtable;
17648 PQExpBuffer query;
17649 PQExpBuffer delqry;
17650 PQExpBuffer trigprefix;
17651 PQExpBuffer trigidentity;
17652 char *qtabname;
17653 char *tgargs;
17654 size_t lentgargs;
17655 const char *p;
17656 int findx;
17657 char *tag;
17660 * we needn't check dobj.dump because TriggerInfo wouldn't have been
17661 * created in the first place for non-dumpable triggers
17663 if (dopt->dataOnly)
17664 return;
17666 query = createPQExpBuffer();
17667 delqry = createPQExpBuffer();
17668 trigprefix = createPQExpBuffer();
17669 trigidentity = createPQExpBuffer();
17671 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17673 appendPQExpBuffer(trigidentity, "%s ", fmtId(tginfo->dobj.name));
17674 appendPQExpBuffer(trigidentity, "ON %s", fmtQualifiedDumpable(tbinfo));
17676 appendPQExpBuffer(delqry, "DROP TRIGGER %s;\n", trigidentity->data);
17678 if (tginfo->tgdef)
17680 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17682 else
17684 if (tginfo->tgisconstraint)
17686 appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17687 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17689 else
17691 appendPQExpBufferStr(query, "CREATE TRIGGER ");
17692 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17694 appendPQExpBufferStr(query, "\n ");
17696 /* Trigger type */
17697 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17698 appendPQExpBufferStr(query, "BEFORE");
17699 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17700 appendPQExpBufferStr(query, "AFTER");
17701 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17702 appendPQExpBufferStr(query, "INSTEAD OF");
17703 else
17705 pg_log_error("unexpected tgtype value: %d", tginfo->tgtype);
17706 exit_nicely(1);
17709 findx = 0;
17710 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17712 appendPQExpBufferStr(query, " INSERT");
17713 findx++;
17715 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17717 if (findx > 0)
17718 appendPQExpBufferStr(query, " OR DELETE");
17719 else
17720 appendPQExpBufferStr(query, " DELETE");
17721 findx++;
17723 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17725 if (findx > 0)
17726 appendPQExpBufferStr(query, " OR UPDATE");
17727 else
17728 appendPQExpBufferStr(query, " UPDATE");
17729 findx++;
17731 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17733 if (findx > 0)
17734 appendPQExpBufferStr(query, " OR TRUNCATE");
17735 else
17736 appendPQExpBufferStr(query, " TRUNCATE");
17737 findx++;
17739 appendPQExpBuffer(query, " ON %s\n",
17740 fmtQualifiedDumpable(tbinfo));
17742 if (tginfo->tgisconstraint)
17744 if (OidIsValid(tginfo->tgconstrrelid))
17746 /* regclass output is already quoted */
17747 appendPQExpBuffer(query, " FROM %s\n ",
17748 tginfo->tgconstrrelname);
17750 if (!tginfo->tgdeferrable)
17751 appendPQExpBufferStr(query, "NOT ");
17752 appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17753 if (tginfo->tginitdeferred)
17754 appendPQExpBufferStr(query, "DEFERRED\n");
17755 else
17756 appendPQExpBufferStr(query, "IMMEDIATE\n");
17759 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17760 appendPQExpBufferStr(query, " FOR EACH ROW\n ");
17761 else
17762 appendPQExpBufferStr(query, " FOR EACH STATEMENT\n ");
17764 /* regproc output is already sufficiently quoted */
17765 appendPQExpBuffer(query, "EXECUTE FUNCTION %s(",
17766 tginfo->tgfname);
17768 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17769 &lentgargs);
17770 p = tgargs;
17771 for (findx = 0; findx < tginfo->tgnargs; findx++)
17773 /* find the embedded null that terminates this trigger argument */
17774 size_t tlen = strlen(p);
17776 if (p + tlen >= tgargs + lentgargs)
17778 /* hm, not found before end of bytea value... */
17779 pg_log_error("invalid argument string (%s) for trigger \"%s\" on table \"%s\"",
17780 tginfo->tgargs,
17781 tginfo->dobj.name,
17782 tbinfo->dobj.name);
17783 exit_nicely(1);
17786 if (findx > 0)
17787 appendPQExpBufferStr(query, ", ");
17788 appendStringLiteralAH(query, p, fout);
17789 p += tlen + 1;
17791 free(tgargs);
17792 appendPQExpBufferStr(query, ");\n");
17795 /* Triggers can depend on extensions */
17796 append_depends_on_extension(fout, query, &tginfo->dobj,
17797 "pg_catalog.pg_trigger", "TRIGGER",
17798 trigidentity->data);
17800 if (tginfo->tgisinternal)
17803 * Triggers marked internal only appear here because their 'tgenabled'
17804 * flag differs from its parent's. The trigger is created already, so
17805 * remove the CREATE and replace it with an ALTER. (Clear out the
17806 * DROP query too, so that pg_dump --create does not cause errors.)
17808 resetPQExpBuffer(query);
17809 resetPQExpBuffer(delqry);
17810 appendPQExpBuffer(query, "\nALTER %sTABLE %s ",
17811 tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "",
17812 fmtQualifiedDumpable(tbinfo));
17813 switch (tginfo->tgenabled)
17815 case 'f':
17816 case 'D':
17817 appendPQExpBufferStr(query, "DISABLE");
17818 break;
17819 case 't':
17820 case 'O':
17821 appendPQExpBufferStr(query, "ENABLE");
17822 break;
17823 case 'R':
17824 appendPQExpBufferStr(query, "ENABLE REPLICA");
17825 break;
17826 case 'A':
17827 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17828 break;
17830 appendPQExpBuffer(query, " TRIGGER %s;\n",
17831 fmtId(tginfo->dobj.name));
17833 else if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17835 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17836 fmtQualifiedDumpable(tbinfo));
17837 switch (tginfo->tgenabled)
17839 case 'D':
17840 case 'f':
17841 appendPQExpBufferStr(query, "DISABLE");
17842 break;
17843 case 'A':
17844 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17845 break;
17846 case 'R':
17847 appendPQExpBufferStr(query, "ENABLE REPLICA");
17848 break;
17849 default:
17850 appendPQExpBufferStr(query, "ENABLE");
17851 break;
17853 appendPQExpBuffer(query, " TRIGGER %s;\n",
17854 fmtId(tginfo->dobj.name));
17857 appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17858 fmtId(tginfo->dobj.name));
17860 tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17862 if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17863 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17864 ARCHIVE_OPTS(.tag = tag,
17865 .namespace = tbinfo->dobj.namespace->dobj.name,
17866 .owner = tbinfo->rolname,
17867 .description = "TRIGGER",
17868 .section = SECTION_POST_DATA,
17869 .createStmt = query->data,
17870 .dropStmt = delqry->data));
17872 if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17873 dumpComment(fout, trigprefix->data, qtabname,
17874 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17875 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17877 free(tag);
17878 destroyPQExpBuffer(query);
17879 destroyPQExpBuffer(delqry);
17880 destroyPQExpBuffer(trigprefix);
17881 destroyPQExpBuffer(trigidentity);
17882 free(qtabname);
17886 * dumpEventTrigger
17887 * write the declaration of one user-defined event trigger
17889 static void
17890 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17892 DumpOptions *dopt = fout->dopt;
17893 PQExpBuffer query;
17894 PQExpBuffer delqry;
17895 char *qevtname;
17897 /* Skip if not to be dumped */
17898 if (!evtinfo->dobj.dump || dopt->dataOnly)
17899 return;
17901 query = createPQExpBuffer();
17902 delqry = createPQExpBuffer();
17904 qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17906 appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17907 appendPQExpBufferStr(query, qevtname);
17908 appendPQExpBufferStr(query, " ON ");
17909 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17911 if (strcmp("", evtinfo->evttags) != 0)
17913 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17914 appendPQExpBufferStr(query, evtinfo->evttags);
17915 appendPQExpBufferChar(query, ')');
17918 appendPQExpBufferStr(query, "\n EXECUTE FUNCTION ");
17919 appendPQExpBufferStr(query, evtinfo->evtfname);
17920 appendPQExpBufferStr(query, "();\n");
17922 if (evtinfo->evtenabled != 'O')
17924 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17925 qevtname);
17926 switch (evtinfo->evtenabled)
17928 case 'D':
17929 appendPQExpBufferStr(query, "DISABLE");
17930 break;
17931 case 'A':
17932 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17933 break;
17934 case 'R':
17935 appendPQExpBufferStr(query, "ENABLE REPLICA");
17936 break;
17937 default:
17938 appendPQExpBufferStr(query, "ENABLE");
17939 break;
17941 appendPQExpBufferStr(query, ";\n");
17944 appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17945 qevtname);
17947 if (dopt->binary_upgrade)
17948 binary_upgrade_extension_member(query, &evtinfo->dobj,
17949 "EVENT TRIGGER", qevtname, NULL);
17951 if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17952 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17953 ARCHIVE_OPTS(.tag = evtinfo->dobj.name,
17954 .owner = evtinfo->evtowner,
17955 .description = "EVENT TRIGGER",
17956 .section = SECTION_POST_DATA,
17957 .createStmt = query->data,
17958 .dropStmt = delqry->data));
17960 if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17961 dumpComment(fout, "EVENT TRIGGER", qevtname,
17962 NULL, evtinfo->evtowner,
17963 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17965 destroyPQExpBuffer(query);
17966 destroyPQExpBuffer(delqry);
17967 free(qevtname);
17971 * dumpRule
17972 * Dump a rule
17974 static void
17975 dumpRule(Archive *fout, RuleInfo *rinfo)
17977 DumpOptions *dopt = fout->dopt;
17978 TableInfo *tbinfo = rinfo->ruletable;
17979 bool is_view;
17980 PQExpBuffer query;
17981 PQExpBuffer cmd;
17982 PQExpBuffer delcmd;
17983 PQExpBuffer ruleprefix;
17984 char *qtabname;
17985 PGresult *res;
17986 char *tag;
17988 /* Skip if not to be dumped */
17989 if (!rinfo->dobj.dump || dopt->dataOnly)
17990 return;
17993 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17994 * we do not want to dump it as a separate object.
17996 if (!rinfo->separate)
17997 return;
18000 * If it's an ON SELECT rule, we want to print it as a view definition,
18001 * instead of a rule.
18003 is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
18005 query = createPQExpBuffer();
18006 cmd = createPQExpBuffer();
18007 delcmd = createPQExpBuffer();
18008 ruleprefix = createPQExpBuffer();
18010 qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
18012 if (is_view)
18014 PQExpBuffer result;
18017 * We need OR REPLACE here because we'll be replacing a dummy view.
18018 * Otherwise this should look largely like the regular view dump code.
18020 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
18021 fmtQualifiedDumpable(tbinfo));
18022 if (nonemptyReloptions(tbinfo->reloptions))
18024 appendPQExpBufferStr(cmd, " WITH (");
18025 appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
18026 appendPQExpBufferChar(cmd, ')');
18028 result = createViewAsClause(fout, tbinfo);
18029 appendPQExpBuffer(cmd, " AS\n%s", result->data);
18030 destroyPQExpBuffer(result);
18031 if (tbinfo->checkoption != NULL)
18032 appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
18033 tbinfo->checkoption);
18034 appendPQExpBufferStr(cmd, ";\n");
18036 else
18038 /* In the rule case, just print pg_get_ruledef's result verbatim */
18039 appendPQExpBuffer(query,
18040 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
18041 rinfo->dobj.catId.oid);
18043 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18045 if (PQntuples(res) != 1)
18047 pg_log_error("query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
18048 rinfo->dobj.name, tbinfo->dobj.name);
18049 exit_nicely(1);
18052 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
18054 PQclear(res);
18058 * Add the command to alter the rules replication firing semantics if it
18059 * differs from the default.
18061 if (rinfo->ev_enabled != 'O')
18063 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
18064 switch (rinfo->ev_enabled)
18066 case 'A':
18067 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
18068 fmtId(rinfo->dobj.name));
18069 break;
18070 case 'R':
18071 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
18072 fmtId(rinfo->dobj.name));
18073 break;
18074 case 'D':
18075 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
18076 fmtId(rinfo->dobj.name));
18077 break;
18081 if (is_view)
18084 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
18085 * REPLACE VIEW to replace the rule with something with minimal
18086 * dependencies.
18088 PQExpBuffer result;
18090 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
18091 fmtQualifiedDumpable(tbinfo));
18092 result = createDummyViewAsClause(fout, tbinfo);
18093 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
18094 destroyPQExpBuffer(result);
18096 else
18098 appendPQExpBuffer(delcmd, "DROP RULE %s ",
18099 fmtId(rinfo->dobj.name));
18100 appendPQExpBuffer(delcmd, "ON %s;\n",
18101 fmtQualifiedDumpable(tbinfo));
18104 appendPQExpBuffer(ruleprefix, "RULE %s ON",
18105 fmtId(rinfo->dobj.name));
18107 tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
18109 if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
18110 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
18111 ARCHIVE_OPTS(.tag = tag,
18112 .namespace = tbinfo->dobj.namespace->dobj.name,
18113 .owner = tbinfo->rolname,
18114 .description = "RULE",
18115 .section = SECTION_POST_DATA,
18116 .createStmt = cmd->data,
18117 .dropStmt = delcmd->data));
18119 /* Dump rule comments */
18120 if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
18121 dumpComment(fout, ruleprefix->data, qtabname,
18122 tbinfo->dobj.namespace->dobj.name,
18123 tbinfo->rolname,
18124 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
18126 free(tag);
18127 destroyPQExpBuffer(query);
18128 destroyPQExpBuffer(cmd);
18129 destroyPQExpBuffer(delcmd);
18130 destroyPQExpBuffer(ruleprefix);
18131 free(qtabname);
18135 * getExtensionMembership --- obtain extension membership data
18137 * We need to identify objects that are extension members as soon as they're
18138 * loaded, so that we can correctly determine whether they need to be dumped.
18139 * Generally speaking, extension member objects will get marked as *not* to
18140 * be dumped, as they will be recreated by the single CREATE EXTENSION
18141 * command. However, in binary upgrade mode we still need to dump the members
18142 * individually.
18144 void
18145 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
18146 int numExtensions)
18148 PQExpBuffer query;
18149 PGresult *res;
18150 int ntups,
18151 nextmembers,
18153 int i_classid,
18154 i_objid,
18155 i_refobjid;
18156 ExtensionMemberId *extmembers;
18157 ExtensionInfo *ext;
18159 /* Nothing to do if no extensions */
18160 if (numExtensions == 0)
18161 return;
18163 query = createPQExpBuffer();
18165 /* refclassid constraint is redundant but may speed the search */
18166 appendPQExpBufferStr(query, "SELECT "
18167 "classid, objid, refobjid "
18168 "FROM pg_depend "
18169 "WHERE refclassid = 'pg_extension'::regclass "
18170 "AND deptype = 'e' "
18171 "ORDER BY 3");
18173 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18175 ntups = PQntuples(res);
18177 i_classid = PQfnumber(res, "classid");
18178 i_objid = PQfnumber(res, "objid");
18179 i_refobjid = PQfnumber(res, "refobjid");
18181 extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
18182 nextmembers = 0;
18185 * Accumulate data into extmembers[].
18187 * Since we ordered the SELECT by referenced ID, we can expect that
18188 * multiple entries for the same extension will appear together; this
18189 * saves on searches.
18191 ext = NULL;
18193 for (i = 0; i < ntups; i++)
18195 CatalogId objId;
18196 Oid extId;
18198 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
18199 objId.oid = atooid(PQgetvalue(res, i, i_objid));
18200 extId = atooid(PQgetvalue(res, i, i_refobjid));
18202 if (ext == NULL ||
18203 ext->dobj.catId.oid != extId)
18204 ext = findExtensionByOid(extId);
18206 if (ext == NULL)
18208 /* shouldn't happen */
18209 pg_log_warning("could not find referenced extension %u", extId);
18210 continue;
18213 extmembers[nextmembers].catId = objId;
18214 extmembers[nextmembers].ext = ext;
18215 nextmembers++;
18218 PQclear(res);
18220 /* Remember the data for use later */
18221 setExtensionMembership(extmembers, nextmembers);
18223 destroyPQExpBuffer(query);
18227 * processExtensionTables --- deal with extension configuration tables
18229 * There are two parts to this process:
18231 * 1. Identify and create dump records for extension configuration tables.
18233 * Extensions can mark tables as "configuration", which means that the user
18234 * is able and expected to modify those tables after the extension has been
18235 * loaded. For these tables, we dump out only the data- the structure is
18236 * expected to be handled at CREATE EXTENSION time, including any indexes or
18237 * foreign keys, which brings us to-
18239 * 2. Record FK dependencies between configuration tables.
18241 * Due to the FKs being created at CREATE EXTENSION time and therefore before
18242 * the data is loaded, we have to work out what the best order for reloading
18243 * the data is, to avoid FK violations when the tables are restored. This is
18244 * not perfect- we can't handle circular dependencies and if any exist they
18245 * will cause an invalid dump to be produced (though at least all of the data
18246 * is included for a user to manually restore). This is currently documented
18247 * but perhaps we can provide a better solution in the future.
18249 void
18250 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
18251 int numExtensions)
18253 DumpOptions *dopt = fout->dopt;
18254 PQExpBuffer query;
18255 PGresult *res;
18256 int ntups,
18258 int i_conrelid,
18259 i_confrelid;
18261 /* Nothing to do if no extensions */
18262 if (numExtensions == 0)
18263 return;
18266 * Identify extension configuration tables and create TableDataInfo
18267 * objects for them, ensuring their data will be dumped even though the
18268 * tables themselves won't be.
18270 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
18271 * user data in a configuration table is treated like schema data. This
18272 * seems appropriate since system data in a config table would get
18273 * reloaded by CREATE EXTENSION.
18275 for (i = 0; i < numExtensions; i++)
18277 ExtensionInfo *curext = &(extinfo[i]);
18278 char *extconfig = curext->extconfig;
18279 char *extcondition = curext->extcondition;
18280 char **extconfigarray = NULL;
18281 char **extconditionarray = NULL;
18282 int nconfigitems;
18283 int nconditionitems;
18285 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
18286 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
18287 nconfigitems == nconditionitems)
18289 int j;
18291 for (j = 0; j < nconfigitems; j++)
18293 TableInfo *configtbl;
18294 Oid configtbloid = atooid(extconfigarray[j]);
18295 bool dumpobj =
18296 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
18298 configtbl = findTableByOid(configtbloid);
18299 if (configtbl == NULL)
18300 continue;
18303 * Tables of not-to-be-dumped extensions shouldn't be dumped
18304 * unless the table or its schema is explicitly included
18306 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
18308 /* check table explicitly requested */
18309 if (table_include_oids.head != NULL &&
18310 simple_oid_list_member(&table_include_oids,
18311 configtbloid))
18312 dumpobj = true;
18314 /* check table's schema explicitly requested */
18315 if (configtbl->dobj.namespace->dobj.dump &
18316 DUMP_COMPONENT_DATA)
18317 dumpobj = true;
18320 /* check table excluded by an exclusion switch */
18321 if (table_exclude_oids.head != NULL &&
18322 simple_oid_list_member(&table_exclude_oids,
18323 configtbloid))
18324 dumpobj = false;
18326 /* check schema excluded by an exclusion switch */
18327 if (simple_oid_list_member(&schema_exclude_oids,
18328 configtbl->dobj.namespace->dobj.catId.oid))
18329 dumpobj = false;
18331 if (dumpobj)
18333 makeTableDataInfo(dopt, configtbl);
18334 if (configtbl->dataObj != NULL)
18336 if (strlen(extconditionarray[j]) > 0)
18337 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
18342 if (extconfigarray)
18343 free(extconfigarray);
18344 if (extconditionarray)
18345 free(extconditionarray);
18349 * Now that all the TableInfoData objects have been created for all the
18350 * extensions, check their FK dependencies and register them to try and
18351 * dump the data out in an order that they can be restored in.
18353 * Note that this is not a problem for user tables as their FKs are
18354 * recreated after the data has been loaded.
18357 query = createPQExpBuffer();
18359 printfPQExpBuffer(query,
18360 "SELECT conrelid, confrelid "
18361 "FROM pg_constraint "
18362 "JOIN pg_depend ON (objid = confrelid) "
18363 "WHERE contype = 'f' "
18364 "AND refclassid = 'pg_extension'::regclass "
18365 "AND classid = 'pg_class'::regclass;");
18367 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18368 ntups = PQntuples(res);
18370 i_conrelid = PQfnumber(res, "conrelid");
18371 i_confrelid = PQfnumber(res, "confrelid");
18373 /* Now get the dependencies and register them */
18374 for (i = 0; i < ntups; i++)
18376 Oid conrelid,
18377 confrelid;
18378 TableInfo *reftable,
18379 *contable;
18381 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
18382 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
18383 contable = findTableByOid(conrelid);
18384 reftable = findTableByOid(confrelid);
18386 if (reftable == NULL ||
18387 reftable->dataObj == NULL ||
18388 contable == NULL ||
18389 contable->dataObj == NULL)
18390 continue;
18393 * Make referencing TABLE_DATA object depend on the referenced table's
18394 * TABLE_DATA object.
18396 addObjectDependency(&contable->dataObj->dobj,
18397 reftable->dataObj->dobj.dumpId);
18399 PQclear(res);
18400 destroyPQExpBuffer(query);
18404 * getDependencies --- obtain available dependency data
18406 static void
18407 getDependencies(Archive *fout)
18409 PQExpBuffer query;
18410 PGresult *res;
18411 int ntups,
18413 int i_classid,
18414 i_objid,
18415 i_refclassid,
18416 i_refobjid,
18417 i_deptype;
18418 DumpableObject *dobj,
18419 *refdobj;
18421 pg_log_info("reading dependency data");
18423 query = createPQExpBuffer();
18426 * Messy query to collect the dependency data we need. Note that we
18427 * ignore the sub-object column, so that dependencies of or on a column
18428 * look the same as dependencies of or on a whole table.
18430 * PIN dependencies aren't interesting, and EXTENSION dependencies were
18431 * already processed by getExtensionMembership.
18433 appendPQExpBufferStr(query, "SELECT "
18434 "classid, objid, refclassid, refobjid, deptype "
18435 "FROM pg_depend "
18436 "WHERE deptype != 'p' AND deptype != 'e'\n");
18439 * Since we don't treat pg_amop entries as separate DumpableObjects, we
18440 * have to translate their dependencies into dependencies of their parent
18441 * opfamily. Ignore internal dependencies though, as those will point to
18442 * their parent opclass, which we needn't consider here (and if we did,
18443 * it'd just result in circular dependencies). Also, "loose" opfamily
18444 * entries will have dependencies on their parent opfamily, which we
18445 * should drop since they'd likewise become useless self-dependencies.
18446 * (But be sure to keep deps on *other* opfamilies; see amopsortfamily.)
18448 * Skip this for pre-8.3 source servers: pg_opfamily doesn't exist there,
18449 * and the (known) cases where it would matter to have these dependencies
18450 * can't arise anyway.
18452 if (fout->remoteVersion >= 80300)
18454 appendPQExpBufferStr(query, "UNION ALL\n"
18455 "SELECT 'pg_opfamily'::regclass AS classid, amopfamily AS objid, refclassid, refobjid, deptype "
18456 "FROM pg_depend d, pg_amop o "
18457 "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18458 "classid = 'pg_amop'::regclass AND objid = o.oid "
18459 "AND NOT (refclassid = 'pg_opfamily'::regclass AND amopfamily = refobjid)\n");
18461 /* Likewise for pg_amproc entries */
18462 appendPQExpBufferStr(query, "UNION ALL\n"
18463 "SELECT 'pg_opfamily'::regclass AS classid, amprocfamily AS objid, refclassid, refobjid, deptype "
18464 "FROM pg_depend d, pg_amproc p "
18465 "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18466 "classid = 'pg_amproc'::regclass AND objid = p.oid "
18467 "AND NOT (refclassid = 'pg_opfamily'::regclass AND amprocfamily = refobjid)\n");
18470 /* Sort the output for efficiency below */
18471 appendPQExpBufferStr(query, "ORDER BY 1,2");
18473 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18475 ntups = PQntuples(res);
18477 i_classid = PQfnumber(res, "classid");
18478 i_objid = PQfnumber(res, "objid");
18479 i_refclassid = PQfnumber(res, "refclassid");
18480 i_refobjid = PQfnumber(res, "refobjid");
18481 i_deptype = PQfnumber(res, "deptype");
18484 * Since we ordered the SELECT by referencing ID, we can expect that
18485 * multiple entries for the same object will appear together; this saves
18486 * on searches.
18488 dobj = NULL;
18490 for (i = 0; i < ntups; i++)
18492 CatalogId objId;
18493 CatalogId refobjId;
18494 char deptype;
18496 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
18497 objId.oid = atooid(PQgetvalue(res, i, i_objid));
18498 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
18499 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
18500 deptype = *(PQgetvalue(res, i, i_deptype));
18502 if (dobj == NULL ||
18503 dobj->catId.tableoid != objId.tableoid ||
18504 dobj->catId.oid != objId.oid)
18505 dobj = findObjectByCatalogId(objId);
18508 * Failure to find objects mentioned in pg_depend is not unexpected,
18509 * since for example we don't collect info about TOAST tables.
18511 if (dobj == NULL)
18513 #ifdef NOT_USED
18514 pg_log_warning("no referencing object %u %u",
18515 objId.tableoid, objId.oid);
18516 #endif
18517 continue;
18520 refdobj = findObjectByCatalogId(refobjId);
18522 if (refdobj == NULL)
18524 #ifdef NOT_USED
18525 pg_log_warning("no referenced object %u %u",
18526 refobjId.tableoid, refobjId.oid);
18527 #endif
18528 continue;
18532 * For 'x' dependencies, mark the object for later; we still add the
18533 * normal dependency, for possible ordering purposes. Currently
18534 * pg_dump_sort.c knows to put extensions ahead of all object types
18535 * that could possibly depend on them, but this is safer.
18537 if (deptype == 'x')
18538 dobj->depends_on_ext = true;
18541 * Ordinarily, table rowtypes have implicit dependencies on their
18542 * tables. However, for a composite type the implicit dependency goes
18543 * the other way in pg_depend; which is the right thing for DROP but
18544 * it doesn't produce the dependency ordering we need. So in that one
18545 * case, we reverse the direction of the dependency.
18547 if (deptype == 'i' &&
18548 dobj->objType == DO_TABLE &&
18549 refdobj->objType == DO_TYPE)
18550 addObjectDependency(refdobj, dobj->dumpId);
18551 else
18552 /* normal case */
18553 addObjectDependency(dobj, refdobj->dumpId);
18556 PQclear(res);
18558 destroyPQExpBuffer(query);
18563 * createBoundaryObjects - create dummy DumpableObjects to represent
18564 * dump section boundaries.
18566 static DumpableObject *
18567 createBoundaryObjects(void)
18569 DumpableObject *dobjs;
18571 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
18573 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
18574 dobjs[0].catId = nilCatalogId;
18575 AssignDumpId(dobjs + 0);
18576 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
18578 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
18579 dobjs[1].catId = nilCatalogId;
18580 AssignDumpId(dobjs + 1);
18581 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
18583 return dobjs;
18587 * addBoundaryDependencies - add dependencies as needed to enforce the dump
18588 * section boundaries.
18590 static void
18591 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
18592 DumpableObject *boundaryObjs)
18594 DumpableObject *preDataBound = boundaryObjs + 0;
18595 DumpableObject *postDataBound = boundaryObjs + 1;
18596 int i;
18598 for (i = 0; i < numObjs; i++)
18600 DumpableObject *dobj = dobjs[i];
18603 * The classification of object types here must match the SECTION_xxx
18604 * values assigned during subsequent ArchiveEntry calls!
18606 switch (dobj->objType)
18608 case DO_NAMESPACE:
18609 case DO_EXTENSION:
18610 case DO_TYPE:
18611 case DO_SHELL_TYPE:
18612 case DO_FUNC:
18613 case DO_AGG:
18614 case DO_OPERATOR:
18615 case DO_ACCESS_METHOD:
18616 case DO_OPCLASS:
18617 case DO_OPFAMILY:
18618 case DO_COLLATION:
18619 case DO_CONVERSION:
18620 case DO_TABLE:
18621 case DO_ATTRDEF:
18622 case DO_PROCLANG:
18623 case DO_CAST:
18624 case DO_DUMMY_TYPE:
18625 case DO_TSPARSER:
18626 case DO_TSDICT:
18627 case DO_TSTEMPLATE:
18628 case DO_TSCONFIG:
18629 case DO_FDW:
18630 case DO_FOREIGN_SERVER:
18631 case DO_TRANSFORM:
18632 case DO_BLOB:
18633 /* Pre-data objects: must come before the pre-data boundary */
18634 addObjectDependency(preDataBound, dobj->dumpId);
18635 break;
18636 case DO_TABLE_DATA:
18637 case DO_SEQUENCE_SET:
18638 case DO_BLOB_DATA:
18639 /* Data objects: must come between the boundaries */
18640 addObjectDependency(dobj, preDataBound->dumpId);
18641 addObjectDependency(postDataBound, dobj->dumpId);
18642 break;
18643 case DO_INDEX:
18644 case DO_INDEX_ATTACH:
18645 case DO_STATSEXT:
18646 case DO_REFRESH_MATVIEW:
18647 case DO_TRIGGER:
18648 case DO_EVENT_TRIGGER:
18649 case DO_DEFAULT_ACL:
18650 case DO_POLICY:
18651 case DO_PUBLICATION:
18652 case DO_PUBLICATION_REL:
18653 case DO_SUBSCRIPTION:
18654 /* Post-data objects: must come after the post-data boundary */
18655 addObjectDependency(dobj, postDataBound->dumpId);
18656 break;
18657 case DO_RULE:
18658 /* Rules are post-data, but only if dumped separately */
18659 if (((RuleInfo *) dobj)->separate)
18660 addObjectDependency(dobj, postDataBound->dumpId);
18661 break;
18662 case DO_CONSTRAINT:
18663 case DO_FK_CONSTRAINT:
18664 /* Constraints are post-data, but only if dumped separately */
18665 if (((ConstraintInfo *) dobj)->separate)
18666 addObjectDependency(dobj, postDataBound->dumpId);
18667 break;
18668 case DO_PRE_DATA_BOUNDARY:
18669 /* nothing to do */
18670 break;
18671 case DO_POST_DATA_BOUNDARY:
18672 /* must come after the pre-data boundary */
18673 addObjectDependency(dobj, preDataBound->dumpId);
18674 break;
18681 * BuildArchiveDependencies - create dependency data for archive TOC entries
18683 * The raw dependency data obtained by getDependencies() is not terribly
18684 * useful in an archive dump, because in many cases there are dependency
18685 * chains linking through objects that don't appear explicitly in the dump.
18686 * For example, a view will depend on its _RETURN rule while the _RETURN rule
18687 * will depend on other objects --- but the rule will not appear as a separate
18688 * object in the dump. We need to adjust the view's dependencies to include
18689 * whatever the rule depends on that is included in the dump.
18691 * Just to make things more complicated, there are also "special" dependencies
18692 * such as the dependency of a TABLE DATA item on its TABLE, which we must
18693 * not rearrange because pg_restore knows that TABLE DATA only depends on
18694 * its table. In these cases we must leave the dependencies strictly as-is
18695 * even if they refer to not-to-be-dumped objects.
18697 * To handle this, the convention is that "special" dependencies are created
18698 * during ArchiveEntry calls, and an archive TOC item that has any such
18699 * entries will not be touched here. Otherwise, we recursively search the
18700 * DumpableObject data structures to build the correct dependencies for each
18701 * archive TOC item.
18703 static void
18704 BuildArchiveDependencies(Archive *fout)
18706 ArchiveHandle *AH = (ArchiveHandle *) fout;
18707 TocEntry *te;
18709 /* Scan all TOC entries in the archive */
18710 for (te = AH->toc->next; te != AH->toc; te = te->next)
18712 DumpableObject *dobj;
18713 DumpId *dependencies;
18714 int nDeps;
18715 int allocDeps;
18717 /* No need to process entries that will not be dumped */
18718 if (te->reqs == 0)
18719 continue;
18720 /* Ignore entries that already have "special" dependencies */
18721 if (te->nDeps > 0)
18722 continue;
18723 /* Otherwise, look up the item's original DumpableObject, if any */
18724 dobj = findObjectByDumpId(te->dumpId);
18725 if (dobj == NULL)
18726 continue;
18727 /* No work if it has no dependencies */
18728 if (dobj->nDeps <= 0)
18729 continue;
18730 /* Set up work array */
18731 allocDeps = 64;
18732 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18733 nDeps = 0;
18734 /* Recursively find all dumpable dependencies */
18735 findDumpableDependencies(AH, dobj,
18736 &dependencies, &nDeps, &allocDeps);
18737 /* And save 'em ... */
18738 if (nDeps > 0)
18740 dependencies = (DumpId *) pg_realloc(dependencies,
18741 nDeps * sizeof(DumpId));
18742 te->dependencies = dependencies;
18743 te->nDeps = nDeps;
18745 else
18746 free(dependencies);
18750 /* Recursive search subroutine for BuildArchiveDependencies */
18751 static void
18752 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18753 DumpId **dependencies, int *nDeps, int *allocDeps)
18755 int i;
18758 * Ignore section boundary objects: if we search through them, we'll
18759 * report lots of bogus dependencies.
18761 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18762 dobj->objType == DO_POST_DATA_BOUNDARY)
18763 return;
18765 for (i = 0; i < dobj->nDeps; i++)
18767 DumpId depid = dobj->dependencies[i];
18769 if (TocIDRequired(AH, depid) != 0)
18771 /* Object will be dumped, so just reference it as a dependency */
18772 if (*nDeps >= *allocDeps)
18774 *allocDeps *= 2;
18775 *dependencies = (DumpId *) pg_realloc(*dependencies,
18776 *allocDeps * sizeof(DumpId));
18778 (*dependencies)[*nDeps] = depid;
18779 (*nDeps)++;
18781 else
18784 * Object will not be dumped, so recursively consider its deps. We
18785 * rely on the assumption that sortDumpableObjects already broke
18786 * any dependency loops, else we might recurse infinitely.
18788 DumpableObject *otherdobj = findObjectByDumpId(depid);
18790 if (otherdobj)
18791 findDumpableDependencies(AH, otherdobj,
18792 dependencies, nDeps, allocDeps);
18799 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18800 * given type OID.
18802 * This does not guarantee to schema-qualify the output, so it should not
18803 * be used to create the target object name for CREATE or ALTER commands.
18805 * Note that the result is cached and must not be freed by the caller.
18807 static const char *
18808 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18810 TypeInfo *typeInfo;
18811 char *result;
18812 PQExpBuffer query;
18813 PGresult *res;
18815 if (oid == 0)
18817 if ((opts & zeroAsOpaque) != 0)
18818 return g_opaque_type;
18819 else if ((opts & zeroAsAny) != 0)
18820 return "'any'";
18821 else if ((opts & zeroAsStar) != 0)
18822 return "*";
18823 else if ((opts & zeroAsNone) != 0)
18824 return "NONE";
18827 /* see if we have the result cached in the type's TypeInfo record */
18828 typeInfo = findTypeByOid(oid);
18829 if (typeInfo && typeInfo->ftypname)
18830 return typeInfo->ftypname;
18832 query = createPQExpBuffer();
18833 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18834 oid);
18836 res = ExecuteSqlQueryForSingleRow(fout, query->data);
18838 /* result of format_type is already quoted */
18839 result = pg_strdup(PQgetvalue(res, 0, 0));
18841 PQclear(res);
18842 destroyPQExpBuffer(query);
18845 * Cache the result for re-use in later requests, if possible. If we
18846 * don't have a TypeInfo for the type, the string will be leaked once the
18847 * caller is done with it ... but that case really should not happen, so
18848 * leaking if it does seems acceptable.
18850 if (typeInfo)
18851 typeInfo->ftypname = result;
18853 return result;
18857 * Return a column list clause for the given relation.
18859 * Special case: if there are no undropped columns in the relation, return
18860 * "", not an invalid "()" column list.
18862 static const char *
18863 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18865 int numatts = ti->numatts;
18866 char **attnames = ti->attnames;
18867 bool *attisdropped = ti->attisdropped;
18868 char *attgenerated = ti->attgenerated;
18869 bool needComma;
18870 int i;
18872 appendPQExpBufferChar(buffer, '(');
18873 needComma = false;
18874 for (i = 0; i < numatts; i++)
18876 if (attisdropped[i])
18877 continue;
18878 if (attgenerated[i])
18879 continue;
18880 if (needComma)
18881 appendPQExpBufferStr(buffer, ", ");
18882 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18883 needComma = true;
18886 if (!needComma)
18887 return ""; /* no undropped columns */
18889 appendPQExpBufferChar(buffer, ')');
18890 return buffer->data;
18894 * Check if a reloptions array is nonempty.
18896 static bool
18897 nonemptyReloptions(const char *reloptions)
18899 /* Don't want to print it if it's just "{}" */
18900 return (reloptions != NULL && strlen(reloptions) > 2);
18904 * Format a reloptions array and append it to the given buffer.
18906 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18908 static void
18909 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18910 const char *prefix, Archive *fout)
18912 bool res;
18914 res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18915 fout->std_strings);
18916 if (!res)
18917 pg_log_warning("could not parse reloptions array");