PostgreSQL Source Code  git master
pg_dump.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_dump.c
4  * pg_dump is a utility for dumping out a postgres database
5  * into a script file.
6  *
7  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
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
13  *
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.
24  *
25  * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
26  *
27  * IDENTIFICATION
28  * src/bin/pg_dump/pg_dump.c
29  *
30  *-------------------------------------------------------------------------
31  */
32 #include "postgres_fe.h"
33 
34 #include <unistd.h>
35 #include <ctype.h>
36 #include <limits.h>
37 #ifdef HAVE_TERMIOS_H
38 #include <termios.h>
39 #endif
40 
41 #include "access/attnum.h"
42 #include "access/sysattr.h"
43 #include "access/transam.h"
44 #include "catalog/pg_aggregate_d.h"
45 #include "catalog/pg_am_d.h"
46 #include "catalog/pg_attribute_d.h"
47 #include "catalog/pg_authid_d.h"
48 #include "catalog/pg_cast_d.h"
49 #include "catalog/pg_class_d.h"
50 #include "catalog/pg_default_acl_d.h"
51 #include "catalog/pg_largeobject_d.h"
52 #include "catalog/pg_largeobject_metadata_d.h"
53 #include "catalog/pg_proc_d.h"
55 #include "catalog/pg_trigger_d.h"
56 #include "catalog/pg_type_d.h"
57 #include "common/connect.h"
58 #include "common/relpath.h"
59 #include "compress_io.h"
60 #include "dumputils.h"
61 #include "fe_utils/option_utils.h"
62 #include "fe_utils/string_utils.h"
63 #include "filter.h"
64 #include "getopt_long.h"
65 #include "libpq/libpq-fs.h"
66 #include "parallel.h"
67 #include "pg_backup_db.h"
68 #include "pg_backup_utils.h"
69 #include "pg_dump.h"
70 #include "storage/block.h"
71 
72 typedef struct
73 {
74  Oid roleoid; /* role's OID */
75  const char *rolename; /* role's name */
76 } RoleNameItem;
77 
78 typedef struct
79 {
80  const char *descr; /* comment for an object */
81  Oid classoid; /* object class (catalog OID) */
82  Oid objoid; /* object OID */
83  int objsubid; /* subobject (table column #) */
84 } CommentItem;
85 
86 typedef struct
87 {
88  const char *provider; /* label provider of this security label */
89  const char *label; /* security label for an object */
90  Oid classoid; /* object class (catalog OID) */
91  Oid objoid; /* object OID */
92  int objsubid; /* subobject (table column #) */
93 } SecLabelItem;
94 
95 typedef enum OidOptions
96 {
101 
102 /* global decls */
103 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
104 
105 static Oid g_last_builtin_oid; /* value of the last builtin oid */
106 
107 /* The specified names/patterns should to match at least one entity */
108 static int strict_names = 0;
109 
111 
112 /*
113  * Object inclusion/exclusion lists
114  *
115  * The string lists record the patterns given by command-line switches,
116  * which we then convert to lists of OIDs of matching objects.
117  */
119 static SimpleOidList schema_include_oids = {NULL, NULL};
121 static SimpleOidList schema_exclude_oids = {NULL, NULL};
122 
125 static SimpleOidList table_include_oids = {NULL, NULL};
128 static SimpleOidList table_exclude_oids = {NULL, NULL};
131 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
132 
135 
137 static SimpleOidList extension_include_oids = {NULL, NULL};
138 
139 static const CatalogId nilCatalogId = {0, 0};
140 
141 /* override for standard extra_float_digits setting */
142 static bool have_extra_float_digits = false;
144 
145 /* sorted table of role names */
146 static RoleNameItem *rolenames = NULL;
147 static int nrolenames = 0;
148 
149 /* sorted table of comments */
150 static CommentItem *comments = NULL;
151 static int ncomments = 0;
152 
153 /* sorted table of security labels */
154 static SecLabelItem *seclabels = NULL;
155 static int nseclabels = 0;
156 
157 /*
158  * The default number of rows per INSERT when
159  * --inserts is specified without --rows-per-insert
160  */
161 #define DUMP_DEFAULT_ROWS_PER_INSERT 1
162 
163 /*
164  * Macro for producing quoted, schema-qualified name of a dumpable object.
165  */
166 #define fmtQualifiedDumpable(obj) \
167  fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
168  (obj)->dobj.name)
169 
170 static void help(const char *progname);
171 static void setup_connection(Archive *AH,
172  const char *dumpencoding, const char *dumpsnapshot,
173  char *use_role);
175 static void expand_schema_name_patterns(Archive *fout,
176  SimpleStringList *patterns,
177  SimpleOidList *oids,
178  bool strict_names);
179 static void expand_extension_name_patterns(Archive *fout,
180  SimpleStringList *patterns,
181  SimpleOidList *oids,
182  bool strict_names);
184  SimpleStringList *patterns,
185  SimpleOidList *oids);
186 static void expand_table_name_patterns(Archive *fout,
187  SimpleStringList *patterns,
188  SimpleOidList *oids,
189  bool strict_names,
190  bool with_child_tables);
191 static void prohibit_crossdb_refs(PGconn *conn, const char *dbname,
192  const char *pattern);
193 
194 static NamespaceInfo *findNamespace(Oid nsoid);
195 static void dumpTableData(Archive *fout, const TableDataInfo *tdinfo);
196 static void refreshMatViewData(Archive *fout, const TableDataInfo *tdinfo);
197 static const char *getRoleName(const char *roleoid_str);
198 static void collectRoleNames(Archive *fout);
199 static void getAdditionalACLs(Archive *fout);
200 static void dumpCommentExtended(Archive *fout, const char *type,
201  const char *name, const char *namespace,
202  const char *owner, CatalogId catalogId,
203  int subid, DumpId dumpId,
204  const char *initdb_comment);
205 static inline void dumpComment(Archive *fout, const char *type,
206  const char *name, const char *namespace,
207  const char *owner, CatalogId catalogId,
208  int subid, DumpId dumpId);
209 static int findComments(Oid classoid, Oid objoid, CommentItem **items);
210 static void collectComments(Archive *fout);
211 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
212  const char *namespace, const char *owner,
213  CatalogId catalogId, int subid, DumpId dumpId);
214 static int findSecLabels(Oid classoid, Oid objoid, SecLabelItem **items);
215 static void collectSecLabels(Archive *fout);
216 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
217 static void dumpNamespace(Archive *fout, const NamespaceInfo *nspinfo);
218 static void dumpExtension(Archive *fout, const ExtensionInfo *extinfo);
219 static void dumpType(Archive *fout, const TypeInfo *tyinfo);
220 static void dumpBaseType(Archive *fout, const TypeInfo *tyinfo);
221 static void dumpEnumType(Archive *fout, const TypeInfo *tyinfo);
222 static void dumpRangeType(Archive *fout, const TypeInfo *tyinfo);
223 static void dumpUndefinedType(Archive *fout, const TypeInfo *tyinfo);
224 static void dumpDomain(Archive *fout, const TypeInfo *tyinfo);
225 static void dumpCompositeType(Archive *fout, const TypeInfo *tyinfo);
226 static void dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
227  PGresult *res);
228 static void dumpShellType(Archive *fout, const ShellTypeInfo *stinfo);
229 static void dumpProcLang(Archive *fout, const ProcLangInfo *plang);
230 static void dumpFunc(Archive *fout, const FuncInfo *finfo);
231 static void dumpCast(Archive *fout, const CastInfo *cast);
232 static void dumpTransform(Archive *fout, const TransformInfo *transform);
233 static void dumpOpr(Archive *fout, const OprInfo *oprinfo);
234 static void dumpAccessMethod(Archive *fout, const AccessMethodInfo *aminfo);
235 static void dumpOpclass(Archive *fout, const OpclassInfo *opcinfo);
236 static void dumpOpfamily(Archive *fout, const OpfamilyInfo *opfinfo);
237 static void dumpCollation(Archive *fout, const CollInfo *collinfo);
238 static void dumpConversion(Archive *fout, const ConvInfo *convinfo);
239 static void dumpRule(Archive *fout, const RuleInfo *rinfo);
240 static void dumpAgg(Archive *fout, const AggInfo *agginfo);
241 static void dumpTrigger(Archive *fout, const TriggerInfo *tginfo);
242 static void dumpEventTrigger(Archive *fout, const EventTriggerInfo *evtinfo);
243 static void dumpTable(Archive *fout, const TableInfo *tbinfo);
244 static void dumpTableSchema(Archive *fout, const TableInfo *tbinfo);
245 static void dumpTableAttach(Archive *fout, const TableAttachInfo *attachinfo);
246 static void dumpAttrDef(Archive *fout, const AttrDefInfo *adinfo);
247 static void dumpSequence(Archive *fout, const TableInfo *tbinfo);
248 static void dumpSequenceData(Archive *fout, const TableDataInfo *tdinfo);
249 static void dumpIndex(Archive *fout, const IndxInfo *indxinfo);
250 static void dumpIndexAttach(Archive *fout, const IndexAttachInfo *attachinfo);
251 static void dumpStatisticsExt(Archive *fout, const StatsExtInfo *statsextinfo);
252 static void dumpConstraint(Archive *fout, const ConstraintInfo *coninfo);
253 static void dumpTableConstraintComment(Archive *fout, const ConstraintInfo *coninfo);
254 static void dumpTSParser(Archive *fout, const TSParserInfo *prsinfo);
255 static void dumpTSDictionary(Archive *fout, const TSDictInfo *dictinfo);
256 static void dumpTSTemplate(Archive *fout, const TSTemplateInfo *tmplinfo);
257 static void dumpTSConfig(Archive *fout, const TSConfigInfo *cfginfo);
258 static void dumpForeignDataWrapper(Archive *fout, const FdwInfo *fdwinfo);
259 static void dumpForeignServer(Archive *fout, const ForeignServerInfo *srvinfo);
260 static void dumpUserMappings(Archive *fout,
261  const char *servername, const char *namespace,
262  const char *owner, CatalogId catalogId, DumpId dumpId);
263 static void dumpDefaultACL(Archive *fout, const DefaultACLInfo *daclinfo);
264 
265 static DumpId dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId,
266  const char *type, const char *name, const char *subname,
267  const char *nspname, const char *owner,
268  const DumpableAcl *dacl);
269 
270 static void getDependencies(Archive *fout);
271 static void BuildArchiveDependencies(Archive *fout);
272 static void findDumpableDependencies(ArchiveHandle *AH, const DumpableObject *dobj,
273  DumpId **dependencies, int *nDeps, int *allocDeps);
274 
276 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
277  DumpableObject *boundaryObjs);
278 
279 static void addConstrChildIdxDeps(DumpableObject *dobj, const IndxInfo *refidx);
280 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
281 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind);
282 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo);
283 static void buildMatViewRefreshDependencies(Archive *fout);
284 static void getTableDataFKConstraints(void);
285 static char *format_function_arguments(const FuncInfo *finfo, const char *funcargs,
286  bool is_agg);
287 static char *format_function_signature(Archive *fout,
288  const FuncInfo *finfo, bool honor_quotes);
289 static char *convertRegProcReference(const char *proc);
290 static char *getFormattedOperatorName(const char *oproid);
291 static char *convertTSFunction(Archive *fout, Oid funcOid);
292 static const char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
293 static void getLOs(Archive *fout);
294 static void dumpLO(Archive *fout, const LoInfo *loinfo);
295 static int dumpLOs(Archive *fout, const void *arg);
296 static void dumpPolicy(Archive *fout, const PolicyInfo *polinfo);
297 static void dumpPublication(Archive *fout, const PublicationInfo *pubinfo);
298 static void dumpPublicationTable(Archive *fout, const PublicationRelInfo *pubrinfo);
299 static void dumpSubscription(Archive *fout, const SubscriptionInfo *subinfo);
300 static void dumpSubscriptionTable(Archive *fout, const SubRelInfo *subrinfo);
301 static void dumpDatabase(Archive *fout);
302 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
303  const char *dbname, Oid dboid);
304 static void dumpEncoding(Archive *AH);
305 static void dumpStdStrings(Archive *AH);
306 static void dumpSearchPath(Archive *AH);
308  PQExpBuffer upgrade_buffer,
309  Oid pg_type_oid,
310  bool force_array_type,
311  bool include_multirange_type);
313  PQExpBuffer upgrade_buffer,
314  const TableInfo *tbinfo);
315 static void binary_upgrade_set_pg_class_oids(Archive *fout,
316  PQExpBuffer upgrade_buffer,
317  Oid pg_class_oid, bool is_index);
318 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
319  const DumpableObject *dobj,
320  const char *objtype,
321  const char *objname,
322  const char *objnamespace);
323 static const char *getAttrName(int attrnum, const TableInfo *tblInfo);
324 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
325 static bool nonemptyReloptions(const char *reloptions);
326 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
327  const char *prefix, Archive *fout);
328 static char *get_synchronized_snapshot(Archive *fout);
329 static void setupDumpWorker(Archive *AH);
330 static TableInfo *getRootTableInfo(const TableInfo *tbinfo);
331 static bool forcePartitionRootLoad(const TableInfo *tbinfo);
332 static void read_dump_filters(const char *filename, DumpOptions *dopt);
333 
334 
335 int
336 main(int argc, char **argv)
337 {
338  int c;
339  const char *filename = NULL;
340  const char *format = "p";
341  TableInfo *tblinfo;
342  int numTables;
343  DumpableObject **dobjs;
344  int numObjs;
345  DumpableObject *boundaryObjs;
346  int i;
347  int optindex;
348  RestoreOptions *ropt;
349  Archive *fout; /* the script file */
350  bool g_verbose = false;
351  const char *dumpencoding = NULL;
352  const char *dumpsnapshot = NULL;
353  char *use_role = NULL;
354  int numWorkers = 1;
355  int plainText = 0;
356  ArchiveFormat archiveFormat = archUnknown;
357  ArchiveMode archiveMode;
358  pg_compress_specification compression_spec = {0};
359  char *compression_detail = NULL;
360  char *compression_algorithm_str = "none";
361  char *error_detail = NULL;
362  bool user_compression_defined = false;
364 
365  static DumpOptions dopt;
366 
367  static struct option long_options[] = {
368  {"data-only", no_argument, NULL, 'a'},
369  {"blobs", no_argument, NULL, 'b'},
370  {"large-objects", no_argument, NULL, 'b'},
371  {"no-blobs", no_argument, NULL, 'B'},
372  {"no-large-objects", no_argument, NULL, 'B'},
373  {"clean", no_argument, NULL, 'c'},
374  {"create", no_argument, NULL, 'C'},
375  {"dbname", required_argument, NULL, 'd'},
376  {"extension", required_argument, NULL, 'e'},
377  {"file", required_argument, NULL, 'f'},
378  {"format", required_argument, NULL, 'F'},
379  {"host", required_argument, NULL, 'h'},
380  {"jobs", 1, NULL, 'j'},
381  {"no-reconnect", no_argument, NULL, 'R'},
382  {"no-owner", no_argument, NULL, 'O'},
383  {"port", required_argument, NULL, 'p'},
384  {"schema", required_argument, NULL, 'n'},
385  {"exclude-schema", required_argument, NULL, 'N'},
386  {"schema-only", no_argument, NULL, 's'},
387  {"superuser", required_argument, NULL, 'S'},
388  {"table", required_argument, NULL, 't'},
389  {"exclude-table", required_argument, NULL, 'T'},
390  {"no-password", no_argument, NULL, 'w'},
391  {"password", no_argument, NULL, 'W'},
392  {"username", required_argument, NULL, 'U'},
393  {"verbose", no_argument, NULL, 'v'},
394  {"no-privileges", no_argument, NULL, 'x'},
395  {"no-acl", no_argument, NULL, 'x'},
396  {"compress", required_argument, NULL, 'Z'},
397  {"encoding", required_argument, NULL, 'E'},
398  {"help", no_argument, NULL, '?'},
399  {"version", no_argument, NULL, 'V'},
400 
401  /*
402  * the following options don't have an equivalent short option letter
403  */
404  {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
405  {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
406  {"column-inserts", no_argument, &dopt.column_inserts, 1},
407  {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
408  {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
409  {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
410  {"exclude-table-data", required_argument, NULL, 4},
411  {"extra-float-digits", required_argument, NULL, 8},
412  {"if-exists", no_argument, &dopt.if_exists, 1},
413  {"inserts", no_argument, NULL, 9},
414  {"lock-wait-timeout", required_argument, NULL, 2},
415  {"no-table-access-method", no_argument, &dopt.outputNoTableAm, 1},
416  {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
417  {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
418  {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
419  {"role", required_argument, NULL, 3},
420  {"section", required_argument, NULL, 5},
421  {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
422  {"snapshot", required_argument, NULL, 6},
423  {"strict-names", no_argument, &strict_names, 1},
424  {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
425  {"no-comments", no_argument, &dopt.no_comments, 1},
426  {"no-publications", no_argument, &dopt.no_publications, 1},
427  {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
428  {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
429  {"no-toast-compression", no_argument, &dopt.no_toast_compression, 1},
430  {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
431  {"no-sync", no_argument, NULL, 7},
432  {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
433  {"rows-per-insert", required_argument, NULL, 10},
434  {"include-foreign-data", required_argument, NULL, 11},
435  {"table-and-children", required_argument, NULL, 12},
436  {"exclude-table-and-children", required_argument, NULL, 13},
437  {"exclude-table-data-and-children", required_argument, NULL, 14},
438  {"sync-method", required_argument, NULL, 15},
439  {"filter", required_argument, NULL, 16},
440 
441  {NULL, 0, NULL, 0}
442  };
443 
444  pg_logging_init(argv[0]);
446  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
447 
448  /*
449  * Initialize what we need for parallel execution, especially for thread
450  * support on Windows.
451  */
453 
454  progname = get_progname(argv[0]);
455 
456  if (argc > 1)
457  {
458  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
459  {
460  help(progname);
461  exit_nicely(0);
462  }
463  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
464  {
465  puts("pg_dump (PostgreSQL) " PG_VERSION);
466  exit_nicely(0);
467  }
468  }
469 
470  InitDumpOptions(&dopt);
471 
472  while ((c = getopt_long(argc, argv, "abBcCd:e:E:f:F:h:j:n:N:Op:RsS:t:T:U:vwWxZ:",
473  long_options, &optindex)) != -1)
474  {
475  switch (c)
476  {
477  case 'a': /* Dump data only */
478  dopt.dataOnly = true;
479  break;
480 
481  case 'b': /* Dump LOs */
482  dopt.outputLOs = true;
483  break;
484 
485  case 'B': /* Don't dump LOs */
486  dopt.dontOutputLOs = true;
487  break;
488 
489  case 'c': /* clean (i.e., drop) schema prior to create */
490  dopt.outputClean = 1;
491  break;
492 
493  case 'C': /* Create DB */
494  dopt.outputCreateDB = 1;
495  break;
496 
497  case 'd': /* database name */
498  dopt.cparams.dbname = pg_strdup(optarg);
499  break;
500 
501  case 'e': /* include extension(s) */
503  dopt.include_everything = false;
504  break;
505 
506  case 'E': /* Dump encoding */
507  dumpencoding = pg_strdup(optarg);
508  break;
509 
510  case 'f':
512  break;
513 
514  case 'F':
516  break;
517 
518  case 'h': /* server host */
519  dopt.cparams.pghost = pg_strdup(optarg);
520  break;
521 
522  case 'j': /* number of dump jobs */
523  if (!option_parse_int(optarg, "-j/--jobs", 1,
524  PG_MAX_JOBS,
525  &numWorkers))
526  exit_nicely(1);
527  break;
528 
529  case 'n': /* include schema(s) */
531  dopt.include_everything = false;
532  break;
533 
534  case 'N': /* exclude schema(s) */
536  break;
537 
538  case 'O': /* Don't reconnect to match owner */
539  dopt.outputNoOwner = 1;
540  break;
541 
542  case 'p': /* server port */
543  dopt.cparams.pgport = pg_strdup(optarg);
544  break;
545 
546  case 'R':
547  /* no-op, still accepted for backwards compatibility */
548  break;
549 
550  case 's': /* dump schema only */
551  dopt.schemaOnly = true;
552  break;
553 
554  case 'S': /* Username for superuser in plain text output */
556  break;
557 
558  case 't': /* include table(s) */
560  dopt.include_everything = false;
561  break;
562 
563  case 'T': /* exclude table(s) */
565  break;
566 
567  case 'U':
569  break;
570 
571  case 'v': /* verbose */
572  g_verbose = true;
574  break;
575 
576  case 'w':
578  break;
579 
580  case 'W':
582  break;
583 
584  case 'x': /* skip ACL dump */
585  dopt.aclsSkip = true;
586  break;
587 
588  case 'Z': /* Compression */
589  parse_compress_options(optarg, &compression_algorithm_str,
590  &compression_detail);
591  user_compression_defined = true;
592  break;
593 
594  case 0:
595  /* This covers the long options. */
596  break;
597 
598  case 2: /* lock-wait-timeout */
600  break;
601 
602  case 3: /* SET ROLE */
603  use_role = pg_strdup(optarg);
604  break;
605 
606  case 4: /* exclude table(s) data */
608  break;
609 
610  case 5: /* section */
612  break;
613 
614  case 6: /* snapshot */
615  dumpsnapshot = pg_strdup(optarg);
616  break;
617 
618  case 7: /* no-sync */
619  dosync = false;
620  break;
621 
622  case 8:
624  if (!option_parse_int(optarg, "--extra-float-digits", -15, 3,
626  exit_nicely(1);
627  break;
628 
629  case 9: /* inserts */
630 
631  /*
632  * dump_inserts also stores --rows-per-insert, careful not to
633  * overwrite that.
634  */
635  if (dopt.dump_inserts == 0)
637  break;
638 
639  case 10: /* rows per insert */
640  if (!option_parse_int(optarg, "--rows-per-insert", 1, INT_MAX,
641  &dopt.dump_inserts))
642  exit_nicely(1);
643  break;
644 
645  case 11: /* include foreign data */
647  optarg);
648  break;
649 
650  case 12: /* include table(s) and their children */
652  optarg);
653  dopt.include_everything = false;
654  break;
655 
656  case 13: /* exclude table(s) and their children */
658  optarg);
659  break;
660 
661  case 14: /* exclude data of table(s) and children */
663  optarg);
664  break;
665 
666  case 15:
668  exit_nicely(1);
669  break;
670 
671  case 16: /* read object filters from file */
672  read_dump_filters(optarg, &dopt);
673  break;
674 
675  default:
676  /* getopt_long already emitted a complaint */
677  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
678  exit_nicely(1);
679  }
680  }
681 
682  /*
683  * Non-option argument specifies database name as long as it wasn't
684  * already specified with -d / --dbname
685  */
686  if (optind < argc && dopt.cparams.dbname == NULL)
687  dopt.cparams.dbname = argv[optind++];
688 
689  /* Complain if any arguments remain */
690  if (optind < argc)
691  {
692  pg_log_error("too many command-line arguments (first is \"%s\")",
693  argv[optind]);
694  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
695  exit_nicely(1);
696  }
697 
698  /* --column-inserts implies --inserts */
699  if (dopt.column_inserts && dopt.dump_inserts == 0)
701 
702  /*
703  * Binary upgrade mode implies dumping sequence data even in schema-only
704  * mode. This is not exposed as a separate option, but kept separate
705  * internally for clarity.
706  */
707  if (dopt.binary_upgrade)
708  dopt.sequence_data = 1;
709 
710  if (dopt.dataOnly && dopt.schemaOnly)
711  pg_fatal("options -s/--schema-only and -a/--data-only cannot be used together");
712 
714  pg_fatal("options -s/--schema-only and --include-foreign-data cannot be used together");
715 
716  if (numWorkers > 1 && foreign_servers_include_patterns.head != NULL)
717  pg_fatal("option --include-foreign-data is not supported with parallel backup");
718 
719  if (dopt.dataOnly && dopt.outputClean)
720  pg_fatal("options -c/--clean and -a/--data-only cannot be used together");
721 
722  if (dopt.if_exists && !dopt.outputClean)
723  pg_fatal("option --if-exists requires option -c/--clean");
724 
725  /*
726  * --inserts are already implied above if --column-inserts or
727  * --rows-per-insert were specified.
728  */
729  if (dopt.do_nothing && dopt.dump_inserts == 0)
730  pg_fatal("option --on-conflict-do-nothing requires option --inserts, --rows-per-insert, or --column-inserts");
731 
732  /* Identify archive format to emit */
733  archiveFormat = parseArchiveFormat(format, &archiveMode);
734 
735  /* archiveFormat specific setup */
736  if (archiveFormat == archNull)
737  plainText = 1;
738 
739  /*
740  * Custom and directory formats are compressed by default with gzip when
741  * available, not the others. If gzip is not available, no compression is
742  * done by default.
743  */
744  if ((archiveFormat == archCustom || archiveFormat == archDirectory) &&
745  !user_compression_defined)
746  {
747 #ifdef HAVE_LIBZ
748  compression_algorithm_str = "gzip";
749 #else
750  compression_algorithm_str = "none";
751 #endif
752  }
753 
754  /*
755  * Compression options
756  */
757  if (!parse_compress_algorithm(compression_algorithm_str,
759  pg_fatal("unrecognized compression algorithm: \"%s\"",
760  compression_algorithm_str);
761 
763  &compression_spec);
764  error_detail = validate_compress_specification(&compression_spec);
765  if (error_detail != NULL)
766  pg_fatal("invalid compression specification: %s",
767  error_detail);
768 
769  error_detail = supports_compression(compression_spec);
770  if (error_detail != NULL)
771  pg_fatal("%s", error_detail);
772 
773  /*
774  * Disable support for zstd workers for now - these are based on
775  * threading, and it's unclear how it interacts with parallel dumps on
776  * platforms where that relies on threads too (e.g. Windows).
777  */
778  if (compression_spec.options & PG_COMPRESSION_OPTION_WORKERS)
779  pg_log_warning("compression option \"%s\" is not currently supported by pg_dump",
780  "workers");
781 
782  /*
783  * If emitting an archive format, we always want to emit a DATABASE item,
784  * in case --create is specified at pg_restore time.
785  */
786  if (!plainText)
787  dopt.outputCreateDB = 1;
788 
789  /* Parallel backup only in the directory archive format so far */
790  if (archiveFormat != archDirectory && numWorkers > 1)
791  pg_fatal("parallel backup only supported by the directory format");
792 
793  /* Open the output file */
794  fout = CreateArchive(filename, archiveFormat, compression_spec,
795  dosync, archiveMode, setupDumpWorker, sync_method);
796 
797  /* Make dump options accessible right away */
798  SetArchiveOptions(fout, &dopt, NULL);
799 
800  /* Register the cleanup hook */
801  on_exit_close_archive(fout);
802 
803  /* Let the archiver know how noisy to be */
804  fout->verbose = g_verbose;
805 
806 
807  /*
808  * We allow the server to be back to 9.2, and up to any minor release of
809  * our own major version. (See also version check in pg_dumpall.c.)
810  */
811  fout->minRemoteVersion = 90200;
812  fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
813 
814  fout->numWorkers = numWorkers;
815 
816  /*
817  * Open the database using the Archiver, so it knows about it. Errors mean
818  * death.
819  */
820  ConnectDatabase(fout, &dopt.cparams, false);
821  setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
822 
823  /*
824  * On hot standbys, never try to dump unlogged table data, since it will
825  * just throw an error.
826  */
827  if (fout->isStandby)
828  dopt.no_unlogged_table_data = true;
829 
830  /*
831  * Find the last built-in OID, if needed (prior to 8.1)
832  *
833  * With 8.1 and above, we can just use FirstNormalObjectId - 1.
834  */
836 
837  pg_log_info("last built-in OID is %u", g_last_builtin_oid);
838 
839  /* Expand schema selection patterns into OID lists */
840  if (schema_include_patterns.head != NULL)
841  {
844  strict_names);
845  if (schema_include_oids.head == NULL)
846  pg_fatal("no matching schemas were found");
847  }
850  false);
851  /* non-matching exclusion patterns aren't an error */
852 
853  /* Expand table selection patterns into OID lists */
856  strict_names, false);
859  strict_names, true);
860  if ((table_include_patterns.head != NULL ||
862  table_include_oids.head == NULL)
863  pg_fatal("no matching tables were found");
864 
867  false, false);
870  false, true);
871 
874  false, false);
877  false, true);
878 
881 
882  /* non-matching exclusion patterns aren't an error */
883 
884  /* Expand extension selection patterns into OID lists */
885  if (extension_include_patterns.head != NULL)
886  {
889  strict_names);
890  if (extension_include_oids.head == NULL)
891  pg_fatal("no matching extensions were found");
892  }
893 
894  /*
895  * Dumping LOs is the default for dumps where an inclusion switch is not
896  * used (an "include everything" dump). -B can be used to exclude LOs
897  * from those dumps. -b can be used to include LOs even when an inclusion
898  * switch is used.
899  *
900  * -s means "schema only" and LOs are data, not schema, so we never
901  * include LOs when -s is used.
902  */
903  if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputLOs)
904  dopt.outputLOs = true;
905 
906  /*
907  * Collect role names so we can map object owner OIDs to names.
908  */
909  collectRoleNames(fout);
910 
911  /*
912  * Now scan the database and create DumpableObject structs for all the
913  * objects we intend to dump.
914  */
915  tblinfo = getSchemaData(fout, &numTables);
916 
917  if (!dopt.schemaOnly)
918  {
919  getTableData(&dopt, tblinfo, numTables, 0);
921  if (dopt.dataOnly)
923  }
924 
925  if (dopt.schemaOnly && dopt.sequence_data)
926  getTableData(&dopt, tblinfo, numTables, RELKIND_SEQUENCE);
927 
928  /*
929  * In binary-upgrade mode, we do not have to worry about the actual LO
930  * data or the associated metadata that resides in the pg_largeobject and
931  * pg_largeobject_metadata tables, respectively.
932  *
933  * However, we do need to collect LO information as there may be comments
934  * or other information on LOs that we do need to dump out.
935  */
936  if (dopt.outputLOs || dopt.binary_upgrade)
937  getLOs(fout);
938 
939  /*
940  * Collect dependency data to assist in ordering the objects.
941  */
942  getDependencies(fout);
943 
944  /*
945  * Collect ACLs, comments, and security labels, if wanted.
946  */
947  if (!dopt.aclsSkip)
948  getAdditionalACLs(fout);
949  if (!dopt.no_comments)
950  collectComments(fout);
951  if (!dopt.no_security_labels)
952  collectSecLabels(fout);
953 
954  /* Lastly, create dummy objects to represent the section boundaries */
955  boundaryObjs = createBoundaryObjects();
956 
957  /* Get pointers to all the known DumpableObjects */
958  getDumpableObjects(&dobjs, &numObjs);
959 
960  /*
961  * Add dummy dependencies to enforce the dump section ordering.
962  */
963  addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
964 
965  /*
966  * Sort the objects into a safe dump order (no forward references).
967  *
968  * We rely on dependency information to help us determine a safe order, so
969  * the initial sort is mostly for cosmetic purposes: we sort by name to
970  * ensure that logically identical schemas will dump identically.
971  */
972  sortDumpableObjectsByTypeName(dobjs, numObjs);
973 
974  sortDumpableObjects(dobjs, numObjs,
975  boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
976 
977  /*
978  * Create archive TOC entries for all the objects to be dumped, in a safe
979  * order.
980  */
981 
982  /*
983  * First the special entries for ENCODING, STDSTRINGS, and SEARCHPATH.
984  */
985  dumpEncoding(fout);
986  dumpStdStrings(fout);
987  dumpSearchPath(fout);
988 
989  /* The database items are always next, unless we don't want them at all */
990  if (dopt.outputCreateDB)
991  dumpDatabase(fout);
992 
993  /* Now the rearrangeable objects. */
994  for (i = 0; i < numObjs; i++)
995  dumpDumpableObject(fout, dobjs[i]);
996 
997  /*
998  * Set up options info to ensure we dump what we want.
999  */
1000  ropt = NewRestoreOptions();
1001  ropt->filename = filename;
1002 
1003  /* if you change this list, see dumpOptionsFromRestoreOptions */
1004  ropt->cparams.dbname = dopt.cparams.dbname ? pg_strdup(dopt.cparams.dbname) : NULL;
1005  ropt->cparams.pgport = dopt.cparams.pgport ? pg_strdup(dopt.cparams.pgport) : NULL;
1006  ropt->cparams.pghost = dopt.cparams.pghost ? pg_strdup(dopt.cparams.pghost) : NULL;
1007  ropt->cparams.username = dopt.cparams.username ? pg_strdup(dopt.cparams.username) : NULL;
1009  ropt->dropSchema = dopt.outputClean;
1010  ropt->dataOnly = dopt.dataOnly;
1011  ropt->schemaOnly = dopt.schemaOnly;
1012  ropt->if_exists = dopt.if_exists;
1013  ropt->column_inserts = dopt.column_inserts;
1014  ropt->dumpSections = dopt.dumpSections;
1015  ropt->aclsSkip = dopt.aclsSkip;
1016  ropt->superuser = dopt.outputSuperuser;
1017  ropt->createDB = dopt.outputCreateDB;
1018  ropt->noOwner = dopt.outputNoOwner;
1019  ropt->noTableAm = dopt.outputNoTableAm;
1020  ropt->noTablespace = dopt.outputNoTablespaces;
1021  ropt->disable_triggers = dopt.disable_triggers;
1022  ropt->use_setsessauth = dopt.use_setsessauth;
1024  ropt->dump_inserts = dopt.dump_inserts;
1025  ropt->no_comments = dopt.no_comments;
1026  ropt->no_publications = dopt.no_publications;
1028  ropt->no_subscriptions = dopt.no_subscriptions;
1029  ropt->lockWaitTimeout = dopt.lockWaitTimeout;
1032  ropt->sequence_data = dopt.sequence_data;
1033  ropt->binary_upgrade = dopt.binary_upgrade;
1034 
1035  ropt->compression_spec = compression_spec;
1036 
1037  ropt->suppressDumpWarnings = true; /* We've already shown them */
1038 
1039  SetArchiveOptions(fout, &dopt, ropt);
1040 
1041  /* Mark which entries should be output */
1043 
1044  /*
1045  * The archive's TOC entries are now marked as to which ones will actually
1046  * be output, so we can set up their dependency lists properly. This isn't
1047  * necessary for plain-text output, though.
1048  */
1049  if (!plainText)
1051 
1052  /*
1053  * And finally we can do the actual output.
1054  *
1055  * Note: for non-plain-text output formats, the output file is written
1056  * inside CloseArchive(). This is, um, bizarre; but not worth changing
1057  * right now.
1058  */
1059  if (plainText)
1060  RestoreArchive(fout);
1061 
1062  CloseArchive(fout);
1063 
1064  exit_nicely(0);
1065 }
1066 
1067 
1068 static void
1069 help(const char *progname)
1070 {
1071  printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
1072  printf(_("Usage:\n"));
1073  printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
1074 
1075  printf(_("\nGeneral options:\n"));
1076  printf(_(" -f, --file=FILENAME output file or directory name\n"));
1077  printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
1078  " plain text (default))\n"));
1079  printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
1080  printf(_(" -v, --verbose verbose mode\n"));
1081  printf(_(" -V, --version output version information, then exit\n"));
1082  printf(_(" -Z, --compress=METHOD[:DETAIL]\n"
1083  " compress as specified\n"));
1084  printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
1085  printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
1086  printf(_(" --sync-method=METHOD set method for syncing files to disk\n"));
1087  printf(_(" -?, --help show this help, then exit\n"));
1088 
1089  printf(_("\nOptions controlling the output content:\n"));
1090  printf(_(" -a, --data-only dump only the data, not the schema\n"));
1091  printf(_(" -b, --large-objects include large objects in dump\n"));
1092  printf(_(" --blobs (same as --large-objects, deprecated)\n"));
1093  printf(_(" -B, --no-large-objects exclude large objects in dump\n"));
1094  printf(_(" --no-blobs (same as --no-large-objects, deprecated)\n"));
1095  printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
1096  printf(_(" -C, --create include commands to create database in dump\n"));
1097  printf(_(" -e, --extension=PATTERN dump the specified extension(s) only\n"));
1098  printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
1099  printf(_(" -n, --schema=PATTERN dump the specified schema(s) only\n"));
1100  printf(_(" -N, --exclude-schema=PATTERN do NOT dump the specified schema(s)\n"));
1101  printf(_(" -O, --no-owner skip restoration of object ownership in\n"
1102  " plain-text format\n"));
1103  printf(_(" -s, --schema-only dump only the schema, no data\n"));
1104  printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
1105  printf(_(" -t, --table=PATTERN dump only the specified table(s)\n"));
1106  printf(_(" -T, --exclude-table=PATTERN do NOT dump the specified table(s)\n"));
1107  printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
1108  printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
1109  printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
1110  printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
1111  printf(_(" --disable-triggers disable triggers during data-only restore\n"));
1112  printf(_(" --enable-row-security enable row security (dump only content user has\n"
1113  " access to)\n"));
1114  printf(_(" --exclude-table-and-children=PATTERN\n"
1115  " do NOT dump the specified table(s), including\n"
1116  " child and partition tables\n"));
1117  printf(_(" --exclude-table-data=PATTERN do NOT dump data for the specified table(s)\n"));
1118  printf(_(" --exclude-table-data-and-children=PATTERN\n"
1119  " do NOT dump data for the specified table(s),\n"
1120  " including child and partition tables\n"));
1121  printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
1122  printf(_(" --filter=FILENAME include or exclude objects and data from dump\n"
1123  " based on expressions in FILENAME\n"));
1124  printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
1125  printf(_(" --include-foreign-data=PATTERN\n"
1126  " include data of foreign tables on foreign\n"
1127  " servers matching PATTERN\n"));
1128  printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
1129  printf(_(" --load-via-partition-root load partitions via the root table\n"));
1130  printf(_(" --no-comments do not dump comments\n"));
1131  printf(_(" --no-publications do not dump publications\n"));
1132  printf(_(" --no-security-labels do not dump security label assignments\n"));
1133  printf(_(" --no-subscriptions do not dump subscriptions\n"));
1134  printf(_(" --no-table-access-method do not dump table access methods\n"));
1135  printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
1136  printf(_(" --no-toast-compression do not dump TOAST compression methods\n"));
1137  printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
1138  printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
1139  printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
1140  printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
1141  printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
1142  printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
1143  printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
1144  printf(_(" --strict-names require table and/or schema include patterns to\n"
1145  " match at least one entity each\n"));
1146  printf(_(" --table-and-children=PATTERN dump only the specified table(s), including\n"
1147  " child and partition tables\n"));
1148  printf(_(" --use-set-session-authorization\n"
1149  " use SET SESSION AUTHORIZATION commands instead of\n"
1150  " ALTER OWNER commands to set ownership\n"));
1151 
1152  printf(_("\nConnection options:\n"));
1153  printf(_(" -d, --dbname=DBNAME database to dump\n"));
1154  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1155  printf(_(" -p, --port=PORT database server port number\n"));
1156  printf(_(" -U, --username=NAME connect as specified database user\n"));
1157  printf(_(" -w, --no-password never prompt for password\n"));
1158  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1159  printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1160 
1161  printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1162  "variable value is used.\n\n"));
1163  printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1164  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1165 }
1166 
1167 static void
1168 setup_connection(Archive *AH, const char *dumpencoding,
1169  const char *dumpsnapshot, char *use_role)
1170 {
1171  DumpOptions *dopt = AH->dopt;
1172  PGconn *conn = GetConnection(AH);
1173  const char *std_strings;
1174 
1176 
1177  /*
1178  * Set the client encoding if requested.
1179  */
1180  if (dumpencoding)
1181  {
1182  if (PQsetClientEncoding(conn, dumpencoding) < 0)
1183  pg_fatal("invalid client encoding \"%s\" specified",
1184  dumpencoding);
1185  }
1186 
1187  /*
1188  * Get the active encoding and the standard_conforming_strings setting, so
1189  * we know how to escape strings.
1190  */
1192 
1193  std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1194  AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1195 
1196  /*
1197  * Set the role if requested. In a parallel dump worker, we'll be passed
1198  * use_role == NULL, but AH->use_role is already set (if user specified it
1199  * originally) and we should use that.
1200  */
1201  if (!use_role && AH->use_role)
1202  use_role = AH->use_role;
1203 
1204  /* Set the role if requested */
1205  if (use_role)
1206  {
1207  PQExpBuffer query = createPQExpBuffer();
1208 
1209  appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1210  ExecuteSqlStatement(AH, query->data);
1211  destroyPQExpBuffer(query);
1212 
1213  /* save it for possible later use by parallel workers */
1214  if (!AH->use_role)
1215  AH->use_role = pg_strdup(use_role);
1216  }
1217 
1218  /* Set the datestyle to ISO to ensure the dump's portability */
1219  ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1220 
1221  /* Likewise, avoid using sql_standard intervalstyle */
1222  ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1223 
1224  /*
1225  * Use an explicitly specified extra_float_digits if it has been provided.
1226  * Otherwise, set extra_float_digits so that we can dump float data
1227  * exactly (given correctly implemented float I/O code, anyway).
1228  */
1230  {
1232 
1233  appendPQExpBuffer(q, "SET extra_float_digits TO %d",
1235  ExecuteSqlStatement(AH, q->data);
1236  destroyPQExpBuffer(q);
1237  }
1238  else
1239  ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1240 
1241  /*
1242  * Disable synchronized scanning, to prevent unpredictable changes in row
1243  * ordering across a dump and reload.
1244  */
1245  ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1246 
1247  /*
1248  * Disable timeouts if supported.
1249  */
1250  ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1251  if (AH->remoteVersion >= 90300)
1252  ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1253  if (AH->remoteVersion >= 90600)
1254  ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1255  if (AH->remoteVersion >= 170000)
1256  ExecuteSqlStatement(AH, "SET transaction_timeout = 0");
1257 
1258  /*
1259  * Quote all identifiers, if requested.
1260  */
1262  ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1263 
1264  /*
1265  * Adjust row-security mode, if supported.
1266  */
1267  if (AH->remoteVersion >= 90500)
1268  {
1269  if (dopt->enable_row_security)
1270  ExecuteSqlStatement(AH, "SET row_security = on");
1271  else
1272  ExecuteSqlStatement(AH, "SET row_security = off");
1273  }
1274 
1275  /*
1276  * Initialize prepared-query state to "nothing prepared". We do this here
1277  * so that a parallel dump worker will have its own state.
1278  */
1279  AH->is_prepared = (bool *) pg_malloc0(NUM_PREP_QUERIES * sizeof(bool));
1280 
1281  /*
1282  * Start transaction-snapshot mode transaction to dump consistent data.
1283  */
1284  ExecuteSqlStatement(AH, "BEGIN");
1285 
1286  /*
1287  * To support the combination of serializable_deferrable with the jobs
1288  * option we use REPEATABLE READ for the worker connections that are
1289  * passed a snapshot. As long as the snapshot is acquired in a
1290  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1291  * REPEATABLE READ transaction provides the appropriate integrity
1292  * guarantees. This is a kluge, but safe for back-patching.
1293  */
1294  if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1296  "SET TRANSACTION ISOLATION LEVEL "
1297  "SERIALIZABLE, READ ONLY, DEFERRABLE");
1298  else
1300  "SET TRANSACTION ISOLATION LEVEL "
1301  "REPEATABLE READ, READ ONLY");
1302 
1303  /*
1304  * If user specified a snapshot to use, select that. In a parallel dump
1305  * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1306  * is already set (if the server can handle it) and we should use that.
1307  */
1308  if (dumpsnapshot)
1309  AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1310 
1311  if (AH->sync_snapshot_id)
1312  {
1313  PQExpBuffer query = createPQExpBuffer();
1314 
1315  appendPQExpBufferStr(query, "SET TRANSACTION SNAPSHOT ");
1317  ExecuteSqlStatement(AH, query->data);
1318  destroyPQExpBuffer(query);
1319  }
1320  else if (AH->numWorkers > 1)
1321  {
1322  if (AH->isStandby && AH->remoteVersion < 100000)
1323  pg_fatal("parallel dumps from standby servers are not supported by this server version");
1325  }
1326 }
1327 
1328 /* Set up connection for a parallel worker process */
1329 static void
1331 {
1332  /*
1333  * We want to re-select all the same values the leader connection is
1334  * using. We'll have inherited directly-usable values in
1335  * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1336  * inherited encoding value back to a string to pass to setup_connection.
1337  */
1338  setup_connection(AH,
1340  NULL,
1341  NULL);
1342 }
1343 
1344 static char *
1346 {
1347  char *query = "SELECT pg_catalog.pg_export_snapshot()";
1348  char *result;
1349  PGresult *res;
1350 
1351  res = ExecuteSqlQueryForSingleRow(fout, query);
1352  result = pg_strdup(PQgetvalue(res, 0, 0));
1353  PQclear(res);
1354 
1355  return result;
1356 }
1357 
1358 static ArchiveFormat
1360 {
1361  ArchiveFormat archiveFormat;
1362 
1363  *mode = archModeWrite;
1364 
1365  if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1366  {
1367  /* This is used by pg_dumpall, and is not documented */
1368  archiveFormat = archNull;
1369  *mode = archModeAppend;
1370  }
1371  else if (pg_strcasecmp(format, "c") == 0)
1372  archiveFormat = archCustom;
1373  else if (pg_strcasecmp(format, "custom") == 0)
1374  archiveFormat = archCustom;
1375  else if (pg_strcasecmp(format, "d") == 0)
1376  archiveFormat = archDirectory;
1377  else if (pg_strcasecmp(format, "directory") == 0)
1378  archiveFormat = archDirectory;
1379  else if (pg_strcasecmp(format, "p") == 0)
1380  archiveFormat = archNull;
1381  else if (pg_strcasecmp(format, "plain") == 0)
1382  archiveFormat = archNull;
1383  else if (pg_strcasecmp(format, "t") == 0)
1384  archiveFormat = archTar;
1385  else if (pg_strcasecmp(format, "tar") == 0)
1386  archiveFormat = archTar;
1387  else
1388  pg_fatal("invalid output format \"%s\" specified", format);
1389  return archiveFormat;
1390 }
1391 
1392 /*
1393  * Find the OIDs of all schemas matching the given list of patterns,
1394  * and append them to the given OID list.
1395  */
1396 static void
1398  SimpleStringList *patterns,
1399  SimpleOidList *oids,
1400  bool strict_names)
1401 {
1402  PQExpBuffer query;
1403  PGresult *res;
1404  SimpleStringListCell *cell;
1405  int i;
1406 
1407  if (patterns->head == NULL)
1408  return; /* nothing to do */
1409 
1410  query = createPQExpBuffer();
1411 
1412  /*
1413  * The loop below runs multiple SELECTs might sometimes result in
1414  * duplicate entries in the OID list, but we don't care.
1415  */
1416 
1417  for (cell = patterns->head; cell; cell = cell->next)
1418  {
1419  PQExpBufferData dbbuf;
1420  int dotcnt;
1421 
1422  appendPQExpBufferStr(query,
1423  "SELECT oid FROM pg_catalog.pg_namespace n\n");
1424  initPQExpBuffer(&dbbuf);
1425  processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1426  false, NULL, "n.nspname", NULL, NULL, &dbbuf,
1427  &dotcnt);
1428  if (dotcnt > 1)
1429  pg_fatal("improper qualified name (too many dotted names): %s",
1430  cell->val);
1431  else if (dotcnt == 1)
1432  prohibit_crossdb_refs(GetConnection(fout), dbbuf.data, cell->val);
1433  termPQExpBuffer(&dbbuf);
1434 
1435  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1436  if (strict_names && PQntuples(res) == 0)
1437  pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
1438 
1439  for (i = 0; i < PQntuples(res); i++)
1440  {
1442  }
1443 
1444  PQclear(res);
1445  resetPQExpBuffer(query);
1446  }
1447 
1448  destroyPQExpBuffer(query);
1449 }
1450 
1451 /*
1452  * Find the OIDs of all extensions matching the given list of patterns,
1453  * and append them to the given OID list.
1454  */
1455 static void
1457  SimpleStringList *patterns,
1458  SimpleOidList *oids,
1459  bool strict_names)
1460 {
1461  PQExpBuffer query;
1462  PGresult *res;
1463  SimpleStringListCell *cell;
1464  int i;
1465 
1466  if (patterns->head == NULL)
1467  return; /* nothing to do */
1468 
1469  query = createPQExpBuffer();
1470 
1471  /*
1472  * The loop below runs multiple SELECTs might sometimes result in
1473  * duplicate entries in the OID list, but we don't care.
1474  */
1475  for (cell = patterns->head; cell; cell = cell->next)
1476  {
1477  int dotcnt;
1478 
1479  appendPQExpBufferStr(query,
1480  "SELECT oid FROM pg_catalog.pg_extension e\n");
1481  processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1482  false, NULL, "e.extname", NULL, NULL, NULL,
1483  &dotcnt);
1484  if (dotcnt > 0)
1485  pg_fatal("improper qualified name (too many dotted names): %s",
1486  cell->val);
1487 
1488  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1489  if (strict_names && PQntuples(res) == 0)
1490  pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
1491 
1492  for (i = 0; i < PQntuples(res); i++)
1493  {
1495  }
1496 
1497  PQclear(res);
1498  resetPQExpBuffer(query);
1499  }
1500 
1501  destroyPQExpBuffer(query);
1502 }
1503 
1504 /*
1505  * Find the OIDs of all foreign servers matching the given list of patterns,
1506  * and append them to the given OID list.
1507  */
1508 static void
1510  SimpleStringList *patterns,
1511  SimpleOidList *oids)
1512 {
1513  PQExpBuffer query;
1514  PGresult *res;
1515  SimpleStringListCell *cell;
1516  int i;
1517 
1518  if (patterns->head == NULL)
1519  return; /* nothing to do */
1520 
1521  query = createPQExpBuffer();
1522 
1523  /*
1524  * The loop below runs multiple SELECTs might sometimes result in
1525  * duplicate entries in the OID list, but we don't care.
1526  */
1527 
1528  for (cell = patterns->head; cell; cell = cell->next)
1529  {
1530  int dotcnt;
1531 
1532  appendPQExpBufferStr(query,
1533  "SELECT oid FROM pg_catalog.pg_foreign_server s\n");
1534  processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1535  false, NULL, "s.srvname", NULL, NULL, NULL,
1536  &dotcnt);
1537  if (dotcnt > 0)
1538  pg_fatal("improper qualified name (too many dotted names): %s",
1539  cell->val);
1540 
1541  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1542  if (PQntuples(res) == 0)
1543  pg_fatal("no matching foreign servers were found for pattern \"%s\"", cell->val);
1544 
1545  for (i = 0; i < PQntuples(res); i++)
1547 
1548  PQclear(res);
1549  resetPQExpBuffer(query);
1550  }
1551 
1552  destroyPQExpBuffer(query);
1553 }
1554 
1555 /*
1556  * Find the OIDs of all tables matching the given list of patterns,
1557  * and append them to the given OID list. See also expand_dbname_patterns()
1558  * in pg_dumpall.c
1559  */
1560 static void
1562  SimpleStringList *patterns, SimpleOidList *oids,
1563  bool strict_names, bool with_child_tables)
1564 {
1565  PQExpBuffer query;
1566  PGresult *res;
1567  SimpleStringListCell *cell;
1568  int i;
1569 
1570  if (patterns->head == NULL)
1571  return; /* nothing to do */
1572 
1573  query = createPQExpBuffer();
1574 
1575  /*
1576  * this might sometimes result in duplicate entries in the OID list, but
1577  * we don't care.
1578  */
1579 
1580  for (cell = patterns->head; cell; cell = cell->next)
1581  {
1582  PQExpBufferData dbbuf;
1583  int dotcnt;
1584 
1585  /*
1586  * Query must remain ABSOLUTELY devoid of unqualified names. This
1587  * would be unnecessary given a pg_table_is_visible() variant taking a
1588  * search_path argument.
1589  *
1590  * For with_child_tables, we start with the basic query's results and
1591  * recursively search the inheritance tree to add child tables.
1592  */
1593  if (with_child_tables)
1594  {
1595  appendPQExpBuffer(query, "WITH RECURSIVE partition_tree (relid) AS (\n");
1596  }
1597 
1598  appendPQExpBuffer(query,
1599  "SELECT c.oid"
1600  "\nFROM pg_catalog.pg_class c"
1601  "\n LEFT JOIN pg_catalog.pg_namespace n"
1602  "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1603  "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1604  "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1605  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1606  RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1607  RELKIND_PARTITIONED_TABLE);
1608  initPQExpBuffer(&dbbuf);
1609  processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1610  false, "n.nspname", "c.relname", NULL,
1611  "pg_catalog.pg_table_is_visible(c.oid)", &dbbuf,
1612  &dotcnt);
1613  if (dotcnt > 2)
1614  pg_fatal("improper relation name (too many dotted names): %s",
1615  cell->val);
1616  else if (dotcnt == 2)
1617  prohibit_crossdb_refs(GetConnection(fout), dbbuf.data, cell->val);
1618  termPQExpBuffer(&dbbuf);
1619 
1620  if (with_child_tables)
1621  {
1622  appendPQExpBuffer(query, "UNION"
1623  "\nSELECT i.inhrelid"
1624  "\nFROM partition_tree p"
1625  "\n JOIN pg_catalog.pg_inherits i"
1626  "\n ON p.relid OPERATOR(pg_catalog.=) i.inhparent"
1627  "\n)"
1628  "\nSELECT relid FROM partition_tree");
1629  }
1630 
1631  ExecuteSqlStatement(fout, "RESET search_path");
1632  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1635  if (strict_names && PQntuples(res) == 0)
1636  pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
1637 
1638  for (i = 0; i < PQntuples(res); i++)
1639  {
1641  }
1642 
1643  PQclear(res);
1644  resetPQExpBuffer(query);
1645  }
1646 
1647  destroyPQExpBuffer(query);
1648 }
1649 
1650 /*
1651  * Verifies that the connected database name matches the given database name,
1652  * and if not, dies with an error about the given pattern.
1653  *
1654  * The 'dbname' argument should be a literal name parsed from 'pattern'.
1655  */
1656 static void
1657 prohibit_crossdb_refs(PGconn *conn, const char *dbname, const char *pattern)
1658 {
1659  const char *db;
1660 
1661  db = PQdb(conn);
1662  if (db == NULL)
1663  pg_fatal("You are currently not connected to a database.");
1664 
1665  if (strcmp(db, dbname) != 0)
1666  pg_fatal("cross-database references are not implemented: %s",
1667  pattern);
1668 }
1669 
1670 /*
1671  * checkExtensionMembership
1672  * Determine whether object is an extension member, and if so,
1673  * record an appropriate dependency and set the object's dump flag.
1674  *
1675  * It's important to call this for each object that could be an extension
1676  * member. Generally, we integrate this with determining the object's
1677  * to-be-dumped-ness, since extension membership overrides other rules for that.
1678  *
1679  * Returns true if object is an extension member, else false.
1680  */
1681 static bool
1683 {
1684  ExtensionInfo *ext = findOwningExtension(dobj->catId);
1685 
1686  if (ext == NULL)
1687  return false;
1688 
1689  dobj->ext_member = true;
1690 
1691  /* Record dependency so that getDependencies needn't deal with that */
1692  addObjectDependency(dobj, ext->dobj.dumpId);
1693 
1694  /*
1695  * In 9.6 and above, mark the member object to have any non-initial ACLs
1696  * dumped. (Any initial ACLs will be removed later, using data from
1697  * pg_init_privs, so that we'll dump only the delta from the extension's
1698  * initial setup.)
1699  *
1700  * Prior to 9.6, we do not include any extension member components.
1701  *
1702  * In binary upgrades, we still dump all components of the members
1703  * individually, since the idea is to exactly reproduce the database
1704  * contents rather than replace the extension contents with something
1705  * different.
1706  *
1707  * Note: it might be interesting someday to implement storage and delta
1708  * dumping of extension members' RLS policies and/or security labels.
1709  * However there is a pitfall for RLS policies: trying to dump them
1710  * requires getting a lock on their tables, and the calling user might not
1711  * have privileges for that. We need no lock to examine a table's ACLs,
1712  * so the current feature doesn't have a problem of that sort.
1713  */
1714  if (fout->dopt->binary_upgrade)
1715  dobj->dump = ext->dobj.dump;
1716  else
1717  {
1718  if (fout->remoteVersion < 90600)
1719  dobj->dump = DUMP_COMPONENT_NONE;
1720  else
1721  dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL);
1722  }
1723 
1724  return true;
1725 }
1726 
1727 /*
1728  * selectDumpableNamespace: policy-setting subroutine
1729  * Mark a namespace as to be dumped or not
1730  */
1731 static void
1733 {
1734  /*
1735  * DUMP_COMPONENT_DEFINITION typically implies a CREATE SCHEMA statement
1736  * and (for --clean) a DROP SCHEMA statement. (In the absence of
1737  * DUMP_COMPONENT_DEFINITION, this value is irrelevant.)
1738  */
1739  nsinfo->create = true;
1740 
1741  /*
1742  * If specific tables are being dumped, do not dump any complete
1743  * namespaces. If specific namespaces are being dumped, dump just those
1744  * namespaces. Otherwise, dump all non-system namespaces.
1745  */
1746  if (table_include_oids.head != NULL)
1747  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1748  else if (schema_include_oids.head != NULL)
1749  nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1751  nsinfo->dobj.catId.oid) ?
1753  else if (fout->remoteVersion >= 90600 &&
1754  strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1755  {
1756  /*
1757  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1758  * they are interesting (and not the original ACLs which were set at
1759  * initdb time, see pg_init_privs).
1760  */
1761  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1762  }
1763  else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1764  strcmp(nsinfo->dobj.name, "information_schema") == 0)
1765  {
1766  /* Other system schemas don't get dumped */
1767  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1768  }
1769  else if (strcmp(nsinfo->dobj.name, "public") == 0)
1770  {
1771  /*
1772  * The public schema is a strange beast that sits in a sort of
1773  * no-mans-land between being a system object and a user object.
1774  * CREATE SCHEMA would fail, so its DUMP_COMPONENT_DEFINITION is just
1775  * a comment and an indication of ownership. If the owner is the
1776  * default, omit that superfluous DUMP_COMPONENT_DEFINITION. Before
1777  * v15, the default owner was BOOTSTRAP_SUPERUSERID.
1778  */
1779  nsinfo->create = false;
1780  nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1781  if (nsinfo->nspowner == ROLE_PG_DATABASE_OWNER)
1782  nsinfo->dobj.dump &= ~DUMP_COMPONENT_DEFINITION;
1784 
1785  /*
1786  * Also, make like it has a comment even if it doesn't; this is so
1787  * that we'll emit a command to drop the comment, if appropriate.
1788  * (Without this, we'd not call dumpCommentExtended for it.)
1789  */
1791  }
1792  else
1793  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1794 
1795  /*
1796  * In any case, a namespace can be excluded by an exclusion switch
1797  */
1798  if (nsinfo->dobj.dump_contains &&
1800  nsinfo->dobj.catId.oid))
1801  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1802 
1803  /*
1804  * If the schema belongs to an extension, allow extension membership to
1805  * override the dump decision for the schema itself. However, this does
1806  * not change dump_contains, so this won't change what we do with objects
1807  * within the schema. (If they belong to the extension, they'll get
1808  * suppressed by it, otherwise not.)
1809  */
1810  (void) checkExtensionMembership(&nsinfo->dobj, fout);
1811 }
1812 
1813 /*
1814  * selectDumpableTable: policy-setting subroutine
1815  * Mark a table as to be dumped or not
1816  */
1817 static void
1819 {
1820  if (checkExtensionMembership(&tbinfo->dobj, fout))
1821  return; /* extension membership overrides all else */
1822 
1823  /*
1824  * If specific tables are being dumped, dump just those tables; else, dump
1825  * according to the parent namespace's dump flag.
1826  */
1827  if (table_include_oids.head != NULL)
1829  tbinfo->dobj.catId.oid) ?
1831  else
1832  tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1833 
1834  /*
1835  * In any case, a table can be excluded by an exclusion switch
1836  */
1837  if (tbinfo->dobj.dump &&
1839  tbinfo->dobj.catId.oid))
1840  tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1841 }
1842 
1843 /*
1844  * selectDumpableType: policy-setting subroutine
1845  * Mark a type as to be dumped or not
1846  *
1847  * If it's a table's rowtype or an autogenerated array type, we also apply a
1848  * special type code to facilitate sorting into the desired order. (We don't
1849  * want to consider those to be ordinary types because that would bring tables
1850  * up into the datatype part of the dump order.) We still set the object's
1851  * dump flag; that's not going to cause the dummy type to be dumped, but we
1852  * need it so that casts involving such types will be dumped correctly -- see
1853  * dumpCast. This means the flag should be set the same as for the underlying
1854  * object (the table or base type).
1855  */
1856 static void
1858 {
1859  /* skip complex types, except for standalone composite types */
1860  if (OidIsValid(tyinfo->typrelid) &&
1861  tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1862  {
1863  TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1864 
1865  tyinfo->dobj.objType = DO_DUMMY_TYPE;
1866  if (tytable != NULL)
1867  tyinfo->dobj.dump = tytable->dobj.dump;
1868  else
1869  tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1870  return;
1871  }
1872 
1873  /* skip auto-generated array and multirange types */
1874  if (tyinfo->isArray || tyinfo->isMultirange)
1875  {
1876  tyinfo->dobj.objType = DO_DUMMY_TYPE;
1877 
1878  /*
1879  * Fall through to set the dump flag; we assume that the subsequent
1880  * rules will do the same thing as they would for the array's base
1881  * type or multirange's range type. (We cannot reliably look up the
1882  * base type here, since getTypes may not have processed it yet.)
1883  */
1884  }
1885 
1886  if (checkExtensionMembership(&tyinfo->dobj, fout))
1887  return; /* extension membership overrides all else */
1888 
1889  /* Dump based on if the contents of the namespace are being dumped */
1890  tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1891 }
1892 
1893 /*
1894  * selectDumpableDefaultACL: policy-setting subroutine
1895  * Mark a default ACL as to be dumped or not
1896  *
1897  * For per-schema default ACLs, dump if the schema is to be dumped.
1898  * Otherwise dump if we are dumping "everything". Note that dataOnly
1899  * and aclsSkip are checked separately.
1900  */
1901 static void
1903 {
1904  /* Default ACLs can't be extension members */
1905 
1906  if (dinfo->dobj.namespace)
1907  /* default ACLs are considered part of the namespace */
1908  dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1909  else
1910  dinfo->dobj.dump = dopt->include_everything ?
1912 }
1913 
1914 /*
1915  * selectDumpableCast: policy-setting subroutine
1916  * Mark a cast as to be dumped or not
1917  *
1918  * Casts do not belong to any particular namespace (since they haven't got
1919  * names), nor do they have identifiable owners. To distinguish user-defined
1920  * casts from built-in ones, we must resort to checking whether the cast's
1921  * OID is in the range reserved for initdb.
1922  */
1923 static void
1925 {
1926  if (checkExtensionMembership(&cast->dobj, fout))
1927  return; /* extension membership overrides all else */
1928 
1929  /*
1930  * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1931  * support ACLs currently.
1932  */
1933  if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1934  cast->dobj.dump = DUMP_COMPONENT_NONE;
1935  else
1936  cast->dobj.dump = fout->dopt->include_everything ?
1938 }
1939 
1940 /*
1941  * selectDumpableProcLang: policy-setting subroutine
1942  * Mark a procedural language as to be dumped or not
1943  *
1944  * Procedural languages do not belong to any particular namespace. To
1945  * identify built-in languages, we must resort to checking whether the
1946  * language's OID is in the range reserved for initdb.
1947  */
1948 static void
1950 {
1951  if (checkExtensionMembership(&plang->dobj, fout))
1952  return; /* extension membership overrides all else */
1953 
1954  /*
1955  * Only include procedural languages when we are dumping everything.
1956  *
1957  * For from-initdb procedural languages, only include ACLs, as we do for
1958  * the pg_catalog namespace. We need this because procedural languages do
1959  * not live in any namespace.
1960  */
1961  if (!fout->dopt->include_everything)
1962  plang->dobj.dump = DUMP_COMPONENT_NONE;
1963  else
1964  {
1965  if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1966  plang->dobj.dump = fout->remoteVersion < 90600 ?
1968  else
1969  plang->dobj.dump = DUMP_COMPONENT_ALL;
1970  }
1971 }
1972 
1973 /*
1974  * selectDumpableAccessMethod: policy-setting subroutine
1975  * Mark an access method as to be dumped or not
1976  *
1977  * Access methods do not belong to any particular namespace. To identify
1978  * built-in access methods, we must resort to checking whether the
1979  * method's OID is in the range reserved for initdb.
1980  */
1981 static void
1983 {
1984  if (checkExtensionMembership(&method->dobj, fout))
1985  return; /* extension membership overrides all else */
1986 
1987  /*
1988  * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1989  * they do not support ACLs currently.
1990  */
1991  if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1992  method->dobj.dump = DUMP_COMPONENT_NONE;
1993  else
1994  method->dobj.dump = fout->dopt->include_everything ?
1996 }
1997 
1998 /*
1999  * selectDumpableExtension: policy-setting subroutine
2000  * Mark an extension as to be dumped or not
2001  *
2002  * Built-in extensions should be skipped except for checking ACLs, since we
2003  * assume those will already be installed in the target database. We identify
2004  * such extensions by their having OIDs in the range reserved for initdb.
2005  * We dump all user-added extensions by default. No extensions are dumped
2006  * if include_everything is false (i.e., a --schema or --table switch was
2007  * given), except if --extension specifies a list of extensions to dump.
2008  */
2009 static void
2011 {
2012  /*
2013  * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
2014  * change permissions on their member objects, if they wish to, and have
2015  * those changes preserved.
2016  */
2017  if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
2018  extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
2019  else
2020  {
2021  /* check if there is a list of extensions to dump */
2022  if (extension_include_oids.head != NULL)
2023  extinfo->dobj.dump = extinfo->dobj.dump_contains =
2025  extinfo->dobj.catId.oid) ?
2027  else
2028  extinfo->dobj.dump = extinfo->dobj.dump_contains =
2029  dopt->include_everything ?
2031  }
2032 }
2033 
2034 /*
2035  * selectDumpablePublicationObject: policy-setting subroutine
2036  * Mark a publication object as to be dumped or not
2037  *
2038  * A publication can have schemas and tables which have schemas, but those are
2039  * ignored in decision making, because publications are only dumped when we are
2040  * dumping everything.
2041  */
2042 static void
2044 {
2045  if (checkExtensionMembership(dobj, fout))
2046  return; /* extension membership overrides all else */
2047 
2048  dobj->dump = fout->dopt->include_everything ?
2050 }
2051 
2052 /*
2053  * selectDumpableStatisticsObject: policy-setting subroutine
2054  * Mark an extended statistics object as to be dumped or not
2055  *
2056  * We dump an extended statistics object if the schema it's in and the table
2057  * it's for are being dumped. (This'll need more thought if statistics
2058  * objects ever support cross-table stats.)
2059  */
2060 static void
2062 {
2063  if (checkExtensionMembership(&sobj->dobj, fout))
2064  return; /* extension membership overrides all else */
2065 
2066  sobj->dobj.dump = sobj->dobj.namespace->dobj.dump_contains;
2067  if (sobj->stattable == NULL ||
2069  sobj->dobj.dump = DUMP_COMPONENT_NONE;
2070 }
2071 
2072 /*
2073  * selectDumpableObject: policy-setting subroutine
2074  * Mark a generic dumpable object as to be dumped or not
2075  *
2076  * Use this only for object types without a special-case routine above.
2077  */
2078 static void
2080 {
2081  if (checkExtensionMembership(dobj, fout))
2082  return; /* extension membership overrides all else */
2083 
2084  /*
2085  * Default policy is to dump if parent namespace is dumpable, or for
2086  * non-namespace-associated items, dump if we're dumping "everything".
2087  */
2088  if (dobj->namespace)
2089  dobj->dump = dobj->namespace->dobj.dump_contains;
2090  else
2091  dobj->dump = fout->dopt->include_everything ?
2093 }
2094 
2095 /*
2096  * Dump a table's contents for loading using the COPY command
2097  * - this routine is called by the Archiver when it wants the table
2098  * to be dumped.
2099  */
2100 static int
2101 dumpTableData_copy(Archive *fout, const void *dcontext)
2102 {
2103  TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
2104  TableInfo *tbinfo = tdinfo->tdtable;
2105  const char *classname = tbinfo->dobj.name;
2107 
2108  /*
2109  * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
2110  * which uses it already.
2111  */
2112  PQExpBuffer clistBuf = createPQExpBuffer();
2113  PGconn *conn = GetConnection(fout);
2114  PGresult *res;
2115  int ret;
2116  char *copybuf;
2117  const char *column_list;
2118 
2119  pg_log_info("dumping contents of table \"%s.%s\"",
2120  tbinfo->dobj.namespace->dobj.name, classname);
2121 
2122  /*
2123  * Specify the column list explicitly so that we have no possibility of
2124  * retrieving data in the wrong column order. (The default column
2125  * ordering of COPY will not be what we want in certain corner cases
2126  * involving ADD COLUMN and inheritance.)
2127  */
2128  column_list = fmtCopyColumnList(tbinfo, clistBuf);
2129 
2130  /*
2131  * Use COPY (SELECT ...) TO when dumping a foreign table's data, and when
2132  * a filter condition was specified. For other cases a simple COPY
2133  * suffices.
2134  */
2135  if (tdinfo->filtercond || tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2136  {
2137  appendPQExpBufferStr(q, "COPY (SELECT ");
2138  /* klugery to get rid of parens in column list */
2139  if (strlen(column_list) > 2)
2140  {
2141  appendPQExpBufferStr(q, column_list + 1);
2142  q->data[q->len - 1] = ' ';
2143  }
2144  else
2145  appendPQExpBufferStr(q, "* ");
2146 
2147  appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
2148  fmtQualifiedDumpable(tbinfo),
2149  tdinfo->filtercond ? tdinfo->filtercond : "");
2150  }
2151  else
2152  {
2153  appendPQExpBuffer(q, "COPY %s %s TO stdout;",
2154  fmtQualifiedDumpable(tbinfo),
2155  column_list);
2156  }
2157  res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
2158  PQclear(res);
2159  destroyPQExpBuffer(clistBuf);
2160 
2161  for (;;)
2162  {
2163  ret = PQgetCopyData(conn, &copybuf, 0);
2164 
2165  if (ret < 0)
2166  break; /* done or error */
2167 
2168  if (copybuf)
2169  {
2170  WriteData(fout, copybuf, ret);
2171  PQfreemem(copybuf);
2172  }
2173 
2174  /* ----------
2175  * THROTTLE:
2176  *
2177  * There was considerable discussion in late July, 2000 regarding
2178  * slowing down pg_dump when backing up large tables. Users with both
2179  * slow & fast (multi-processor) machines experienced performance
2180  * degradation when doing a backup.
2181  *
2182  * Initial attempts based on sleeping for a number of ms for each ms
2183  * of work were deemed too complex, then a simple 'sleep in each loop'
2184  * implementation was suggested. The latter failed because the loop
2185  * was too tight. Finally, the following was implemented:
2186  *
2187  * If throttle is non-zero, then
2188  * See how long since the last sleep.
2189  * Work out how long to sleep (based on ratio).
2190  * If sleep is more than 100ms, then
2191  * sleep
2192  * reset timer
2193  * EndIf
2194  * EndIf
2195  *
2196  * where the throttle value was the number of ms to sleep per ms of
2197  * work. The calculation was done in each loop.
2198  *
2199  * Most of the hard work is done in the backend, and this solution
2200  * still did not work particularly well: on slow machines, the ratio
2201  * was 50:1, and on medium paced machines, 1:1, and on fast
2202  * multi-processor machines, it had little or no effect, for reasons
2203  * that were unclear.
2204  *
2205  * Further discussion ensued, and the proposal was dropped.
2206  *
2207  * For those people who want this feature, it can be implemented using
2208  * gettimeofday in each loop, calculating the time since last sleep,
2209  * multiplying that by the sleep ratio, then if the result is more
2210  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
2211  * function to sleep for a subsecond period ie.
2212  *
2213  * select(0, NULL, NULL, NULL, &tvi);
2214  *
2215  * This will return after the interval specified in the structure tvi.
2216  * Finally, call gettimeofday again to save the 'last sleep time'.
2217  * ----------
2218  */
2219  }
2220  archprintf(fout, "\\.\n\n\n");
2221 
2222  if (ret == -2)
2223  {
2224  /* copy data transfer failed */
2225  pg_log_error("Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.", classname);
2226  pg_log_error_detail("Error message from server: %s", PQerrorMessage(conn));
2227  pg_log_error_detail("Command was: %s", q->data);
2228  exit_nicely(1);
2229  }
2230 
2231  /* Check command status and return to normal libpq state */
2232  res = PQgetResult(conn);
2234  {
2235  pg_log_error("Dumping the contents of table \"%s\" failed: PQgetResult() failed.", classname);
2236  pg_log_error_detail("Error message from server: %s", PQerrorMessage(conn));
2237  pg_log_error_detail("Command was: %s", q->data);
2238  exit_nicely(1);
2239  }
2240  PQclear(res);
2241 
2242  /* Do this to ensure we've pumped libpq back to idle state */
2243  if (PQgetResult(conn) != NULL)
2244  pg_log_warning("unexpected extra results during COPY of table \"%s\"",
2245  classname);
2246 
2247  destroyPQExpBuffer(q);
2248  return 1;
2249 }
2250 
2251 /*
2252  * Dump table data using INSERT commands.
2253  *
2254  * Caution: when we restore from an archive file direct to database, the
2255  * INSERT commands emitted by this function have to be parsed by
2256  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
2257  * E'' strings, or dollar-quoted strings. So don't emit anything like that.
2258  */
2259 static int
2260 dumpTableData_insert(Archive *fout, const void *dcontext)
2261 {
2262  TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
2263  TableInfo *tbinfo = tdinfo->tdtable;
2264  DumpOptions *dopt = fout->dopt;
2266  PQExpBuffer insertStmt = NULL;
2267  char *attgenerated;
2268  PGresult *res;
2269  int nfields,
2270  i;
2271  int rows_per_statement = dopt->dump_inserts;
2272  int rows_this_statement = 0;
2273 
2274  /*
2275  * If we're going to emit INSERTs with column names, the most efficient
2276  * way to deal with generated columns is to exclude them entirely. For
2277  * INSERTs without column names, we have to emit DEFAULT rather than the
2278  * actual column value --- but we can save a few cycles by fetching nulls
2279  * rather than the uninteresting-to-us value.
2280  */
2281  attgenerated = (char *) pg_malloc(tbinfo->numatts * sizeof(char));
2282  appendPQExpBufferStr(q, "DECLARE _pg_dump_cursor CURSOR FOR SELECT ");
2283  nfields = 0;
2284  for (i = 0; i < tbinfo->numatts; i++)
2285  {
2286  if (tbinfo->attisdropped[i])
2287  continue;
2288  if (tbinfo->attgenerated[i] && dopt->column_inserts)
2289  continue;
2290  if (nfields > 0)
2291  appendPQExpBufferStr(q, ", ");
2292  if (tbinfo->attgenerated[i])
2293  appendPQExpBufferStr(q, "NULL");
2294  else
2295  appendPQExpBufferStr(q, fmtId(tbinfo->attnames[i]));
2296  attgenerated[nfields] = tbinfo->attgenerated[i];
2297  nfields++;
2298  }
2299  /* Servers before 9.4 will complain about zero-column SELECT */
2300  if (nfields == 0)
2301  appendPQExpBufferStr(q, "NULL");
2302  appendPQExpBuffer(q, " FROM ONLY %s",
2303  fmtQualifiedDumpable(tbinfo));
2304  if (tdinfo->filtercond)
2305  appendPQExpBuffer(q, " %s", tdinfo->filtercond);
2306 
2307  ExecuteSqlStatement(fout, q->data);
2308 
2309  while (1)
2310  {
2311  res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
2312  PGRES_TUPLES_OK);
2313 
2314  /* cross-check field count, allowing for dummy NULL if any */
2315  if (nfields != PQnfields(res) &&
2316  !(nfields == 0 && PQnfields(res) == 1))
2317  pg_fatal("wrong number of fields retrieved from table \"%s\"",
2318  tbinfo->dobj.name);
2319 
2320  /*
2321  * First time through, we build as much of the INSERT statement as
2322  * possible in "insertStmt", which we can then just print for each
2323  * statement. If the table happens to have zero dumpable columns then
2324  * this will be a complete statement, otherwise it will end in
2325  * "VALUES" and be ready to have the row's column values printed.
2326  */
2327  if (insertStmt == NULL)
2328  {
2329  TableInfo *targettab;
2330 
2331  insertStmt = createPQExpBuffer();
2332 
2333  /*
2334  * When load-via-partition-root is set or forced, get the root
2335  * table name for the partition table, so that we can reload data
2336  * through the root table.
2337  */
2338  if (tbinfo->ispartition &&
2339  (dopt->load_via_partition_root ||
2340  forcePartitionRootLoad(tbinfo)))
2341  targettab = getRootTableInfo(tbinfo);
2342  else
2343  targettab = tbinfo;
2344 
2345  appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
2346  fmtQualifiedDumpable(targettab));
2347 
2348  /* corner case for zero-column table */
2349  if (nfields == 0)
2350  {
2351  appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
2352  }
2353  else
2354  {
2355  /* append the list of column names if required */
2356  if (dopt->column_inserts)
2357  {
2358  appendPQExpBufferChar(insertStmt, '(');
2359  for (int field = 0; field < nfields; field++)
2360  {
2361  if (field > 0)
2362  appendPQExpBufferStr(insertStmt, ", ");
2363  appendPQExpBufferStr(insertStmt,
2364  fmtId(PQfname(res, field)));
2365  }
2366  appendPQExpBufferStr(insertStmt, ") ");
2367  }
2368 
2369  if (tbinfo->needs_override)
2370  appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
2371 
2372  appendPQExpBufferStr(insertStmt, "VALUES");
2373  }
2374  }
2375 
2376  for (int tuple = 0; tuple < PQntuples(res); tuple++)
2377  {
2378  /* Write the INSERT if not in the middle of a multi-row INSERT. */
2379  if (rows_this_statement == 0)
2380  archputs(insertStmt->data, fout);
2381 
2382  /*
2383  * If it is zero-column table then we've already written the
2384  * complete statement, which will mean we've disobeyed
2385  * --rows-per-insert when it's set greater than 1. We do support
2386  * a way to make this multi-row with: SELECT UNION ALL SELECT
2387  * UNION ALL ... but that's non-standard so we should avoid it
2388  * given that using INSERTs is mostly only ever needed for
2389  * cross-database exports.
2390  */
2391  if (nfields == 0)
2392  continue;
2393 
2394  /* Emit a row heading */
2395  if (rows_per_statement == 1)
2396  archputs(" (", fout);
2397  else if (rows_this_statement > 0)
2398  archputs(",\n\t(", fout);
2399  else
2400  archputs("\n\t(", fout);
2401 
2402  for (int field = 0; field < nfields; field++)
2403  {
2404  if (field > 0)
2405  archputs(", ", fout);
2406  if (attgenerated[field])
2407  {
2408  archputs("DEFAULT", fout);
2409  continue;
2410  }
2411  if (PQgetisnull(res, tuple, field))
2412  {
2413  archputs("NULL", fout);
2414  continue;
2415  }
2416 
2417  /* XXX This code is partially duplicated in ruleutils.c */
2418  switch (PQftype(res, field))
2419  {
2420  case INT2OID:
2421  case INT4OID:
2422  case INT8OID:
2423  case OIDOID:
2424  case FLOAT4OID:
2425  case FLOAT8OID:
2426  case NUMERICOID:
2427  {
2428  /*
2429  * These types are printed without quotes unless
2430  * they contain values that aren't accepted by the
2431  * scanner unquoted (e.g., 'NaN'). Note that
2432  * strtod() and friends might accept NaN, so we
2433  * can't use that to test.
2434  *
2435  * In reality we only need to defend against
2436  * infinity and NaN, so we need not get too crazy
2437  * about pattern matching here.
2438  */
2439  const char *s = PQgetvalue(res, tuple, field);
2440 
2441  if (strspn(s, "0123456789 +-eE.") == strlen(s))
2442  archputs(s, fout);
2443  else
2444  archprintf(fout, "'%s'", s);
2445  }
2446  break;
2447 
2448  case BITOID:
2449  case VARBITOID:
2450  archprintf(fout, "B'%s'",
2451  PQgetvalue(res, tuple, field));
2452  break;
2453 
2454  case BOOLOID:
2455  if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2456  archputs("true", fout);
2457  else
2458  archputs("false", fout);
2459  break;
2460 
2461  default:
2462  /* All other types are printed as string literals. */
2463  resetPQExpBuffer(q);
2465  PQgetvalue(res, tuple, field),
2466  fout);
2467  archputs(q->data, fout);
2468  break;
2469  }
2470  }
2471 
2472  /* Terminate the row ... */
2473  archputs(")", fout);
2474 
2475  /* ... and the statement, if the target no. of rows is reached */
2476  if (++rows_this_statement >= rows_per_statement)
2477  {
2478  if (dopt->do_nothing)
2479  archputs(" ON CONFLICT DO NOTHING;\n", fout);
2480  else
2481  archputs(";\n", fout);
2482  /* Reset the row counter */
2483  rows_this_statement = 0;
2484  }
2485  }
2486 
2487  if (PQntuples(res) <= 0)
2488  {
2489  PQclear(res);
2490  break;
2491  }
2492  PQclear(res);
2493  }
2494 
2495  /* Terminate any statements that didn't make the row count. */
2496  if (rows_this_statement > 0)
2497  {
2498  if (dopt->do_nothing)
2499  archputs(" ON CONFLICT DO NOTHING;\n", fout);
2500  else
2501  archputs(";\n", fout);
2502  }
2503 
2504  archputs("\n\n", fout);
2505 
2506  ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2507 
2508  destroyPQExpBuffer(q);
2509  if (insertStmt != NULL)
2510  destroyPQExpBuffer(insertStmt);
2511  free(attgenerated);
2512 
2513  return 1;
2514 }
2515 
2516 /*
2517  * getRootTableInfo:
2518  * get the root TableInfo for the given partition table.
2519  */
2520 static TableInfo *
2522 {
2523  TableInfo *parentTbinfo;
2524 
2525  Assert(tbinfo->ispartition);
2526  Assert(tbinfo->numParents == 1);
2527 
2528  parentTbinfo = tbinfo->parents[0];
2529  while (parentTbinfo->ispartition)
2530  {
2531  Assert(parentTbinfo->numParents == 1);
2532  parentTbinfo = parentTbinfo->parents[0];
2533  }
2534 
2535  return parentTbinfo;
2536 }
2537 
2538 /*
2539  * forcePartitionRootLoad
2540  * Check if we must force load_via_partition_root for this partition.
2541  *
2542  * This is required if any level of ancestral partitioned table has an
2543  * unsafe partitioning scheme.
2544  */
2545 static bool
2547 {
2548  TableInfo *parentTbinfo;
2549 
2550  Assert(tbinfo->ispartition);
2551  Assert(tbinfo->numParents == 1);
2552 
2553  parentTbinfo = tbinfo->parents[0];
2554  if (parentTbinfo->unsafe_partitions)
2555  return true;
2556  while (parentTbinfo->ispartition)
2557  {
2558  Assert(parentTbinfo->numParents == 1);
2559  parentTbinfo = parentTbinfo->parents[0];
2560  if (parentTbinfo->unsafe_partitions)
2561  return true;
2562  }
2563 
2564  return false;
2565 }
2566 
2567 /*
2568  * dumpTableData -
2569  * dump the contents of a single table
2570  *
2571  * Actually, this just makes an ArchiveEntry for the table contents.
2572  */
2573 static void
2574 dumpTableData(Archive *fout, const TableDataInfo *tdinfo)
2575 {
2576  DumpOptions *dopt = fout->dopt;
2577  TableInfo *tbinfo = tdinfo->tdtable;
2578  PQExpBuffer copyBuf = createPQExpBuffer();
2579  PQExpBuffer clistBuf = createPQExpBuffer();
2580  DataDumperPtr dumpFn;
2581  char *tdDefn = NULL;
2582  char *copyStmt;
2583  const char *copyFrom;
2584 
2585  /* We had better have loaded per-column details about this table */
2586  Assert(tbinfo->interesting);
2587 
2588  /*
2589  * When load-via-partition-root is set or forced, get the root table name
2590  * for the partition table, so that we can reload data through the root
2591  * table. Then construct a comment to be inserted into the TOC entry's
2592  * defn field, so that such cases can be identified reliably.
2593  */
2594  if (tbinfo->ispartition &&
2595  (dopt->load_via_partition_root ||
2596  forcePartitionRootLoad(tbinfo)))
2597  {
2598  TableInfo *parentTbinfo;
2599 
2600  parentTbinfo = getRootTableInfo(tbinfo);
2601  copyFrom = fmtQualifiedDumpable(parentTbinfo);
2602  printfPQExpBuffer(copyBuf, "-- load via partition root %s",
2603  copyFrom);
2604  tdDefn = pg_strdup(copyBuf->data);
2605  }
2606  else
2607  copyFrom = fmtQualifiedDumpable(tbinfo);
2608 
2609  if (dopt->dump_inserts == 0)
2610  {
2611  /* Dump/restore using COPY */
2612  dumpFn = dumpTableData_copy;
2613  /* must use 2 steps here 'cause fmtId is nonreentrant */
2614  printfPQExpBuffer(copyBuf, "COPY %s ",
2615  copyFrom);
2616  appendPQExpBuffer(copyBuf, "%s FROM stdin;\n",
2617  fmtCopyColumnList(tbinfo, clistBuf));
2618  copyStmt = copyBuf->data;
2619  }
2620  else
2621  {
2622  /* Restore using INSERT */
2623  dumpFn = dumpTableData_insert;
2624  copyStmt = NULL;
2625  }
2626 
2627  /*
2628  * Note: although the TableDataInfo is a full DumpableObject, we treat its
2629  * dependency on its table as "special" and pass it to ArchiveEntry now.
2630  * See comments for BuildArchiveDependencies.
2631  */
2632  if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2633  {
2634  TocEntry *te;
2635 
2636  te = ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2637  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2638  .namespace = tbinfo->dobj.namespace->dobj.name,
2639  .owner = tbinfo->rolname,
2640  .description = "TABLE DATA",
2641  .section = SECTION_DATA,
2642  .createStmt = tdDefn,
2643  .copyStmt = copyStmt,
2644  .deps = &(tbinfo->dobj.dumpId),
2645  .nDeps = 1,
2646  .dumpFn = dumpFn,
2647  .dumpArg = tdinfo));
2648 
2649  /*
2650  * Set the TocEntry's dataLength in case we are doing a parallel dump
2651  * and want to order dump jobs by table size. We choose to measure
2652  * dataLength in table pages (including TOAST pages) during dump, so
2653  * no scaling is needed.
2654  *
2655  * However, relpages is declared as "integer" in pg_class, and hence
2656  * also in TableInfo, but it's really BlockNumber a/k/a unsigned int.
2657  * Cast so that we get the right interpretation of table sizes
2658  * exceeding INT_MAX pages.
2659  */
2660  te->dataLength = (BlockNumber) tbinfo->relpages;
2661  te->dataLength += (BlockNumber) tbinfo->toastpages;
2662 
2663  /*
2664  * If pgoff_t is only 32 bits wide, the above refinement is useless,
2665  * and instead we'd better worry about integer overflow. Clamp to
2666  * INT_MAX if the correct result exceeds that.
2667  */
2668  if (sizeof(te->dataLength) == 4 &&
2669  (tbinfo->relpages < 0 || tbinfo->toastpages < 0 ||
2670  te->dataLength < 0))
2671  te->dataLength = INT_MAX;
2672  }
2673 
2674  destroyPQExpBuffer(copyBuf);
2675  destroyPQExpBuffer(clistBuf);
2676 }
2677 
2678 /*
2679  * refreshMatViewData -
2680  * load or refresh the contents of a single materialized view
2681  *
2682  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2683  * statement.
2684  */
2685 static void
2687 {
2688  TableInfo *tbinfo = tdinfo->tdtable;
2689  PQExpBuffer q;
2690 
2691  /* If the materialized view is not flagged as populated, skip this. */
2692  if (!tbinfo->relispopulated)
2693  return;
2694 
2695  q = createPQExpBuffer();
2696 
2697  appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2698  fmtQualifiedDumpable(tbinfo));
2699 
2700  if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2701  ArchiveEntry(fout,
2702  tdinfo->dobj.catId, /* catalog ID */
2703  tdinfo->dobj.dumpId, /* dump ID */
2704  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2705  .namespace = tbinfo->dobj.namespace->dobj.name,
2706  .owner = tbinfo->rolname,
2707  .description = "MATERIALIZED VIEW DATA",
2708  .section = SECTION_POST_DATA,
2709  .createStmt = q->data,
2710  .deps = tdinfo->dobj.dependencies,
2711  .nDeps = tdinfo->dobj.nDeps));
2712 
2713  destroyPQExpBuffer(q);
2714 }
2715 
2716 /*
2717  * getTableData -
2718  * set up dumpable objects representing the contents of tables
2719  */
2720 static void
2721 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind)
2722 {
2723  int i;
2724 
2725  for (i = 0; i < numTables; i++)
2726  {
2727  if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2728  (!relkind || tblinfo[i].relkind == relkind))
2729  makeTableDataInfo(dopt, &(tblinfo[i]));
2730  }
2731 }
2732 
2733 /*
2734  * Make a dumpable object for the data of this specific table
2735  *
2736  * Note: we make a TableDataInfo if and only if we are going to dump the
2737  * table data; the "dump" field in such objects isn't very interesting.
2738  */
2739 static void
2741 {
2742  TableDataInfo *tdinfo;
2743 
2744  /*
2745  * Nothing to do if we already decided to dump the table. This will
2746  * happen for "config" tables.
2747  */
2748  if (tbinfo->dataObj != NULL)
2749  return;
2750 
2751  /* Skip VIEWs (no data to dump) */
2752  if (tbinfo->relkind == RELKIND_VIEW)
2753  return;
2754  /* Skip FOREIGN TABLEs (no data to dump) unless requested explicitly */
2755  if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
2758  tbinfo->foreign_server)))
2759  return;
2760  /* Skip partitioned tables (data in partitions) */
2761  if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2762  return;
2763 
2764  /* Don't dump data in unlogged tables, if so requested */
2765  if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2766  dopt->no_unlogged_table_data)
2767  return;
2768 
2769  /* Check that the data is not explicitly excluded */
2771  tbinfo->dobj.catId.oid))
2772  return;
2773 
2774  /* OK, let's dump it */
2775  tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2776 
2777  if (tbinfo->relkind == RELKIND_MATVIEW)
2778  tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2779  else if (tbinfo->relkind == RELKIND_SEQUENCE)
2780  tdinfo->dobj.objType = DO_SEQUENCE_SET;
2781  else
2782  tdinfo->dobj.objType = DO_TABLE_DATA;
2783 
2784  /*
2785  * Note: use tableoid 0 so that this object won't be mistaken for
2786  * something that pg_depend entries apply to.
2787  */
2788  tdinfo->dobj.catId.tableoid = 0;
2789  tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2790  AssignDumpId(&tdinfo->dobj);
2791  tdinfo->dobj.name = tbinfo->dobj.name;
2792  tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2793  tdinfo->tdtable = tbinfo;
2794  tdinfo->filtercond = NULL; /* might get set later */
2795  addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2796 
2797  /* A TableDataInfo contains data, of course */
2798  tdinfo->dobj.components |= DUMP_COMPONENT_DATA;
2799 
2800  tbinfo->dataObj = tdinfo;
2801 
2802  /* Make sure that we'll collect per-column info for this table. */
2803  tbinfo->interesting = true;
2804 }
2805 
2806 /*
2807  * The refresh for a materialized view must be dependent on the refresh for
2808  * any materialized view that this one is dependent on.
2809  *
2810  * This must be called after all the objects are created, but before they are
2811  * sorted.
2812  */
2813 static void
2815 {
2816  PQExpBuffer query;
2817  PGresult *res;
2818  int ntups,
2819  i;
2820  int i_classid,
2821  i_objid,
2822  i_refobjid;
2823 
2824  /* No Mat Views before 9.3. */
2825  if (fout->remoteVersion < 90300)
2826  return;
2827 
2828  query = createPQExpBuffer();
2829 
2830  appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2831  "( "
2832  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2833  "FROM pg_depend d1 "
2834  "JOIN pg_class c1 ON c1.oid = d1.objid "
2835  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2836  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2837  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2838  "AND d2.objid = r1.oid "
2839  "AND d2.refobjid <> d1.objid "
2840  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2841  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2842  CppAsString2(RELKIND_VIEW) ") "
2843  "WHERE d1.classid = 'pg_class'::regclass "
2844  "UNION "
2845  "SELECT w.objid, d3.refobjid, c3.relkind "
2846  "FROM w "
2847  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2848  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2849  "AND d3.objid = r3.oid "
2850  "AND d3.refobjid <> w.refobjid "
2851  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2852  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2853  CppAsString2(RELKIND_VIEW) ") "
2854  ") "
2855  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2856  "FROM w "
2857  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2858 
2859  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2860 
2861  ntups = PQntuples(res);
2862 
2863  i_classid = PQfnumber(res, "classid");
2864  i_objid = PQfnumber(res, "objid");
2865  i_refobjid = PQfnumber(res, "refobjid");
2866 
2867  for (i = 0; i < ntups; i++)
2868  {
2869  CatalogId objId;
2870  CatalogId refobjId;
2871  DumpableObject *dobj;
2872  DumpableObject *refdobj;
2873  TableInfo *tbinfo;
2874  TableInfo *reftbinfo;
2875 
2876  objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2877  objId.oid = atooid(PQgetvalue(res, i, i_objid));
2878  refobjId.tableoid = objId.tableoid;
2879  refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2880 
2881  dobj = findObjectByCatalogId(objId);
2882  if (dobj == NULL)
2883  continue;
2884 
2885  Assert(dobj->objType == DO_TABLE);
2886  tbinfo = (TableInfo *) dobj;
2887  Assert(tbinfo->relkind == RELKIND_MATVIEW);
2888  dobj = (DumpableObject *) tbinfo->dataObj;
2889  if (dobj == NULL)
2890  continue;
2891  Assert(dobj->objType == DO_REFRESH_MATVIEW);
2892 
2893  refdobj = findObjectByCatalogId(refobjId);
2894  if (refdobj == NULL)
2895  continue;
2896 
2897  Assert(refdobj->objType == DO_TABLE);
2898  reftbinfo = (TableInfo *) refdobj;
2899  Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2900  refdobj = (DumpableObject *) reftbinfo->dataObj;
2901  if (refdobj == NULL)
2902  continue;
2903  Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2904 
2905  addObjectDependency(dobj, refdobj->dumpId);
2906 
2907  if (!reftbinfo->relispopulated)
2908  tbinfo->relispopulated = false;
2909  }
2910 
2911  PQclear(res);
2912 
2913  destroyPQExpBuffer(query);
2914 }
2915 
2916 /*
2917  * getTableDataFKConstraints -
2918  * add dump-order dependencies reflecting foreign key constraints
2919  *
2920  * This code is executed only in a data-only dump --- in schema+data dumps
2921  * we handle foreign key issues by not creating the FK constraints until
2922  * after the data is loaded. In a data-only dump, however, we want to
2923  * order the table data objects in such a way that a table's referenced
2924  * tables are restored first. (In the presence of circular references or
2925  * self-references this may be impossible; we'll detect and complain about
2926  * that during the dependency sorting step.)
2927  */
2928 static void
2930 {
2931  DumpableObject **dobjs;
2932  int numObjs;
2933  int i;
2934 
2935  /* Search through all the dumpable objects for FK constraints */
2936  getDumpableObjects(&dobjs, &numObjs);
2937  for (i = 0; i < numObjs; i++)
2938  {
2939  if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2940  {
2941  ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2942  TableInfo *ftable;
2943 
2944  /* Not interesting unless both tables are to be dumped */
2945  if (cinfo->contable == NULL ||
2946  cinfo->contable->dataObj == NULL)
2947  continue;
2948  ftable = findTableByOid(cinfo->confrelid);
2949  if (ftable == NULL ||
2950  ftable->dataObj == NULL)
2951  continue;
2952 
2953  /*
2954  * Okay, make referencing table's TABLE_DATA object depend on the
2955  * referenced table's TABLE_DATA object.
2956  */
2958  ftable->dataObj->dobj.dumpId);
2959  }
2960  }
2961  free(dobjs);
2962 }
2963 
2964 
2965 /*
2966  * dumpDatabase:
2967  * dump the database definition
2968  */
2969 static void
2971 {
2972  DumpOptions *dopt = fout->dopt;
2973  PQExpBuffer dbQry = createPQExpBuffer();
2974  PQExpBuffer delQry = createPQExpBuffer();
2975  PQExpBuffer creaQry = createPQExpBuffer();
2976  PQExpBuffer labelq = createPQExpBuffer();
2977  PGconn *conn = GetConnection(fout);
2978  PGresult *res;
2979  int i_tableoid,
2980  i_oid,
2981  i_datname,
2982  i_datdba,
2983  i_encoding,
2984  i_datlocprovider,
2985  i_collate,
2986  i_ctype,
2987  i_datlocale,
2988  i_daticurules,
2989  i_frozenxid,
2990  i_minmxid,
2991  i_datacl,
2992  i_acldefault,
2993  i_datistemplate,
2994  i_datconnlimit,
2995  i_datcollversion,
2996  i_tablespace;
2997  CatalogId dbCatId;
2998  DumpId dbDumpId;
2999  DumpableAcl dbdacl;
3000  const char *datname,
3001  *dba,
3002  *encoding,
3003  *datlocprovider,
3004  *collate,
3005  *ctype,
3006  *locale,
3007  *icurules,
3008  *datistemplate,
3009  *datconnlimit,
3010  *tablespace;
3011  uint32 frozenxid,
3012  minmxid;
3013  char *qdatname;
3014 
3015  pg_log_info("saving database definition");
3016 
3017  /*
3018  * Fetch the database-level properties for this database.
3019  */
3020  appendPQExpBufferStr(dbQry, "SELECT tableoid, oid, datname, "
3021  "datdba, "
3022  "pg_encoding_to_char(encoding) AS encoding, "
3023  "datcollate, datctype, datfrozenxid, "
3024  "datacl, acldefault('d', datdba) AS acldefault, "
3025  "datistemplate, datconnlimit, ");
3026  if (fout->remoteVersion >= 90300)
3027  appendPQExpBufferStr(dbQry, "datminmxid, ");
3028  else
3029  appendPQExpBufferStr(dbQry, "0 AS datminmxid, ");
3030  if (fout->remoteVersion >= 170000)
3031  appendPQExpBufferStr(dbQry, "datlocprovider, datlocale, datcollversion, ");
3032  else if (fout->remoteVersion >= 150000)
3033  appendPQExpBufferStr(dbQry, "datlocprovider, daticulocale AS datlocale, datcollversion, ");
3034  else
3035  appendPQExpBufferStr(dbQry, "'c' AS datlocprovider, NULL AS datlocale, NULL AS datcollversion, ");
3036  if (fout->remoteVersion >= 160000)
3037  appendPQExpBufferStr(dbQry, "daticurules, ");
3038  else
3039  appendPQExpBufferStr(dbQry, "NULL AS daticurules, ");
3040  appendPQExpBufferStr(dbQry,
3041  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
3042  "shobj_description(oid, 'pg_database') AS description "
3043  "FROM pg_database "
3044  "WHERE datname = current_database()");
3045 
3046  res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
3047 
3048  i_tableoid = PQfnumber(res, "tableoid");
3049  i_oid = PQfnumber(res, "oid");
3050  i_datname = PQfnumber(res, "datname");
3051  i_datdba = PQfnumber(res, "datdba");
3052  i_encoding = PQfnumber(res, "encoding");
3053  i_datlocprovider = PQfnumber(res, "datlocprovider");
3054  i_collate = PQfnumber(res, "datcollate");
3055  i_ctype = PQfnumber(res, "datctype");
3056  i_datlocale = PQfnumber(res, "datlocale");
3057  i_daticurules = PQfnumber(res, "daticurules");
3058  i_frozenxid = PQfnumber(res, "datfrozenxid");
3059  i_minmxid = PQfnumber(res, "datminmxid");
3060  i_datacl = PQfnumber(res, "datacl");
3061  i_acldefault = PQfnumber(res, "acldefault");
3062  i_datistemplate = PQfnumber(res, "datistemplate");
3063  i_datconnlimit = PQfnumber(res, "datconnlimit");
3064  i_datcollversion = PQfnumber(res, "datcollversion");
3065  i_tablespace = PQfnumber(res, "tablespace");
3066 
3067  dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
3068  dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
3069  datname = PQgetvalue(res, 0, i_datname);
3070  dba = getRoleName(PQgetvalue(res, 0, i_datdba));
3071  encoding = PQgetvalue(res, 0, i_encoding);
3072  datlocprovider = PQgetvalue(res, 0, i_datlocprovider);
3073  collate = PQgetvalue(res, 0, i_collate);
3074  ctype = PQgetvalue(res, 0, i_ctype);
3075  if (!PQgetisnull(res, 0, i_datlocale))
3076  locale = PQgetvalue(res, 0, i_datlocale);
3077  else
3078  locale = NULL;
3079  if (!PQgetisnull(res, 0, i_daticurules))
3080  icurules = PQgetvalue(res, 0, i_daticurules);
3081  else
3082  icurules = NULL;
3083  frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
3084  minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
3085  dbdacl.acl = PQgetvalue(res, 0, i_datacl);
3086  dbdacl.acldefault = PQgetvalue(res, 0, i_acldefault);
3087  datistemplate = PQgetvalue(res, 0, i_datistemplate);
3088  datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
3089  tablespace = PQgetvalue(res, 0, i_tablespace);
3090 
3091  qdatname = pg_strdup(fmtId(datname));
3092 
3093  /*
3094  * Prepare the CREATE DATABASE command. We must specify OID (if we want
3095  * to preserve that), as well as the encoding, locale, and tablespace
3096  * since those can't be altered later. Other DB properties are left to
3097  * the DATABASE PROPERTIES entry, so that they can be applied after
3098  * reconnecting to the target DB.
3099  */
3100  if (dopt->binary_upgrade)
3101  {
3102  appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0 OID = %u",
3103  qdatname, dbCatId.oid);
3104  }
3105  else
3106  {
3107  appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
3108  qdatname);
3109  }
3110  if (strlen(encoding) > 0)
3111  {
3112  appendPQExpBufferStr(creaQry, " ENCODING = ");
3113  appendStringLiteralAH(creaQry, encoding, fout);
3114  }
3115 
3116  appendPQExpBufferStr(creaQry, " LOCALE_PROVIDER = ");
3117  if (datlocprovider[0] == 'b')
3118  appendPQExpBufferStr(creaQry, "builtin");
3119  else if (datlocprovider[0] == 'c')
3120  appendPQExpBufferStr(creaQry, "libc");
3121  else if (datlocprovider[0] == 'i')
3122  appendPQExpBufferStr(creaQry, "icu");
3123  else
3124  pg_fatal("unrecognized locale provider: %s",
3125  datlocprovider);
3126 
3127  if (strlen(collate) > 0 && strcmp(collate, ctype) == 0)
3128  {
3129  appendPQExpBufferStr(creaQry, " LOCALE = ");
3130  appendStringLiteralAH(creaQry, collate, fout);
3131  }
3132  else
3133  {
3134  if (strlen(collate) > 0)
3135  {
3136  appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
3137  appendStringLiteralAH(creaQry, collate, fout);
3138  }
3139  if (strlen(ctype) > 0)
3140  {
3141  appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
3142  appendStringLiteralAH(creaQry, ctype, fout);
3143  }
3144  }
3145  if (locale)
3146  {
3147  if (datlocprovider[0] == 'b')
3148  appendPQExpBufferStr(creaQry, " BUILTIN_LOCALE = ");
3149  else
3150  appendPQExpBufferStr(creaQry, " ICU_LOCALE = ");
3151 
3152  appendStringLiteralAH(creaQry, locale, fout);
3153  }
3154 
3155  if (icurules)
3156  {
3157  appendPQExpBufferStr(creaQry, " ICU_RULES = ");
3158  appendStringLiteralAH(creaQry, icurules, fout);
3159  }
3160 
3161  /*
3162  * For binary upgrade, carry over the collation version. For normal
3163  * dump/restore, omit the version, so that it is computed upon restore.
3164  */
3165  if (dopt->binary_upgrade)
3166  {
3167  if (!PQgetisnull(res, 0, i_datcollversion))
3168  {
3169  appendPQExpBufferStr(creaQry, " COLLATION_VERSION = ");
3170  appendStringLiteralAH(creaQry,
3171  PQgetvalue(res, 0, i_datcollversion),
3172  fout);
3173  }
3174  }
3175 
3176  /*
3177  * Note: looking at dopt->outputNoTablespaces here is completely the wrong
3178  * thing; the decision whether to specify a tablespace should be left till
3179  * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
3180  * label the DATABASE entry with the tablespace and let the normal
3181  * tablespace selection logic work ... but CREATE DATABASE doesn't pay
3182  * attention to default_tablespace, so that won't work.
3183  */
3184  if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
3185  !dopt->outputNoTablespaces)
3186  appendPQExpBuffer(creaQry, " TABLESPACE = %s",
3187  fmtId(tablespace));
3188  appendPQExpBufferStr(creaQry, ";\n");
3189 
3190  appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
3191  qdatname);
3192 
3193  dbDumpId = createDumpId();
3194 
3195  ArchiveEntry(fout,
3196  dbCatId, /* catalog ID */
3197  dbDumpId, /* dump ID */
3198  ARCHIVE_OPTS(.tag = datname,
3199  .owner = dba,
3200  .description = "DATABASE",
3201  .section = SECTION_PRE_DATA,
3202  .createStmt = creaQry->data,
3203  .dropStmt = delQry->data));
3204 
3205  /* Compute correct tag for archive entry */
3206  appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
3207 
3208  /* Dump DB comment if any */
3209  {
3210  /*
3211  * 8.2 and up keep comments on shared objects in a shared table, so we
3212  * cannot use the dumpComment() code used for other database objects.
3213  * Be careful that the ArchiveEntry parameters match that function.
3214  */
3215  char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
3216 
3217  if (comment && *comment && !dopt->no_comments)
3218  {
3219  resetPQExpBuffer(dbQry);
3220 
3221  /*
3222  * Generates warning when loaded into a differently-named
3223  * database.
3224  */
3225  appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
3226  appendStringLiteralAH(dbQry, comment, fout);
3227  appendPQExpBufferStr(dbQry, ";\n");
3228 
3230  ARCHIVE_OPTS(.tag = labelq->data,
3231  .owner = dba,
3232  .description = "COMMENT",
3233  .section = SECTION_NONE,
3234  .createStmt = dbQry->data,
3235  .deps = &dbDumpId,
3236  .nDeps = 1));
3237  }
3238  }
3239 
3240  /* Dump DB security label, if enabled */
3241  if (!dopt->no_security_labels)
3242  {
3243  PGresult *shres;
3244  PQExpBuffer seclabelQry;
3245 
3246  seclabelQry = createPQExpBuffer();
3247 
3248  buildShSecLabelQuery("pg_database", dbCatId.oid, seclabelQry);
3249  shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
3250  resetPQExpBuffer(seclabelQry);
3251  emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
3252  if (seclabelQry->len > 0)
3254  ARCHIVE_OPTS(.tag = labelq->data,
3255  .owner = dba,
3256  .description = "SECURITY LABEL",
3257  .section = SECTION_NONE,
3258  .createStmt = seclabelQry->data,
3259  .deps = &dbDumpId,
3260  .nDeps = 1));
3261  destroyPQExpBuffer(seclabelQry);
3262  PQclear(shres);
3263  }
3264 
3265  /*
3266  * Dump ACL if any. Note that we do not support initial privileges
3267  * (pg_init_privs) on databases.
3268  */
3269  dbdacl.privtype = 0;
3270  dbdacl.initprivs = NULL;
3271 
3272  dumpACL(fout, dbDumpId, InvalidDumpId, "DATABASE",
3273  qdatname, NULL, NULL,
3274  dba, &dbdacl);
3275 
3276  /*
3277  * Now construct a DATABASE PROPERTIES archive entry to restore any
3278  * non-default database-level properties. (The reason this must be
3279  * separate is that we cannot put any additional commands into the TOC
3280  * entry that has CREATE DATABASE. pg_restore would execute such a group
3281  * in an implicit transaction block, and the backend won't allow CREATE
3282  * DATABASE in that context.)
3283  */
3284  resetPQExpBuffer(creaQry);
3285  resetPQExpBuffer(delQry);
3286 
3287  if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
3288  appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
3289  qdatname, datconnlimit);
3290 
3291  if (strcmp(datistemplate, "t") == 0)
3292  {
3293  appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
3294  qdatname);
3295 
3296  /*
3297  * The backend won't accept DROP DATABASE on a template database. We
3298  * can deal with that by removing the template marking before the DROP
3299  * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
3300  * since no such command is currently supported, fake it with a direct
3301  * UPDATE on pg_database.
3302  */
3303  appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
3304  "SET datistemplate = false WHERE datname = ");
3305  appendStringLiteralAH(delQry, datname, fout);
3306  appendPQExpBufferStr(delQry, ";\n");
3307  }
3308 
3309  /*
3310  * We do not restore pg_database.dathasloginevt because it is set
3311  * automatically on login event trigger creation.
3312  */
3313 
3314  /* Add database-specific SET options */
3315  dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
3316 
3317  /*
3318  * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
3319  * entry, too, for lack of a better place.
3320  */
3321  if (dopt->binary_upgrade)
3322  {
3323  appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
3324  appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
3325  "SET datfrozenxid = '%u', datminmxid = '%u'\n"
3326  "WHERE datname = ",
3327  frozenxid, minmxid);
3328  appendStringLiteralAH(creaQry, datname, fout);
3329  appendPQExpBufferStr(creaQry, ";\n");
3330  }
3331 
3332  if (creaQry->len > 0)
3334  ARCHIVE_OPTS(.tag = datname,
3335  .owner = dba,
3336  .description = "DATABASE PROPERTIES",
3337  .section = SECTION_PRE_DATA,
3338  .createStmt = creaQry->data,
3339  .dropStmt = delQry->data,
3340  .deps = &dbDumpId));
3341 
3342  /*
3343  * pg_largeobject comes from the old system intact, so set its
3344  * relfrozenxids, relminmxids and relfilenode.
3345  */
3346  if (dopt->binary_upgrade)
3347  {
3348  PGresult *lo_res;
3349  PQExpBuffer loFrozenQry = createPQExpBuffer();
3350  PQExpBuffer loOutQry = createPQExpBuffer();
3351  PQExpBuffer loHorizonQry = createPQExpBuffer();
3352  int ii_relfrozenxid,
3353  ii_relfilenode,
3354  ii_oid,
3355  ii_relminmxid;
3356 
3357  /*
3358  * pg_largeobject
3359  */
3360  if (fout->remoteVersion >= 90300)
3361  appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid, relfilenode, oid\n"
3362  "FROM pg_catalog.pg_class\n"
3363  "WHERE oid IN (%u, %u);\n",
3364  LargeObjectRelationId, LargeObjectLOidPNIndexId);
3365  else
3366  appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid, relfilenode, oid\n"
3367  "FROM pg_catalog.pg_class\n"
3368  "WHERE oid IN (%u, %u);\n",
3369  LargeObjectRelationId, LargeObjectLOidPNIndexId);
3370 
3371  lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
3372 
3373  ii_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
3374  ii_relminmxid = PQfnumber(lo_res, "relminmxid");
3375  ii_relfilenode = PQfnumber(lo_res, "relfilenode");
3376  ii_oid = PQfnumber(lo_res, "oid");
3377 
3378  appendPQExpBufferStr(loHorizonQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
3379  appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, preserve pg_largeobject and index relfilenodes\n");
3380  for (int i = 0; i < PQntuples(lo_res); ++i)
3381  {
3382  Oid oid;
3383  RelFileNumber relfilenumber;
3384 
3385  appendPQExpBuffer(loHorizonQry, "UPDATE pg_catalog.pg_class\n"
3386  "SET relfrozenxid = '%u', relminmxid = '%u'\n"
3387  "WHERE oid = %u;\n",
3388  atooid(PQgetvalue(lo_res, i, ii_relfrozenxid)),
3389  atooid(PQgetvalue(lo_res, i, ii_relminmxid)),
3390  atooid(PQgetvalue(lo_res, i, ii_oid)));
3391 
3392  oid = atooid(PQgetvalue(lo_res, i, ii_oid));
3393  relfilenumber = atooid(PQgetvalue(lo_res, i, ii_relfilenode));
3394 
3395  if (oid == LargeObjectRelationId)
3396  appendPQExpBuffer(loOutQry,
3397  "SELECT pg_catalog.binary_upgrade_set_next_heap_relfilenode('%u'::pg_catalog.oid);\n",
3398  relfilenumber);
3399  else if (oid == LargeObjectLOidPNIndexId)
3400  appendPQExpBuffer(loOutQry,
3401  "SELECT pg_catalog.binary_upgrade_set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
3402  relfilenumber);
3403  }
3404 
3405  appendPQExpBufferStr(loOutQry,
3406  "TRUNCATE pg_catalog.pg_largeobject;\n");
3407  appendPQExpBufferStr(loOutQry, loHorizonQry->data);
3408 
3410  ARCHIVE_OPTS(.tag = "pg_largeobject",
3411  .description = "pg_largeobject",
3412  .section = SECTION_PRE_DATA,
3413  .createStmt = loOutQry->data));
3414 
3415  PQclear(lo_res);
3416 
3417  destroyPQExpBuffer(loFrozenQry);
3418  destroyPQExpBuffer(loHorizonQry);
3419  destroyPQExpBuffer(loOutQry);
3420  }
3421 
3422  PQclear(res);
3423 
3424  free(qdatname);
3425  destroyPQExpBuffer(dbQry);
3426  destroyPQExpBuffer(delQry);
3427  destroyPQExpBuffer(creaQry);
3428  destroyPQExpBuffer(labelq);
3429 }
3430 
3431 /*
3432  * Collect any database-specific or role-and-database-specific SET options
3433  * for this database, and append them to outbuf.
3434  */
3435 static void
3437  const char *dbname, Oid dboid)
3438 {
3439  PGconn *conn = GetConnection(AH);
3441  PGresult *res;
3442 
3443  /* First collect database-specific options */
3444  printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
3445  "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3446  dboid);
3447 
3448  res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3449 
3450  for (int i = 0; i < PQntuples(res); i++)
3452  "DATABASE", dbname, NULL, NULL,
3453  outbuf);
3454 
3455  PQclear(res);
3456 
3457  /* Now look for role-and-database-specific options */
3458  printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3459  "FROM pg_db_role_setting s, pg_roles r "
3460  "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3461  dboid);
3462 
3463  res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3464 
3465  for (int i = 0; i < PQntuples(res); i++)
3467  "ROLE", PQgetvalue(res, i, 0),
3468  "DATABASE", dbname,
3469  outbuf);
3470 
3471  PQclear(res);
3472 
3474 }
3475 
3476 /*
3477  * dumpEncoding: put the correct encoding into the archive
3478  */
3479 static void
3481 {
3482  const char *encname = pg_encoding_to_char(AH->encoding);
3484 
3485  pg_log_info("saving encoding = %s", encname);
3486 
3487  appendPQExpBufferStr(qry, "SET client_encoding = ");
3488  appendStringLiteralAH(qry, encname, AH);
3489  appendPQExpBufferStr(qry, ";\n");
3490 
3492  ARCHIVE_OPTS(.tag = "ENCODING",
3493  .description = "ENCODING",
3494  .section = SECTION_PRE_DATA,
3495  .createStmt = qry->data));
3496 
3497  destroyPQExpBuffer(qry);
3498 }
3499 
3500 
3501 /*
3502  * dumpStdStrings: put the correct escape string behavior into the archive
3503  */
3504 static void
3506 {
3507  const char *stdstrings = AH->std_strings ? "on" : "off";
3509 
3510  pg_log_info("saving standard_conforming_strings = %s",
3511  stdstrings);
3512 
3513  appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3514  stdstrings);
3515 
3517  ARCHIVE_OPTS(.tag = "STDSTRINGS",
3518  .description = "STDSTRINGS",
3519  .section = SECTION_PRE_DATA,
3520  .createStmt = qry->data));
3521 
3522  destroyPQExpBuffer(qry);
3523 }
3524 
3525 /*
3526  * dumpSearchPath: record the active search_path in the archive
3527  */
3528 static void
3530 {
3532  PQExpBuffer path = createPQExpBuffer();
3533  PGresult *res;
3534  char **schemanames = NULL;
3535  int nschemanames = 0;
3536  int i;
3537 
3538  /*
3539  * We use the result of current_schemas(), not the search_path GUC,
3540  * because that might contain wildcards such as "$user", which won't
3541  * necessarily have the same value during restore. Also, this way avoids
3542  * listing schemas that may appear in search_path but not actually exist,
3543  * which seems like a prudent exclusion.
3544  */
3546  "SELECT pg_catalog.current_schemas(false)");
3547 
3548  if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3549  pg_fatal("could not parse result of current_schemas()");
3550 
3551  /*
3552  * We use set_config(), not a simple "SET search_path" command, because
3553  * the latter has less-clean behavior if the search path is empty. While
3554  * that's likely to get fixed at some point, it seems like a good idea to
3555  * be as backwards-compatible as possible in what we put into archives.
3556  */
3557  for (i = 0; i < nschemanames; i++)
3558  {
3559  if (i > 0)
3560  appendPQExpBufferStr(path, ", ");
3561  appendPQExpBufferStr(path, fmtId(schemanames[i]));
3562  }
3563 
3564  appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3565  appendStringLiteralAH(qry, path->data, AH);
3566  appendPQExpBufferStr(qry, ", false);\n");
3567 
3568  pg_log_info("saving search_path = %s", path->data);
3569 
3571  ARCHIVE_OPTS(.tag = "SEARCHPATH",
3572  .description = "SEARCHPATH",
3573  .section = SECTION_PRE_DATA,
3574  .createStmt = qry->data));
3575 
3576  /* Also save it in AH->searchpath, in case we're doing plain text dump */
3577  AH->searchpath = pg_strdup(qry->data);
3578 
3579  free(schemanames);
3580  PQclear(res);
3581  destroyPQExpBuffer(qry);
3582  destroyPQExpBuffer(path);
3583 }
3584 
3585 
3586 /*
3587  * getLOs:
3588  * Collect schema-level data about large objects
3589  */
3590 static void
3592 {
3593  DumpOptions *dopt = fout->dopt;
3594  PQExpBuffer loQry = createPQExpBuffer();
3595  LoInfo *loinfo;
3596  DumpableObject *lodata;
3597  PGresult *res;
3598  int ntups;
3599  int i;
3600  int i_oid;
3601  int i_lomowner;
3602  int i_lomacl;
3603  int i_acldefault;
3604 
3605  pg_log_info("reading large objects");
3606 
3607  /* Fetch LO OIDs, and owner/ACL data */
3608  appendPQExpBufferStr(loQry,
3609  "SELECT oid, lomowner, lomacl, "
3610  "acldefault('L', lomowner) AS acldefault "
3611  "FROM pg_largeobject_metadata");
3612 
3613  res = ExecuteSqlQuery(fout, loQry->data, PGRES_TUPLES_OK);
3614 
3615  i_oid = PQfnumber(res, "oid");
3616  i_lomowner = PQfnumber(res, "lomowner");
3617  i_lomacl = PQfnumber(res, "lomacl");
3618  i_acldefault = PQfnumber(res, "acldefault");
3619 
3620  ntups = PQntuples(res);
3621 
3622  /*
3623  * Each large object has its own "BLOB" archive entry.
3624  */
3625  loinfo = (LoInfo *) pg_malloc(ntups * sizeof(LoInfo));
3626 
3627  for (i = 0; i < ntups; i++)
3628  {
3629  loinfo[i].dobj.objType = DO_LARGE_OBJECT;
3630  loinfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3631  loinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3632  AssignDumpId(&loinfo[i].dobj);
3633 
3634  loinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3635  loinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3636  loinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
3637  loinfo[i].dacl.privtype = 0;
3638  loinfo[i].dacl.initprivs = NULL;
3639  loinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_lomowner));
3640 
3641  /* LOs have data */
3642  loinfo[i].dobj.components |= DUMP_COMPONENT_DATA;
3643 
3644  /* Mark whether LO has an ACL */
3645  if (!PQgetisnull(res, i, i_lomacl))
3646  loinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
3647 
3648  /*
3649  * In binary-upgrade mode for LOs, we do *not* dump out the LO data,
3650  * as it will be copied by pg_upgrade, which simply copies the
3651  * pg_largeobject table. We *do* however dump out anything but the
3652  * data, as pg_upgrade copies just pg_largeobject, but not
3653  * pg_largeobject_metadata, after the dump is restored.
3654  */
3655  if (dopt->binary_upgrade)
3656  loinfo[i].dobj.dump &= ~DUMP_COMPONENT_DATA;
3657  }
3658 
3659  /*
3660  * If we have any large objects, a "BLOBS" archive entry is needed. This
3661  * is just a placeholder for sorting; it carries no data now.
3662  */
3663  if (ntups > 0)
3664  {
3665  lodata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3666  lodata->objType = DO_LARGE_OBJECT_DATA;
3667  lodata->catId = nilCatalogId;
3668  AssignDumpId(lodata);
3669  lodata->name = pg_strdup("BLOBS");
3670  lodata->components |= DUMP_COMPONENT_DATA;
3671  }
3672 
3673  PQclear(res);
3674  destroyPQExpBuffer(loQry);
3675 }
3676 
3677 /*
3678  * dumpLO
3679  *
3680  * dump the definition (metadata) of the given large object
3681  */
3682 static void
3683 dumpLO(Archive *fout, const LoInfo *loinfo)
3684 {
3685  PQExpBuffer cquery = createPQExpBuffer();
3686  PQExpBuffer dquery = createPQExpBuffer();
3687 
3688  appendPQExpBuffer(cquery,
3689  "SELECT pg_catalog.lo_create('%s');\n",
3690  loinfo->dobj.name);
3691 
3692  appendPQExpBuffer(dquery,
3693  "SELECT pg_catalog.lo_unlink('%s');\n",
3694  loinfo->dobj.name);
3695 
3696  if (loinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3697  ArchiveEntry(fout, loinfo->dobj.catId, loinfo->dobj.dumpId,
3698  ARCHIVE_OPTS(.tag = loinfo->dobj.name,
3699  .owner = loinfo->rolname,
3700  .description = "BLOB",
3701  .section = SECTION_PRE_DATA,
3702  .createStmt = cquery->data,
3703  .dropStmt = dquery->data));
3704 
3705  /* Dump comment if any */
3706  if (loinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3707  dumpComment(fout, "LARGE OBJECT", loinfo->dobj.name,
3708  NULL, loinfo->rolname,
3709  loinfo->dobj.catId, 0, loinfo->dobj.dumpId);
3710 
3711  /* Dump security label if any */
3712  if (loinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3713  dumpSecLabel(fout, "LARGE OBJECT", loinfo->dobj.name,
3714  NULL, loinfo->rolname,
3715  loinfo->dobj.catId, 0, loinfo->dobj.dumpId);
3716 
3717  /* Dump ACL if any */
3718  if (loinfo->dobj.dump & DUMP_COMPONENT_ACL)
3719  dumpACL(fout, loinfo->dobj.dumpId, InvalidDumpId, "LARGE OBJECT",
3720  loinfo->dobj.name, NULL,
3721  NULL, loinfo->rolname, &loinfo->dacl);
3722 
3723  destroyPQExpBuffer(cquery);
3724  destroyPQExpBuffer(dquery);
3725 }
3726 
3727 /*
3728  * dumpLOs:
3729  * dump the data contents of all large objects
3730  */
3731 static int
3732 dumpLOs(Archive *fout, const void *arg)
3733 {
3734  const char *loQry;
3735  const char *loFetchQry;
3736  PGconn *conn = GetConnection(fout);
3737  PGresult *res;
3738  char buf[LOBBUFSIZE];
3739  int ntups;
3740  int i;
3741  int cnt;
3742 
3743  pg_log_info("saving large objects");
3744 
3745  /*
3746  * Currently, we re-fetch all LO OIDs using a cursor. Consider scanning
3747  * the already-in-memory dumpable objects instead...
3748  */
3749  loQry =
3750  "DECLARE looid CURSOR FOR "
3751  "SELECT oid FROM pg_largeobject_metadata ORDER BY 1";
3752 
3753  ExecuteSqlStatement(fout, loQry);
3754 
3755  /* Command to fetch from cursor */
3756  loFetchQry = "FETCH 1000 IN looid";
3757 
3758  do
3759  {
3760  /* Do a fetch */
3761  res = ExecuteSqlQuery(fout, loFetchQry, PGRES_TUPLES_OK);
3762 
3763  /* Process the tuples, if any */
3764  ntups = PQntuples(res);
3765  for (i = 0; i < ntups; i++)
3766  {
3767  Oid loOid;
3768  int loFd;
3769 
3770  loOid = atooid(PQgetvalue(res, i, 0));
3771  /* Open the LO */
3772  loFd = lo_open(conn, loOid, INV_READ);
3773  if (loFd == -1)
3774  pg_fatal("could not open large object %u: %s",
3775  loOid, PQerrorMessage(conn));
3776 
3777  StartLO(fout, loOid);
3778 
3779  /* Now read it in chunks, sending data to archive */
3780  do
3781  {
3782  cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3783  if (cnt < 0)
3784  pg_fatal("error reading large object %u: %s",
3785  loOid, PQerrorMessage(conn));
3786 
3787  WriteData(fout, buf, cnt);
3788  } while (cnt > 0);
3789 
3790  lo_close(conn, loFd);
3791 
3792  EndLO(fout, loOid);
3793  }
3794 
3795  PQclear(res);
3796  } while (ntups > 0);
3797 
3798  return 1;
3799 }
3800 
3801 /*
3802  * getPolicies
3803  * get information about all RLS policies on dumpable tables.
3804  */
3805 void
3806 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3807 {
3808  PQExpBuffer query;
3809  PQExpBuffer tbloids;
3810  PGresult *res;
3811  PolicyInfo *polinfo;
3812  int i_oid;
3813  int i_tableoid;
3814  int i_polrelid;
3815  int i_polname;
3816  int i_polcmd;
3817  int i_polpermissive;
3818  int i_polroles;
3819  int i_polqual;
3820  int i_polwithcheck;
3821  int i,
3822  j,
3823  ntups;
3824 
3825  /* No policies before 9.5 */
3826  if (fout->remoteVersion < 90500)
3827  return;
3828 
3829  query = createPQExpBuffer();
3830  tbloids = createPQExpBuffer();
3831 
3832  /*
3833  * Identify tables of interest, and check which ones have RLS enabled.
3834  */
3835  appendPQExpBufferChar(tbloids, '{');
3836  for (i = 0; i < numTables; i++)
3837  {
3838  TableInfo *tbinfo = &tblinfo[i];
3839 
3840  /* Ignore row security on tables not to be dumped */
3841  if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3842  continue;
3843 
3844  /* It can't have RLS or policies if it's not a table */
3845  if (tbinfo->relkind != RELKIND_RELATION &&
3846  tbinfo->relkind != RELKIND_PARTITIONED_TABLE)
3847  continue;
3848 
3849  /* Add it to the list of table OIDs to be probed below */
3850  if (tbloids->len > 1) /* do we have more than the '{'? */
3851  appendPQExpBufferChar(tbloids, ',');
3852  appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
3853 
3854  /* Is RLS enabled? (That's separate from whether it has policies) */
3855  if (tbinfo->rowsec)
3856  {
3858 
3859  /*
3860  * We represent RLS being enabled on a table by creating a
3861  * PolicyInfo object with null polname.
3862  *
3863  * Note: use tableoid 0 so that this object won't be mistaken for
3864  * something that pg_depend entries apply to.
3865  */
3866  polinfo = pg_malloc(sizeof(PolicyInfo));
3867  polinfo->dobj.objType = DO_POLICY;
3868  polinfo->dobj.catId.tableoid = 0;
3869  polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3870  AssignDumpId(&polinfo->dobj);
3871  polinfo->dobj.namespace = tbinfo->dobj.namespace;
3872  polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3873  polinfo->poltable = tbinfo;
3874  polinfo->polname = NULL;
3875  polinfo->polcmd = '\0';
3876  polinfo->polpermissive = 0;
3877  polinfo->polroles = NULL;
3878  polinfo->polqual = NULL;
3879  polinfo->polwithcheck = NULL;
3880  }
3881  }
3882  appendPQExpBufferChar(tbloids, '}');
3883 
3884  /*
3885  * Now, read all RLS policies belonging to the tables of interest, and
3886  * create PolicyInfo objects for them. (Note that we must filter the
3887  * results server-side not locally, because we dare not apply pg_get_expr
3888  * to tables we don't have lock on.)
3889  */
3890  pg_log_info("reading row-level security policies");
3891 
3892  printfPQExpBuffer(query,
3893  "SELECT pol.oid, pol.tableoid, pol.polrelid, pol.polname, pol.polcmd, ");
3894  if (fout->remoteVersion >= 100000)
3895  appendPQExpBufferStr(query, "pol.polpermissive, ");
3896  else
3897  appendPQExpBufferStr(query, "'t' as polpermissive, ");
3898  appendPQExpBuffer(query,
3899  "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3900  " 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, "
3901  "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3902  "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3903  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
3904  "JOIN pg_catalog.pg_policy pol ON (src.tbloid = pol.polrelid)",
3905  tbloids->data);
3906 
3907  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3908 
3909  ntups = PQntuples(res);
3910  if (ntups > 0)
3911  {
3912  i_oid = PQfnumber(res, "oid");
3913  i_tableoid = PQfnumber(res, "tableoid");
3914  i_polrelid = PQfnumber(res, "polrelid");
3915  i_polname = PQfnumber(res, "polname");
3916  i_polcmd = PQfnumber(res, "polcmd");
3917  i_polpermissive = PQfnumber(res, "polpermissive");
3918  i_polroles = PQfnumber(res, "polroles");
3919  i_polqual = PQfnumber(res, "polqual");
3920  i_polwithcheck = PQfnumber(res, "polwithcheck");
3921 
3922  polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3923 
3924  for (j = 0; j < ntups; j++)
3925  {
3926  Oid polrelid = atooid(PQgetvalue(res, j, i_polrelid));
3927  TableInfo *tbinfo = findTableByOid(polrelid);
3928 
3930 
3931  polinfo[j].dobj.objType = DO_POLICY;
3932  polinfo[j].dobj.catId.tableoid =
3933  atooid(PQgetvalue(res, j, i_tableoid));
3934  polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3935  AssignDumpId(&polinfo[j].dobj);
3936  polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3937  polinfo[j].poltable = tbinfo;
3938  polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3939  polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3940 
3941  polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3942  polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3943 
3944  if (PQgetisnull(res, j, i_polroles))
3945  polinfo[j].polroles = NULL;
3946  else
3947  polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3948 
3949  if (PQgetisnull(res, j, i_polqual))
3950  polinfo[j].polqual = NULL;
3951  else
3952  polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3953 
3954  if (PQgetisnull(res, j, i_polwithcheck))
3955  polinfo[j].polwithcheck = NULL;
3956  else
3957  polinfo[j].polwithcheck
3958  = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3959  }
3960  }
3961 
3962  PQclear(res);
3963 
3964  destroyPQExpBuffer(query);
3965  destroyPQExpBuffer(tbloids);
3966 }
3967 
3968 /*
3969  * dumpPolicy
3970  * dump the definition of the given policy
3971  */
3972 static void
3973 dumpPolicy(Archive *fout, const PolicyInfo *polinfo)
3974 {
3975  DumpOptions *dopt = fout->dopt;
3976  TableInfo *tbinfo = polinfo->poltable;
3977  PQExpBuffer query;
3978  PQExpBuffer delqry;
3979  PQExpBuffer polprefix;
3980  char *qtabname;
3981  const char *cmd;
3982  char *tag;
3983 
3984  /* Do nothing in data-only dump */
3985  if (dopt->dataOnly)
3986  return;
3987 
3988  /*
3989  * If polname is NULL, then this record is just indicating that ROW LEVEL
3990  * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3991  * ROW LEVEL SECURITY.
3992  */
3993  if (polinfo->polname == NULL)
3994  {
3995  query = createPQExpBuffer();
3996 
3997  appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3998  fmtQualifiedDumpable(tbinfo));
3999 
4000  /*
4001  * We must emit the ROW SECURITY object's dependency on its table
4002  * explicitly, because it will not match anything in pg_depend (unlike
4003  * the case for other PolicyInfo objects).
4004  */
4005  if (polinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4006  ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
4007  ARCHIVE_OPTS(.tag = polinfo->dobj.name,
4008  .namespace = polinfo->dobj.namespace->dobj.name,
4009  .owner = tbinfo->rolname,
4010  .description = "ROW SECURITY",
4011  .section = SECTION_POST_DATA,
4012  .createStmt = query->data,
4013  .deps = &(tbinfo->dobj.dumpId),
4014  .nDeps = 1));
4015 
4016  destroyPQExpBuffer(query);
4017  return;
4018  }
4019 
4020  if (polinfo->polcmd == '*')
4021  cmd = "";
4022  else if (polinfo->polcmd == 'r')
4023  cmd = " FOR SELECT";
4024  else if (polinfo->polcmd == 'a')
4025  cmd = " FOR INSERT";
4026  else if (polinfo->polcmd == 'w')
4027  cmd = " FOR UPDATE";
4028  else if (polinfo->polcmd == 'd')
4029  cmd = " FOR DELETE";
4030  else
4031  pg_fatal("unexpected policy command type: %c",
4032  polinfo->polcmd);
4033 
4034  query = createPQExpBuffer();
4035  delqry = createPQExpBuffer();
4036  polprefix = createPQExpBuffer();
4037 
4038  qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
4039 
4040  appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
4041 
4042  appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
4043  !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
4044 
4045  if (polinfo->polroles != NULL)
4046  appendPQExpBuffer(query, " TO %s", polinfo->polroles);
4047 
4048  if (polinfo->polqual != NULL)
4049  appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
4050 
4051  if (polinfo->polwithcheck != NULL)
4052  appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
4053 
4054  appendPQExpBufferStr(query, ";\n");
4055 
4056  appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
4057  appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
4058 
4059  appendPQExpBuffer(polprefix, "POLICY %s ON",
4060  fmtId(polinfo->polname));
4061 
4062  tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
4063 
4064  if (polinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4065  ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
4066  ARCHIVE_OPTS(.tag = tag,
4067  .namespace = polinfo->dobj.namespace->dobj.name,
4068  .owner = tbinfo->rolname,
4069  .description = "POLICY",
4070  .section = SECTION_POST_DATA,
4071  .createStmt = query->data,
4072  .dropStmt = delqry->data));
4073 
4074  if (polinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4075  dumpComment(fout, polprefix->data, qtabname,
4076  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
4077  polinfo->dobj.catId, 0, polinfo->dobj.dumpId);
4078 
4079  free(tag);
4080  destroyPQExpBuffer(query);
4081  destroyPQExpBuffer(delqry);
4082  destroyPQExpBuffer(polprefix);
4083  free(qtabname);
4084 }
4085 
4086 /*
4087  * getPublications
4088  * get information about publications
4089  */
4091 getPublications(Archive *fout, int *numPublications)
4092 {
4093  DumpOptions *dopt = fout->dopt;
4094  PQExpBuffer query;
4095  PGresult *res;
4096  PublicationInfo *pubinfo;
4097  int i_tableoid;
4098  int i_oid;
4099  int i_pubname;
4100  int i_pubowner;
4101  int i_puballtables;
4102  int i_pubinsert;
4103  int i_pubupdate;
4104  int i_pubdelete;
4105  int i_pubtruncate;
4106  int i_pubviaroot;
4107  int i,
4108  ntups;
4109 
4110  if (dopt->no_publications || fout->remoteVersion < 100000)
4111  {
4112  *numPublications = 0;
4113  return NULL;
4114  }
4115 
4116  query = createPQExpBuffer();
4117 
4118  resetPQExpBuffer(query);
4119 
4120  /* Get the publications. */
4121  if (fout->remoteVersion >= 130000)
4122  appendPQExpBufferStr(query,
4123  "SELECT p.tableoid, p.oid, p.pubname, "
4124  "p.pubowner, "
4125  "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate, p.pubviaroot "
4126  "FROM pg_publication p");
4127  else if (fout->remoteVersion >= 110000)
4128  appendPQExpBufferStr(query,
4129  "SELECT p.tableoid, p.oid, p.pubname, "
4130  "p.pubowner, "
4131  "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate, false AS pubviaroot "
4132  "FROM pg_publication p");
4133  else
4134  appendPQExpBufferStr(query,
4135  "SELECT p.tableoid, p.oid, p.pubname, "
4136  "p.pubowner, "
4137  "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate, false AS pubviaroot "
4138  "FROM pg_publication p");
4139 
4140  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4141 
4142  ntups = PQntuples(res);
4143 
4144  i_tableoid = PQfnumber(res, "tableoid");
4145  i_oid = PQfnumber(res, "oid");
4146  i_pubname = PQfnumber(res, "pubname");
4147  i_pubowner = PQfnumber(res, "pubowner");
4148  i_puballtables = PQfnumber(res, "puballtables");
4149  i_pubinsert = PQfnumber(res, "pubinsert");
4150  i_pubupdate = PQfnumber(res, "pubupdate");
4151  i_pubdelete = PQfnumber(res, "pubdelete");
4152  i_pubtruncate = PQfnumber(res, "pubtruncate");
4153  i_pubviaroot = PQfnumber(res, "pubviaroot");
4154 
4155  pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
4156 
4157  for (i = 0; i < ntups; i++)
4158  {
4159  pubinfo[i].dobj.objType = DO_PUBLICATION;
4160  pubinfo[i].dobj.catId.tableoid =
4161  atooid(PQgetvalue(res, i, i_tableoid));
4162  pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4163  AssignDumpId(&pubinfo[i].dobj);
4164  pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
4165  pubinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_pubowner));
4166  pubinfo[i].puballtables =
4167  (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
4168  pubinfo[i].pubinsert =
4169  (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
4170  pubinfo[i].pubupdate =
4171  (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
4172  pubinfo[i].pubdelete =
4173  (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
4174  pubinfo[i].pubtruncate =
4175  (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
4176  pubinfo[i].pubviaroot =
4177  (strcmp(PQgetvalue(res, i, i_pubviaroot), "t") == 0);
4178 
4179  /* Decide whether we want to dump it */
4180  selectDumpableObject(&(pubinfo[i].dobj), fout);
4181  }
4182  PQclear(res);
4183 
4184  destroyPQExpBuffer(query);
4185 
4186  *numPublications = ntups;
4187  return pubinfo;
4188 }
4189 
4190 /*
4191  * dumpPublication
4192  * dump the definition of the given publication
4193  */
4194 static void
4196 {
4197  DumpOptions *dopt = fout->dopt;
4198  PQExpBuffer delq;
4199  PQExpBuffer query;
4200  char *qpubname;
4201  bool first = true;
4202 
4203  /* Do nothing in data-only dump */
4204  if (dopt->dataOnly)
4205  return;
4206 
4207  delq = createPQExpBuffer();
4208  query = createPQExpBuffer();
4209 
4210  qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
4211 
4212  appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
4213  qpubname);
4214 
4215  appendPQExpBuffer(query, "CREATE PUBLICATION %s",
4216  qpubname);
4217 
4218  if (pubinfo->puballtables)
4219  appendPQExpBufferStr(query, " FOR ALL TABLES");
4220 
4221  appendPQExpBufferStr(query, " WITH (publish = '");
4222  if (pubinfo->pubinsert)
4223  {
4224  appendPQExpBufferStr(query, "insert");
4225  first = false;
4226  }
4227 
4228  if (pubinfo->pubupdate)
4229  {
4230  if (!first)
4231  appendPQExpBufferStr(query, ", ");
4232 
4233  appendPQExpBufferStr(query, "update");
4234  first = false;
4235  }
4236 
4237  if (pubinfo->pubdelete)
4238  {
4239  if (!first)
4240  appendPQExpBufferStr(query, ", ");
4241 
4242  appendPQExpBufferStr(query, "delete");
4243  first = false;
4244  }
4245 
4246  if (pubinfo->pubtruncate)
4247  {
4248  if (!first)
4249  appendPQExpBufferStr(query, ", ");
4250 
4251  appendPQExpBufferStr(query, "truncate");
4252  first = false;
4253  }
4254 
4255  appendPQExpBufferChar(query, '\'');
4256 
4257  if (pubinfo->pubviaroot)
4258  appendPQExpBufferStr(query, ", publish_via_partition_root = true");
4259 
4260  appendPQExpBufferStr(query, ");\n");
4261 
4262  if (pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4263  ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
4264  ARCHIVE_OPTS(.tag = pubinfo->dobj.name,
4265  .owner = pubinfo->rolname,
4266  .description = "PUBLICATION",
4267  .section = SECTION_POST_DATA,
4268  .createStmt = query->data,
4269  .dropStmt = delq->data));
4270 
4271  if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4272  dumpComment(fout, "PUBLICATION", qpubname,
4273  NULL, pubinfo->rolname,
4274  pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
4275 
4276  if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4277  dumpSecLabel(fout, "PUBLICATION", qpubname,
4278  NULL, pubinfo->rolname,
4279  pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
4280 
4281  destroyPQExpBuffer(delq);
4282  destroyPQExpBuffer(query);
4283  free(qpubname);
4284 }
4285 
4286 /*
4287  * getPublicationNamespaces
4288  * get information about publication membership for dumpable schemas.
4289  */
4290 void
4292 {
4293  PQExpBuffer query;
4294  PGresult *res;
4295  PublicationSchemaInfo *pubsinfo;
4296  DumpOptions *dopt = fout->dopt;
4297  int i_tableoid;
4298  int i_oid;
4299  int i_pnpubid;
4300  int i_pnnspid;
4301  int i,
4302  j,
4303  ntups;
4304 
4305  if (dopt->no_publications || fout->remoteVersion < 150000)
4306  return;
4307 
4308  query = createPQExpBuffer();
4309 
4310  /* Collect all publication membership info. */
4311  appendPQExpBufferStr(query,
4312  "SELECT tableoid, oid, pnpubid, pnnspid "
4313  "FROM pg_catalog.pg_publication_namespace");
4314  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4315 
4316  ntups = PQntuples(res);
4317 
4318  i_tableoid = PQfnumber(res, "tableoid");
4319  i_oid = PQfnumber(res, "oid");
4320  i_pnpubid = PQfnumber(res, "pnpubid");
4321  i_pnnspid = PQfnumber(res, "pnnspid");
4322 
4323  /* this allocation may be more than we need */
4324  pubsinfo = pg_malloc(ntups * sizeof(PublicationSchemaInfo));
4325  j = 0;
4326 
4327  for (i = 0; i < ntups; i++)
4328  {
4329  Oid pnpubid = atooid(PQgetvalue(res, i, i_pnpubid));
4330  Oid pnnspid = atooid(PQgetvalue(res, i, i_pnnspid));
4331  PublicationInfo *pubinfo;
4332  NamespaceInfo *nspinfo;
4333 
4334  /*
4335  * Ignore any entries for which we aren't interested in either the
4336  * publication or the rel.
4337  */
4338  pubinfo = findPublicationByOid(pnpubid);
4339  if (pubinfo == NULL)
4340  continue;
4341  nspinfo = findNamespaceByOid(pnnspid);
4342  if (nspinfo == NULL)
4343  continue;
4344 
4345  /*
4346  * We always dump publication namespaces unless the corresponding
4347  * namespace is excluded from the dump.
4348  */
4349  if (nspinfo->dobj.dump == DUMP_COMPONENT_NONE)
4350  continue;
4351 
4352  /* OK, make a DumpableObject for this relationship */
4354  pubsinfo[j].dobj.catId.tableoid =
4355  atooid(PQgetvalue(res, i, i_tableoid));
4356  pubsinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4357  AssignDumpId(&pubsinfo[j].dobj);
4358  pubsinfo[j].dobj.namespace = nspinfo->dobj.namespace;
4359  pubsinfo[j].dobj.name = nspinfo->dobj.name;
4360  pubsinfo[j].publication = pubinfo;
4361  pubsinfo[j].pubschema = nspinfo;
4362 
4363  /* Decide whether we want to dump it */
4364  selectDumpablePublicationObject(&(pubsinfo[j].dobj), fout);
4365 
4366  j++;
4367  }
4368 
4369  PQclear(res);
4370  destroyPQExpBuffer(query);
4371 }
4372 
4373 /*
4374  * getPublicationTables
4375  * get information about publication membership for dumpable tables.
4376  */
4377 void
4378 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
4379 {
4380  PQExpBuffer query;
4381  PGresult *res;
4382  PublicationRelInfo *pubrinfo;
4383  DumpOptions *dopt = fout->dopt;
4384  int i_tableoid;
4385  int i_oid;
4386  int i_prpubid;
4387  int i_prrelid;
4388  int i_prrelqual;
4389  int i_prattrs;
4390  int i,
4391  j,
4392  ntups;
4393 
4394  if (dopt->no_publications || fout->remoteVersion < 100000)
4395  return;
4396 
4397  query = createPQExpBuffer();
4398 
4399  /* Collect all publication membership info. */
4400  if (fout->remoteVersion >= 150000)
4401  appendPQExpBufferStr(query,
4402  "SELECT tableoid, oid, prpubid, prrelid, "
4403  "pg_catalog.pg_get_expr(prqual, prrelid) AS prrelqual, "
4404  "(CASE\n"
4405  " WHEN pr.prattrs IS NOT NULL THEN\n"
4406  " (SELECT array_agg(attname)\n"
4407  " FROM\n"
4408  " pg_catalog.generate_series(0, pg_catalog.array_upper(pr.prattrs::pg_catalog.int2[], 1)) s,\n"
4409  " pg_catalog.pg_attribute\n"
4410  " WHERE attrelid = pr.prrelid AND attnum = prattrs[s])\n"
4411  " ELSE NULL END) prattrs "
4412  "FROM pg_catalog.pg_publication_rel pr");
4413  else
4414  appendPQExpBufferStr(query,
4415  "SELECT tableoid, oid, prpubid, prrelid, "
4416  "NULL AS prrelqual, NULL AS prattrs "
4417  "FROM pg_catalog.pg_publication_rel");
4418  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4419 
4420  ntups = PQntuples(res);
4421 
4422  i_tableoid = PQfnumber(res, "tableoid");
4423  i_oid = PQfnumber(res, "oid");
4424  i_prpubid = PQfnumber(res, "prpubid");
4425  i_prrelid = PQfnumber(res, "prrelid");
4426  i_prrelqual = PQfnumber(res, "prrelqual");
4427  i_prattrs = PQfnumber(res, "prattrs");
4428 
4429  /* this allocation may be more than we need */
4430  pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
4431  j = 0;
4432 
4433  for (i = 0; i < ntups; i++)
4434  {
4435  Oid prpubid = atooid(PQgetvalue(res, i, i_prpubid));
4436  Oid prrelid = atooid(PQgetvalue(res, i, i_prrelid));
4437  PublicationInfo *pubinfo;
4438  TableInfo *tbinfo;
4439 
4440  /*
4441  * Ignore any entries for which we aren't interested in either the
4442  * publication or the rel.
4443  */
4444  pubinfo = findPublicationByOid(prpubid);
4445  if (pubinfo == NULL)
4446  continue;
4447  tbinfo = findTableByOid(prrelid);
4448  if (tbinfo == NULL)
4449  continue;
4450 
4451  /*
4452  * Ignore publication membership of tables whose definitions are not
4453  * to be dumped.
4454  */
4455  if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4456  continue;
4457 
4458  /* OK, make a DumpableObject for this relationship */
4459  pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
4460  pubrinfo[j].dobj.catId.tableoid =
4461  atooid(PQgetvalue(res, i, i_tableoid));
4462  pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4463  AssignDumpId(&pubrinfo[j].dobj);
4464  pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4465  pubrinfo[j].dobj.name = tbinfo->dobj.name;
4466  pubrinfo[j].publication = pubinfo;
4467  pubrinfo[j].pubtable = tbinfo;
4468  if (PQgetisnull(res, i, i_prrelqual))
4469  pubrinfo[j].pubrelqual = NULL;
4470  else
4471  pubrinfo[j].pubrelqual = pg_strdup(PQgetvalue(res, i, i_prrelqual));
4472 
4473  if (!PQgetisnull(res, i, i_prattrs))
4474  {
4475  char **attnames;
4476  int nattnames;
4477  PQExpBuffer attribs;
4478 
4479  if (!parsePGArray(PQgetvalue(res, i, i_prattrs),
4480  &attnames, &nattnames))
4481  pg_fatal("could not parse %s array", "prattrs");
4482  attribs = createPQExpBuffer();
4483  for (int k = 0; k < nattnames; k++)
4484  {
4485  if (k > 0)
4486  appendPQExpBufferStr(attribs, ", ");
4487 
4488  appendPQExpBufferStr(attribs, fmtId(attnames[k]));
4489  }
4490  pubrinfo[j].pubrattrs = attribs->data;
4491  }
4492  else
4493  pubrinfo[j].pubrattrs = NULL;
4494 
4495  /* Decide whether we want to dump it */
4496  selectDumpablePublicationObject(&(pubrinfo[j].dobj), fout);
4497 
4498  j++;
4499  }
4500 
4501  PQclear(res);
4502  destroyPQExpBuffer(query);
4503 }
4504 
4505 /*
4506  * dumpPublicationNamespace
4507  * dump the definition of the given publication schema mapping.
4508  */
4509 static void
4511 {
4512  DumpOptions *dopt = fout->dopt;
4513  NamespaceInfo *schemainfo = pubsinfo->pubschema;
4514  PublicationInfo *pubinfo = pubsinfo->publication;
4515  PQExpBuffer query;
4516  char *tag;
4517 
4518  /* Do nothing in data-only dump */
4519  if (dopt->dataOnly)
4520  return;
4521 
4522  tag = psprintf("%s %s", pubinfo->dobj.name, schemainfo->dobj.name);
4523 
4524  query = createPQExpBuffer();
4525 
4526  appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name));
4527  appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name));
4528 
4529  /*
4530  * There is no point in creating drop query as the drop is done by schema
4531  * drop.
4532  */
4533  if (pubsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4534  ArchiveEntry(fout, pubsinfo->dobj.catId, pubsinfo->dobj.dumpId,
4535  ARCHIVE_OPTS(.tag = tag,
4536  .namespace = schemainfo->dobj.name,
4537  .owner = pubinfo->rolname,
4538  .description = "PUBLICATION TABLES IN SCHEMA",
4539  .section = SECTION_POST_DATA,
4540  .createStmt = query->data));
4541 
4542  /* These objects can't currently have comments or seclabels */
4543 
4544  free(tag);
4545  destroyPQExpBuffer(query);
4546 }
4547 
4548 /*
4549  * dumpPublicationTable
4550  * dump the definition of the given publication table mapping
4551  */
4552 static void
4554 {
4555  DumpOptions *dopt = fout->dopt;
4556  PublicationInfo *pubinfo = pubrinfo->publication;
4557  TableInfo *tbinfo = pubrinfo->pubtable;
4558  PQExpBuffer query;
4559  char *tag;
4560 
4561  /* Do nothing in data-only dump */
4562  if (dopt->dataOnly)
4563  return;
4564 
4565  tag = psprintf("%s %s", pubinfo->dobj.name, tbinfo->dobj.name);
4566 
4567  query = createPQExpBuffer();
4568 
4569  appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
4570  fmtId(pubinfo->dobj.name));
4571  appendPQExpBuffer(query, " %s",
4572  fmtQualifiedDumpable(tbinfo));
4573 
4574  if (pubrinfo->pubrattrs)
4575  appendPQExpBuffer(query, " (%s)", pubrinfo->pubrattrs);
4576 
4577  if (pubrinfo->pubrelqual)
4578  {
4579  /*
4580  * It's necessary to add parentheses around the expression because
4581  * pg_get_expr won't supply the parentheses for things like WHERE
4582  * TRUE.
4583  */
4584  appendPQExpBuffer(query, " WHERE (%s)", pubrinfo->pubrelqual);
4585  }
4586  appendPQExpBufferStr(query, ";\n");
4587 
4588  /*
4589  * There is no point in creating a drop query as the drop is done by table
4590  * drop. (If you think to change this, see also _printTocEntry().)
4591  * Although this object doesn't really have ownership as such, set the
4592  * owner field anyway to ensure that the command is run by the correct
4593  * role at restore time.
4594  */
4595  if (pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4596  ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4597  ARCHIVE_OPTS(.tag = tag,
4598  .namespace = tbinfo->dobj.namespace->dobj.name,
4599  .owner = pubinfo->rolname,
4600  .description = "PUBLICATION TABLE",
4601  .section = SECTION_POST_DATA,
4602  .createStmt = query->data));
4603 
4604  /* These objects can't currently have comments or seclabels */
4605 
4606  free(tag);
4607  destroyPQExpBuffer(query);
4608 }
4609 
4610 /*
4611  * Is the currently connected user a superuser?
4612  */
4613 static bool
4615 {
4616  ArchiveHandle *AH = (ArchiveHandle *) fout;
4617  const char *val;
4618 
4619  val = PQparameterStatus(AH->connection, "is_superuser");
4620 
4621  if (val && strcmp(val, "on") == 0)
4622  return true;
4623 
4624  return false;
4625 }
4626 
4627 /*
4628  * getSubscriptions
4629  * get information about subscriptions
4630  */
4631 void
4633 {
4634  DumpOptions *dopt = fout->dopt;
4635  PQExpBuffer query;
4636  PGresult *res;
4637  SubscriptionInfo *subinfo;
4638  int i_tableoid;
4639  int i_oid;
4640  int i_subname;
4641  int i_subowner;
4642  int i_subbinary;
4643  int i_substream;
4644  int i_subtwophasestate;
4645  int i_subdisableonerr;
4646  int i_subpasswordrequired;
4647  int i_subrunasowner;
4648  int i_subconninfo;
4649  int i_subslotname;
4650  int i_subsynccommit;
4651  int i_subpublications;
4652  int i_suborigin;
4653  int i_suboriginremotelsn;
4654  int i_subenabled;
4655  int i_subfailover;
4656  int i,
4657  ntups;
4658 
4659  if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4660  return;
4661 
4662  if (!is_superuser(fout))
4663  {
4664  int n;
4665 
4666  res = ExecuteSqlQuery(fout,
4667  "SELECT count(*) FROM pg_subscription "
4668  "WHERE subdbid = (SELECT oid FROM pg_database"
4669  " WHERE datname = current_database())",
4670  PGRES_TUPLES_OK);
4671  n = atoi(PQgetvalue(res, 0, 0));
4672  if (n > 0)
4673  pg_log_warning("subscriptions not dumped because current user is not a superuser");
4674  PQclear(res);
4675  return;
4676  }
4677 
4678  query = createPQExpBuffer();
4679 
4680  /* Get the subscriptions in current database. */
4681  appendPQExpBufferStr(query,
4682  "SELECT s.tableoid, s.oid, s.subname,\n"
4683  " s.subowner,\n"
4684  " s.subconninfo, s.subslotname, s.subsynccommit,\n"
4685  " s.subpublications,\n");
4686 
4687  if (fout->remoteVersion >= 140000)
4688  appendPQExpBufferStr(query, " s.subbinary,\n");
4689  else
4690  appendPQExpBufferStr(query, " false AS subbinary,\n");
4691 
4692  if (fout->remoteVersion >= 140000)
4693  appendPQExpBufferStr(query, " s.substream,\n");
4694  else
4695  appendPQExpBufferStr(query, " 'f' AS substream,\n");
4696 
4697  if (fout->remoteVersion >= 150000)
4698  appendPQExpBufferStr(query,
4699  " s.subtwophasestate,\n"
4700  " s.subdisableonerr,\n");
4701  else
4702  appendPQExpBuffer(query,
4703  " '%c' AS subtwophasestate,\n"
4704  " false AS subdisableonerr,\n",
4706 
4707  if (fout->remoteVersion >= 160000)
4708  appendPQExpBufferStr(query,
4709  " s.subpasswordrequired,\n"
4710  " s.subrunasowner,\n"
4711  " s.suborigin,\n");
4712  else
4713  appendPQExpBuffer(query,
4714  " 't' AS subpasswordrequired,\n"
4715  " 't' AS subrunasowner,\n"
4716  " '%s' AS suborigin,\n",
4718 
4719  if (dopt->binary_upgrade && fout->remoteVersion >= 170000)
4720  appendPQExpBufferStr(query, " o.remote_lsn AS suboriginremotelsn,\n"
4721  " s.subenabled,\n"
4722  " s.subfailover\n");
4723  else
4724  appendPQExpBufferStr(query, " NULL AS suboriginremotelsn,\n"
4725  " false AS subenabled,\n"
4726  " false AS subfailover\n");
4727 
4728  appendPQExpBufferStr(query,
4729  "FROM pg_subscription s\n");
4730 
4731  if (dopt->binary_upgrade && fout->remoteVersion >= 170000)
4732  appendPQExpBufferStr(query,
4733  "LEFT JOIN pg_catalog.pg_replication_origin_status o \n"
4734  " ON o.external_id = 'pg_' || s.oid::text \n");
4735 
4736  appendPQExpBufferStr(query,
4737  "WHERE s.subdbid = (SELECT oid FROM pg_database\n"
4738  " WHERE datname = current_database())");
4739 
4740  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4741 
4742  ntups = PQntuples(res);
4743 
4744  /*
4745  * Get subscription fields. We don't include subskiplsn in the dump as
4746  * after restoring the dump this value may no longer be relevant.
4747  */
4748  i_tableoid = PQfnumber(res, "tableoid");
4749  i_oid = PQfnumber(res, "oid");
4750  i_subname = PQfnumber(res, "subname");
4751  i_subowner = PQfnumber(res, "subowner");
4752  i_subbinary = PQfnumber(res, "subbinary");
4753  i_substream = PQfnumber(res, "substream");
4754  i_subtwophasestate = PQfnumber(res, "subtwophasestate");
4755  i_subdisableonerr = PQfnumber(res, "subdisableonerr");
4756  i_subpasswordrequired = PQfnumber(res, "subpasswordrequired");
4757  i_subrunasowner = PQfnumber(res, "subrunasowner");
4758  i_subconninfo = PQfnumber(res, "subconninfo");
4759  i_subslotname = PQfnumber(res, "subslotname");
4760  i_subsynccommit = PQfnumber(res, "subsynccommit");
4761  i_subpublications = PQfnumber(res, "subpublications");
4762  i_suborigin = PQfnumber(res, "suborigin");
4763  i_suboriginremotelsn = PQfnumber(res, "suboriginremotelsn");
4764  i_subenabled = PQfnumber(res, "subenabled");
4765  i_subfailover = PQfnumber(res, "subfailover");
4766 
4767  subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4768 
4769  for (i = 0; i < ntups; i++)
4770  {
4771  subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4772  subinfo[i].dobj.catId.tableoid =
4773  atooid(PQgetvalue(res, i, i_tableoid));
4774  subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4775  AssignDumpId(&subinfo[i].dobj);
4776  subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4777  subinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_subowner));
4778 
4779  subinfo[i].subbinary =
4780  pg_strdup(PQgetvalue(res, i, i_subbinary));
4781  subinfo[i].substream =
4782  pg_strdup(PQgetvalue(res, i, i_substream));
4783  subinfo[i].subtwophasestate =
4784  pg_strdup(PQgetvalue(res, i, i_subtwophasestate));
4785  subinfo[i].subdisableonerr =
4786  pg_strdup(PQgetvalue(res, i, i_subdisableonerr));
4787  subinfo[i].subpasswordrequired =
4788  pg_strdup(PQgetvalue(res, i, i_subpasswordrequired));
4789  subinfo[i].subrunasowner =
4790  pg_strdup(PQgetvalue(res, i, i_subrunasowner));
4791  subinfo[i].subconninfo =
4792  pg_strdup(PQgetvalue(res, i, i_subconninfo));
4793  if (PQgetisnull(res, i, i_subslotname))
4794  subinfo[i].subslotname = NULL;
4795  else
4796  subinfo[i].subslotname =
4797  pg_strdup(PQgetvalue(res, i, i_subslotname));
4798  subinfo[i].subsynccommit =
4799  pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4800  subinfo[i].subpublications =
4801  pg_strdup(PQgetvalue(res, i, i_subpublications));
4802  subinfo[i].suborigin = pg_strdup(PQgetvalue(res, i, i_suborigin));
4803  if (PQgetisnull(res, i, i_suboriginremotelsn))
4804  subinfo[i].suboriginremotelsn = NULL;
4805  else
4806  subinfo[i].suboriginremotelsn =
4807  pg_strdup(PQgetvalue(res, i, i_suboriginremotelsn));
4808  subinfo[i].subenabled =
4809  pg_strdup(PQgetvalue(res, i, i_subenabled));
4810  subinfo[i].subfailover =
4811  pg_strdup(PQgetvalue(res, i, i_subfailover));
4812 
4813  /* Decide whether we want to dump it */
4814  selectDumpableObject(&(subinfo[i].dobj), fout);
4815  }
4816  PQclear(res);
4817 
4818  destroyPQExpBuffer(query);
4819 }
4820 
4821 /*
4822  * getSubscriptionTables
4823  * Get information about subscription membership for dumpable tables. This
4824  * will be used only in binary-upgrade mode for PG17 or later versions.
4825  */
4826 void
4828 {
4829  DumpOptions *dopt = fout->dopt;
4830  SubscriptionInfo *subinfo = NULL;
4831  SubRelInfo *subrinfo;
4832  PGresult *res;
4833  int i_srsubid;
4834  int i_srrelid;
4835  int i_srsubstate;
4836  int i_srsublsn;
4837  int ntups;
4838  Oid last_srsubid = InvalidOid;
4839 
4840  if (dopt->no_subscriptions || !dopt->binary_upgrade ||
4841  fout->remoteVersion < 170000)
4842  return;
4843 
4844  res = ExecuteSqlQuery(fout,
4845  "SELECT srsubid, srrelid, srsubstate, srsublsn "
4846  "FROM pg_catalog.pg_subscription_rel "
4847  "ORDER BY srsubid",
4848  PGRES_TUPLES_OK);
4849  ntups = PQntuples(res);
4850  if (ntups == 0)
4851  goto cleanup;
4852 
4853  /* Get pg_subscription_rel attributes */
4854  i_srsubid = PQfnumber(res, "srsubid");
4855  i_srrelid = PQfnumber(res, "srrelid");
4856  i_srsubstate = PQfnumber(res, "srsubstate");
4857  i_srsublsn = PQfnumber(res, "srsublsn");
4858 
4859  subrinfo = pg_malloc(ntups * sizeof(SubRelInfo));
4860  for (int i = 0; i < ntups; i++)
4861  {
4862  Oid cur_srsubid = atooid(PQgetvalue(res, i, i_srsubid));
4863  Oid relid = atooid(PQgetvalue(res, i, i_srrelid));
4864  TableInfo *tblinfo;
4865 
4866  /*
4867  * If we switched to a new subscription, check if the subscription
4868  * exists.
4869  */
4870  if (cur_srsubid != last_srsubid)
4871  {
4872  subinfo = findSubscriptionByOid(cur_srsubid);
4873  if (subinfo == NULL)
4874  pg_fatal("subscription with OID %u does not exist", cur_srsubid);
4875 
4876  last_srsubid = cur_srsubid;
4877  }
4878 
4879  tblinfo = findTableByOid(relid);
4880  if (tblinfo == NULL)
4881  pg_fatal("failed sanity check, table with OID %u not found",
4882  relid);
4883 
4884  /* OK, make a DumpableObject for this relationship */
4885  subrinfo[i].dobj.objType = DO_SUBSCRIPTION_REL;
4886  subrinfo[i].dobj.catId.tableoid = relid;
4887  subrinfo[i].dobj.catId.oid = cur_srsubid;
4888  AssignDumpId(&subrinfo[i].dobj);
4889  subrinfo[i].dobj.name = pg_strdup(subinfo->dobj.name);
4890  subrinfo[i].tblinfo = tblinfo;
4891  subrinfo[i].srsubstate = PQgetvalue(res, i, i_srsubstate)[0];
4892  if (PQgetisnull(res, i, i_srsublsn))
4893  subrinfo[i].srsublsn = NULL;
4894  else
4895  subrinfo[i].srsublsn = pg_strdup(PQgetvalue(res, i, i_srsublsn));
4896 
4897  subrinfo[i].subinfo = subinfo;
4898 
4899  /* Decide whether we want to dump it */
4900  selectDumpableObject(&(subrinfo[i].dobj), fout);
4901  }
4902 
4903 cleanup:
4904  PQclear(res);
4905 }
4906 
4907 /*
4908  * dumpSubscriptionTable
4909  * Dump the definition of the given subscription table mapping. This will be
4910  * used only in binary-upgrade mode for PG17 or later versions.
4911  */
4912 static void
4914 {
4915  DumpOptions *dopt = fout->dopt;
4916  SubscriptionInfo *subinfo = subrinfo->subinfo;
4917  PQExpBuffer query;
4918  char *tag;
4919 
4920  /* Do nothing in data-only dump */
4921  if (dopt->dataOnly)
4922  return;
4923 
4924  Assert(fout->dopt->binary_upgrade && fout->remoteVersion >= 170000);
4925 
4926  tag = psprintf("%s %s", subinfo->dobj.name, subrinfo->dobj.name);
4927 
4928  query = createPQExpBuffer();
4929 
4930  if (subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4931  {
4932  /*
4933  * binary_upgrade_add_sub_rel_state will add the subscription relation
4934  * to pg_subscription_rel table. This will be used only in
4935  * binary-upgrade mode.
4936  */
4937  appendPQExpBufferStr(query,
4938  "\n-- For binary upgrade, must preserve the subscriber table.\n");
4939  appendPQExpBufferStr(query,
4940  "SELECT pg_catalog.binary_upgrade_add_sub_rel_state(");
4941  appendStringLiteralAH(query, subrinfo->dobj.name, fout);
4942  appendPQExpBuffer(query,
4943  ", %u, '%c'",
4944  subrinfo->tblinfo->dobj.catId.oid,
4945  subrinfo->srsubstate);
4946 
4947  if (subrinfo->srsublsn && subrinfo->srsublsn[0] != '\0')
4948  appendPQExpBuffer(query, ", '%s'", subrinfo->srsublsn);
4949  else
4950  appendPQExpBuffer(query, ", NULL");
4951 
4952  appendPQExpBufferStr(query, ");\n");
4953  }
4954 
4955  /*
4956  * There is no point in creating a drop query as the drop is done by table
4957  * drop. (If you think to change this, see also _printTocEntry().)
4958  * Although this object doesn't really have ownership as such, set the
4959  * owner field anyway to ensure that the command is run by the correct
4960  * role at restore time.
4961  */
4962  if (subrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4963  ArchiveEntry(fout, subrinfo->dobj.catId, subrinfo->dobj.dumpId,
4964  ARCHIVE_OPTS(.tag = tag,
4965  .namespace = subrinfo->tblinfo->dobj.namespace->dobj.name,
4966  .owner = subinfo->rolname,
4967  .description = "SUBSCRIPTION TABLE",
4968  .section = SECTION_POST_DATA,
4969  .createStmt = query->data));
4970 
4971  /* These objects can't currently have comments or seclabels */
4972 
4973  free(tag);
4974  destroyPQExpBuffer(query);
4975 }
4976 
4977 /*
4978  * dumpSubscription
4979  * dump the definition of the given subscription
4980  */
4981 static void
4983 {
4984  DumpOptions *dopt = fout->dopt;
4985  PQExpBuffer delq;
4986  PQExpBuffer query;
4987  PQExpBuffer publications;
4988  char *qsubname;
4989  char **pubnames = NULL;
4990  int npubnames = 0;
4991  int i;
4992  char two_phase_disabled[] = {LOGICALREP_TWOPHASE_STATE_DISABLED, '\0'};
4993 
4994  /* Do nothing in data-only dump */
4995  if (dopt->dataOnly)
4996  return;
4997 
4998  delq = createPQExpBuffer();
4999  query = createPQExpBuffer();
5000 
5001  qsubname = pg_strdup(fmtId(subinfo->dobj.name));
5002 
5003  appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
5004  qsubname);
5005 
5006  appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
5007  qsubname);
5008  appendStringLiteralAH(query, subinfo->subconninfo, fout);
5009 
5010  /* Build list of quoted publications and append them to query. */
5011  if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
5012  pg_fatal("could not parse %s array", "subpublications");
5013 
5014  publications = createPQExpBuffer();
5015  for (i = 0; i < npubnames; i++)
5016  {
5017  if (i > 0)
5018  appendPQExpBufferStr(publications, ", ");
5019 
5020  appendPQExpBufferStr(publications, fmtId(pubnames[i]));
5021  }
5022 
5023  appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
5024  if (subinfo->subslotname)
5025  appendStringLiteralAH(query, subinfo->subslotname, fout);
5026  else
5027  appendPQExpBufferStr(query, "NONE");
5028 
5029  if (strcmp(subinfo->subbinary, "t") == 0)
5030  appendPQExpBufferStr(query, ", binary = true");
5031 
5032  if (strcmp(subinfo->substream, "t") == 0)
5033  appendPQExpBufferStr(query, ", streaming = on");
5034  else if (strcmp(subinfo->substream, "p") == 0)
5035  appendPQExpBufferStr(query, ", streaming = parallel");
5036 
5037  if (strcmp(subinfo->subtwophasestate, two_phase_disabled) != 0)
5038  appendPQExpBufferStr(query, ", two_phase = on");
5039 
5040  if (strcmp(subinfo->subdisableonerr, "t") == 0)
5041  appendPQExpBufferStr(query, ", disable_on_error = true");
5042 
5043  if (strcmp(subinfo->subpasswordrequired, "t") != 0)
5044  appendPQExpBuffer(query, ", password_required = false");
5045 
5046  if (strcmp(subinfo->subrunasowner, "t") == 0)
5047  appendPQExpBufferStr(query, ", run_as_owner = true");
5048 
5049  if (strcmp(subinfo->subsynccommit, "off") != 0)
5050  appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
5051 
5052  if (pg_strcasecmp(subinfo->suborigin, LOGICALREP_ORIGIN_ANY) != 0)
5053  appendPQExpBuffer(query, ", origin = %s", subinfo->suborigin);
5054 
5055  appendPQExpBufferStr(query, ");\n");
5056 
5057  /*
5058  * In binary-upgrade mode, we allow the replication to continue after the
5059  * upgrade.
5060  */
5061  if (dopt->binary_upgrade && fout->remoteVersion >= 170000)
5062  {
5063  if (subinfo->suboriginremotelsn)
5064  {
5065  /*
5066  * Preserve the remote_lsn for the subscriber's replication
5067  * origin. This value is required to start the replication from
5068  * the position before the upgrade. This value will be stale if
5069  * the publisher gets upgraded before the subscriber node.
5070  * However, this shouldn't be a problem as the upgrade of the
5071  * publisher ensures that all the transactions were replicated
5072  * before upgrading it.
5073  */
5074  appendPQExpBufferStr(query,
5075  "\n-- For binary upgrade, must preserve the remote_lsn for the subscriber's replication origin.\n");
5076  appendPQExpBufferStr(query,
5077  "SELECT pg_catalog.binary_upgrade_replorigin_advance(");
5078  appendStringLiteralAH(query, subinfo->dobj.name, fout);
5079  appendPQExpBuffer(query, ", '%s');\n", subinfo->suboriginremotelsn);
5080  }
5081 
5082  if (strcmp(subinfo->subfailover, "t") == 0)
5083  {
5084  /*
5085  * Enable the failover to allow the subscription's slot to be
5086  * synced to the standbys after the upgrade.
5087  */
5088  appendPQExpBufferStr(query,
5089  "\n-- For binary upgrade, must preserve the subscriber's failover option.\n");
5090  appendPQExpBuffer(query, "ALTER SUBSCRIPTION %s SET(failover = true);\n", qsubname);
5091  }
5092 
5093  if (strcmp(subinfo->subenabled, "t") == 0)
5094  {
5095  /*
5096  * Enable the subscription to allow the replication to continue
5097  * after the upgrade.
5098  */
5099  appendPQExpBufferStr(query,
5100  "\n-- For binary upgrade, must preserve the subscriber's running state.\n");
5101  appendPQExpBuffer(query, "ALTER SUBSCRIPTION %s ENABLE;\n", qsubname);
5102  }
5103  }
5104 
5105  if (subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
5106  ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
5107  ARCHIVE_OPTS(.tag = subinfo->dobj.name,
5108  .owner = subinfo->rolname,
5109  .description = "SUBSCRIPTION",
5110  .section = SECTION_POST_DATA,
5111  .createStmt = query->data,
5112  .dropStmt = delq->data));
5113 
5114  if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
5115  dumpComment(fout, "SUBSCRIPTION", qsubname,
5116  NULL, subinfo->rolname,
5117  subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
5118 
5119  if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
5120  dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
5121  NULL, subinfo->rolname,
5122  subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
5123 
5124  destroyPQExpBuffer(publications);
5125  free(pubnames);
5126 
5127  destroyPQExpBuffer(delq);
5128  destroyPQExpBuffer(query);
5129  free(qsubname);
5130 }
5131 
5132 /*
5133  * Given a "create query", append as many ALTER ... DEPENDS ON EXTENSION as
5134  * the object needs.
5135  */
5136 static void
5138  PQExpBuffer create,
5139  const DumpableObject *dobj,
5140  const char *catalog,
5141  const char *keyword,
5142  const char *objname)
5143 {
5144  if (dobj->depends_on_ext)
5145  {
5146  char *nm;
5147  PGresult *res;
5148  PQExpBuffer query;
5149  int ntups;
5150  int i_extname;
5151  int i;
5152 
5153  /* dodge fmtId() non-reentrancy */
5154  nm = pg_strdup(objname);
5155 
5156  query = createPQExpBuffer();
5157  appendPQExpBuffer(query,
5158  "SELECT e.extname "
5159  "FROM pg_catalog.pg_depend d, pg_catalog.pg_extension e "
5160  "WHERE d.refobjid = e.oid AND classid = '%s'::pg_catalog.regclass "
5161  "AND objid = '%u'::pg_catalog.oid AND deptype = 'x' "
5162  "AND refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass",
5163  catalog,
5164  dobj->catId.oid);
5165  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5166  ntups = PQntuples(res);
5167  i_extname = PQfnumber(res, "extname");
5168  for (i = 0; i < ntups; i++)
5169  {
5170  appendPQExpBuffer(create, "\nALTER %s %s DEPENDS ON EXTENSION %s;",
5171  keyword, nm,
5172  fmtId(PQgetvalue(res, i, i_extname)));
5173  }
5174 
5175  PQclear(res);
5176  destroyPQExpBuffer(query);
5177  pg_free(nm);
5178  }
5179 }
5180 
5181 static Oid
5183 {
5184  /*
5185  * If the old version didn't assign an array type, but the new version
5186  * does, we must select an unused type OID to assign. This currently only
5187  * happens for domains, when upgrading pre-v11 to v11 and up.
5188  *
5189  * Note: local state here is kind of ugly, but we must have some, since we
5190  * mustn't choose the same unused OID more than once.
5191  */
5192  static Oid next_possible_free_oid = FirstNormalObjectId;
5193  PGresult *res;
5194  bool is_dup;
5195 
5196  do
5197  {
5198  ++next_possible_free_oid;
5199  printfPQExpBuffer(upgrade_query,
5200  "SELECT EXISTS(SELECT 1 "
5201  "FROM pg_catalog.pg_type "
5202  "WHERE oid = '%u'::pg_catalog.oid);",
5203  next_possible_free_oid);
5204  res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
5205  is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
5206  PQclear(res);
5207  } while (is_dup);
5208 
5209  return next_possible_free_oid;
5210 }
5211 
5212 static void
5214  PQExpBuffer upgrade_buffer,
5215  Oid pg_type_oid,
5216  bool force_array_type,
5217  bool include_multirange_type)
5218 {
5219  PQExpBuffer upgrade_query = createPQExpBuffer();
5220  PGresult *res;
5221  Oid pg_type_array_oid;
5222  Oid pg_type_multirange_oid;
5223  Oid pg_type_multirange_array_oid;
5224 
5225  appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
5226  appendPQExpBuffer(upgrade_buffer,
5227  "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5228  pg_type_oid);
5229 
5230  appendPQExpBuffer(upgrade_query,
5231  "SELECT typarray "
5232  "FROM pg_catalog.pg_type "
5233  "WHERE oid = '%u'::pg_catalog.oid;",
5234  pg_type_oid);
5235 
5236  res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
5237 
5238  pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
5239 
5240  PQclear(res);
5241 
5242  if (!OidIsValid(pg_type_array_oid) && force_array_type)
5243  pg_type_array_oid = get_next_possible_free_pg_type_oid(fout, upgrade_query);
5244 
5245  if (OidIsValid(pg_type_array_oid))
5246  {
5247  appendPQExpBufferStr(upgrade_buffer,
5248  "\n-- For binary upgrade, must preserve pg_type array oid\n");
5249  appendPQExpBuffer(upgrade_buffer,
5250  "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5251  pg_type_array_oid);
5252  }
5253 
5254  /*
5255  * Pre-set the multirange type oid and its own array type oid.
5256  */
5257  if (include_multirange_type)
5258  {
5259  if (fout->remoteVersion >= 140000)
5260  {
5261  printfPQExpBuffer(upgrade_query,
5262  "SELECT t.oid, t.typarray "
5263  "FROM pg_catalog.pg_type t "
5264  "JOIN pg_catalog.pg_range r "
5265  "ON t.oid = r.rngmultitypid "
5266  "WHERE r.rngtypid = '%u'::pg_catalog.oid;",
5267  pg_type_oid);
5268 
5269  res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
5270 
5271  pg_type_multirange_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
5272  pg_type_multirange_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
5273 
5274  PQclear(res);
5275  }
5276  else
5277  {
5278  pg_type_multirange_oid = get_next_possible_free_pg_type_oid(fout, upgrade_query);
5279  pg_type_multirange_array_oid = get_next_possible_free_pg_type_oid(fout, upgrade_query);
5280  }
5281 
5282  appendPQExpBufferStr(upgrade_buffer,
5283  "\n-- For binary upgrade, must preserve multirange pg_type oid\n");
5284  appendPQExpBuffer(upgrade_buffer,
5285  "SELECT pg_catalog.binary_upgrade_set_next_multirange_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5286  pg_type_multirange_oid);
5287  appendPQExpBufferStr(upgrade_buffer,
5288  "\n-- For binary upgrade, must preserve multirange pg_type array oid\n");
5289  appendPQExpBuffer(upgrade_buffer,
5290  "SELECT pg_catalog.binary_upgrade_set_next_multirange_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5291  pg_type_multirange_array_oid);
5292  }
5293 
5294  destroyPQExpBuffer(upgrade_query);
5295 }
5296 
5297 static void
5299  PQExpBuffer upgrade_buffer,
5300  const TableInfo *tbinfo)
5301 {
5302  Oid pg_type_oid = tbinfo->reltype;
5303 
5304  if (OidIsValid(pg_type_oid))
5305  binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
5306  pg_type_oid, false, false);
5307 }
5308 
5309 static void
5311  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
5312  bool is_index)
5313 {
5314  PQExpBuffer upgrade_query = createPQExpBuffer();
5315  PGresult *upgrade_res;
5316  RelFileNumber relfilenumber;
5317  Oid toast_oid;
5318  RelFileNumber toast_relfilenumber;
5319  char relkind;
5320  Oid toast_index_oid;
5321  RelFileNumber toast_index_relfilenumber;
5322 
5323  /*
5324  * Preserve the OID and relfilenumber of the table, table's index, table's
5325  * toast table and toast table's index if any.
5326  *
5327  * One complexity is that the current table definition might not require
5328  * the creation of a TOAST table, but the old database might have a TOAST
5329  * table that was created earlier, before some wide columns were dropped.
5330  * By setting the TOAST oid we force creation of the TOAST heap and index
5331  * by the new backend, so we can copy the files during binary upgrade
5332  * without worrying about this case.
5333  */
5334  appendPQExpBuffer(upgrade_query,
5335  "SELECT c.relkind, c.relfilenode, c.reltoastrelid, ct.relfilenode AS toast_relfilenode, i.indexrelid, cti.relfilenode AS toast_index_relfilenode "
5336  "FROM pg_catalog.pg_class c LEFT JOIN "
5337  "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
5338  "LEFT JOIN pg_catalog.pg_class ct ON (c.reltoastrelid = ct.oid) "
5339  "LEFT JOIN pg_catalog.pg_class AS cti ON (i.indexrelid = cti.oid) "
5340  "WHERE c.oid = '%u'::pg_catalog.oid;",
5341  pg_class_oid);
5342 
5343  upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
5344 
5345  relkind = *PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "relkind"));
5346 
5347  relfilenumber = atooid(PQgetvalue(upgrade_res, 0,
5348  PQfnumber(upgrade_res, "relfilenode")));
5349  toast_oid = atooid(PQgetvalue(upgrade_res, 0,
5350  PQfnumber(upgrade_res, "reltoastrelid")));
5351  toast_relfilenumber = atooid(PQgetvalue(upgrade_res, 0,
5352  PQfnumber(upgrade_res, "toast_relfilenode")));
5353  toast_index_oid = atooid(PQgetvalue(upgrade_res, 0,
5354  PQfnumber(upgrade_res, "indexrelid")));
5355  toast_index_relfilenumber = atooid(PQgetvalue(upgrade_res, 0,
5356  PQfnumber(upgrade_res, "toast_index_relfilenode")));
5357 
5358  appendPQExpBufferStr(upgrade_buffer,
5359  "\n-- For binary upgrade, must preserve pg_class oids and relfilenodes\n");
5360 
5361  if (!is_index)
5362  {
5363  appendPQExpBuffer(upgrade_buffer,
5364  "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
5365  pg_class_oid);
5366 
5367  /*
5368  * Not every relation has storage. Also, in a pre-v12 database,
5369  * partitioned tables have a relfilenumber, which should not be
5370  * preserved when upgrading.
5371  */
5372  if (RelFileNumberIsValid(relfilenumber) && relkind != RELKIND_PARTITIONED_TABLE)
5373  appendPQExpBuffer(upgrade_buffer,
5374  "SELECT pg_catalog.binary_upgrade_set_next_heap_relfilenode('%u'::pg_catalog.oid);\n",
5375  relfilenumber);
5376 
5377  /*
5378  * In a pre-v12 database, partitioned tables might be marked as having
5379  * toast tables, but we should ignore them if so.
5380  */
5381  if (OidIsValid(toast_oid) &&
5382  relkind != RELKIND_PARTITIONED_TABLE)
5383  {
5384  appendPQExpBuffer(upgrade_buffer,
5385  "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
5386  toast_oid);
5387  appendPQExpBuffer(upgrade_buffer,
5388  "SELECT pg_catalog.binary_upgrade_set_next_toast_relfilenode('%u'::pg_catalog.oid);\n",
5389  toast_relfilenumber);
5390 
5391  /* every toast table has an index */
5392  appendPQExpBuffer(upgrade_buffer,
5393  "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
5394  toast_index_oid);
5395  appendPQExpBuffer(upgrade_buffer,
5396  "SELECT pg_catalog.binary_upgrade_set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
5397  toast_index_relfilenumber);
5398  }
5399 
5400  PQclear(upgrade_res);
5401  }
5402  else
5403  {
5404  /* Preserve the OID and relfilenumber of the index */
5405  appendPQExpBuffer(upgrade_buffer,
5406  "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
5407  pg_class_oid);
5408  appendPQExpBuffer(upgrade_buffer,
5409  "SELECT pg_catalog.binary_upgrade_set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
5410  relfilenumber);
5411  }
5412 
5413  appendPQExpBufferChar(upgrade_buffer, '\n');
5414 
5415  destroyPQExpBuffer(upgrade_query);
5416 }
5417 
5418 /*
5419  * If the DumpableObject is a member of an extension, add a suitable
5420  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
5421  *
5422  * For somewhat historical reasons, objname should already be quoted,
5423  * but not objnamespace (if any).
5424  */
5425 static void
5427  const DumpableObject *dobj,
5428  const char *objtype,
5429  const char *objname,
5430  const char *objnamespace)
5431 {
5432  DumpableObject *extobj = NULL;
5433  int i;
5434 
5435  if (!dobj->ext_member)
5436  return;
5437 
5438  /*
5439  * Find the parent extension. We could avoid this search if we wanted to
5440  * add a link field to DumpableObject, but the space costs of that would
5441  * be considerable. We assume that member objects could only have a
5442  * direct dependency on their own extension, not any others.
5443  */
5444  for (i = 0; i < dobj->nDeps; i++)
5445  {
5446  extobj = findObjectByDumpId(dobj->dependencies[i]);
5447  if (extobj && extobj->objType == DO_EXTENSION)
5448  break;
5449  extobj = NULL;
5450  }
5451  if (extobj == NULL)
5452  pg_fatal("could not find parent extension for %s %s",
5453  objtype, objname);
5454 
5455  appendPQExpBufferStr(upgrade_buffer,
5456  "\n-- For binary upgrade, handle extension membership the hard way\n");
5457  appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
5458  fmtId(extobj->name),
5459  objtype);
5460  if (objnamespace && *objnamespace)
5461  appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
5462  appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
5463 }
5464 
5465 /*
5466  * getNamespaces:
5467  * read all namespaces in the system catalogs and return them in the
5468  * NamespaceInfo* structure
5469  *
5470  * numNamespaces is set to the number of namespaces read in
5471  */
5472 NamespaceInfo *
5473 getNamespaces(Archive *fout, int *numNamespaces)
5474 {
5475  PGresult *res;
5476  int ntups;
5477  int i;
5478  PQExpBuffer query;
5479  NamespaceInfo *nsinfo;
5480  int i_tableoid;
5481  int i_oid;
5482  int i_nspname;
5483  int i_nspowner;
5484  int i_nspacl;
5485  int i_acldefault;
5486 
5487  query = createPQExpBuffer();
5488 
5489  /*
5490  * we fetch all namespaces including system ones, so that every object we
5491  * read in can be linked to a containing namespace.
5492  */
5493  appendPQExpBufferStr(query, "SELECT n.tableoid, n.oid, n.nspname, "
5494  "n.nspowner, "
5495  "n.nspacl, "
5496  "acldefault('n', n.nspowner) AS acldefault "
5497  "FROM pg_namespace n");
5498 
5499  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5500 
5501  ntups = PQntuples(res);
5502 
5503  nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
5504 
5505  i_tableoid = PQfnumber(res, "tableoid");
5506  i_oid = PQfnumber(res, "oid");
5507  i_nspname = PQfnumber(res, "nspname");
5508  i_nspowner = PQfnumber(res, "nspowner");
5509  i_nspacl = PQfnumber(res, "nspacl");
5510  i_acldefault = PQfnumber(res, "acldefault");
5511 
5512  for (i = 0; i < ntups; i++)
5513  {
5514  const char *nspowner;
5515 
5516  nsinfo[i].dobj.objType = DO_NAMESPACE;
5517  nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5518  nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5519  AssignDumpId(&nsinfo[i].dobj);
5520  nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
5521  nsinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_nspacl));
5522  nsinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
5523  nsinfo[i].dacl.privtype = 0;
5524  nsinfo[i].dacl.initprivs = NULL;
5525  nspowner = PQgetvalue(res, i, i_nspowner);
5526  nsinfo[i].nspowner = atooid(nspowner);
5527  nsinfo[i].rolname = getRoleName(nspowner);
5528 
5529  /* Decide whether to dump this namespace */
5530  selectDumpableNamespace(&nsinfo[i], fout);
5531 
5532  /* Mark whether namespace has an ACL */
5533  if (!PQgetisnull(res, i, i_nspacl))
5534  nsinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
5535 
5536  /*
5537  * We ignore any pg_init_privs.initprivs entry for the public schema
5538  * and assume a predetermined default, for several reasons. First,
5539  * dropping and recreating the schema removes its pg_init_privs entry,
5540  * but an empty destination database starts with this ACL nonetheless.
5541  * Second, we support dump/reload of public schema ownership changes.
5542  * ALTER SCHEMA OWNER filters nspacl through aclnewowner(), but
5543  * initprivs continues to reflect the initial owner. Hence,
5544  * synthesize the value that nspacl will have after the restore's
5545  * ALTER SCHEMA OWNER. Third, this makes the destination database
5546  * match the source's ACL, even if the latter was an initdb-default
5547  * ACL, which changed in v15. An upgrade pulls in changes to most
5548  * system object ACLs that the DBA had not customized. We've made the
5549  * public schema depart from that, because changing its ACL so easily
5550  * breaks applications.
5551  */
5552  if (strcmp(nsinfo[i].dobj.name, "public") == 0)
5553  {
5554  PQExpBuffer aclarray = createPQExpBuffer();
5555  PQExpBuffer aclitem = createPQExpBuffer();
5556 
5557  /* Standard ACL as of v15 is {owner=UC/owner,=U/owner} */
5558  appendPQExpBufferChar(aclarray, '{');
5559  quoteAclUserName(aclitem, nsinfo[i].rolname);
5560  appendPQExpBufferStr(aclitem, "=UC/");
5561  quoteAclUserName(aclitem, nsinfo[i].rolname);
5562  appendPGArray(aclarray, aclitem->data);
5563  resetPQExpBuffer(aclitem);
5564  appendPQExpBufferStr(aclitem, "=U/");
5565  quoteAclUserName(aclitem, nsinfo[i].rolname);
5566  appendPGArray(aclarray, aclitem->data);
5567  appendPQExpBufferChar(aclarray, '}');
5568 
5569  nsinfo[i].dacl.privtype = 'i';
5570  nsinfo[i].dacl.initprivs = pstrdup(aclarray->data);
5571  nsinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
5572 
5573  destroyPQExpBuffer(aclarray);
5574  destroyPQExpBuffer(aclitem);
5575  }
5576  }
5577 
5578  PQclear(res);
5579  destroyPQExpBuffer(query);
5580 
5581  *numNamespaces = ntups;
5582 
5583  return nsinfo;
5584 }
5585 
5586 /*
5587  * findNamespace:
5588  * given a namespace OID, look up the info read by getNamespaces
5589  */
5590 static NamespaceInfo *
5592 {
5593  NamespaceInfo *nsinfo;
5594 
5595  nsinfo = findNamespaceByOid(nsoid);
5596  if (nsinfo == NULL)
5597  pg_fatal("schema with OID %u does not exist", nsoid);
5598  return nsinfo;
5599 }
5600 
5601 /*
5602  * getExtensions:
5603  * read all extensions in the system catalogs and return them in the
5604  * ExtensionInfo* structure
5605  *
5606  * numExtensions is set to the number of extensions read in
5607  */
5608 ExtensionInfo *
5609 getExtensions(Archive *fout, int *numExtensions)
5610 {
5611  DumpOptions *dopt = fout->dopt;
5612  PGresult *res;
5613  int ntups;
5614  int i;
5615  PQExpBuffer query;
5616  ExtensionInfo *extinfo;
5617  int i_tableoid;
5618  int i_oid;
5619  int i_extname;
5620  int i_nspname;
5621  int i_extrelocatable;
5622  int i_extversion;
5623  int i_extconfig;
5624  int i_extcondition;
5625 
5626  query = createPQExpBuffer();
5627 
5628  appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
5629  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
5630  "FROM pg_extension x "
5631  "JOIN pg_namespace n ON n.oid = x.extnamespace");
5632 
5633  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5634 
5635  ntups = PQntuples(res);
5636 
5637  extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
5638 
5639  i_tableoid = PQfnumber(res, "tableoid");
5640  i_oid = PQfnumber(res, "oid");
5641  i_extname = PQfnumber(res, "extname");
5642  i_nspname = PQfnumber(res, "nspname");
5643  i_extrelocatable = PQfnumber(res, "extrelocatable");
5644  i_extversion = PQfnumber(res, "extversion");
5645  i_extconfig = PQfnumber(res, "extconfig");
5646  i_extcondition = PQfnumber(res, "extcondition");
5647 
5648  for (i = 0; i < ntups; i++)
5649  {
5650  extinfo[i].dobj.objType = DO_EXTENSION;
5651  extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5652  extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5653  AssignDumpId(&extinfo[i].dobj);
5654  extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
5655  extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
5656  extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
5657  extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
5658  extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
5659  extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
5660 
5661  /* Decide whether we want to dump it */
5662  selectDumpableExtension(&(extinfo[i]), dopt);
5663  }
5664 
5665  PQclear(res);
5666  destroyPQExpBuffer(query);
5667 
5668  *numExtensions = ntups;
5669 
5670  return extinfo;
5671 }
5672 
5673 /*
5674  * getTypes:
5675  * read all types in the system catalogs and return them in the
5676  * TypeInfo* structure
5677  *
5678  * numTypes is set to the number of types read in
5679  *
5680  * NB: this must run after getFuncs() because we assume we can do
5681  * findFuncByOid().
5682  */
5683 TypeInfo *
5684 getTypes(Archive *fout, int *numTypes)
5685 {
5686  PGresult *res;
5687  int ntups;
5688  int i;
5689  PQExpBuffer query = createPQExpBuffer();
5690  TypeInfo *tyinfo;
5691  ShellTypeInfo *stinfo;
5692  int i_tableoid;
5693  int i_oid;
5694  int i_typname;
5695  int i_typnamespace;
5696  int i_typacl;
5697  int i_acldefault;
5698  int i_typowner;
5699  int i_typelem;
5700  int i_typrelid;
5701  int i_typrelkind;
5702  int i_typtype;
5703  int i_typisdefined;
5704  int i_isarray;
5705 
5706  /*
5707  * we include even the built-in types because those may be used as array
5708  * elements by user-defined types
5709  *
5710  * we filter out the built-in types when we dump out the types
5711  *
5712  * same approach for undefined (shell) types and array types
5713  *
5714  * Note: as of 8.3 we can reliably detect whether a type is an
5715  * auto-generated array type by checking the element type's typarray.
5716  * (Before that the test is capable of generating false positives.) We
5717  * still check for name beginning with '_', though, so as to avoid the
5718  * cost of the subselect probe for all standard types. This would have to
5719  * be revisited if the backend ever allows renaming of array types.
5720  */
5721  appendPQExpBufferStr(query, "SELECT tableoid, oid, typname, "
5722  "typnamespace, typacl, "
5723  "acldefault('T', typowner) AS acldefault, "
5724  "typowner, "
5725  "typelem, typrelid, "
5726  "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5727  "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5728  "typtype, typisdefined, "
5729  "typname[0] = '_' AND typelem != 0 AND "
5730  "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
5731  "FROM pg_type");
5732 
5733  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5734 
5735  ntups = PQntuples(res);
5736 
5737  tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
5738 
5739  i_tableoid = PQfnumber(res, "tableoid");
5740  i_oid = PQfnumber(res, "oid");
5741  i_typname = PQfnumber(res, "typname");
5742  i_typnamespace = PQfnumber(res, "typnamespace");
5743  i_typacl = PQfnumber(res, "typacl");
5744  i_acldefault = PQfnumber(res, "acldefault");
5745  i_typowner = PQfnumber(res, "typowner");
5746  i_typelem = PQfnumber(res, "typelem");
5747  i_typrelid = PQfnumber(res, "typrelid");
5748  i_typrelkind = PQfnumber(res, "typrelkind");
5749  i_typtype = PQfnumber(res, "typtype");
5750  i_typisdefined = PQfnumber(res, "typisdefined");
5751  i_isarray = PQfnumber(res, "isarray");
5752 
5753  for (i = 0; i < ntups; i++)
5754  {
5755  tyinfo[i].dobj.objType = DO_TYPE;
5756  tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5757  tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5758  AssignDumpId(&tyinfo[i].dobj);
5759  tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
5760  tyinfo[i].dobj.namespace =
5761  findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)));
5762  tyinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_typacl));
5763  tyinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
5764  tyinfo[i].dacl.privtype = 0;
5765  tyinfo[i].dacl.initprivs = NULL;
5766  tyinfo[i].ftypname = NULL; /* may get filled later */
5767  tyinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_typowner));
5768  tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
5769  tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
5770  tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
5771  tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
5772  tyinfo[i].shellType = NULL;
5773 
5774  if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
5775  tyinfo[i].isDefined = true;
5776  else
5777  tyinfo[i].isDefined = false;
5778 
5779  if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
5780  tyinfo[i].isArray = true;
5781  else
5782  tyinfo[i].isArray = false;
5783 
5784  if (tyinfo[i].typtype == TYPTYPE_MULTIRANGE)
5785  tyinfo[i].isMultirange = true;
5786  else
5787  tyinfo[i].isMultirange = false;
5788 
5789  /* Decide whether we want to dump it */
5790  selectDumpableType(&tyinfo[i], fout);
5791 
5792  /* Mark whether type has an ACL */
5793  if (!PQgetisnull(res, i, i_typacl))
5794  tyinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
5795 
5796  /*
5797  * If it's a domain, fetch info about its constraints, if any
5798  */
5799  tyinfo[i].nDomChecks = 0;
5800  tyinfo[i].domChecks = NULL;
5801  if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
5802  tyinfo[i].typtype == TYPTYPE_DOMAIN)
5803  getDomainConstraints(fout, &(tyinfo[i]));
5804 
5805  /*
5806  * If it's a base type, make a DumpableObject representing a shell
5807  * definition of the type. We will need to dump that ahead of the I/O
5808  * functions for the type. Similarly, range types need a shell
5809  * definition in case they have a canonicalize function.
5810  *
5811  * Note: the shell type doesn't have a catId. You might think it
5812  * should copy the base type's catId, but then it might capture the
5813  * pg_depend entries for the type, which we don't want.
5814  */
5815  if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
5816  (tyinfo[i].typtype == TYPTYPE_BASE ||
5817  tyinfo[i].typtype == TYPTYPE_RANGE))
5818  {
5819  stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
5820  stinfo->dobj.objType = DO_SHELL_TYPE;
5821  stinfo->dobj.catId = nilCatalogId;
5822  AssignDumpId(&stinfo->dobj);
5823  stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
5824  stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
5825  stinfo->baseType = &(tyinfo[i]);
5826  tyinfo[i].shellType = stinfo;
5827 
5828  /*
5829  * Initially mark the shell type as not to be dumped. We'll only
5830  * dump it if the I/O or canonicalize functions need to be dumped;
5831  * this is taken care of while sorting dependencies.
5832  */
5833  stinfo->dobj.dump = DUMP_COMPONENT_NONE;
5834  }
5835  }
5836 
5837  *numTypes = ntups;
5838 
5839  PQclear(res);
5840 
5841  destroyPQExpBuffer(query);
5842 
5843  return tyinfo;
5844 }
5845 
5846 /*
5847  * getOperators:
5848  * read all operators in the system catalogs and return them in the
5849  * OprInfo* structure
5850  *
5851  * numOprs is set to the number of operators read in
5852  */
5853 OprInfo *
5854 getOperators(Archive *fout, int *numOprs)
5855 {
5856  PGresult *res;
5857  int ntups;
5858  int i;
5859  PQExpBuffer query = createPQExpBuffer();
5860  OprInfo *oprinfo;
5861  int i_tableoid;
5862  int i_oid;
5863  int i_oprname;
5864  int i_oprnamespace;
5865  int i_oprowner;
5866  int i_oprkind;
5867  int i_oprcode;
5868 
5869  /*
5870  * find all operators, including builtin operators; we filter out
5871  * system-defined operators at dump-out time.
5872  */
5873 
5874  appendPQExpBufferStr(query, "SELECT tableoid, oid, oprname, "
5875  "oprnamespace, "
5876  "oprowner, "
5877  "oprkind, "
5878  "oprcode::oid AS oprcode "
5879  "FROM pg_operator");
5880 
5881  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5882 
5883  ntups = PQntuples(res);
5884  *numOprs = ntups;
5885 
5886  oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
5887 
5888  i_tableoid = PQfnumber(res, "tableoid");
5889  i_oid = PQfnumber(res, "oid");
5890  i_oprname = PQfnumber(res, "oprname");
5891  i_oprnamespace = PQfnumber(res, "oprnamespace");
5892  i_oprowner = PQfnumber(res, "oprowner");
5893  i_oprkind = PQfnumber(res, "oprkind");
5894  i_oprcode = PQfnumber(res, "oprcode");
5895 
5896  for (i = 0; i < ntups; i++)
5897  {
5898  oprinfo[i].dobj.objType = DO_OPERATOR;
5899  oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5900  oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5901  AssignDumpId(&oprinfo[i].dobj);
5902  oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
5903  oprinfo[i].dobj.namespace =
5904  findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)));
5905  oprinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_oprowner));
5906  oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
5907  oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
5908 
5909  /* Decide whether we want to dump it */
5910  selectDumpableObject(&(oprinfo[i].dobj), fout);
5911  }
5912 
5913  PQclear(res);
5914 
5915  destroyPQExpBuffer(query);
5916 
5917  return oprinfo;
5918 }
5919 
5920 /*
5921  * getCollations:
5922  * read all collations in the system catalogs and return them in the
5923  * CollInfo* structure
5924  *
5925  * numCollations is set to the number of collations read in
5926  */
5927 CollInfo *
5928 getCollations(Archive *fout, int *numCollations)
5929 {
5930  PGresult *res;
5931  int ntups;
5932  int i;
5933  PQExpBuffer query;
5934  CollInfo *collinfo;
5935  int i_tableoid;
5936  int i_oid;
5937  int i_collname;
5938  int i_collnamespace;
5939  int i_collowner;
5940 
5941  query = createPQExpBuffer();
5942 
5943  /*
5944  * find all collations, including builtin collations; we filter out
5945  * system-defined collations at dump-out time.
5946  */
5947 
5948  appendPQExpBufferStr(query, "SELECT tableoid, oid, collname, "
5949  "collnamespace, "
5950  "collowner "
5951  "FROM pg_collation");
5952 
5953  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5954 
5955  ntups = PQntuples(res);
5956  *numCollations = ntups;
5957 
5958  collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5959 
5960  i_tableoid = PQfnumber(res, "tableoid");
5961  i_oid = PQfnumber(res, "oid");
5962  i_collname = PQfnumber(res, "collname");
5963  i_collnamespace = PQfnumber(res, "collnamespace");
5964  i_collowner = PQfnumber(res, "collowner");
5965 
5966  for (i = 0; i < ntups; i++)
5967  {
5968  collinfo[i].dobj.objType = DO_COLLATION;
5969  collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5970  collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5971  AssignDumpId(&collinfo[i].dobj);
5972  collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5973  collinfo[i].dobj.namespace =
5974  findNamespace(atooid(PQgetvalue(res, i, i_collnamespace)));
5975  collinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_collowner));
5976 
5977  /* Decide whether we want to dump it */
5978  selectDumpableObject(&(collinfo[i].dobj), fout);
5979  }
5980 
5981  PQclear(res);
5982 
5983  destroyPQExpBuffer(query);
5984 
5985  return collinfo;
5986 }
5987 
5988 /*
5989  * getConversions:
5990  * read all conversions in the system catalogs and return them in the
5991  * ConvInfo* structure
5992  *
5993  * numConversions is set to the number of conversions read in
5994  */
5995 ConvInfo *
5996 getConversions(Archive *fout, int *numConversions)
5997 {
5998  PGresult *res;
5999  int ntups;
6000  int i;
6001  PQExpBuffer query;
6002  ConvInfo *convinfo;
6003  int i_tableoid;
6004  int i_oid;
6005  int i_conname;
6006  int i_connamespace;
6007  int i_conowner;
6008 
6009  query = createPQExpBuffer();
6010 
6011  /*
6012  * find all conversions, including builtin conversions; we filter out
6013  * system-defined conversions at dump-out time.
6014  */
6015 
6016  appendPQExpBufferStr(query, "SELECT tableoid, oid, conname, "
6017  "connamespace, "
6018  "conowner "
6019  "FROM pg_conversion");
6020 
6021  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6022 
6023  ntups = PQntuples(res);
6024  *numConversions = ntups;
6025 
6026  convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
6027 
6028  i_tableoid = PQfnumber(res, "tableoid");
6029  i_oid = PQfnumber(res, "oid");
6030  i_conname = PQfnumber(res, "conname");
6031  i_connamespace = PQfnumber(res, "connamespace");
6032  i_conowner = PQfnumber(res, "conowner");
6033 
6034  for (i = 0; i < ntups; i++)
6035  {
6036  convinfo[i].dobj.objType = DO_CONVERSION;
6037  convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6038  convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6039  AssignDumpId(&convinfo[i].dobj);
6040  convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
6041  convinfo[i].dobj.namespace =
6042  findNamespace(atooid(PQgetvalue(res, i, i_connamespace)));
6043  convinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_conowner));
6044 
6045  /* Decide whether we want to dump it */
6046  selectDumpableObject(&(convinfo[i].dobj), fout);
6047  }
6048 
6049  PQclear(res);
6050 
6051  destroyPQExpBuffer(query);
6052 
6053  return convinfo;
6054 }
6055 
6056 /*
6057  * getAccessMethods:
6058  * read all user-defined access methods in the system catalogs and return
6059  * them in the AccessMethodInfo* structure
6060  *
6061  * numAccessMethods is set to the number of access methods read in
6062  */
6064 getAccessMethods(Archive *fout, int *numAccessMethods)
6065 {
6066  PGresult *res;
6067  int ntups;
6068  int i;
6069  PQExpBuffer query;
6070  AccessMethodInfo *aminfo;
6071  int i_tableoid;
6072  int i_oid;
6073  int i_amname;
6074  int i_amhandler;
6075  int i_amtype;
6076 
6077  /* Before 9.6, there are no user-defined access methods */
6078  if (fout->remoteVersion < 90600)
6079  {
6080  *numAccessMethods = 0;
6081  return NULL;
6082  }
6083 
6084  query = createPQExpBuffer();
6085 
6086  /* Select all access methods from pg_am table */
6087  appendPQExpBufferStr(query, "SELECT tableoid, oid, amname, amtype, "
6088  "amhandler::pg_catalog.regproc AS amhandler "
6089  "FROM pg_am");
6090 
6091  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6092 
6093  ntups = PQntuples(res);
6094  *numAccessMethods = ntups;
6095 
6096  aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
6097 
6098  i_tableoid = PQfnumber(res, "tableoid");
6099  i_oid = PQfnumber(res, "oid");
6100  i_amname = PQfnumber(res, "amname");
6101  i_amhandler = PQfnumber(res, "amhandler");
6102  i_amtype = PQfnumber(res, "amtype");
6103 
6104  for (i = 0; i < ntups; i++)
6105  {
6106  aminfo[i].dobj.objType = DO_ACCESS_METHOD;
6107  aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6108  aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6109  AssignDumpId(&aminfo[i].dobj);
6110  aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
6111  aminfo[i].dobj.namespace = NULL;
6112  aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
6113  aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
6114 
6115  /* Decide whether we want to dump it */
6116  selectDumpableAccessMethod(&(aminfo[i]), fout);
6117  }
6118 
6119  PQclear(res);
6120 
6121  destroyPQExpBuffer(query);
6122 
6123  return aminfo;
6124 }
6125 
6126 
6127 /*
6128  * getOpclasses:
6129  * read all opclasses in the system catalogs and return them in the
6130  * OpclassInfo* structure
6131  *
6132  * numOpclasses is set to the number of opclasses read in
6133  */
6134 OpclassInfo *
6135 getOpclasses(Archive *fout, int *numOpclasses)
6136 {
6137  PGresult *res;
6138  int ntups;
6139  int i;
6140  PQExpBuffer query = createPQExpBuffer();
6141  OpclassInfo *opcinfo;
6142  int i_tableoid;
6143  int i_oid;
6144  int i_opcname;
6145  int i_opcnamespace;
6146  int i_opcowner;
6147 
6148  /*
6149  * find all opclasses, including builtin opclasses; we filter out
6150  * system-defined opclasses at dump-out time.
6151  */
6152 
6153  appendPQExpBufferStr(query, "SELECT tableoid, oid, opcname, "
6154  "opcnamespace, "
6155  "opcowner "
6156  "FROM pg_opclass");
6157 
6158  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6159 
6160  ntups = PQntuples(res);
6161  *numOpclasses = ntups;
6162 
6163  opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
6164 
6165  i_tableoid = PQfnumber(res, "tableoid");
6166  i_oid = PQfnumber(res, "oid");
6167  i_opcname = PQfnumber(res, "opcname");
6168  i_opcnamespace = PQfnumber(res, "opcnamespace");
6169  i_opcowner = PQfnumber(res, "opcowner");
6170 
6171  for (i = 0; i < ntups; i++)
6172  {
6173  opcinfo[i].dobj.objType = DO_OPCLASS;
6174  opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6175  opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6176  AssignDumpId(&opcinfo[i].dobj);
6177  opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
6178  opcinfo[i].dobj.namespace =
6179  findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)));
6180  opcinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_opcowner));
6181 
6182  /* Decide whether we want to dump it */
6183  selectDumpableObject(&(opcinfo[i].dobj), fout);
6184  }
6185 
6186  PQclear(res);
6187 
6188  destroyPQExpBuffer(query);
6189 
6190  return opcinfo;
6191 }
6192 
6193 /*
6194  * getOpfamilies:
6195  * read all opfamilies in the system catalogs and return them in the
6196  * OpfamilyInfo* structure
6197  *
6198  * numOpfamilies is set to the number of opfamilies read in
6199  */
6200 OpfamilyInfo *
6201 getOpfamilies(Archive *fout, int *numOpfamilies)
6202 {
6203  PGresult *res;
6204  int ntups;
6205  int i;
6206  PQExpBuffer query;
6207  OpfamilyInfo *opfinfo;
6208  int i_tableoid;
6209  int i_oid;
6210  int i_opfname;
6211  int i_opfnamespace;
6212  int i_opfowner;
6213 
6214  query = createPQExpBuffer();
6215 
6216  /*
6217  * find all opfamilies, including builtin opfamilies; we filter out
6218  * system-defined opfamilies at dump-out time.
6219  */
6220 
6221  appendPQExpBufferStr(query, "SELECT tableoid, oid, opfname, "
6222  "opfnamespace, "
6223  "opfowner "
6224  "FROM pg_opfamily");
6225 
6226  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6227 
6228  ntups = PQntuples(res);
6229  *numOpfamilies = ntups;
6230 
6231  opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
6232 
6233  i_tableoid = PQfnumber(res, "tableoid");
6234  i_oid = PQfnumber(res, "oid");
6235  i_opfname = PQfnumber(res, "opfname");
6236  i_opfnamespace = PQfnumber(res, "opfnamespace");
6237  i_opfowner = PQfnumber(res, "opfowner");
6238 
6239  for (i = 0; i < ntups; i++)
6240  {
6241  opfinfo[i].dobj.objType = DO_OPFAMILY;
6242  opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6243  opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6244  AssignDumpId(&opfinfo[i].dobj);
6245  opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
6246  opfinfo[i].dobj.namespace =
6247  findNamespace(atooid(PQgetvalue(res, i, i_opfnamespace)));
6248  opfinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_opfowner));
6249 
6250  /* Decide whether we want to dump it */
6251  selectDumpableObject(&(opfinfo[i].dobj), fout);
6252  }
6253 
6254  PQclear(res);
6255 
6256  destroyPQExpBuffer(query);
6257 
6258  return opfinfo;
6259 }
6260 
6261 /*
6262  * getAggregates:
6263  * read all the user-defined aggregates in the system catalogs and
6264  * return them in the AggInfo* structure
6265  *
6266  * numAggs is set to the number of aggregates read in
6267  */
6268 AggInfo *
6269 getAggregates(Archive *fout, int *numAggs)
6270 {
6271  DumpOptions *dopt = fout->dopt;
6272  PGresult *res;
6273  int ntups;
6274  int i;
6275  PQExpBuffer query = createPQExpBuffer();
6276  AggInfo *agginfo;
6277  int i_tableoid;
6278  int i_oid;
6279  int i_aggname;
6280  int i_aggnamespace;
6281  int i_pronargs;
6282  int i_proargtypes;
6283  int i_proowner;
6284  int i_aggacl;
6285  int i_acldefault;
6286 
6287  /*
6288  * Find all interesting aggregates. See comment in getFuncs() for the
6289  * rationale behind the filtering logic.
6290  */
6291  if (fout->remoteVersion >= 90600)
6292  {
6293  const char *agg_check;
6294 
6295  agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
6296  : "p.proisagg");
6297 
6298  appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
6299  "p.proname AS aggname, "
6300  "p.pronamespace AS aggnamespace, "
6301  "p.pronargs, p.proargtypes, "
6302  "p.proowner, "
6303  "p.proacl AS aggacl, "
6304  "acldefault('f', p.proowner) AS acldefault "
6305  "FROM pg_proc p "
6306  "LEFT JOIN pg_init_privs pip ON "
6307  "(p.oid = pip.objoid "
6308  "AND pip.classoid = 'pg_proc'::regclass "
6309  "AND pip.objsubid = 0) "
6310  "WHERE %s AND ("
6311  "p.pronamespace != "
6312  "(SELECT oid FROM pg_namespace "
6313  "WHERE nspname = 'pg_catalog') OR "
6314  "p.proacl IS DISTINCT FROM pip.initprivs",
6315  agg_check);
6316  if (dopt->binary_upgrade)
6317  appendPQExpBufferStr(query,
6318  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6319  "classid = 'pg_proc'::regclass AND "
6320  "objid = p.oid AND "
6321  "refclassid = 'pg_extension'::regclass AND "
6322  "deptype = 'e')");
6323  appendPQExpBufferChar(query, ')');
6324  }
6325  else
6326  {
6327  appendPQExpBufferStr(query, "SELECT tableoid, oid, proname AS aggname, "
6328  "pronamespace AS aggnamespace, "
6329  "pronargs, proargtypes, "
6330  "proowner, "
6331  "proacl AS aggacl, "
6332  "acldefault('f', proowner) AS acldefault "
6333  "FROM pg_proc p "
6334  "WHERE proisagg AND ("
6335  "pronamespace != "
6336  "(SELECT oid FROM pg_namespace "
6337  "WHERE nspname = 'pg_catalog')");
6338  if (dopt->binary_upgrade)
6339  appendPQExpBufferStr(query,
6340  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6341  "classid = 'pg_proc'::regclass AND "
6342  "objid = p.oid AND "
6343  "refclassid = 'pg_extension'::regclass AND "
6344  "deptype = 'e')");
6345  appendPQExpBufferChar(query, ')');
6346  }
6347 
6348  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6349 
6350  ntups = PQntuples(res);
6351  *numAggs = ntups;
6352 
6353  agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
6354 
6355  i_tableoid = PQfnumber(res, "tableoid");
6356  i_oid = PQfnumber(res, "oid");
6357  i_aggname = PQfnumber(res, "aggname");
6358  i_aggnamespace = PQfnumber(res, "aggnamespace");
6359  i_pronargs = PQfnumber(res, "pronargs");
6360  i_proargtypes = PQfnumber(res, "proargtypes");
6361  i_proowner = PQfnumber(res, "proowner");
6362  i_aggacl = PQfnumber(res, "aggacl");
6363  i_acldefault = PQfnumber(res, "acldefault");
6364 
6365  for (i = 0; i < ntups; i++)
6366  {
6367  agginfo[i].aggfn.dobj.objType = DO_AGG;
6368  agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6369  agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6370  AssignDumpId(&agginfo[i].aggfn.dobj);
6371  agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
6372  agginfo[i].aggfn.dobj.namespace =
6373  findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)));
6374  agginfo[i].aggfn.dacl.acl = pg_strdup(PQgetvalue(res, i, i_aggacl));
6375  agginfo[i].aggfn.dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
6376  agginfo[i].aggfn.dacl.privtype = 0;
6377  agginfo[i].aggfn.dacl.initprivs = NULL;
6378  agginfo[i].aggfn.rolname = getRoleName(PQgetvalue(res, i, i_proowner));
6379  agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
6380  agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
6381  agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
6382  if (agginfo[i].aggfn.nargs == 0)
6383  agginfo[i].aggfn.argtypes = NULL;
6384  else
6385  {
6386  agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
6387  parseOidArray(PQgetvalue(res, i, i_proargtypes),
6388  agginfo[i].aggfn.argtypes,
6389  agginfo[i].aggfn.nargs);
6390  }
6391  agginfo[i].aggfn.postponed_def = false; /* might get set during sort */
6392 
6393  /* Decide whether we want to dump it */
6394  selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
6395 
6396  /* Mark whether aggregate has an ACL */
6397  if (!PQgetisnull(res, i, i_aggacl))
6398  agginfo[i].aggfn.dobj.components |= DUMP_COMPONENT_ACL;
6399  }
6400 
6401  PQclear(res);
6402 
6403  destroyPQExpBuffer(query);
6404 
6405  return agginfo;
6406 }
6407 
6408 /*
6409  * getFuncs:
6410  * read all the user-defined functions in the system catalogs and
6411  * return them in the FuncInfo* structure
6412  *
6413  * numFuncs is set to the number of functions read in
6414  */
6415 FuncInfo *
6416 getFuncs(Archive *fout, int *numFuncs)
6417 {
6418  DumpOptions *dopt = fout->dopt;
6419  PGresult *res;
6420  int ntups;
6421  int i;
6422  PQExpBuffer query = createPQExpBuffer();
6423  FuncInfo *finfo;
6424  int i_tableoid;
6425  int i_oid;
6426  int i_proname;
6427  int i_pronamespace;
6428  int i_proowner;
6429  int i_prolang;
6430  int i_pronargs;
6431  int i_proargtypes;
6432  int i_prorettype;
6433  int i_proacl;
6434  int i_acldefault;
6435 
6436  /*
6437  * Find all interesting functions. This is a bit complicated:
6438  *
6439  * 1. Always exclude aggregates; those are handled elsewhere.
6440  *
6441  * 2. Always exclude functions that are internally dependent on something
6442  * else, since presumably those will be created as a result of creating
6443  * the something else. This currently acts only to suppress constructor
6444  * functions for range types. Note this is OK only because the
6445  * constructors don't have any dependencies the range type doesn't have;
6446  * otherwise we might not get creation ordering correct.
6447  *
6448  * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
6449  * they're members of extensions and we are in binary-upgrade mode then
6450  * include them, since we want to dump extension members individually in
6451  * that mode. Also, if they are used by casts or transforms then we need
6452  * to gather the information about them, though they won't be dumped if
6453  * they are built-in. Also, in 9.6 and up, include functions in
6454  * pg_catalog if they have an ACL different from what's shown in
6455  * pg_init_privs (so we have to join to pg_init_privs; annoying).
6456  */
6457  if (fout->remoteVersion >= 90600)
6458  {
6459  const char *not_agg_check;
6460 
6461  not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
6462  : "NOT p.proisagg");
6463 
6464  appendPQExpBuffer(query,
6465  "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
6466  "p.pronargs, p.proargtypes, p.prorettype, "
6467  "p.proacl, "
6468  "acldefault('f', p.proowner) AS acldefault, "
6469  "p.pronamespace, "
6470  "p.proowner "
6471  "FROM pg_proc p "
6472  "LEFT JOIN pg_init_privs pip ON "
6473  "(p.oid = pip.objoid "
6474  "AND pip.classoid = 'pg_proc'::regclass "
6475  "AND pip.objsubid = 0) "
6476  "WHERE %s"
6477  "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
6478  "WHERE classid = 'pg_proc'::regclass AND "
6479  "objid = p.oid AND deptype = 'i')"
6480  "\n AND ("
6481  "\n pronamespace != "
6482  "(SELECT oid FROM pg_namespace "
6483  "WHERE nspname = 'pg_catalog')"
6484  "\n OR EXISTS (SELECT 1 FROM pg_cast"
6485  "\n WHERE pg_cast.oid > %u "
6486  "\n AND p.oid = pg_cast.castfunc)"
6487  "\n OR EXISTS (SELECT 1 FROM pg_transform"
6488  "\n WHERE pg_transform.oid > %u AND "
6489  "\n (p.oid = pg_transform.trffromsql"
6490  "\n OR p.oid = pg_transform.trftosql))",
6491  not_agg_check,
6494  if (dopt->binary_upgrade)
6495  appendPQExpBufferStr(query,
6496  "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6497  "classid = 'pg_proc'::regclass AND "
6498  "objid = p.oid AND "
6499  "refclassid = 'pg_extension'::regclass AND "
6500  "deptype = 'e')");
6501  appendPQExpBufferStr(query,
6502  "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
6503  appendPQExpBufferChar(query, ')');
6504  }
6505  else
6506  {
6507  appendPQExpBuffer(query,
6508  "SELECT tableoid, oid, proname, prolang, "
6509  "pronargs, proargtypes, prorettype, proacl, "
6510  "acldefault('f', proowner) AS acldefault, "
6511  "pronamespace, "
6512  "proowner "
6513  "FROM pg_proc p "
6514  "WHERE NOT proisagg"
6515  "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
6516  "WHERE classid = 'pg_proc'::regclass AND "
6517  "objid = p.oid AND deptype = 'i')"
6518  "\n AND ("
6519  "\n pronamespace != "
6520  "(SELECT oid FROM pg_namespace "
6521  "WHERE nspname = 'pg_catalog')"
6522  "\n OR EXISTS (SELECT 1 FROM pg_cast"
6523  "\n WHERE pg_cast.oid > '%u'::oid"
6524  "\n AND p.oid = pg_cast.castfunc)",
6526 
6527  if (fout->remoteVersion >= 90500)
6528  appendPQExpBuffer(query,
6529  "\n OR EXISTS (SELECT 1 FROM pg_transform"
6530  "\n WHERE pg_transform.oid > '%u'::oid"
6531  "\n AND (p.oid = pg_transform.trffromsql"
6532  "\n OR p.oid = pg_transform.trftosql))",
6534 
6535  if (dopt->binary_upgrade)
6536  appendPQExpBufferStr(query,
6537  "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6538  "classid = 'pg_proc'::regclass AND "
6539  "objid = p.oid AND "
6540  "refclassid = 'pg_extension'::regclass AND "
6541  "deptype = 'e')");
6542  appendPQExpBufferChar(query, ')');
6543  }
6544 
6545  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6546 
6547  ntups = PQntuples(res);
6548 
6549  *numFuncs = ntups;
6550 
6551  finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
6552 
6553  i_tableoid = PQfnumber(res, "tableoid");
6554  i_oid = PQfnumber(res, "oid");
6555  i_proname = PQfnumber(res, "proname");
6556  i_pronamespace = PQfnumber(res, "pronamespace");
6557  i_proowner = PQfnumber(res, "proowner");
6558  i_prolang = PQfnumber(res, "prolang");
6559  i_pronargs = PQfnumber(res, "pronargs");
6560  i_proargtypes = PQfnumber(res, "proargtypes");
6561  i_prorettype = PQfnumber(res, "prorettype");
6562  i_proacl = PQfnumber(res, "proacl");
6563  i_acldefault = PQfnumber(res, "acldefault");
6564 
6565  for (i = 0; i < ntups; i++)
6566  {
6567  finfo[i].dobj.objType = DO_FUNC;
6568  finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6569  finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6570  AssignDumpId(&finfo[i].dobj);
6571  finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
6572  finfo[i].dobj.namespace =
6573  findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)));
6574  finfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_proacl));
6575  finfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
6576  finfo[i].dacl.privtype = 0;
6577  finfo[i].dacl.initprivs = NULL;
6578  finfo[i].rolname = getRoleName(PQgetvalue(res, i, i_proowner));
6579  finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
6580  finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
6581  finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
6582  if (finfo[i].nargs == 0)
6583  finfo[i].argtypes = NULL;
6584  else
6585  {
6586  finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
6587  parseOidArray(PQgetvalue(res, i, i_proargtypes),
6588  finfo[i].argtypes, finfo[i].nargs);
6589  }
6590  finfo[i].postponed_def = false; /* might get set during sort */
6591 
6592  /* Decide whether we want to dump it */
6593  selectDumpableObject(&(finfo[i].dobj), fout);
6594 
6595  /* Mark whether function has an ACL */
6596  if (!PQgetisnull(res, i, i_proacl))
6597  finfo[i].dobj.components |= DUMP_COMPONENT_ACL;
6598  }
6599 
6600  PQclear(res);
6601 
6602  destroyPQExpBuffer(query);
6603 
6604  return finfo;
6605 }
6606 
6607 /*
6608  * getTables
6609  * read all the tables (no indexes) in the system catalogs,
6610  * and return them as an array of TableInfo structures
6611  *
6612  * *numTables is set to the number of tables read in
6613  */
6614 TableInfo *
6615 getTables(Archive *fout, int *numTables)
6616 {
6617  DumpOptions *dopt = fout->dopt;
6618  PGresult *res;
6619  int ntups;
6620  int i;
6621  PQExpBuffer query = createPQExpBuffer();
6622  TableInfo *tblinfo;
6623  int i_reltableoid;
6624  int i_reloid;
6625  int i_relname;
6626  int i_relnamespace;
6627  int i_relkind;
6628  int i_reltype;
6629  int i_relowner;
6630  int i_relchecks;
6631  int i_relhasindex;
6632  int i_relhasrules;
6633  int i_relpages;
6634  int i_toastpages;
6635  int i_owning_tab;
6636  int i_owning_col;
6637  int i_reltablespace;
6638  int i_relhasoids;
6639  int i_relhastriggers;
6640  int i_relpersistence;
6641  int i_relispopulated;
6642  int i_relreplident;
6643  int i_relrowsec;
6644  int i_relforcerowsec;
6645  int i_relfrozenxid;
6646  int i_toastfrozenxid;
6647  int i_toastoid;
6648  int i_relminmxid;
6649  int i_toastminmxid;
6650  int i_reloptions;
6651  int i_checkoption;
6652  int i_toastreloptions;
6653  int i_reloftype;
6654  int i_foreignserver;
6655  int i_amname;
6656  int i_is_identity_sequence;
6657  int i_relacl;
6658  int i_acldefault;
6659  int i_ispartition;
6660 
6661  /*
6662  * Find all the tables and table-like objects.
6663  *
6664  * We must fetch all tables in this phase because otherwise we cannot
6665  * correctly identify inherited columns, owned sequences, etc.
6666  *
6667  * We include system catalogs, so that we can work if a user table is
6668  * defined to inherit from a system catalog (pretty weird, but...)
6669  *
6670  * Note: in this phase we should collect only a minimal amount of
6671  * information about each table, basically just enough to decide if it is
6672  * interesting. In particular, since we do not yet have lock on any user
6673  * table, we MUST NOT invoke any server-side data collection functions
6674  * (for instance, pg_get_partkeydef()). Those are likely to fail or give
6675  * wrong answers if any concurrent DDL is happening.
6676  */
6677 
6678  appendPQExpBufferStr(query,
6679  "SELECT c.tableoid, c.oid, c.relname, "
6680  "c.relnamespace, c.relkind, c.reltype, "
6681  "c.relowner, "
6682  "c.relchecks, "
6683  "c.relhasindex, c.relhasrules, c.relpages, "
6684  "c.relhastriggers, "
6685  "c.relpersistence, "
6686  "c.reloftype, "
6687  "c.relacl, "
6688  "acldefault(CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
6689  " THEN 's'::\"char\" ELSE 'r'::\"char\" END, c.relowner) AS acldefault, "
6690  "CASE WHEN c.relkind = " CppAsString2(RELKIND_FOREIGN_TABLE) " THEN "
6691  "(SELECT ftserver FROM pg_catalog.pg_foreign_table WHERE ftrelid = c.oid) "
6692  "ELSE 0 END AS foreignserver, "
6693  "c.relfrozenxid, tc.relfrozenxid AS tfrozenxid, "
6694  "tc.oid AS toid, "
6695  "tc.relpages AS toastpages, "
6696  "tc.reloptions AS toast_reloptions, "
6697  "d.refobjid AS owning_tab, "
6698  "d.refobjsubid AS owning_col, "
6699  "tsp.spcname AS reltablespace, ");
6700 
6701  if (fout->remoteVersion >= 120000)
6702  appendPQExpBufferStr(query,
6703  "false AS relhasoids, ");
6704  else
6705  appendPQExpBufferStr(query,
6706  "c.relhasoids, ");
6707 
6708  if (fout->remoteVersion >= 90300)
6709  appendPQExpBufferStr(query,
6710  "c.relispopulated, ");
6711  else
6712  appendPQExpBufferStr(query,
6713  "'t' as relispopulated, ");
6714 
6715  if (fout->remoteVersion >= 90400)
6716  appendPQExpBufferStr(query,
6717  "c.relreplident, ");
6718  else
6719  appendPQExpBufferStr(query,
6720  "'d' AS relreplident, ");
6721 
6722  if (fout->remoteVersion >= 90500)
6723  appendPQExpBufferStr(query,
6724  "c.relrowsecurity, c.relforcerowsecurity, ");
6725  else
6726  appendPQExpBufferStr(query,
6727  "false AS relrowsecurity, "
6728  "false AS relforcerowsecurity, ");
6729 
6730  if (fout->remoteVersion >= 90300)
6731  appendPQExpBufferStr(query,
6732  "c.relminmxid, tc.relminmxid AS tminmxid, ");
6733  else
6734  appendPQExpBufferStr(query,
6735  "0 AS relminmxid, 0 AS tminmxid, ");
6736 
6737  if (fout->remoteVersion >= 90300)
6738  appendPQExpBufferStr(query,
6739  "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6740  "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6741  "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, ");
6742  else
6743  appendPQExpBufferStr(query,
6744  "c.reloptions, NULL AS checkoption, ");
6745 
6746  if (fout->remoteVersion >= 90600)
6747  appendPQExpBufferStr(query,
6748  "am.amname, ");
6749  else
6750  appendPQExpBufferStr(query,
6751  "NULL AS amname, ");
6752 
6753  if (fout->remoteVersion >= 90600)
6754  appendPQExpBufferStr(query,
6755  "(d.deptype = 'i') IS TRUE AS is_identity_sequence, ");
6756  else
6757  appendPQExpBufferStr(query,
6758  "false AS is_identity_sequence, ");
6759 
6760  if (fout->remoteVersion >= 100000)
6761  appendPQExpBufferStr(query,
6762  "c.relispartition AS ispartition ");
6763  else
6764  appendPQExpBufferStr(query,
6765  "false AS ispartition ");
6766 
6767  /*
6768  * Left join to pg_depend to pick up dependency info linking sequences to
6769  * their owning column, if any (note this dependency is AUTO except for
6770  * identity sequences, where it's INTERNAL). Also join to pg_tablespace to
6771  * collect the spcname.
6772  */
6773  appendPQExpBufferStr(query,
6774  "\nFROM pg_class c\n"
6775  "LEFT JOIN pg_depend d ON "
6776  "(c.relkind = " CppAsString2(RELKIND_SEQUENCE) " AND "
6777  "d.classid = 'pg_class'::regclass AND d.objid = c.oid AND "
6778  "d.objsubid = 0 AND "
6779  "d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i'))\n"
6780  "LEFT JOIN pg_tablespace tsp ON (tsp.oid = c.reltablespace)\n");
6781 
6782  /*
6783  * In 9.6 and up, left join to pg_am to pick up the amname.
6784  */
6785  if (fout->remoteVersion >= 90600)
6786  appendPQExpBufferStr(query,
6787  "LEFT JOIN pg_am am ON (c.relam = am.oid)\n");
6788 
6789  /*
6790  * We purposefully ignore toast OIDs for partitioned tables; the reason is
6791  * that versions 10 and 11 have them, but later versions do not, so
6792  * emitting them causes the upgrade to fail.
6793  */
6794  appendPQExpBufferStr(query,
6795  "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid"
6796  " AND tc.relkind = " CppAsString2(RELKIND_TOASTVALUE)
6797  " AND c.relkind <> " CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n");
6798 
6799  /*
6800  * Restrict to interesting relkinds (in particular, not indexes). Not all
6801  * relkinds are possible in older servers, but it's not worth the trouble
6802  * to emit a version-dependent list.
6803  *
6804  * Composite-type table entries won't be dumped as such, but we have to
6805  * make a DumpableObject for them so that we can track dependencies of the
6806  * composite type (pg_depend entries for columns of the composite type
6807  * link to the pg_class entry not the pg_type entry).
6808  */
6809  appendPQExpBufferStr(query,
6810  "WHERE c.relkind IN ("
6811  CppAsString2(RELKIND_RELATION) ", "
6812  CppAsString2(RELKIND_SEQUENCE) ", "
6813  CppAsString2(RELKIND_VIEW) ", "
6814  CppAsString2(RELKIND_COMPOSITE_TYPE) ", "
6815  CppAsString2(RELKIND_MATVIEW) ", "
6816  CppAsString2(RELKIND_FOREIGN_TABLE) ", "
6817  CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n"
6818  "ORDER BY c.oid");
6819 
6820  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6821 
6822  ntups = PQntuples(res);
6823 
6824  *numTables = ntups;
6825 
6826  /*
6827  * Extract data from result and lock dumpable tables. We do the locking
6828  * before anything else, to minimize the window wherein a table could
6829  * disappear under us.
6830  *
6831  * Note that we have to save info about all tables here, even when dumping
6832  * only one, because we don't yet know which tables might be inheritance
6833  * ancestors of the target table.
6834  */
6835  tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6836 
6837  i_reltableoid = PQfnumber(res, "tableoid");
6838  i_reloid = PQfnumber(res, "oid");
6839  i_relname = PQfnumber(res, "relname");
6840  i_relnamespace = PQfnumber(res, "relnamespace");
6841  i_relkind = PQfnumber(res, "relkind");
6842  i_reltype = PQfnumber(res, "reltype");
6843  i_relowner = PQfnumber(res, "relowner");
6844  i_relchecks = PQfnumber(res, "relchecks");
6845  i_relhasindex = PQfnumber(res, "relhasindex");
6846  i_relhasrules = PQfnumber(res, "relhasrules");
6847  i_relpages = PQfnumber(res, "relpages");
6848  i_toastpages = PQfnumber(res, "toastpages");
6849  i_owning_tab = PQfnumber(res, "owning_tab");
6850  i_owning_col = PQfnumber(res, "owning_col");
6851  i_reltablespace = PQfnumber(res, "reltablespace");
6852  i_relhasoids = PQfnumber(res, "relhasoids");
6853  i_relhastriggers = PQfnumber(res, "relhastriggers");
6854  i_relpersistence = PQfnumber(res, "relpersistence");
6855  i_relispopulated = PQfnumber(res, "relispopulated");
6856  i_relreplident = PQfnumber(res, "relreplident");
6857  i_relrowsec = PQfnumber(res, "relrowsecurity");
6858  i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6859  i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6860  i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6861  i_toastoid = PQfnumber(res, "toid");
6862  i_relminmxid = PQfnumber(res, "relminmxid");
6863  i_toastminmxid = PQfnumber(res, "tminmxid");
6864  i_reloptions = PQfnumber(res, "reloptions");
6865  i_checkoption = PQfnumber(res, "checkoption");
6866  i_toastreloptions = PQfnumber(res, "toast_reloptions");
6867  i_reloftype = PQfnumber(res, "reloftype");
6868  i_foreignserver = PQfnumber(res, "foreignserver");
6869  i_amname = PQfnumber(res, "amname");
6870  i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6871  i_relacl = PQfnumber(res, "relacl");
6872  i_acldefault = PQfnumber(res, "acldefault");
6873  i_ispartition = PQfnumber(res, "ispartition");
6874 
6875  if (dopt->lockWaitTimeout)
6876  {
6877  /*
6878  * Arrange to fail instead of waiting forever for a table lock.
6879  *
6880  * NB: this coding assumes that the only queries issued within the
6881  * following loop are LOCK TABLEs; else the timeout may be undesirably
6882  * applied to other things too.
6883  */
6884  resetPQExpBuffer(query);
6885  appendPQExpBufferStr(query, "SET statement_timeout = ");
6887  ExecuteSqlStatement(fout, query->data);
6888  }
6889 
6890  resetPQExpBuffer(query);
6891 
6892  for (i = 0; i < ntups; i++)
6893  {
6894  tblinfo[i].dobj.objType = DO_TABLE;
6895  tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6896  tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6897  AssignDumpId(&tblinfo[i].dobj);
6898  tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6899  tblinfo[i].dobj.namespace =
6900  findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)));
6901  tblinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_relacl));
6902  tblinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
6903  tblinfo[i].dacl.privtype = 0;
6904  tblinfo[i].dacl.initprivs = NULL;
6905  tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6906  tblinfo[i].reltype = atooid(PQgetvalue(res, i, i_reltype));
6907  tblinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_relowner));
6908  tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6909  tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6910  tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6911  tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6912  if (PQgetisnull(res, i, i_toastpages))
6913  tblinfo[i].toastpages = 0;
6914  else
6915  tblinfo[i].toastpages = atoi(PQgetvalue(res, i, i_toastpages));
6916  if (PQgetisnull(res, i, i_owning_tab))
6917  {
6918  tblinfo[i].owning_tab = InvalidOid;
6919  tblinfo[i].owning_col = 0;
6920  }
6921  else
6922  {
6923  tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6924  tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6925  }
6926  tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6927  tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6928  tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6929  tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6930  tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6931  tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6932  tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6933  tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6934  tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6935  tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6936  tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6937  tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6938  tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6939  tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6940  if (PQgetisnull(res, i, i_checkoption))
6941  tblinfo[i].checkoption = NULL;
6942  else
6943  tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6944  tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6945  tblinfo[i].reloftype = atooid(PQgetvalue(res, i, i_reloftype));
6946  tblinfo[i].foreign_server = atooid(PQgetvalue(res, i, i_foreignserver));
6947  if (PQgetisnull(res, i, i_amname))
6948  tblinfo[i].amname = NULL;
6949  else
6950  tblinfo[i].amname = pg_strdup(PQgetvalue(res, i, i_amname));
6951  tblinfo[i].is_identity_sequence = (strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6952  tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6953 
6954  /* other fields were zeroed above */
6955 
6956  /*
6957  * Decide whether we want to dump this table.
6958  */
6959  if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6960  tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6961  else
6962  selectDumpableTable(&tblinfo[i], fout);
6963 
6964  /*
6965  * Now, consider the table "interesting" if we need to dump its
6966  * definition or its data. Later on, we'll skip a lot of data
6967  * collection for uninteresting tables.
6968  *
6969  * Note: the "interesting" flag will also be set by flagInhTables for
6970  * parents of interesting tables, so that we collect necessary
6971  * inheritance info even when the parents are not themselves being
6972  * dumped. This is the main reason why we need an "interesting" flag
6973  * that's separate from the components-to-dump bitmask.
6974  */
6975  tblinfo[i].interesting = (tblinfo[i].dobj.dump &
6977  DUMP_COMPONENT_DATA)) != 0;
6978 
6979  tblinfo[i].dummy_view = false; /* might get set during sort */
6980  tblinfo[i].postponed_def = false; /* might get set during sort */
6981 
6982  /* Tables have data */
6983  tblinfo[i].dobj.components |= DUMP_COMPONENT_DATA;
6984 
6985  /* Mark whether table has an ACL */
6986  if (!PQgetisnull(res, i, i_relacl))
6987  tblinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
6988  tblinfo[i].hascolumnACLs = false; /* may get set later */
6989 
6990  /*
6991  * Read-lock target tables to make sure they aren't DROPPED or altered
6992  * in schema before we get around to dumping them.
6993  *
6994  * Note that we don't explicitly lock parents of the target tables; we
6995  * assume our lock on the child is enough to prevent schema
6996  * alterations to parent tables.
6997  *
6998  * NOTE: it'd be kinda nice to lock other relations too, not only
6999  * plain or partitioned tables, but the backend doesn't presently
7000  * allow that.
7001  *
7002  * We only need to lock the table for certain components; see
7003  * pg_dump.h
7004  */
7005  if ((tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK) &&
7006  (tblinfo[i].relkind == RELKIND_RELATION ||
7007  tblinfo[i].relkind == RELKIND_PARTITIONED_TABLE))
7008  {
7009  /*
7010  * Tables are locked in batches. When dumping from a remote
7011  * server this can save a significant amount of time by reducing
7012  * the number of round trips.
7013  */
7014  if (query->len == 0)
7015  appendPQExpBuffer(query, "LOCK TABLE %s",
7016  fmtQualifiedDumpable(&tblinfo[i]));
7017  else
7018  {
7019  appendPQExpBuffer(query, ", %s",
7020  fmtQualifiedDumpable(&tblinfo[i]));
7021 
7022  /* Arbitrarily end a batch when query length reaches 100K. */
7023  if (query->len >= 100000)
7024  {
7025  /* Lock another batch of tables. */
7026  appendPQExpBufferStr(query, " IN ACCESS SHARE MODE");
7027  ExecuteSqlStatement(fout, query->data);
7028  resetPQExpBuffer(query);
7029  }
7030  }
7031  }
7032  }
7033 
7034  if (query->len != 0)
7035  {
7036  /* Lock the tables in the last batch. */
7037  appendPQExpBufferStr(query, " IN ACCESS SHARE MODE");
7038  ExecuteSqlStatement(fout, query->data);
7039  }
7040 
7041  if (dopt->lockWaitTimeout)
7042  {
7043  ExecuteSqlStatement(fout, "SET statement_timeout = 0");
7044  }
7045 
7046  PQclear(res);
7047 
7048  destroyPQExpBuffer(query);
7049 
7050  return tblinfo;
7051 }
7052 
7053 /*
7054  * getOwnedSeqs
7055  * identify owned sequences and mark them as dumpable if owning table is
7056  *
7057  * We used to do this in getTables(), but it's better to do it after the
7058  * index used by findTableByOid() has been set up.
7059  */
7060 void
7061 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
7062 {
7063  int i;
7064 
7065  /*
7066  * Force sequences that are "owned" by table columns to be dumped whenever
7067  * their owning table is being dumped.
7068  */
7069  for (i = 0; i < numTables; i++)
7070  {
7071  TableInfo *seqinfo = &tblinfo[i];
7072  TableInfo *owning_tab;
7073 
7074  if (!OidIsValid(seqinfo->owning_tab))
7075  continue; /* not an owned sequence */
7076 
7077  owning_tab = findTableByOid(seqinfo->owning_tab);
7078  if (owning_tab == NULL)
7079  pg_fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
7080  seqinfo->owning_tab, seqinfo->dobj.catId.oid);
7081 
7082  /*
7083  * Only dump identity sequences if we're going to dump the table that
7084  * it belongs to.
7085  */
7086  if (owning_tab->dobj.dump == DUMP_COMPONENT_NONE &&
7087  seqinfo->is_identity_sequence)
7088  {
7089  seqinfo->dobj.dump = DUMP_COMPONENT_NONE;
7090  continue;
7091  }
7092 
7093  /*
7094  * Otherwise we need to dump the components that are being dumped for
7095  * the table and any components which the sequence is explicitly
7096  * marked with.
7097  *
7098  * We can't simply use the set of components which are being dumped
7099  * for the table as the table might be in an extension (and only the
7100  * non-extension components, eg: ACLs if changed, security labels, and
7101  * policies, are being dumped) while the sequence is not (and
7102  * therefore the definition and other components should also be
7103  * dumped).
7104  *
7105  * If the sequence is part of the extension then it should be properly
7106  * marked by checkExtensionMembership() and this will be a no-op as
7107  * the table will be equivalently marked.
7108  */
7109  seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
7110 
7111  if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
7112  seqinfo->interesting = true;
7113  }
7114 }
7115 
7116 /*
7117  * getInherits
7118  * read all the inheritance information
7119  * from the system catalogs return them in the InhInfo* structure
7120  *
7121  * numInherits is set to the number of pairs read in
7122  */
7123 InhInfo *
7124 getInherits(Archive *fout, int *numInherits)
7125 {
7126  PGresult *res;
7127  int ntups;
7128  int i;
7129  PQExpBuffer query = createPQExpBuffer();
7130  InhInfo *inhinfo;
7131 
7132  int i_inhrelid;
7133  int i_inhparent;
7134 
7135  /* find all the inheritance information */
7136  appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
7137 
7138  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7139 
7140  ntups = PQntuples(res);
7141 
7142  *numInherits = ntups;
7143 
7144  inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
7145 
7146  i_inhrelid = PQfnumber(res, "inhrelid");
7147  i_inhparent = PQfnumber(res, "inhparent");
7148 
7149  for (i = 0; i < ntups; i++)
7150  {
7151  inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
7152  inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
7153  }
7154 
7155  PQclear(res);
7156 
7157  destroyPQExpBuffer(query);
7158 
7159  return inhinfo;
7160 }
7161 
7162 /*
7163  * getPartitioningInfo
7164  * get information about partitioning
7165  *
7166  * For the most part, we only collect partitioning info about tables we
7167  * intend to dump. However, this function has to consider all partitioned
7168  * tables in the database, because we need to know about parents of partitions
7169  * we are going to dump even if the parents themselves won't be dumped.
7170  *
7171  * Specifically, what we need to know is whether each partitioned table
7172  * has an "unsafe" partitioning scheme that requires us to force
7173  * load-via-partition-root mode for its children. Currently the only case
7174  * for which we force that is hash partitioning on enum columns, since the
7175  * hash codes depend on enum value OIDs which won't be replicated across
7176  * dump-and-reload. There are other cases in which load-via-partition-root
7177  * might be necessary, but we expect users to cope with them.
7178  */
7179 void
7181 {
7182  PQExpBuffer query;
7183  PGresult *res;
7184  int ntups;
7185 
7186  /* hash partitioning didn't exist before v11 */
7187  if (fout->remoteVersion < 110000)
7188  return;
7189  /* needn't bother if schema-only dump */
7190  if (fout->dopt->schemaOnly)
7191  return;
7192 
7193  query = createPQExpBuffer();
7194 
7195  /*
7196  * Unsafe partitioning schemes are exactly those for which hash enum_ops
7197  * appears among the partition opclasses. We needn't check partstrat.
7198  *
7199  * Note that this query may well retrieve info about tables we aren't
7200  * going to dump and hence have no lock on. That's okay since we need not
7201  * invoke any unsafe server-side functions.
7202  */
7203  appendPQExpBufferStr(query,
7204  "SELECT partrelid FROM pg_partitioned_table WHERE\n"
7205  "(SELECT c.oid FROM pg_opclass c JOIN pg_am a "
7206  "ON c.opcmethod = a.oid\n"
7207  "WHERE opcname = 'enum_ops' "
7208  "AND opcnamespace = 'pg_catalog'::regnamespace "
7209  "AND amname = 'hash') = ANY(partclass)");
7210 
7211  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7212 
7213  ntups = PQntuples(res);
7214 
7215  for (int i = 0; i < ntups; i++)
7216  {
7217  Oid tabrelid = atooid(PQgetvalue(res, i, 0));
7218  TableInfo *tbinfo;
7219 
7220  tbinfo = findTableByOid(tabrelid);
7221  if (tbinfo == NULL)
7222  pg_fatal("failed sanity check, table OID %u appearing in pg_partitioned_table not found",
7223  tabrelid);
7224  tbinfo->unsafe_partitions = true;
7225  }
7226 
7227  PQclear(res);
7228 
7229  destroyPQExpBuffer(query);
7230 }
7231 
7232 /*
7233  * getIndexes
7234  * get information about every index on a dumpable table
7235  *
7236  * Note: index data is not returned directly to the caller, but it
7237  * does get entered into the DumpableObject tables.
7238  */
7239 void
7240 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
7241 {
7242  PQExpBuffer query = createPQExpBuffer();
7243  PQExpBuffer tbloids = createPQExpBuffer();
7244  PGresult *res;
7245  int ntups;
7246  int curtblindx;
7247  IndxInfo *indxinfo;
7248  int i_tableoid,
7249  i_oid,
7250  i_indrelid,
7251  i_indexname,
7252  i_parentidx,
7253  i_indexdef,
7254  i_indnkeyatts,
7255  i_indnatts,
7256  i_indkey,
7257  i_indisclustered,
7258  i_indisreplident,
7259  i_indnullsnotdistinct,
7260  i_contype,
7261  i_conname,
7262  i_condeferrable,
7263  i_condeferred,
7264  i_conperiod,
7265  i_contableoid,
7266  i_conoid,
7267  i_condef,
7268  i_tablespace,
7269  i_indreloptions,
7270  i_indstatcols,
7271  i_indstatvals;
7272 
7273  /*
7274  * We want to perform just one query against pg_index. However, we
7275  * mustn't try to select every row of the catalog and then sort it out on
7276  * the client side, because some of the server-side functions we need
7277  * would be unsafe to apply to tables we don't have lock on. Hence, we
7278  * build an array of the OIDs of tables we care about (and now have lock
7279  * on!), and use a WHERE clause to constrain which rows are selected.
7280  */
7281  appendPQExpBufferChar(tbloids, '{');
7282  for (int i = 0; i < numTables; i++)
7283  {
7284  TableInfo *tbinfo = &tblinfo[i];
7285 
7286  if (!tbinfo->hasindex)
7287  continue;
7288 
7289  /*
7290  * We can ignore indexes of uninteresting tables.
7291  */
7292  if (!tbinfo->interesting)
7293  continue;
7294 
7295  /* OK, we need info for this table */
7296  if (tbloids->len > 1) /* do we have more than the '{'? */
7297  appendPQExpBufferChar(tbloids, ',');
7298  appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
7299  }
7300  appendPQExpBufferChar(tbloids, '}');
7301 
7302  appendPQExpBufferStr(query,
7303  "SELECT t.tableoid, t.oid, i.indrelid, "
7304  "t.relname AS indexname, "
7305  "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7306  "i.indkey, i.indisclustered, "
7307  "c.contype, c.conname, "
7308  "c.condeferrable, c.condeferred, "
7309  "c.tableoid AS contableoid, "
7310  "c.oid AS conoid, "
7311  "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7312  "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7313  "t.reloptions AS indreloptions, ");
7314 
7315 
7316  if (fout->remoteVersion >= 90400)
7317  appendPQExpBufferStr(query,
7318  "i.indisreplident, ");
7319  else
7320  appendPQExpBufferStr(query,
7321  "false AS indisreplident, ");
7322 
7323  if (fout->remoteVersion >= 110000)
7324  appendPQExpBufferStr(query,
7325  "inh.inhparent AS parentidx, "
7326  "i.indnkeyatts AS indnkeyatts, "
7327  "i.indnatts AS indnatts, "
7328  "(SELECT pg_catalog.array_agg(attnum ORDER BY attnum) "
7329  " FROM pg_catalog.pg_attribute "
7330  " WHERE attrelid = i.indexrelid AND "
7331  " attstattarget >= 0) AS indstatcols, "
7332  "(SELECT pg_catalog.array_agg(attstattarget ORDER BY attnum) "
7333  " FROM pg_catalog.pg_attribute "
7334  " WHERE attrelid = i.indexrelid AND "
7335  " attstattarget >= 0) AS indstatvals, ");
7336  else
7337  appendPQExpBufferStr(query,
7338  "0 AS parentidx, "
7339  "i.indnatts AS indnkeyatts, "
7340  "i.indnatts AS indnatts, "
7341  "'' AS indstatcols, "
7342  "'' AS indstatvals, ");
7343 
7344  if (fout->remoteVersion >= 150000)
7345  appendPQExpBufferStr(query,
7346  "i.indnullsnotdistinct, ");
7347  else
7348  appendPQExpBufferStr(query,
7349  "false AS indnullsnotdistinct, ");
7350 
7351  if (fout->remoteVersion >= 170000)
7352  appendPQExpBufferStr(query,
7353  "c.conperiod ");
7354  else
7355  appendPQExpBufferStr(query,
7356  "NULL AS conperiod ");
7357 
7358  /*
7359  * The point of the messy-looking outer join is to find a constraint that
7360  * is related by an internal dependency link to the index. If we find one,
7361  * create a CONSTRAINT entry linked to the INDEX entry. We assume an
7362  * index won't have more than one internal dependency.
7363  *
7364  * Note: the check on conrelid is redundant, but useful because that
7365  * column is indexed while conindid is not.
7366  */
7367  if (fout->remoteVersion >= 110000)
7368  {
7369  appendPQExpBuffer(query,
7370  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
7371  "JOIN pg_catalog.pg_index i ON (src.tbloid = i.indrelid) "
7372  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7373  "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
7374  "LEFT JOIN pg_catalog.pg_constraint c "
7375  "ON (i.indrelid = c.conrelid AND "
7376  "i.indexrelid = c.conindid AND "
7377  "c.contype IN ('p','u','x')) "
7378  "LEFT JOIN pg_catalog.pg_inherits inh "
7379  "ON (inh.inhrelid = indexrelid) "
7380  "WHERE (i.indisvalid OR t2.relkind = 'p') "
7381  "AND i.indisready "
7382  "ORDER BY i.indrelid, indexname",
7383  tbloids->data);
7384  }
7385  else
7386  {
7387  /*
7388  * the test on indisready is necessary in 9.2, and harmless in
7389  * earlier/later versions
7390  */
7391  appendPQExpBuffer(query,
7392  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
7393  "JOIN pg_catalog.pg_index i ON (src.tbloid = i.indrelid) "
7394  "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7395  "LEFT JOIN pg_catalog.pg_constraint c "
7396  "ON (i.indrelid = c.conrelid AND "
7397  "i.indexrelid = c.conindid AND "
7398  "c.contype IN ('p','u','x')) "
7399  "WHERE i.indisvalid AND i.indisready "
7400  "ORDER BY i.indrelid, indexname",
7401  tbloids->data);
7402  }
7403 
7404  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7405 
7406  ntups = PQntuples(res);
7407 
7408  i_tableoid = PQfnumber(res, "tableoid");
7409  i_oid = PQfnumber(res, "oid");
7410  i_indrelid = PQfnumber(res, "indrelid");
7411  i_indexname = PQfnumber(res, "indexname");
7412  i_parentidx = PQfnumber(res, "parentidx");
7413  i_indexdef = PQfnumber(res, "indexdef");
7414  i_indnkeyatts = PQfnumber(res, "indnkeyatts");
7415  i_indnatts = PQfnumber(res, "indnatts");
7416  i_indkey = PQfnumber(res, "indkey");
7417  i_indisclustered = PQfnumber(res, "indisclustered");
7418  i_indisreplident = PQfnumber(res, "indisreplident");
7419  i_indnullsnotdistinct = PQfnumber(res, "indnullsnotdistinct");
7420  i_contype = PQfnumber(res, "contype");
7421  i_conname = PQfnumber(res, "conname");
7422  i_condeferrable = PQfnumber(res, "condeferrable");
7423  i_condeferred = PQfnumber(res, "condeferred");
7424  i_conperiod = PQfnumber(res, "conperiod");
7425  i_contableoid = PQfnumber(res, "contableoid");
7426  i_conoid = PQfnumber(res, "conoid");
7427  i_condef = PQfnumber(res, "condef");
7428  i_tablespace = PQfnumber(res, "tablespace");
7429  i_indreloptions = PQfnumber(res, "indreloptions");
7430  i_indstatcols = PQfnumber(res, "indstatcols");
7431  i_indstatvals = PQfnumber(res, "indstatvals");
7432 
7433  indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
7434 
7435  /*
7436  * Outer loop iterates once per table, not once per row. Incrementing of
7437  * j is handled by the inner loop.
7438  */
7439  curtblindx = -1;
7440  for (int j = 0; j < ntups;)
7441  {
7442  Oid indrelid = atooid(PQgetvalue(res, j, i_indrelid));
7443  TableInfo *tbinfo = NULL;
7444  int numinds;
7445 
7446  /* Count rows for this table */
7447  for (numinds = 1; numinds < ntups - j; numinds++)
7448  if (atooid(PQgetvalue(res, j + numinds, i_indrelid)) != indrelid)
7449  break;
7450 
7451  /*
7452  * Locate the associated TableInfo; we rely on tblinfo[] being in OID
7453  * order.
7454  */
7455  while (++curtblindx < numTables)
7456  {
7457  tbinfo = &tblinfo[curtblindx];
7458  if (tbinfo->dobj.catId.oid == indrelid)
7459  break;
7460  }
7461  if (curtblindx >= numTables)
7462  pg_fatal("unrecognized table OID %u", indrelid);
7463  /* cross-check that we only got requested tables */
7464  if (!tbinfo->hasindex ||
7465  !tbinfo->interesting)
7466  pg_fatal("unexpected index data for table \"%s\"",
7467  tbinfo->dobj.name);
7468 
7469  /* Save data for this table */
7470  tbinfo->indexes = indxinfo + j;
7471  tbinfo->numIndexes = numinds;
7472 
7473  for (int c = 0; c < numinds; c++, j++)
7474  {
7475  char contype;
7476 
7477  indxinfo[j].dobj.objType = DO_INDEX;
7478  indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7479  indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7480  AssignDumpId(&indxinfo[j].dobj);
7481  indxinfo[j].dobj.dump = tbinfo->dobj.dump;
7482  indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
7483  indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7484  indxinfo[j].indextable = tbinfo;
7485  indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
7486  indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
7487  indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
7488  indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
7489  indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
7490  indxinfo[j].indstatcols = pg_strdup(PQgetvalue(res, j, i_indstatcols));
7491  indxinfo[j].indstatvals = pg_strdup(PQgetvalue(res, j, i_indstatvals));
7492  indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
7493  parseOidArray(PQgetvalue(res, j, i_indkey),
7494  indxinfo[j].indkeys, indxinfo[j].indnattrs);
7495  indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
7496  indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
7497  indxinfo[j].indnullsnotdistinct = (PQgetvalue(res, j, i_indnullsnotdistinct)[0] == 't');
7498  indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
7499  indxinfo[j].partattaches = (SimplePtrList)
7500  {
7501  NULL, NULL
7502  };
7503  contype = *(PQgetvalue(res, j, i_contype));
7504 
7505  if (contype == 'p' || contype == 'u' || contype == 'x')
7506  {
7507  /*
7508  * If we found a constraint matching the index, create an
7509  * entry for it.
7510  */
7511  ConstraintInfo *constrinfo;
7512 
7513  constrinfo = (ConstraintInfo *) pg_malloc(sizeof(ConstraintInfo));
7514  constrinfo->dobj.objType = DO_CONSTRAINT;
7515  constrinfo->dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7516  constrinfo->dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7517  AssignDumpId(&constrinfo->dobj);
7518  constrinfo->dobj.dump = tbinfo->dobj.dump;
7519  constrinfo->dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7520  constrinfo->dobj.namespace = tbinfo->dobj.namespace;
7521  constrinfo->contable = tbinfo;
7522  constrinfo->condomain = NULL;
7523  constrinfo->contype = contype;
7524  if (contype == 'x')
7525  constrinfo->condef = pg_strdup(PQgetvalue(res, j, i_condef));
7526  else
7527  constrinfo->condef = NULL;
7528  constrinfo->confrelid = InvalidOid;
7529  constrinfo->conindex = indxinfo[j].dobj.dumpId;
7530  constrinfo->condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7531  constrinfo->condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7532  constrinfo->conperiod = *(PQgetvalue(res, j, i_conperiod)) == 't';
7533  constrinfo->conislocal = true;
7534  constrinfo->separate = true;
7535 
7536  indxinfo[j].indexconstraint = constrinfo->dobj.dumpId;
7537  }
7538  else
7539  {
7540  /* Plain secondary index */
7541  indxinfo[j].indexconstraint = 0;
7542  }
7543  }
7544  }
7545 
7546  PQclear(res);
7547 
7548  destroyPQExpBuffer(query);
7549  destroyPQExpBuffer(tbloids);
7550 }
7551 
7552 /*
7553  * getExtendedStatistics
7554  * get information about extended-statistics objects.
7555  *
7556  * Note: extended statistics data is not returned directly to the caller, but
7557  * it does get entered into the DumpableObject tables.
7558  */
7559 void
7561 {
7562  PQExpBuffer query;
7563  PGresult *res;
7564  StatsExtInfo *statsextinfo;
7565  int ntups;
7566  int i_tableoid;
7567  int i_oid;
7568  int i_stxname;
7569  int i_stxnamespace;
7570  int i_stxowner;
7571  int i_stxrelid;
7572  int i_stattarget;
7573  int i;
7574 
7575  /* Extended statistics were new in v10 */
7576  if (fout->remoteVersion < 100000)
7577  return;
7578 
7579  query = createPQExpBuffer();
7580 
7581  if (fout->remoteVersion < 130000)
7582  appendPQExpBufferStr(query, "SELECT tableoid, oid, stxname, "
7583  "stxnamespace, stxowner, stxrelid, NULL AS stxstattarget "
7584  "FROM pg_catalog.pg_statistic_ext");
7585  else
7586  appendPQExpBufferStr(query, "SELECT tableoid, oid, stxname, "
7587  "stxnamespace, stxowner, stxrelid, stxstattarget "
7588  "FROM pg_catalog.pg_statistic_ext");
7589 
7590  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7591 
7592  ntups = PQntuples(res);
7593 
7594  i_tableoid = PQfnumber(res, "tableoid");
7595  i_oid = PQfnumber(res, "oid");
7596  i_stxname = PQfnumber(res, "stxname");
7597  i_stxnamespace = PQfnumber(res, "stxnamespace");
7598  i_stxowner = PQfnumber(res, "stxowner");
7599  i_stxrelid = PQfnumber(res, "stxrelid");
7600  i_stattarget = PQfnumber(res, "stxstattarget");
7601 
7602  statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7603 
7604  for (i = 0; i < ntups; i++)
7605  {
7606  statsextinfo[i].dobj.objType = DO_STATSEXT;
7607  statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7608  statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7609  AssignDumpId(&statsextinfo[i].dobj);
7610  statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7611  statsextinfo[i].dobj.namespace =
7612  findNamespace(atooid(PQgetvalue(res, i, i_stxnamespace)));
7613  statsextinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_stxowner));
7614  statsextinfo[i].stattable =
7615  findTableByOid(atooid(PQgetvalue(res, i, i_stxrelid)));
7616  if (PQgetisnull(res, i, i_stattarget))
7617  statsextinfo[i].stattarget = -1;
7618  else
7619  statsextinfo[i].stattarget = atoi(PQgetvalue(res, i, i_stattarget));
7620 
7621  /* Decide whether we want to dump it */
7622  selectDumpableStatisticsObject(&(statsextinfo[i]), fout);
7623  }
7624 
7625  PQclear(res);
7626  destroyPQExpBuffer(query);
7627 }
7628 
7629 /*
7630  * getConstraints
7631  *
7632  * Get info about constraints on dumpable tables.
7633  *
7634  * Currently handles foreign keys only.
7635  * Unique and primary key constraints are handled with indexes,
7636  * while check constraints are processed in getTableAttrs().
7637  */
7638 void
7639 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7640 {
7641  PQExpBuffer query = createPQExpBuffer();
7642  PQExpBuffer tbloids = createPQExpBuffer();
7643  PGresult *res;
7644  int ntups;
7645  int curtblindx;
7646  TableInfo *tbinfo = NULL;
7647  ConstraintInfo *constrinfo;
7648  int i_contableoid,
7649  i_conoid,
7650  i_conrelid,
7651  i_conname,
7652  i_confrelid,
7653  i_conindid,
7654  i_condef;
7655 
7656  /*
7657  * We want to perform just one query against pg_constraint. However, we
7658  * mustn't try to select every row of the catalog and then sort it out on
7659  * the client side, because some of the server-side functions we need
7660  * would be unsafe to apply to tables we don't have lock on. Hence, we
7661  * build an array of the OIDs of tables we care about (and now have lock
7662  * on!), and use a WHERE clause to constrain which rows are selected.
7663  */
7664  appendPQExpBufferChar(tbloids, '{');
7665  for (int i = 0; i < numTables; i++)
7666  {
7667  TableInfo *tinfo = &tblinfo[i];
7668 
7669  /*
7670  * For partitioned tables, foreign keys have no triggers so they must
7671  * be included anyway in case some foreign keys are defined.
7672  */
7673  if ((!tinfo->hastriggers &&
7674  tinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7675  !(tinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7676  continue;
7677 
7678  /* OK, we need info for this table */
7679  if (tbloids->len > 1) /* do we have more than the '{'? */
7680  appendPQExpBufferChar(tbloids, ',');
7681  appendPQExpBuffer(tbloids, "%u", tinfo->dobj.catId.oid);
7682  }
7683  appendPQExpBufferChar(tbloids, '}');
7684 
7685  appendPQExpBufferStr(query,
7686  "SELECT c.tableoid, c.oid, "
7687  "conrelid, conname, confrelid, ");
7688  if (fout->remoteVersion >= 110000)
7689  appendPQExpBufferStr(query, "conindid, ");
7690  else
7691  appendPQExpBufferStr(query, "0 AS conindid, ");
7692  appendPQExpBuffer(query,
7693  "pg_catalog.pg_get_constraintdef(c.oid) AS condef\n"
7694  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
7695  "JOIN pg_catalog.pg_constraint c ON (src.tbloid = c.conrelid)\n"
7696  "WHERE contype = 'f' ",
7697  tbloids->data);
7698  if (fout->remoteVersion >= 110000)
7699  appendPQExpBufferStr(query,
7700  "AND conparentid = 0 ");
7701  appendPQExpBufferStr(query,
7702  "ORDER BY conrelid, conname");
7703 
7704  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7705 
7706  ntups = PQntuples(res);
7707 
7708  i_contableoid = PQfnumber(res, "tableoid");
7709  i_conoid = PQfnumber(res, "oid");
7710  i_conrelid = PQfnumber(res, "conrelid");
7711  i_conname = PQfnumber(res, "conname");
7712  i_confrelid = PQfnumber(res, "confrelid");
7713  i_conindid = PQfnumber(res, "conindid");
7714  i_condef = PQfnumber(res, "condef");
7715 
7716  constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7717 
7718  curtblindx = -1;
7719  for (int j = 0; j < ntups; j++)
7720  {
7721  Oid conrelid = atooid(PQgetvalue(res, j, i_conrelid));
7722  TableInfo *reftable;
7723 
7724  /*
7725  * Locate the associated TableInfo; we rely on tblinfo[] being in OID
7726  * order.
7727  */
7728  if (tbinfo == NULL || tbinfo->dobj.catId.oid != conrelid)
7729  {
7730  while (++curtblindx < numTables)
7731  {
7732  tbinfo = &tblinfo[curtblindx];
7733  if (tbinfo->dobj.catId.oid == conrelid)
7734  break;
7735  }
7736  if (curtblindx >= numTables)
7737  pg_fatal("unrecognized table OID %u", conrelid);
7738  }
7739 
7740  constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7741  constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7742  constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7743  AssignDumpId(&constrinfo[j].dobj);
7744  constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7745  constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7746  constrinfo[j].contable = tbinfo;
7747  constrinfo[j].condomain = NULL;
7748  constrinfo[j].contype = 'f';
7749  constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7750  constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7751  constrinfo[j].conindex = 0;
7752  constrinfo[j].condeferrable = false;
7753  constrinfo[j].condeferred = false;
7754  constrinfo[j].conislocal = true;
7755  constrinfo[j].separate = true;
7756 
7757  /*
7758  * Restoring an FK that points to a partitioned table requires that
7759  * all partition indexes have been attached beforehand. Ensure that
7760  * happens by making the constraint depend on each index partition
7761  * attach object.
7762  */
7763  reftable = findTableByOid(constrinfo[j].confrelid);
7764  if (reftable && reftable->relkind == RELKIND_PARTITIONED_TABLE)
7765  {
7766  Oid indexOid = atooid(PQgetvalue(res, j, i_conindid));
7767 
7768  if (indexOid != InvalidOid)
7769  {
7770  for (int k = 0; k < reftable->numIndexes; k++)
7771  {
7772  IndxInfo *refidx;
7773 
7774  /* not our index? */
7775  if (reftable->indexes[k].dobj.catId.oid != indexOid)
7776  continue;
7777 
7778  refidx = &reftable->indexes[k];
7779  addConstrChildIdxDeps(&constrinfo[j].dobj, refidx);
7780  break;
7781  }
7782  }
7783  }
7784  }
7785 
7786  PQclear(res);
7787 
7788  destroyPQExpBuffer(query);
7789  destroyPQExpBuffer(tbloids);
7790 }
7791 
7792 /*
7793  * addConstrChildIdxDeps
7794  *
7795  * Recursive subroutine for getConstraints
7796  *
7797  * Given an object representing a foreign key constraint and an index on the
7798  * partitioned table it references, mark the constraint object as dependent
7799  * on the DO_INDEX_ATTACH object of each index partition, recursively
7800  * drilling down to their partitions if any. This ensures that the FK is not
7801  * restored until the index is fully marked valid.
7802  */
7803 static void
7805 {
7806  SimplePtrListCell *cell;
7807 
7808  Assert(dobj->objType == DO_FK_CONSTRAINT);
7809 
7810  for (cell = refidx->partattaches.head; cell; cell = cell->next)
7811  {
7812  IndexAttachInfo *attach = (IndexAttachInfo *) cell->ptr;
7813 
7814  addObjectDependency(dobj, attach->dobj.dumpId);
7815 
7816  if (attach->partitionIdx->partattaches.head != NULL)
7817  addConstrChildIdxDeps(dobj, attach->partitionIdx);
7818  }
7819 }
7820 
7821 /*
7822  * getDomainConstraints
7823  *
7824  * Get info about constraints on a domain.
7825  */
7826 static void
7828 {
7829  int i;
7830  ConstraintInfo *constrinfo;
7831  PQExpBuffer query = createPQExpBuffer();
7832  PGresult *res;
7833  int i_tableoid,
7834  i_oid,
7835  i_conname,
7836  i_consrc;
7837  int ntups;
7838 
7840  {
7841  /* Set up query for constraint-specific details */
7842  appendPQExpBufferStr(query,
7843  "PREPARE getDomainConstraints(pg_catalog.oid) AS\n"
7844  "SELECT tableoid, oid, conname, "
7845  "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7846  "convalidated "
7847  "FROM pg_catalog.pg_constraint "
7848  "WHERE contypid = $1 "
7849  "ORDER BY conname");
7850 
7851  ExecuteSqlStatement(fout, query->data);
7852 
7854  }
7855 
7856  printfPQExpBuffer(query,
7857  "EXECUTE getDomainConstraints('%u')",
7858  tyinfo->dobj.catId.oid);
7859 
7860  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7861 
7862  ntups = PQntuples(res);
7863 
7864  i_tableoid = PQfnumber(res, "tableoid");
7865  i_oid = PQfnumber(res, "oid");
7866  i_conname = PQfnumber(res, "conname");
7867  i_consrc = PQfnumber(res, "consrc");
7868 
7869  constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7870 
7871  tyinfo->nDomChecks = ntups;
7872  tyinfo->domChecks = constrinfo;
7873 
7874  for (i = 0; i < ntups; i++)
7875  {
7876  bool validated = PQgetvalue(res, i, 4)[0] == 't';
7877 
7878  constrinfo[i].dobj.objType = DO_CONSTRAINT;
7879  constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7880  constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7881  AssignDumpId(&constrinfo[i].dobj);
7882  constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7883  constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7884  constrinfo[i].contable = NULL;
7885  constrinfo[i].condomain = tyinfo;
7886  constrinfo[i].contype = 'c';
7887  constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7888  constrinfo[i].confrelid = InvalidOid;
7889  constrinfo[i].conindex = 0;
7890  constrinfo[i].condeferrable = false;
7891  constrinfo[i].condeferred = false;
7892  constrinfo[i].conislocal = true;
7893 
7894  constrinfo[i].separate = !validated;
7895 
7896  /*
7897  * Make the domain depend on the constraint, ensuring it won't be
7898  * output till any constraint dependencies are OK. If the constraint
7899  * has not been validated, it's going to be dumped after the domain
7900  * anyway, so this doesn't matter.
7901  */
7902  if (validated)
7903  addObjectDependency(&tyinfo->dobj,
7904  constrinfo[i].dobj.dumpId);
7905  }
7906 
7907  PQclear(res);
7908 
7909  destroyPQExpBuffer(query);
7910 }
7911 
7912 /*
7913  * getRules
7914  * get basic information about every rule in the system
7915  *
7916  * numRules is set to the number of rules read in
7917  */
7918 RuleInfo *
7919 getRules(Archive *fout, int *numRules)
7920 {
7921  PGresult *res;
7922  int ntups;
7923  int i;
7924  PQExpBuffer query = createPQExpBuffer();
7925  RuleInfo *ruleinfo;
7926  int i_tableoid;
7927  int i_oid;
7928  int i_rulename;
7929  int i_ruletable;
7930  int i_ev_type;
7931  int i_is_instead;
7932  int i_ev_enabled;
7933 
7934  appendPQExpBufferStr(query, "SELECT "
7935  "tableoid, oid, rulename, "
7936  "ev_class AS ruletable, ev_type, is_instead, "
7937  "ev_enabled "
7938  "FROM pg_rewrite "
7939  "ORDER BY oid");
7940 
7941  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7942 
7943  ntups = PQntuples(res);
7944 
7945  *numRules = ntups;
7946 
7947  ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7948 
7949  i_tableoid = PQfnumber(res, "tableoid");
7950  i_oid = PQfnumber(res, "oid");
7951  i_rulename = PQfnumber(res, "rulename");
7952  i_ruletable = PQfnumber(res, "ruletable");
7953  i_ev_type = PQfnumber(res, "ev_type");
7954  i_is_instead = PQfnumber(res, "is_instead");
7955  i_ev_enabled = PQfnumber(res, "ev_enabled");
7956 
7957  for (i = 0; i < ntups; i++)
7958  {
7959  Oid ruletableoid;
7960 
7961  ruleinfo[i].dobj.objType = DO_RULE;
7962  ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7963  ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7964  AssignDumpId(&ruleinfo[i].dobj);
7965  ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7966  ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7967  ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7968  if (ruleinfo[i].ruletable == NULL)
7969  pg_fatal("failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found",
7970  ruletableoid, ruleinfo[i].dobj.catId.oid);
7971  ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7972  ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7973  ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7974  ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7975  ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7976  if (ruleinfo[i].ruletable)
7977  {
7978  /*
7979  * If the table is a view or materialized view, force its ON
7980  * SELECT rule to be sorted before the view itself --- this
7981  * ensures that any dependencies for the rule affect the table's
7982  * positioning. Other rules are forced to appear after their
7983  * table.
7984  */
7985  if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7986  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7987  ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7988  {
7989  addObjectDependency(&ruleinfo[i].ruletable->dobj,
7990  ruleinfo[i].dobj.dumpId);
7991  /* We'll merge the rule into CREATE VIEW, if possible */
7992  ruleinfo[i].separate = false;
7993  }
7994  else
7995  {
7996  addObjectDependency(&ruleinfo[i].dobj,
7997  ruleinfo[i].ruletable->dobj.dumpId);
7998  ruleinfo[i].separate = true;
7999  }
8000  }
8001  else
8002  ruleinfo[i].separate = true;
8003  }
8004 
8005  PQclear(res);
8006 
8007  destroyPQExpBuffer(query);
8008 
8009  return ruleinfo;
8010 }
8011 
8012 /*
8013  * getTriggers
8014  * get information about every trigger on a dumpable table
8015  *
8016  * Note: trigger data is not returned directly to the caller, but it
8017  * does get entered into the DumpableObject tables.
8018  */
8019 void
8020 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
8021 {
8022  PQExpBuffer query = createPQExpBuffer();
8023  PQExpBuffer tbloids = createPQExpBuffer();
8024  PGresult *res;
8025  int ntups;
8026  int curtblindx;
8027  TriggerInfo *tginfo;
8028  int i_tableoid,
8029  i_oid,
8030  i_tgrelid,
8031  i_tgname,
8032  i_tgenabled,
8033  i_tgispartition,
8034  i_tgdef;
8035 
8036  /*
8037  * We want to perform just one query against pg_trigger. However, we
8038  * mustn't try to select every row of the catalog and then sort it out on
8039  * the client side, because some of the server-side functions we need
8040  * would be unsafe to apply to tables we don't have lock on. Hence, we
8041  * build an array of the OIDs of tables we care about (and now have lock
8042  * on!), and use a WHERE clause to constrain which rows are selected.
8043  */
8044  appendPQExpBufferChar(tbloids, '{');
8045  for (int i = 0; i < numTables; i++)
8046  {
8047  TableInfo *tbinfo = &tblinfo[i];
8048 
8049  if (!tbinfo->hastriggers ||
8050  !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
8051  continue;
8052 
8053  /* OK, we need info for this table */
8054  if (tbloids->len > 1) /* do we have more than the '{'? */
8055  appendPQExpBufferChar(tbloids, ',');
8056  appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
8057  }
8058  appendPQExpBufferChar(tbloids, '}');
8059 
8060  if (fout->remoteVersion >= 150000)
8061  {
8062  /*
8063  * NB: think not to use pretty=true in pg_get_triggerdef. It could
8064  * result in non-forward-compatible dumps of WHEN clauses due to
8065  * under-parenthesization.
8066  *
8067  * NB: We need to see partition triggers in case the tgenabled flag
8068  * has been changed from the parent.
8069  */
8070  appendPQExpBuffer(query,
8071  "SELECT t.tgrelid, t.tgname, "
8072  "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8073  "t.tgenabled, t.tableoid, t.oid, "
8074  "t.tgparentid <> 0 AS tgispartition\n"
8075  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8076  "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8077  "LEFT JOIN pg_catalog.pg_trigger u ON (u.oid = t.tgparentid) "
8078  "WHERE ((NOT t.tgisinternal AND t.tgparentid = 0) "
8079  "OR t.tgenabled != u.tgenabled) "
8080  "ORDER BY t.tgrelid, t.tgname",
8081  tbloids->data);
8082  }
8083  else if (fout->remoteVersion >= 130000)
8084  {
8085  /*
8086  * NB: think not to use pretty=true in pg_get_triggerdef. It could
8087  * result in non-forward-compatible dumps of WHEN clauses due to
8088  * under-parenthesization.
8089  *
8090  * NB: We need to see tgisinternal triggers in partitions, in case the
8091  * tgenabled flag has been changed from the parent.
8092  */
8093  appendPQExpBuffer(query,
8094  "SELECT t.tgrelid, t.tgname, "
8095  "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8096  "t.tgenabled, t.tableoid, t.oid, t.tgisinternal as tgispartition\n"
8097  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8098  "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8099  "LEFT JOIN pg_catalog.pg_trigger u ON (u.oid = t.tgparentid) "
8100  "WHERE (NOT t.tgisinternal OR t.tgenabled != u.tgenabled) "
8101  "ORDER BY t.tgrelid, t.tgname",
8102  tbloids->data);
8103  }
8104  else if (fout->remoteVersion >= 110000)
8105  {
8106  /*
8107  * NB: We need to see tgisinternal triggers in partitions, in case the
8108  * tgenabled flag has been changed from the parent. No tgparentid in
8109  * version 11-12, so we have to match them via pg_depend.
8110  *
8111  * See above about pretty=true in pg_get_triggerdef.
8112  */
8113  appendPQExpBuffer(query,
8114  "SELECT t.tgrelid, t.tgname, "
8115  "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8116  "t.tgenabled, t.tableoid, t.oid, t.tgisinternal as tgispartition "
8117  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8118  "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8119  "LEFT JOIN pg_catalog.pg_depend AS d ON "
8120  " d.classid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
8121  " d.refclassid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
8122  " d.objid = t.oid "
8123  "LEFT JOIN pg_catalog.pg_trigger AS pt ON pt.oid = refobjid "
8124  "WHERE (NOT t.tgisinternal OR t.tgenabled != pt.tgenabled) "
8125  "ORDER BY t.tgrelid, t.tgname",
8126  tbloids->data);
8127  }
8128  else
8129  {
8130  /* See above about pretty=true in pg_get_triggerdef */
8131  appendPQExpBuffer(query,
8132  "SELECT t.tgrelid, t.tgname, "
8133  "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8134  "t.tgenabled, false as tgispartition, "
8135  "t.tableoid, t.oid "
8136  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8137  "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8138  "WHERE NOT tgisinternal "
8139  "ORDER BY t.tgrelid, t.tgname",
8140  tbloids->data);
8141  }
8142 
8143  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8144 
8145  ntups = PQntuples(res);
8146 
8147  i_tableoid = PQfnumber(res, "tableoid");
8148  i_oid = PQfnumber(res, "oid");
8149  i_tgrelid = PQfnumber(res, "tgrelid");
8150  i_tgname = PQfnumber(res, "tgname");
8151  i_tgenabled = PQfnumber(res, "tgenabled");
8152  i_tgispartition = PQfnumber(res, "tgispartition");
8153  i_tgdef = PQfnumber(res, "tgdef");
8154 
8155  tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
8156 
8157  /*
8158  * Outer loop iterates once per table, not once per row. Incrementing of
8159  * j is handled by the inner loop.
8160  */
8161  curtblindx = -1;
8162  for (int j = 0; j < ntups;)
8163  {
8164  Oid tgrelid = atooid(PQgetvalue(res, j, i_tgrelid));
8165  TableInfo *tbinfo = NULL;
8166  int numtrigs;
8167 
8168  /* Count rows for this table */
8169  for (numtrigs = 1; numtrigs < ntups - j; numtrigs++)
8170  if (atooid(PQgetvalue(res, j + numtrigs, i_tgrelid)) != tgrelid)
8171  break;
8172 
8173  /*
8174  * Locate the associated TableInfo; we rely on tblinfo[] being in OID
8175  * order.
8176  */
8177  while (++curtblindx < numTables)
8178  {
8179  tbinfo = &tblinfo[curtblindx];
8180  if (tbinfo->dobj.catId.oid == tgrelid)
8181  break;
8182  }
8183  if (curtblindx >= numTables)
8184  pg_fatal("unrecognized table OID %u", tgrelid);
8185 
8186  /* Save data for this table */
8187  tbinfo->triggers = tginfo + j;
8188  tbinfo->numTriggers = numtrigs;
8189 
8190  for (int c = 0; c < numtrigs; c++, j++)
8191  {
8192  tginfo[j].dobj.objType = DO_TRIGGER;
8193  tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
8194  tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
8195  AssignDumpId(&tginfo[j].dobj);
8196  tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
8197  tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
8198  tginfo[j].tgtable = tbinfo;
8199  tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
8200  tginfo[j].tgispartition = *(PQgetvalue(res, j, i_tgispartition)) == 't';
8201  tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
8202  }
8203  }
8204 
8205  PQclear(res);
8206 
8207  destroyPQExpBuffer(query);
8208  destroyPQExpBuffer(tbloids);
8209 }
8210 
8211 /*
8212  * getEventTriggers
8213  * get information about event triggers
8214  */
8216 getEventTriggers(Archive *fout, int *numEventTriggers)
8217 {
8218  int i;
8219  PQExpBuffer query;
8220  PGresult *res;
8221  EventTriggerInfo *evtinfo;
8222  int i_tableoid,
8223  i_oid,
8224  i_evtname,
8225  i_evtevent,
8226  i_evtowner,
8227  i_evttags,
8228  i_evtfname,
8229  i_evtenabled;
8230  int ntups;
8231 
8232  /* Before 9.3, there are no event triggers */
8233  if (fout->remoteVersion < 90300)
8234  {
8235  *numEventTriggers = 0;
8236  return NULL;
8237  }
8238 
8239  query = createPQExpBuffer();
8240 
8241  appendPQExpBufferStr(query,
8242  "SELECT e.tableoid, e.oid, evtname, evtenabled, "
8243  "evtevent, evtowner, "
8244  "array_to_string(array("
8245  "select quote_literal(x) "
8246  " from unnest(evttags) as t(x)), ', ') as evttags, "
8247  "e.evtfoid::regproc as evtfname "
8248  "FROM pg_event_trigger e "
8249  "ORDER BY e.oid");
8250 
8251  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8252 
8253  ntups = PQntuples(res);
8254 
8255  *numEventTriggers = ntups;
8256 
8257  evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
8258 
8259  i_tableoid = PQfnumber(res, "tableoid");
8260  i_oid = PQfnumber(res, "oid");
8261  i_evtname = PQfnumber(res, "evtname");
8262  i_evtevent = PQfnumber(res, "evtevent");
8263  i_evtowner = PQfnumber(res, "evtowner");
8264  i_evttags = PQfnumber(res, "evttags");
8265  i_evtfname = PQfnumber(res, "evtfname");
8266  i_evtenabled = PQfnumber(res, "evtenabled");
8267 
8268  for (i = 0; i < ntups; i++)
8269  {
8270  evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
8271  evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8272  evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8273  AssignDumpId(&evtinfo[i].dobj);
8274  evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
8275  evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
8276  evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
8277  evtinfo[i].evtowner = getRoleName(PQgetvalue(res, i, i_evtowner));
8278  evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
8279  evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
8280  evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
8281 
8282  /* Decide whether we want to dump it */
8283  selectDumpableObject(&(evtinfo[i].dobj), fout);
8284  }
8285 
8286  PQclear(res);
8287 
8288  destroyPQExpBuffer(query);
8289 
8290  return evtinfo;
8291 }
8292 
8293 /*
8294  * getProcLangs
8295  * get basic information about every procedural language in the system
8296  *
8297  * numProcLangs is set to the number of langs read in
8298  *
8299  * NB: this must run after getFuncs() because we assume we can do
8300  * findFuncByOid().
8301  */
8302 ProcLangInfo *
8303 getProcLangs(Archive *fout, int *numProcLangs)
8304 {
8305  PGresult *res;
8306  int ntups;
8307  int i;
8308  PQExpBuffer query = createPQExpBuffer();
8309  ProcLangInfo *planginfo;
8310  int i_tableoid;
8311  int i_oid;
8312  int i_lanname;
8313  int i_lanpltrusted;
8314  int i_lanplcallfoid;
8315  int i_laninline;
8316  int i_lanvalidator;
8317  int i_lanacl;
8318  int i_acldefault;
8319  int i_lanowner;
8320 
8321  appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8322  "lanname, lanpltrusted, lanplcallfoid, "
8323  "laninline, lanvalidator, "
8324  "lanacl, "
8325  "acldefault('l', lanowner) AS acldefault, "
8326  "lanowner "
8327  "FROM pg_language "
8328  "WHERE lanispl "
8329  "ORDER BY oid");
8330 
8331  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8332 
8333  ntups = PQntuples(res);
8334 
8335  *numProcLangs = ntups;
8336 
8337  planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
8338 
8339  i_tableoid = PQfnumber(res, "tableoid");
8340  i_oid = PQfnumber(res, "oid");
8341  i_lanname = PQfnumber(res, "lanname");
8342  i_lanpltrusted = PQfnumber(res, "lanpltrusted");
8343  i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
8344  i_laninline = PQfnumber(res, "laninline");
8345  i_lanvalidator = PQfnumber(res, "lanvalidator");
8346  i_lanacl = PQfnumber(res, "lanacl");
8347  i_acldefault = PQfnumber(res, "acldefault");
8348  i_lanowner = PQfnumber(res, "lanowner");
8349 
8350  for (i = 0; i < ntups; i++)
8351  {
8352  planginfo[i].dobj.objType = DO_PROCLANG;
8353  planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8354  planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8355  AssignDumpId(&planginfo[i].dobj);
8356 
8357  planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
8358  planginfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_lanacl));
8359  planginfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
8360  planginfo[i].dacl.privtype = 0;
8361  planginfo[i].dacl.initprivs = NULL;
8362  planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
8363  planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
8364  planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
8365  planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
8366  planginfo[i].lanowner = getRoleName(PQgetvalue(res, i, i_lanowner));
8367 
8368  /* Decide whether we want to dump it */
8369  selectDumpableProcLang(&(planginfo[i]), fout);
8370 
8371  /* Mark whether language has an ACL */
8372  if (!PQgetisnull(res, i, i_lanacl))
8373  planginfo[i].dobj.components |= DUMP_COMPONENT_ACL;
8374  }
8375 
8376  PQclear(res);
8377 
8378  destroyPQExpBuffer(query);
8379 
8380  return planginfo;
8381 }
8382 
8383 /*
8384  * getCasts
8385  * get basic information about most casts in the system
8386  *
8387  * numCasts is set to the number of casts read in
8388  *
8389  * Skip casts from a range to its multirange, since we'll create those
8390  * automatically.
8391  */
8392 CastInfo *
8393 getCasts(Archive *fout, int *numCasts)
8394 {
8395  PGresult *res;
8396  int ntups;
8397  int i;
8398  PQExpBuffer query = createPQExpBuffer();
8399  CastInfo *castinfo;
8400  int i_tableoid;
8401  int i_oid;
8402  int i_castsource;
8403  int i_casttarget;
8404  int i_castfunc;
8405  int i_castcontext;
8406  int i_castmethod;
8407 
8408  if (fout->remoteVersion >= 140000)
8409  {
8410  appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8411  "castsource, casttarget, castfunc, castcontext, "
8412  "castmethod "
8413  "FROM pg_cast c "
8414  "WHERE NOT EXISTS ( "
8415  "SELECT 1 FROM pg_range r "
8416  "WHERE c.castsource = r.rngtypid "
8417  "AND c.casttarget = r.rngmultitypid "
8418  ") "
8419  "ORDER BY 3,4");
8420  }
8421  else
8422  {
8423  appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8424  "castsource, casttarget, castfunc, castcontext, "
8425  "castmethod "
8426  "FROM pg_cast ORDER BY 3,4");
8427  }
8428 
8429  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8430 
8431  ntups = PQntuples(res);
8432 
8433  *numCasts = ntups;
8434 
8435  castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
8436 
8437  i_tableoid = PQfnumber(res, "tableoid");
8438  i_oid = PQfnumber(res, "oid");
8439  i_castsource = PQfnumber(res, "castsource");
8440  i_casttarget = PQfnumber(res, "casttarget");
8441  i_castfunc = PQfnumber(res, "castfunc");
8442  i_castcontext = PQfnumber(res, "castcontext");
8443  i_castmethod = PQfnumber(res, "castmethod");
8444 
8445  for (i = 0; i < ntups; i++)
8446  {
8447  PQExpBufferData namebuf;
8448  TypeInfo *sTypeInfo;
8449  TypeInfo *tTypeInfo;
8450 
8451  castinfo[i].dobj.objType = DO_CAST;
8452  castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8453  castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8454  AssignDumpId(&castinfo[i].dobj);
8455  castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
8456  castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
8457  castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
8458  castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
8459  castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
8460 
8461  /*
8462  * Try to name cast as concatenation of typnames. This is only used
8463  * for purposes of sorting. If we fail to find either type, the name
8464  * will be an empty string.
8465  */
8466  initPQExpBuffer(&namebuf);
8467  sTypeInfo = findTypeByOid(castinfo[i].castsource);
8468  tTypeInfo = findTypeByOid(castinfo[i].casttarget);
8469  if (sTypeInfo && tTypeInfo)
8470  appendPQExpBuffer(&namebuf, "%s %s",
8471  sTypeInfo->dobj.name, tTypeInfo->dobj.name);
8472  castinfo[i].dobj.name = namebuf.data;
8473 
8474  /* Decide whether we want to dump it */
8475  selectDumpableCast(&(castinfo[i]), fout);
8476  }
8477 
8478  PQclear(res);
8479 
8480  destroyPQExpBuffer(query);
8481 
8482  return castinfo;
8483 }
8484 
8485 static char *
8487 {
8488  PQExpBuffer query;
8489  PGresult *res;
8490  char *lanname;
8491 
8492  query = createPQExpBuffer();
8493  appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
8494  res = ExecuteSqlQueryForSingleRow(fout, query->data);
8495  lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
8496  destroyPQExpBuffer(query);
8497  PQclear(res);
8498 
8499  return lanname;
8500 }
8501 
8502 /*
8503  * getTransforms
8504  * get basic information about every transform in the system
8505  *
8506  * numTransforms is set to the number of transforms read in
8507  */
8508 TransformInfo *
8509 getTransforms(Archive *fout, int *numTransforms)
8510 {
8511  PGresult *res;
8512  int ntups;
8513  int i;
8514  PQExpBuffer query;
8515  TransformInfo *transforminfo;
8516  int i_tableoid;
8517  int i_oid;
8518  int i_trftype;
8519  int i_trflang;
8520  int i_trffromsql;
8521  int i_trftosql;
8522 
8523  /* Transforms didn't exist pre-9.5 */
8524  if (fout->remoteVersion < 90500)
8525  {
8526  *numTransforms = 0;
8527  return NULL;
8528  }
8529 
8530  query = createPQExpBuffer();
8531 
8532  appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8533  "trftype, trflang, trffromsql::oid, trftosql::oid "
8534  "FROM pg_transform "
8535  "ORDER BY 3,4");
8536 
8537  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8538 
8539  ntups = PQntuples(res);
8540 
8541  *numTransforms = ntups;
8542 
8543  transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8544 
8545  i_tableoid = PQfnumber(res, "tableoid");
8546  i_oid = PQfnumber(res, "oid");
8547  i_trftype = PQfnumber(res, "trftype");
8548  i_trflang = PQfnumber(res, "trflang");
8549  i_trffromsql = PQfnumber(res, "trffromsql");
8550  i_trftosql = PQfnumber(res, "trftosql");
8551 
8552  for (i = 0; i < ntups; i++)
8553  {
8554  PQExpBufferData namebuf;
8555  TypeInfo *typeInfo;
8556  char *lanname;
8557 
8558  transforminfo[i].dobj.objType = DO_TRANSFORM;
8559  transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8560  transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8561  AssignDumpId(&transforminfo[i].dobj);
8562  transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8563  transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8564  transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8565  transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8566 
8567  /*
8568  * Try to name transform as concatenation of type and language name.
8569  * This is only used for purposes of sorting. If we fail to find
8570  * either, the name will be an empty string.
8571  */
8572  initPQExpBuffer(&namebuf);
8573  typeInfo = findTypeByOid(transforminfo[i].trftype);
8574  lanname = get_language_name(fout, transforminfo[i].trflang);
8575  if (typeInfo && lanname)
8576  appendPQExpBuffer(&namebuf, "%s %s",
8577  typeInfo->dobj.name, lanname);
8578  transforminfo[i].dobj.name = namebuf.data;
8579  free(lanname);
8580 
8581  /* Decide whether we want to dump it */
8582  selectDumpableObject(&(transforminfo[i].dobj), fout);
8583  }
8584 
8585  PQclear(res);
8586 
8587  destroyPQExpBuffer(query);
8588 
8589  return transforminfo;
8590 }
8591 
8592 /*
8593  * getTableAttrs -
8594  * for each interesting table, read info about its attributes
8595  * (names, types, default values, CHECK constraints, etc)
8596  *
8597  * modifies tblinfo
8598  */
8599 void
8600 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8601 {
8602  DumpOptions *dopt = fout->dopt;
8604  PQExpBuffer tbloids = createPQExpBuffer();
8605  PQExpBuffer checkoids = createPQExpBuffer();
8606  PGresult *res;
8607  int ntups;
8608  int curtblindx;
8609  int i_attrelid;
8610  int i_attnum;
8611  int i_attname;
8612  int i_atttypname;
8613  int i_attstattarget;
8614  int i_attstorage;
8615  int i_typstorage;
8616  int i_attidentity;
8617  int i_attgenerated;
8618  int i_attisdropped;
8619  int i_attlen;
8620  int i_attalign;
8621  int i_attislocal;
8622  int i_notnull_name;
8623  int i_notnull_noinherit;
8624  int i_notnull_is_pk;
8625  int i_notnull_inh;
8626  int i_attoptions;
8627  int i_attcollation;
8628  int i_attcompression;
8629  int i_attfdwoptions;
8630  int i_attmissingval;
8631  int i_atthasdef;
8632 
8633  /*
8634  * We want to perform just one query against pg_attribute, and then just
8635  * one against pg_attrdef (for DEFAULTs) and two against pg_constraint
8636  * (for CHECK constraints and for NOT NULL constraints). However, we
8637  * mustn't try to select every row of those catalogs and then sort it out
8638  * on the client side, because some of the server-side functions we need
8639  * would be unsafe to apply to tables we don't have lock on. Hence, we
8640  * build an array of the OIDs of tables we care about (and now have lock
8641  * on!), and use a WHERE clause to constrain which rows are selected.
8642  */
8643  appendPQExpBufferChar(tbloids, '{');
8644  appendPQExpBufferChar(checkoids, '{');
8645  for (int i = 0; i < numTables; i++)
8646  {
8647  TableInfo *tbinfo = &tblinfo[i];
8648 
8649  /* Don't bother to collect info for sequences */
8650  if (tbinfo->relkind == RELKIND_SEQUENCE)
8651  continue;
8652 
8653  /* Don't bother with uninteresting tables, either */
8654  if (!tbinfo->interesting)
8655  continue;
8656 
8657  /* OK, we need info for this table */
8658  if (tbloids->len > 1) /* do we have more than the '{'? */
8659  appendPQExpBufferChar(tbloids, ',');
8660  appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
8661 
8662  if (tbinfo->ncheck > 0)
8663  {
8664  /* Also make a list of the ones with check constraints */
8665  if (checkoids->len > 1) /* do we have more than the '{'? */
8666  appendPQExpBufferChar(checkoids, ',');
8667  appendPQExpBuffer(checkoids, "%u", tbinfo->dobj.catId.oid);
8668  }
8669  }
8670  appendPQExpBufferChar(tbloids, '}');
8671  appendPQExpBufferChar(checkoids, '}');
8672 
8673  /*
8674  * Find all the user attributes and their types.
8675  *
8676  * Since we only want to dump COLLATE clauses for attributes whose
8677  * collation is different from their type's default, we use a CASE here to
8678  * suppress uninteresting attcollations cheaply.
8679  */
8681  "SELECT\n"
8682  "a.attrelid,\n"
8683  "a.attnum,\n"
8684  "a.attname,\n"
8685  "a.attstattarget,\n"
8686  "a.attstorage,\n"
8687  "t.typstorage,\n"
8688  "a.atthasdef,\n"
8689  "a.attisdropped,\n"
8690  "a.attlen,\n"
8691  "a.attalign,\n"
8692  "a.attislocal,\n"
8693  "pg_catalog.format_type(t.oid, a.atttypmod) AS atttypname,\n"
8694  "array_to_string(a.attoptions, ', ') AS attoptions,\n"
8695  "CASE WHEN a.attcollation <> t.typcollation "
8696  "THEN a.attcollation ELSE 0 END AS attcollation,\n"
8697  "pg_catalog.array_to_string(ARRAY("
8698  "SELECT pg_catalog.quote_ident(option_name) || "
8699  "' ' || pg_catalog.quote_literal(option_value) "
8700  "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8701  "ORDER BY option_name"
8702  "), E',\n ') AS attfdwoptions,\n");
8703 
8704  /*
8705  * Find out any NOT NULL markings for each column. In 17 and up we have
8706  * to read pg_constraint, and keep track whether it's NO INHERIT; in older
8707  * versions we rely on pg_attribute.attnotnull.
8708  *
8709  * We also track whether the constraint was defined directly in this table
8710  * or via an ancestor, for binary upgrade.
8711  *
8712  * Lastly, we need to know if the PK for the table involves each column;
8713  * for columns that are there we need a NOT NULL marking even if there's
8714  * no explicit constraint, to avoid the table having to be scanned for
8715  * NULLs after the data is loaded when the PK is created, later in the
8716  * dump; for this case we add throwaway constraints that are dropped once
8717  * the PK is created.
8718  */
8719  if (fout->remoteVersion >= 170000)
8721  "co.conname AS notnull_name,\n"
8722  "co.connoinherit AS notnull_noinherit,\n"
8723  "copk.conname IS NOT NULL as notnull_is_pk,\n"
8724  "coalesce(NOT co.conislocal, true) AS notnull_inh,\n");
8725  else
8727  "CASE WHEN a.attnotnull THEN '' ELSE NULL END AS notnull_name,\n"
8728  "false AS notnull_noinherit,\n"
8729  "copk.conname IS NOT NULL AS notnull_is_pk,\n"
8730  "NOT a.attislocal AS notnull_inh,\n");
8731 
8732  if (fout->remoteVersion >= 140000)
8734  "a.attcompression AS attcompression,\n");
8735  else
8737  "'' AS attcompression,\n");
8738 
8739  if (fout->remoteVersion >= 100000)
8741  "a.attidentity,\n");
8742  else
8744  "'' AS attidentity,\n");
8745 
8746  if (fout->remoteVersion >= 110000)
8748  "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8749  "THEN a.attmissingval ELSE null END AS attmissingval,\n");
8750  else
8752  "NULL AS attmissingval,\n");
8753 
8754  if (fout->remoteVersion >= 120000)
8756  "a.attgenerated\n");
8757  else
8759  "'' AS attgenerated\n");
8760 
8761  /* need left join to pg_type to not fail on dropped columns ... */
8763  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8764  "JOIN pg_catalog.pg_attribute a ON (src.tbloid = a.attrelid) "
8765  "LEFT JOIN pg_catalog.pg_type t "
8766  "ON (a.atttypid = t.oid)\n",
8767  tbloids->data);
8768 
8769  /*
8770  * In versions 16 and up, we need pg_constraint for explicit NOT NULL
8771  * entries. Also, we need to know if the NOT NULL for each column is
8772  * backing a primary key.
8773  */
8774  if (fout->remoteVersion >= 170000)
8776  " LEFT JOIN pg_catalog.pg_constraint co ON "
8777  "(a.attrelid = co.conrelid\n"
8778  " AND co.contype = 'n' AND "
8779  "co.conkey = array[a.attnum])\n");
8780 
8782  "LEFT JOIN pg_catalog.pg_constraint copk ON "
8783  "(copk.conrelid = src.tbloid\n"
8784  " AND copk.contype = 'p' AND "
8785  "copk.conkey @> array[a.attnum])\n"
8786  "WHERE a.attnum > 0::pg_catalog.int2\n"
8787  "ORDER BY a.attrelid, a.attnum");
8788 
8789  res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8790 
8791  ntups = PQntuples(res);
8792 
8793  i_attrelid = PQfnumber(res, "attrelid");
8794  i_attnum = PQfnumber(res, "attnum");
8795  i_attname = PQfnumber(res, "attname");
8796  i_atttypname = PQfnumber(res, "atttypname");
8797  i_attstattarget = PQfnumber(res, "attstattarget");
8798  i_attstorage = PQfnumber(res, "attstorage");
8799  i_typstorage = PQfnumber(res, "typstorage");
8800  i_attidentity = PQfnumber(res, "attidentity");
8801  i_attgenerated = PQfnumber(res, "attgenerated");
8802  i_attisdropped = PQfnumber(res, "attisdropped");
8803  i_attlen = PQfnumber(res, "attlen");
8804  i_attalign = PQfnumber(res, "attalign");
8805  i_attislocal = PQfnumber(res, "attislocal");
8806  i_notnull_name = PQfnumber(res, "notnull_name");
8807  i_notnull_noinherit = PQfnumber(res, "notnull_noinherit");
8808  i_notnull_is_pk = PQfnumber(res, "notnull_is_pk");
8809  i_notnull_inh = PQfnumber(res, "notnull_inh");
8810  i_attoptions = PQfnumber(res, "attoptions");
8811  i_attcollation = PQfnumber(res, "attcollation");
8812  i_attcompression = PQfnumber(res, "attcompression");
8813  i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8814  i_attmissingval = PQfnumber(res, "attmissingval");
8815  i_atthasdef = PQfnumber(res, "atthasdef");
8816 
8817  /* Within the next loop, we'll accumulate OIDs of tables with defaults */
8818  resetPQExpBuffer(tbloids);
8819  appendPQExpBufferChar(tbloids, '{');
8820 
8821  /*
8822  * Outer loop iterates once per table, not once per row. Incrementing of
8823  * r is handled by the inner loop.
8824  */
8825  curtblindx = -1;
8826  for (int r = 0; r < ntups;)
8827  {
8828  Oid attrelid = atooid(PQgetvalue(res, r, i_attrelid));
8829  TableInfo *tbinfo = NULL;
8830  int numatts;
8831  bool hasdefaults;
8832  int notnullcount;
8833 
8834  /* Count rows for this table */
8835  for (numatts = 1; numatts < ntups - r; numatts++)
8836  if (atooid(PQgetvalue(res, r + numatts, i_attrelid)) != attrelid)
8837  break;
8838 
8839  /*
8840  * Locate the associated TableInfo; we rely on tblinfo[] being in OID
8841  * order.
8842  */
8843  while (++curtblindx < numTables)
8844  {
8845  tbinfo = &tblinfo[curtblindx];
8846  if (tbinfo->dobj.catId.oid == attrelid)
8847  break;
8848  }
8849  if (curtblindx >= numTables)
8850  pg_fatal("unrecognized table OID %u", attrelid);
8851  /* cross-check that we only got requested tables */
8852  if (tbinfo->relkind == RELKIND_SEQUENCE ||
8853  !tbinfo->interesting)
8854  pg_fatal("unexpected column data for table \"%s\"",
8855  tbinfo->dobj.name);
8856 
8857  notnullcount = 0;
8858 
8859  /* Save data for this table */
8860  tbinfo->numatts = numatts;
8861  tbinfo->attnames = (char **) pg_malloc(numatts * sizeof(char *));
8862  tbinfo->atttypnames = (char **) pg_malloc(numatts * sizeof(char *));
8863  tbinfo->attstattarget = (int *) pg_malloc(numatts * sizeof(int));
8864  tbinfo->attstorage = (char *) pg_malloc(numatts * sizeof(char));
8865  tbinfo->typstorage = (char *) pg_malloc(numatts * sizeof(char));
8866  tbinfo->attidentity = (char *) pg_malloc(numatts * sizeof(char));
8867  tbinfo->attgenerated = (char *) pg_malloc(numatts * sizeof(char));
8868  tbinfo->attisdropped = (bool *) pg_malloc(numatts * sizeof(bool));
8869  tbinfo->attlen = (int *) pg_malloc(numatts * sizeof(int));
8870  tbinfo->attalign = (char *) pg_malloc(numatts * sizeof(char));
8871  tbinfo->attislocal = (bool *) pg_malloc(numatts * sizeof(bool));
8872  tbinfo->attoptions = (char **) pg_malloc(numatts * sizeof(char *));
8873  tbinfo->attcollation = (Oid *) pg_malloc(numatts * sizeof(Oid));
8874  tbinfo->attcompression = (char *) pg_malloc(numatts * sizeof(char));
8875  tbinfo->attfdwoptions = (char **) pg_malloc(numatts * sizeof(char *));
8876  tbinfo->attmissingval = (char **) pg_malloc(numatts * sizeof(char *));
8877  tbinfo->notnull_constrs = (char **) pg_malloc(numatts * sizeof(char *));
8878  tbinfo->notnull_noinh = (bool *) pg_malloc(numatts * sizeof(bool));
8879  tbinfo->notnull_throwaway = (bool *) pg_malloc(numatts * sizeof(bool));
8880  tbinfo->notnull_inh = (bool *) pg_malloc(numatts * sizeof(bool));
8881  tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(numatts * sizeof(AttrDefInfo *));
8882  hasdefaults = false;
8883 
8884  for (int j = 0; j < numatts; j++, r++)
8885  {
8886  bool use_named_notnull = false;
8887  bool use_unnamed_notnull = false;
8888  bool use_throwaway_notnull = false;
8889 
8890  if (j + 1 != atoi(PQgetvalue(res, r, i_attnum)))
8891  pg_fatal("invalid column numbering in table \"%s\"",
8892  tbinfo->dobj.name);
8893  tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, r, i_attname));
8894  tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, r, i_atttypname));
8895  if (PQgetisnull(res, r, i_attstattarget))
8896  tbinfo->attstattarget[j] = -1;
8897  else
8898  tbinfo->attstattarget[j] = atoi(PQgetvalue(res, r, i_attstattarget));
8899  tbinfo->attstorage[j] = *(PQgetvalue(res, r, i_attstorage));
8900  tbinfo->typstorage[j] = *(PQgetvalue(res, r, i_typstorage));
8901  tbinfo->attidentity[j] = *(PQgetvalue(res, r, i_attidentity));
8902  tbinfo->attgenerated[j] = *(PQgetvalue(res, r, i_attgenerated));
8903  tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8904  tbinfo->attisdropped[j] = (PQgetvalue(res, r, i_attisdropped)[0] == 't');
8905  tbinfo->attlen[j] = atoi(PQgetvalue(res, r, i_attlen));
8906  tbinfo->attalign[j] = *(PQgetvalue(res, r, i_attalign));
8907  tbinfo->attislocal[j] = (PQgetvalue(res, r, i_attislocal)[0] == 't');
8908 
8909  /*
8910  * Not-null constraints require a jumping through a few hoops.
8911  * First, if the user has specified a constraint name that's not
8912  * the system-assigned default name, then we need to preserve
8913  * that. But if they haven't, then we don't want to use the
8914  * verbose syntax in the dump output. (Also, in versions prior to
8915  * 17, there was no constraint name at all.)
8916  *
8917  * (XXX Comparing the name this way to a supposed default name is
8918  * a bit of a hack, but it beats having to store a boolean flag in
8919  * pg_constraint just for this, or having to compute the knowledge
8920  * at pg_dump time from the server.)
8921  *
8922  * We also need to know if a column is part of the primary key. In
8923  * that case, we want to mark the column as not-null at table
8924  * creation time, so that the table doesn't have to be scanned to
8925  * check for nulls when the PK is created afterwards; this is
8926  * especially critical during pg_upgrade (where the data would not
8927  * be scanned at all otherwise.) If the column is part of the PK
8928  * and does not have any other not-null constraint, then we
8929  * fabricate a throwaway constraint name that we later use to
8930  * remove the constraint after the PK has been created.
8931  *
8932  * For inheritance child tables, we don't want to print not-null
8933  * when the constraint was defined at the parent level instead of
8934  * locally.
8935  */
8936 
8937  /*
8938  * We use notnull_inh to suppress unwanted not-null constraints in
8939  * inheritance children, when said constraints come from the
8940  * parent(s).
8941  */
8942  tbinfo->notnull_inh[j] = PQgetvalue(res, r, i_notnull_inh)[0] == 't';
8943 
8944  if (fout->remoteVersion < 170000)
8945  {
8946  if (!PQgetisnull(res, r, i_notnull_name) &&
8947  dopt->binary_upgrade &&
8948  !tbinfo->ispartition &&
8949  tbinfo->notnull_inh[j])
8950  {
8951  use_named_notnull = true;
8952  /* XXX should match ChooseConstraintName better */
8953  tbinfo->notnull_constrs[j] =
8954  psprintf("%s_%s_not_null", tbinfo->dobj.name,
8955  tbinfo->attnames[j]);
8956  }
8957  else if (PQgetvalue(res, r, i_notnull_is_pk)[0] == 't')
8958  use_throwaway_notnull = true;
8959  else if (!PQgetisnull(res, r, i_notnull_name))
8960  use_unnamed_notnull = true;
8961  }
8962  else
8963  {
8964  if (!PQgetisnull(res, r, i_notnull_name))
8965  {
8966  /*
8967  * In binary upgrade of inheritance child tables, must
8968  * have a constraint name that we can UPDATE later.
8969  */
8970  if (dopt->binary_upgrade &&
8971  !tbinfo->ispartition &&
8972  tbinfo->notnull_inh[j])
8973  {
8974  use_named_notnull = true;
8975  tbinfo->notnull_constrs[j] =
8976  pstrdup(PQgetvalue(res, r, i_notnull_name));
8977 
8978  }
8979  else
8980  {
8981  char *default_name;
8982 
8983  /* XXX should match ChooseConstraintName better */
8984  default_name = psprintf("%s_%s_not_null", tbinfo->dobj.name,
8985  tbinfo->attnames[j]);
8986  if (strcmp(default_name,
8987  PQgetvalue(res, r, i_notnull_name)) == 0)
8988  use_unnamed_notnull = true;
8989  else
8990  {
8991  use_named_notnull = true;
8992  tbinfo->notnull_constrs[j] =
8993  pstrdup(PQgetvalue(res, r, i_notnull_name));
8994  }
8995  }
8996  }
8997  else if (PQgetvalue(res, r, i_notnull_is_pk)[0] == 't')
8998  use_throwaway_notnull = true;
8999  }
9000 
9001  if (use_unnamed_notnull)
9002  {
9003  tbinfo->notnull_constrs[j] = "";
9004  tbinfo->notnull_throwaway[j] = false;
9005  }
9006  else if (use_named_notnull)
9007  {
9008  /* The name itself has already been determined */
9009  tbinfo->notnull_throwaway[j] = false;
9010  }
9011  else if (use_throwaway_notnull)
9012  {
9013  tbinfo->notnull_constrs[j] =
9014  psprintf("pgdump_throwaway_notnull_%d", notnullcount++);
9015  tbinfo->notnull_throwaway[j] = true;
9016  tbinfo->notnull_inh[j] = false;
9017  }
9018  else
9019  {
9020  tbinfo->notnull_constrs[j] = NULL;
9021  tbinfo->notnull_throwaway[j] = false;
9022  }
9023 
9024  /*
9025  * Throwaway constraints must always be NO INHERIT; otherwise do
9026  * what the catalog says.
9027  */
9028  tbinfo->notnull_noinh[j] = use_throwaway_notnull ||
9029  PQgetvalue(res, r, i_notnull_noinherit)[0] == 't';
9030 
9031  tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, r, i_attoptions));
9032  tbinfo->attcollation[j] = atooid(PQgetvalue(res, r, i_attcollation));
9033  tbinfo->attcompression[j] = *(PQgetvalue(res, r, i_attcompression));
9034  tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, r, i_attfdwoptions));
9035  tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, r, i_attmissingval));
9036  tbinfo->attrdefs[j] = NULL; /* fix below */
9037  if (PQgetvalue(res, r, i_atthasdef)[0] == 't')
9038  hasdefaults = true;
9039  }
9040 
9041  if (hasdefaults)
9042  {
9043  /* Collect OIDs of interesting tables that have defaults */
9044  if (tbloids->len > 1) /* do we have more than the '{'? */
9045  appendPQExpBufferChar(tbloids, ',');
9046  appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
9047  }
9048  }
9049 
9050  PQclear(res);
9051 
9052  /*
9053  * Now get info about column defaults. This is skipped for a data-only
9054  * dump, as it is only needed for table schemas.
9055  */
9056  if (!dopt->dataOnly && tbloids->len > 1)
9057  {
9058  AttrDefInfo *attrdefs;
9059  int numDefaults;
9060  TableInfo *tbinfo = NULL;
9061 
9062  pg_log_info("finding table default expressions");
9063 
9064  appendPQExpBufferChar(tbloids, '}');
9065 
9066  printfPQExpBuffer(q, "SELECT a.tableoid, a.oid, adrelid, adnum, "
9067  "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc\n"
9068  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
9069  "JOIN pg_catalog.pg_attrdef a ON (src.tbloid = a.adrelid)\n"
9070  "ORDER BY a.adrelid, a.adnum",
9071  tbloids->data);
9072 
9073  res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
9074 
9075  numDefaults = PQntuples(res);
9076  attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
9077 
9078  curtblindx = -1;
9079  for (int j = 0; j < numDefaults; j++)
9080  {
9081  Oid adtableoid = atooid(PQgetvalue(res, j, 0));
9082  Oid adoid = atooid(PQgetvalue(res, j, 1));
9083  Oid adrelid = atooid(PQgetvalue(res, j, 2));
9084  int adnum = atoi(PQgetvalue(res, j, 3));
9085  char *adsrc = PQgetvalue(res, j, 4);
9086 
9087  /*
9088  * Locate the associated TableInfo; we rely on tblinfo[] being in
9089  * OID order.
9090  */
9091  if (tbinfo == NULL || tbinfo->dobj.catId.oid != adrelid)
9092  {
9093  while (++curtblindx < numTables)
9094  {
9095  tbinfo = &tblinfo[curtblindx];
9096  if (tbinfo->dobj.catId.oid == adrelid)
9097  break;
9098  }
9099  if (curtblindx >= numTables)
9100  pg_fatal("unrecognized table OID %u", adrelid);
9101  }
9102 
9103  if (adnum <= 0 || adnum > tbinfo->numatts)
9104  pg_fatal("invalid adnum value %d for table \"%s\"",
9105  adnum, tbinfo->dobj.name);
9106 
9107  /*
9108  * dropped columns shouldn't have defaults, but just in case,
9109  * ignore 'em
9110  */
9111  if (tbinfo->attisdropped[adnum - 1])
9112  continue;
9113 
9114  attrdefs[j].dobj.objType = DO_ATTRDEF;
9115  attrdefs[j].dobj.catId.tableoid = adtableoid;
9116  attrdefs[j].dobj.catId.oid = adoid;
9117  AssignDumpId(&attrdefs[j].dobj);
9118  attrdefs[j].adtable = tbinfo;
9119  attrdefs[j].adnum = adnum;
9120  attrdefs[j].adef_expr = pg_strdup(adsrc);
9121 
9122  attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
9123  attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
9124 
9125  attrdefs[j].dobj.dump = tbinfo->dobj.dump;
9126 
9127  /*
9128  * Figure out whether the default/generation expression should be
9129  * dumped as part of the main CREATE TABLE (or similar) command or
9130  * as a separate ALTER TABLE (or similar) command. The preference
9131  * is to put it into the CREATE command, but in some cases that's
9132  * not possible.
9133  */
9134  if (tbinfo->attgenerated[adnum - 1])
9135  {
9136  /*
9137  * Column generation expressions cannot be dumped separately,
9138  * because there is no syntax for it. By setting separate to
9139  * false here we prevent the "default" from being processed as
9140  * its own dumpable object. Later, flagInhAttrs() will mark
9141  * it as not to be dumped at all, if possible (that is, if it
9142  * can be inherited from a parent).
9143  */
9144  attrdefs[j].separate = false;
9145  }
9146  else if (tbinfo->relkind == RELKIND_VIEW)
9147  {
9148  /*
9149  * Defaults on a VIEW must always be dumped as separate ALTER
9150  * TABLE commands.
9151  */
9152  attrdefs[j].separate = true;
9153  }
9154  else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
9155  {
9156  /* column will be suppressed, print default separately */
9157  attrdefs[j].separate = true;
9158  }
9159  else
9160  {
9161  attrdefs[j].separate = false;
9162  }
9163 
9164  if (!attrdefs[j].separate)
9165  {
9166  /*
9167  * Mark the default as needing to appear before the table, so
9168  * that any dependencies it has must be emitted before the
9169  * CREATE TABLE. If this is not possible, we'll change to
9170  * "separate" mode while sorting dependencies.
9171  */
9172  addObjectDependency(&tbinfo->dobj,
9173  attrdefs[j].dobj.dumpId);
9174  }
9175 
9176  tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
9177  }
9178 
9179  PQclear(res);
9180  }
9181 
9182  /*
9183  * Get info about table CHECK constraints. This is skipped for a
9184  * data-only dump, as it is only needed for table schemas.
9185  */
9186  if (!dopt->dataOnly && checkoids->len > 2)
9187  {
9188  ConstraintInfo *constrs;
9189  int numConstrs;
9190  int i_tableoid;
9191  int i_oid;
9192  int i_conrelid;
9193  int i_conname;
9194  int i_consrc;
9195  int i_conislocal;
9196  int i_convalidated;
9197 
9198  pg_log_info("finding table check constraints");
9199 
9200  resetPQExpBuffer(q);
9202  "SELECT c.tableoid, c.oid, conrelid, conname, "
9203  "pg_catalog.pg_get_constraintdef(c.oid) AS consrc, "
9204  "conislocal, convalidated "
9205  "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
9206  "JOIN pg_catalog.pg_constraint c ON (src.tbloid = c.conrelid)\n"
9207  "WHERE contype = 'c' "
9208  "ORDER BY c.conrelid, c.conname",
9209  checkoids->data);
9210 
9211  res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
9212 
9213  numConstrs = PQntuples(res);
9214  constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
9215 
9216  i_tableoid = PQfnumber(res, "tableoid");
9217  i_oid = PQfnumber(res, "oid");
9218  i_conrelid = PQfnumber(res, "conrelid");
9219  i_conname = PQfnumber(res, "conname");
9220  i_consrc = PQfnumber(res, "consrc");
9221  i_conislocal = PQfnumber(res, "conislocal");
9222  i_convalidated = PQfnumber(res, "convalidated");
9223 
9224  /* As above, this loop iterates once per table, not once per row */
9225  curtblindx = -1;
9226  for (int j = 0; j < numConstrs;)
9227  {
9228  Oid conrelid = atooid(PQgetvalue(res, j, i_conrelid));
9229  TableInfo *tbinfo = NULL;
9230  int numcons;
9231 
9232  /* Count rows for this table */
9233  for (numcons = 1; numcons < numConstrs - j; numcons++)
9234  if (atooid(PQgetvalue(res, j + numcons, i_conrelid)) != conrelid)
9235  break;
9236 
9237  /*
9238  * Locate the associated TableInfo; we rely on tblinfo[] being in
9239  * OID order.
9240  */
9241  while (++curtblindx < numTables)
9242  {
9243  tbinfo = &tblinfo[curtblindx];
9244  if (tbinfo->dobj.catId.oid == conrelid)
9245  break;
9246  }
9247  if (curtblindx >= numTables)
9248  pg_fatal("unrecognized table OID %u", conrelid);
9249 
9250  if (numcons != tbinfo->ncheck)
9251  {
9252  pg_log_error(ngettext("expected %d check constraint on table \"%s\" but found %d",
9253  "expected %d check constraints on table \"%s\" but found %d",
9254  tbinfo->ncheck),
9255  tbinfo->ncheck, tbinfo->dobj.name, numcons);
9256  pg_log_error_hint("The system catalogs might be corrupted.");
9257  exit_nicely(1);
9258  }
9259 
9260  tbinfo->checkexprs = constrs + j;
9261 
9262  for (int c = 0; c < numcons; c++, j++)
9263  {
9264  bool validated = PQgetvalue(res, j, i_convalidated)[0] == 't';
9265 
9266  constrs[j].dobj.objType = DO_CONSTRAINT;
9267  constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
9268  constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
9269  AssignDumpId(&constrs[j].dobj);
9270  constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
9271  constrs[j].dobj.namespace = tbinfo->dobj.namespace;
9272  constrs[j].contable = tbinfo;
9273  constrs[j].condomain = NULL;
9274  constrs[j].contype = 'c';
9275  constrs[j].condef = pg_strdup(PQgetvalue(res, j, i_consrc));
9276  constrs[j].confrelid = InvalidOid;
9277  constrs[j].conindex = 0;
9278  constrs[j].condeferrable = false;
9279  constrs[j].condeferred = false;
9280  constrs[j].conislocal = (PQgetvalue(res, j, i_conislocal)[0] == 't');
9281 
9282  /*
9283  * An unvalidated constraint needs to be dumped separately, so
9284  * that potentially-violating existing data is loaded before
9285  * the constraint.
9286  */
9287  constrs[j].separate = !validated;
9288 
9289  constrs[j].dobj.dump = tbinfo->dobj.dump;
9290 
9291  /*
9292  * Mark the constraint as needing to appear before the table
9293  * --- this is so that any other dependencies of the
9294  * constraint will be emitted before we try to create the
9295  * table. If the constraint is to be dumped separately, it
9296  * will be dumped after data is loaded anyway, so don't do it.
9297  * (There's an automatic dependency in the opposite direction
9298  * anyway, so don't need to add one manually here.)
9299  */
9300  if (!constrs[j].separate)
9301  addObjectDependency(&tbinfo->dobj,
9302  constrs[j].dobj.dumpId);
9303 
9304  /*
9305  * We will detect later whether the constraint must be split
9306  * out from the table definition.
9307  */
9308  }
9309  }
9310 
9311  PQclear(res);
9312  }
9313 
9314  destroyPQExpBuffer(q);
9315  destroyPQExpBuffer(tbloids);
9316  destroyPQExpBuffer(checkoids);
9317 }
9318 
9319 /*
9320  * Test whether a column should be printed as part of table's CREATE TABLE.
9321  * Column number is zero-based.
9322  *
9323  * Normally this is always true, but it's false for dropped columns, as well
9324  * as those that were inherited without any local definition. (If we print
9325  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
9326  * For partitions, it's always true, because we want the partitions to be
9327  * created independently and ATTACH PARTITION used afterwards.
9328  *
9329  * In binary_upgrade mode, we must print all columns and fix the attislocal/
9330  * attisdropped state later, so as to keep control of the physical column
9331  * order.
9332  *
9333  * This function exists because there are scattered nonobvious places that
9334  * must be kept in sync with this decision.
9335  */
9336 bool
9337 shouldPrintColumn(const DumpOptions *dopt, const TableInfo *tbinfo, int colno)
9338 {
9339  if (dopt->binary_upgrade)
9340  return true;
9341  if (tbinfo->attisdropped[colno])
9342  return false;
9343  return (tbinfo->attislocal[colno] || tbinfo->ispartition);
9344 }
9345 
9346 
9347 /*
9348  * getTSParsers:
9349  * read all text search parsers in the system catalogs and return them
9350  * in the TSParserInfo* structure
9351  *
9352  * numTSParsers is set to the number of parsers read in
9353  */
9354 TSParserInfo *
9355 getTSParsers(Archive *fout, int *numTSParsers)
9356 {
9357  PGresult *res;
9358  int ntups;
9359  int i;
9360  PQExpBuffer query;
9361  TSParserInfo *prsinfo;
9362  int i_tableoid;
9363  int i_oid;
9364  int i_prsname;
9365  int i_prsnamespace;
9366  int i_prsstart;
9367  int i_prstoken;
9368  int i_prsend;
9369  int i_prsheadline;
9370  int i_prslextype;
9371 
9372  query = createPQExpBuffer();
9373 
9374  /*
9375  * find all text search objects, including builtin ones; we filter out
9376  * system-defined objects at dump-out time.
9377  */
9378 
9379  appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
9380  "prsstart::oid, prstoken::oid, "
9381  "prsend::oid, prsheadline::oid, prslextype::oid "
9382  "FROM pg_ts_parser");
9383 
9384  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9385 
9386  ntups = PQntuples(res);
9387  *numTSParsers = ntups;
9388 
9389  prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
9390 
9391  i_tableoid = PQfnumber(res, "tableoid");
9392  i_oid = PQfnumber(res, "oid");
9393  i_prsname = PQfnumber(res, "prsname");
9394  i_prsnamespace = PQfnumber(res, "prsnamespace");
9395  i_prsstart = PQfnumber(res, "prsstart");
9396  i_prstoken = PQfnumber(res, "prstoken");
9397  i_prsend = PQfnumber(res, "prsend");
9398  i_prsheadline = PQfnumber(res, "prsheadline");
9399  i_prslextype = PQfnumber(res, "prslextype");
9400 
9401  for (i = 0; i < ntups; i++)
9402  {
9403  prsinfo[i].dobj.objType = DO_TSPARSER;
9404  prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9405  prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9406  AssignDumpId(&prsinfo[i].dobj);
9407  prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
9408  prsinfo[i].dobj.namespace =
9409  findNamespace(atooid(PQgetvalue(res, i, i_prsnamespace)));
9410  prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
9411  prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
9412  prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
9413  prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
9414  prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
9415 
9416  /* Decide whether we want to dump it */
9417  selectDumpableObject(&(prsinfo[i].dobj), fout);
9418  }
9419 
9420  PQclear(res);
9421 
9422  destroyPQExpBuffer(query);
9423 
9424  return prsinfo;
9425 }
9426 
9427 /*
9428  * getTSDictionaries:
9429  * read all text search dictionaries in the system catalogs and return them
9430  * in the TSDictInfo* structure
9431  *
9432  * numTSDicts is set to the number of dictionaries read in
9433  */
9434 TSDictInfo *
9435 getTSDictionaries(Archive *fout, int *numTSDicts)
9436 {
9437  PGresult *res;
9438  int ntups;
9439  int i;
9440  PQExpBuffer query;
9441  TSDictInfo *dictinfo;
9442  int i_tableoid;
9443  int i_oid;
9444  int i_dictname;
9445  int i_dictnamespace;
9446  int i_dictowner;
9447  int i_dicttemplate;
9448  int i_dictinitoption;
9449 
9450  query = createPQExpBuffer();
9451 
9452  appendPQExpBufferStr(query, "SELECT tableoid, oid, dictname, "
9453  "dictnamespace, dictowner, "
9454  "dicttemplate, dictinitoption "
9455  "FROM pg_ts_dict");
9456 
9457  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9458 
9459  ntups = PQntuples(res);
9460  *numTSDicts = ntups;
9461 
9462  dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
9463 
9464  i_tableoid = PQfnumber(res, "tableoid");
9465  i_oid = PQfnumber(res, "oid");
9466  i_dictname = PQfnumber(res, "dictname");
9467  i_dictnamespace = PQfnumber(res, "dictnamespace");
9468  i_dictowner = PQfnumber(res, "dictowner");
9469  i_dictinitoption = PQfnumber(res, "dictinitoption");
9470  i_dicttemplate = PQfnumber(res, "dicttemplate");
9471 
9472  for (i = 0; i < ntups; i++)
9473  {
9474  dictinfo[i].dobj.objType = DO_TSDICT;
9475  dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9476  dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9477  AssignDumpId(&dictinfo[i].dobj);
9478  dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
9479  dictinfo[i].dobj.namespace =
9480  findNamespace(atooid(PQgetvalue(res, i, i_dictnamespace)));
9481  dictinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_dictowner));
9482  dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
9483  if (PQgetisnull(res, i, i_dictinitoption))
9484  dictinfo[i].dictinitoption = NULL;
9485  else
9486  dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
9487 
9488  /* Decide whether we want to dump it */
9489  selectDumpableObject(&(dictinfo[i].dobj), fout);
9490  }
9491 
9492  PQclear(res);
9493 
9494  destroyPQExpBuffer(query);
9495 
9496  return dictinfo;
9497 }
9498 
9499 /*
9500  * getTSTemplates:
9501  * read all text search templates in the system catalogs and return them
9502  * in the TSTemplateInfo* structure
9503  *
9504  * numTSTemplates is set to the number of templates read in
9505  */
9507 getTSTemplates(Archive *fout, int *numTSTemplates)
9508 {
9509  PGresult *res;
9510  int ntups;
9511  int i;
9512  PQExpBuffer query;
9513  TSTemplateInfo *tmplinfo;
9514  int i_tableoid;
9515  int i_oid;
9516  int i_tmplname;
9517  int i_tmplnamespace;
9518  int i_tmplinit;
9519  int i_tmpllexize;
9520 
9521  query = createPQExpBuffer();
9522 
9523  appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
9524  "tmplnamespace, tmplinit::oid, tmpllexize::oid "
9525  "FROM pg_ts_template");
9526 
9527  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9528 
9529  ntups = PQntuples(res);
9530  *numTSTemplates = ntups;
9531 
9532  tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
9533 
9534  i_tableoid = PQfnumber(res, "tableoid");
9535  i_oid = PQfnumber(res, "oid");
9536  i_tmplname = PQfnumber(res, "tmplname");
9537  i_tmplnamespace = PQfnumber(res, "tmplnamespace");
9538  i_tmplinit = PQfnumber(res, "tmplinit");
9539  i_tmpllexize = PQfnumber(res, "tmpllexize");
9540 
9541  for (i = 0; i < ntups; i++)
9542  {
9543  tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
9544  tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9545  tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9546  AssignDumpId(&tmplinfo[i].dobj);
9547  tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
9548  tmplinfo[i].dobj.namespace =
9549  findNamespace(atooid(PQgetvalue(res, i, i_tmplnamespace)));
9550  tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
9551  tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
9552 
9553  /* Decide whether we want to dump it */
9554  selectDumpableObject(&(tmplinfo[i].dobj), fout);
9555  }
9556 
9557  PQclear(res);
9558 
9559  destroyPQExpBuffer(query);
9560 
9561  return tmplinfo;
9562 }
9563 
9564 /*
9565  * getTSConfigurations:
9566  * read all text search configurations in the system catalogs and return
9567  * them in the TSConfigInfo* structure
9568  *
9569  * numTSConfigs is set to the number of configurations read in
9570  */
9571 TSConfigInfo *
9572 getTSConfigurations(Archive *fout, int *numTSConfigs)
9573 {
9574  PGresult *res;
9575  int ntups;
9576  int i;
9577  PQExpBuffer query;
9578  TSConfigInfo *cfginfo;
9579  int i_tableoid;
9580  int i_oid;
9581  int i_cfgname;
9582  int i_cfgnamespace;
9583  int i_cfgowner;
9584  int i_cfgparser;
9585 
9586  query = createPQExpBuffer();
9587 
9588  appendPQExpBufferStr(query, "SELECT tableoid, oid, cfgname, "
9589  "cfgnamespace, cfgowner, cfgparser "
9590  "FROM pg_ts_config");
9591 
9592  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9593 
9594  ntups = PQntuples(res);
9595  *numTSConfigs = ntups;
9596 
9597  cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
9598 
9599  i_tableoid = PQfnumber(res, "tableoid");
9600  i_oid = PQfnumber(res, "oid");
9601  i_cfgname = PQfnumber(res, "cfgname");
9602  i_cfgnamespace = PQfnumber(res, "cfgnamespace");
9603  i_cfgowner = PQfnumber(res, "cfgowner");
9604  i_cfgparser = PQfnumber(res, "cfgparser");
9605 
9606  for (i = 0; i < ntups; i++)
9607  {
9608  cfginfo[i].dobj.objType = DO_TSCONFIG;
9609  cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9610  cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9611  AssignDumpId(&cfginfo[i].dobj);
9612  cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
9613  cfginfo[i].dobj.namespace =
9614  findNamespace(atooid(PQgetvalue(res, i, i_cfgnamespace)));
9615  cfginfo[i].rolname = getRoleName(PQgetvalue(res, i, i_cfgowner));
9616  cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
9617 
9618  /* Decide whether we want to dump it */
9619  selectDumpableObject(&(cfginfo[i].dobj), fout);
9620  }
9621 
9622  PQclear(res);
9623 
9624  destroyPQExpBuffer(query);
9625 
9626  return cfginfo;
9627 }
9628 
9629 /*
9630  * getForeignDataWrappers:
9631  * read all foreign-data wrappers in the system catalogs and return
9632  * them in the FdwInfo* structure
9633  *
9634  * numForeignDataWrappers is set to the number of fdws read in
9635  */
9636 FdwInfo *
9637 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
9638 {
9639  PGresult *res;
9640  int ntups;
9641  int i;
9642  PQExpBuffer query;
9643  FdwInfo *fdwinfo;
9644  int i_tableoid;
9645  int i_oid;
9646  int i_fdwname;
9647  int i_fdwowner;
9648  int i_fdwhandler;
9649  int i_fdwvalidator;
9650  int i_fdwacl;
9651  int i_acldefault;
9652  int i_fdwoptions;
9653 
9654  query = createPQExpBuffer();
9655 
9656  appendPQExpBufferStr(query, "SELECT tableoid, oid, fdwname, "
9657  "fdwowner, "
9658  "fdwhandler::pg_catalog.regproc, "
9659  "fdwvalidator::pg_catalog.regproc, "
9660  "fdwacl, "
9661  "acldefault('F', fdwowner) AS acldefault, "
9662  "array_to_string(ARRAY("
9663  "SELECT quote_ident(option_name) || ' ' || "
9664  "quote_literal(option_value) "
9665  "FROM pg_options_to_table(fdwoptions) "
9666  "ORDER BY option_name"
9667  "), E',\n ') AS fdwoptions "
9668  "FROM pg_foreign_data_wrapper");
9669 
9670  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9671 
9672  ntups = PQntuples(res);
9673  *numForeignDataWrappers = ntups;
9674 
9675  fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9676 
9677  i_tableoid = PQfnumber(res, "tableoid");
9678  i_oid = PQfnumber(res, "oid");
9679  i_fdwname = PQfnumber(res, "fdwname");
9680  i_fdwowner = PQfnumber(res, "fdwowner");
9681  i_fdwhandler = PQfnumber(res, "fdwhandler");
9682  i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9683  i_fdwacl = PQfnumber(res, "fdwacl");
9684  i_acldefault = PQfnumber(res, "acldefault");
9685  i_fdwoptions = PQfnumber(res, "fdwoptions");
9686 
9687  for (i = 0; i < ntups; i++)
9688  {
9689  fdwinfo[i].dobj.objType = DO_FDW;
9690  fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9691  fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9692  AssignDumpId(&fdwinfo[i].dobj);
9693  fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9694  fdwinfo[i].dobj.namespace = NULL;
9695  fdwinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9696  fdwinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
9697  fdwinfo[i].dacl.privtype = 0;
9698  fdwinfo[i].dacl.initprivs = NULL;
9699  fdwinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_fdwowner));
9700  fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9701  fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9702  fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9703 
9704  /* Decide whether we want to dump it */
9705  selectDumpableObject(&(fdwinfo[i].dobj), fout);
9706 
9707  /* Mark whether FDW has an ACL */
9708  if (!PQgetisnull(res, i, i_fdwacl))
9709  fdwinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
9710  }
9711 
9712  PQclear(res);
9713 
9714  destroyPQExpBuffer(query);
9715 
9716  return fdwinfo;
9717 }
9718 
9719 /*
9720  * getForeignServers:
9721  * read all foreign servers in the system catalogs and return
9722  * them in the ForeignServerInfo * structure
9723  *
9724  * numForeignServers is set to the number of servers read in
9725  */
9727 getForeignServers(Archive *fout, int *numForeignServers)
9728 {
9729  PGresult *res;
9730  int ntups;
9731  int i;
9732  PQExpBuffer query;
9733  ForeignServerInfo *srvinfo;
9734  int i_tableoid;
9735  int i_oid;
9736  int i_srvname;
9737  int i_srvowner;
9738  int i_srvfdw;
9739  int i_srvtype;
9740  int i_srvversion;
9741  int i_srvacl;
9742  int i_acldefault;
9743  int i_srvoptions;
9744 
9745  query = createPQExpBuffer();
9746 
9747  appendPQExpBufferStr(query, "SELECT tableoid, oid, srvname, "
9748  "srvowner, "
9749  "srvfdw, srvtype, srvversion, srvacl, "
9750  "acldefault('S', srvowner) AS acldefault, "
9751  "array_to_string(ARRAY("
9752  "SELECT quote_ident(option_name) || ' ' || "
9753  "quote_literal(option_value) "
9754  "FROM pg_options_to_table(srvoptions) "
9755  "ORDER BY option_name"
9756  "), E',\n ') AS srvoptions "
9757  "FROM pg_foreign_server");
9758 
9759  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9760 
9761  ntups = PQntuples(res);
9762  *numForeignServers = ntups;
9763 
9764  srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9765 
9766  i_tableoid = PQfnumber(res, "tableoid");
9767  i_oid = PQfnumber(res, "oid");
9768  i_srvname = PQfnumber(res, "srvname");
9769  i_srvowner = PQfnumber(res, "srvowner");
9770  i_srvfdw = PQfnumber(res, "srvfdw");
9771  i_srvtype = PQfnumber(res, "srvtype");
9772  i_srvversion = PQfnumber(res, "srvversion");
9773  i_srvacl = PQfnumber(res, "srvacl");
9774  i_acldefault = PQfnumber(res, "acldefault");
9775  i_srvoptions = PQfnumber(res, "srvoptions");
9776 
9777  for (i = 0; i < ntups; i++)
9778  {
9779  srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9780  srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9781  srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9782  AssignDumpId(&srvinfo[i].dobj);
9783  srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9784  srvinfo[i].dobj.namespace = NULL;
9785  srvinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9786  srvinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
9787  srvinfo[i].dacl.privtype = 0;
9788  srvinfo[i].dacl.initprivs = NULL;
9789  srvinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_srvowner));
9790  srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9791  srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9792  srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9793  srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9794 
9795  /* Decide whether we want to dump it */
9796  selectDumpableObject(&(srvinfo[i].dobj), fout);
9797 
9798  /* Servers have user mappings */
9800 
9801  /* Mark whether server has an ACL */
9802  if (!PQgetisnull(res, i, i_srvacl))
9803  srvinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
9804  }
9805 
9806  PQclear(res);
9807 
9808  destroyPQExpBuffer(query);
9809 
9810  return srvinfo;
9811 }
9812 
9813 /*
9814  * getDefaultACLs:
9815  * read all default ACL information in the system catalogs and return
9816  * them in the DefaultACLInfo structure
9817  *
9818  * numDefaultACLs is set to the number of ACLs read in
9819  */
9821 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9822 {
9823  DumpOptions *dopt = fout->dopt;
9824  DefaultACLInfo *daclinfo;
9825  PQExpBuffer query;
9826  PGresult *res;
9827  int i_oid;
9828  int i_tableoid;
9829  int i_defaclrole;
9830  int i_defaclnamespace;
9831  int i_defaclobjtype;
9832  int i_defaclacl;
9833  int i_acldefault;
9834  int i,
9835  ntups;
9836 
9837  query = createPQExpBuffer();
9838 
9839  /*
9840  * Global entries (with defaclnamespace=0) replace the hard-wired default
9841  * ACL for their object type. We should dump them as deltas from the
9842  * default ACL, since that will be used as a starting point for
9843  * interpreting the ALTER DEFAULT PRIVILEGES commands. On the other hand,
9844  * non-global entries can only add privileges not revoke them. We must
9845  * dump those as-is (i.e., as deltas from an empty ACL).
9846  *
9847  * We can use defaclobjtype as the object type for acldefault(), except
9848  * for the case of 'S' (DEFACLOBJ_SEQUENCE) which must be converted to
9849  * 's'.
9850  */
9851  appendPQExpBufferStr(query,
9852  "SELECT oid, tableoid, "
9853  "defaclrole, "
9854  "defaclnamespace, "
9855  "defaclobjtype, "
9856  "defaclacl, "
9857  "CASE WHEN defaclnamespace = 0 THEN "
9858  "acldefault(CASE WHEN defaclobjtype = 'S' "
9859  "THEN 's'::\"char\" ELSE defaclobjtype END, "
9860  "defaclrole) ELSE '{}' END AS acldefault "
9861  "FROM pg_default_acl");
9862 
9863  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9864 
9865  ntups = PQntuples(res);
9866  *numDefaultACLs = ntups;
9867 
9868  daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9869 
9870  i_oid = PQfnumber(res, "oid");
9871  i_tableoid = PQfnumber(res, "tableoid");
9872  i_defaclrole = PQfnumber(res, "defaclrole");
9873  i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9874  i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9875  i_defaclacl = PQfnumber(res, "defaclacl");
9876  i_acldefault = PQfnumber(res, "acldefault");
9877 
9878  for (i = 0; i < ntups; i++)
9879  {
9880  Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9881 
9882  daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9883  daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9884  daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9885  AssignDumpId(&daclinfo[i].dobj);
9886  /* cheesy ... is it worth coming up with a better object name? */
9887  daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9888 
9889  if (nspid != InvalidOid)
9890  daclinfo[i].dobj.namespace = findNamespace(nspid);
9891  else
9892  daclinfo[i].dobj.namespace = NULL;
9893 
9894  daclinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9895  daclinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
9896  daclinfo[i].dacl.privtype = 0;
9897  daclinfo[i].dacl.initprivs = NULL;
9898  daclinfo[i].defaclrole = getRoleName(PQgetvalue(res, i, i_defaclrole));
9899  daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9900 
9901  /* Default ACLs are ACLs, of course */
9902  daclinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
9903 
9904  /* Decide whether we want to dump it */
9905  selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9906  }
9907 
9908  PQclear(res);
9909 
9910  destroyPQExpBuffer(query);
9911 
9912  return daclinfo;
9913 }
9914 
9915 /*
9916  * getRoleName -- look up the name of a role, given its OID
9917  *
9918  * In current usage, we don't expect failures, so error out for a bad OID.
9919  */
9920 static const char *
9921 getRoleName(const char *roleoid_str)
9922 {
9923  Oid roleoid = atooid(roleoid_str);
9924 
9925  /*
9926  * Do binary search to find the appropriate item.
9927  */
9928  if (nrolenames > 0)
9929  {
9930  RoleNameItem *low = &rolenames[0];
9931  RoleNameItem *high = &rolenames[nrolenames - 1];
9932 
9933  while (low <= high)
9934  {
9935  RoleNameItem *middle = low + (high - low) / 2;
9936 
9937  if (roleoid < middle->roleoid)
9938  high = middle - 1;
9939  else if (roleoid > middle->roleoid)
9940  low = middle + 1;
9941  else
9942  return middle->rolename; /* found a match */
9943  }
9944  }
9945 
9946  pg_fatal("role with OID %u does not exist", roleoid);
9947  return NULL; /* keep compiler quiet */
9948 }
9949 
9950 /*
9951  * collectRoleNames --
9952  *
9953  * Construct a table of all known roles.
9954  * The table is sorted by OID for speed in lookup.
9955  */
9956 static void
9958 {
9959  PGresult *res;
9960  const char *query;
9961  int i;
9962 
9963  query = "SELECT oid, rolname FROM pg_catalog.pg_roles ORDER BY 1";
9964 
9965  res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
9966 
9968 
9970 
9971  for (i = 0; i < nrolenames; i++)
9972  {
9975  }
9976 
9977  PQclear(res);
9978 }
9979 
9980 /*
9981  * getAdditionalACLs
9982  *
9983  * We have now created all the DumpableObjects, and collected the ACL data
9984  * that appears in the directly-associated catalog entries. However, there's
9985  * more ACL-related info to collect. If any of a table's columns have ACLs,
9986  * we must set the TableInfo's DUMP_COMPONENT_ACL components flag, as well as
9987  * its hascolumnACLs flag (we won't store the ACLs themselves here, though).
9988  * Also, in versions having the pg_init_privs catalog, read that and load the
9989  * information into the relevant DumpableObjects.
9990  */
9991 static void
9993 {
9994  PQExpBuffer query = createPQExpBuffer();
9995  PGresult *res;
9996  int ntups,
9997  i;
9998 
9999  /* Check for per-column ACLs */
10000  appendPQExpBufferStr(query,
10001  "SELECT DISTINCT attrelid FROM pg_attribute "
10002  "WHERE attacl IS NOT NULL");
10003 
10004  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10005 
10006  ntups = PQntuples(res);
10007  for (i = 0; i < ntups; i++)
10008  {
10009  Oid relid = atooid(PQgetvalue(res, i, 0));
10010  TableInfo *tblinfo;
10011 
10012  tblinfo = findTableByOid(relid);
10013  /* OK to ignore tables we haven't got a DumpableObject for */
10014  if (tblinfo)
10015  {
10016  tblinfo->dobj.components |= DUMP_COMPONENT_ACL;
10017  tblinfo->hascolumnACLs = true;
10018  }
10019  }
10020  PQclear(res);
10021 
10022  /* Fetch initial-privileges data */
10023  if (fout->remoteVersion >= 90600)
10024  {
10025  printfPQExpBuffer(query,
10026  "SELECT objoid, classoid, objsubid, privtype, initprivs "
10027  "FROM pg_init_privs");
10028 
10029  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10030 
10031  ntups = PQntuples(res);
10032  for (i = 0; i < ntups; i++)
10033  {
10034  Oid objoid = atooid(PQgetvalue(res, i, 0));
10035  Oid classoid = atooid(PQgetvalue(res, i, 1));
10036  int objsubid = atoi(PQgetvalue(res, i, 2));
10037  char privtype = *(PQgetvalue(res, i, 3));
10038  char *initprivs = PQgetvalue(res, i, 4);
10039  CatalogId objId;
10040  DumpableObject *dobj;
10041 
10042  objId.tableoid = classoid;
10043  objId.oid = objoid;
10044  dobj = findObjectByCatalogId(objId);
10045  /* OK to ignore entries we haven't got a DumpableObject for */
10046  if (dobj)
10047  {
10048  /* Cope with sub-object initprivs */
10049  if (objsubid != 0)
10050  {
10051  if (dobj->objType == DO_TABLE)
10052  {
10053  /* For a column initprivs, set the table's ACL flags */
10054  dobj->components |= DUMP_COMPONENT_ACL;
10055  ((TableInfo *) dobj)->hascolumnACLs = true;
10056  }
10057  else
10058  pg_log_warning("unsupported pg_init_privs entry: %u %u %d",
10059  classoid, objoid, objsubid);
10060  continue;
10061  }
10062 
10063  /*
10064  * We ignore any pg_init_privs.initprivs entry for the public
10065  * schema, as explained in getNamespaces().
10066  */
10067  if (dobj->objType == DO_NAMESPACE &&
10068  strcmp(dobj->name, "public") == 0)
10069  continue;
10070 
10071  /* Else it had better be of a type we think has ACLs */
10072  if (dobj->objType == DO_NAMESPACE ||
10073  dobj->objType == DO_TYPE ||
10074  dobj->objType == DO_FUNC ||
10075  dobj->objType == DO_AGG ||
10076  dobj->objType == DO_TABLE ||
10077  dobj->objType == DO_PROCLANG ||
10078  dobj->objType == DO_FDW ||
10079  dobj->objType == DO_FOREIGN_SERVER)
10080  {
10081  DumpableObjectWithAcl *daobj = (DumpableObjectWithAcl *) dobj;
10082 
10083  daobj->dacl.privtype = privtype;
10084  daobj->dacl.initprivs = pstrdup(initprivs);
10085  }
10086  else
10087  pg_log_warning("unsupported pg_init_privs entry: %u %u %d",
10088  classoid, objoid, objsubid);
10089  }
10090  }
10091  PQclear(res);
10092  }
10093 
10094  destroyPQExpBuffer(query);
10095 }
10096 
10097 /*
10098  * dumpCommentExtended --
10099  *
10100  * This routine is used to dump any comments associated with the
10101  * object handed to this routine. The routine takes the object type
10102  * and object name (ready to print, except for schema decoration), plus
10103  * the namespace and owner of the object (for labeling the ArchiveEntry),
10104  * plus catalog ID and subid which are the lookup key for pg_description,
10105  * plus the dump ID for the object (for setting a dependency).
10106  * If a matching pg_description entry is found, it is dumped.
10107  *
10108  * Note: in some cases, such as comments for triggers and rules, the "type"
10109  * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
10110  * but it doesn't seem worth complicating the API for all callers to make
10111  * it cleaner.
10112  *
10113  * Note: although this routine takes a dumpId for dependency purposes,
10114  * that purpose is just to mark the dependency in the emitted dump file
10115  * for possible future use by pg_restore. We do NOT use it for determining
10116  * ordering of the comment in the dump file, because this routine is called
10117  * after dependency sorting occurs. This routine should be called just after
10118  * calling ArchiveEntry() for the specified object.
10119  */
10120 static void
10121 dumpCommentExtended(Archive *fout, const char *type,
10122  const char *name, const char *namespace,
10123  const char *owner, CatalogId catalogId,
10124  int subid, DumpId dumpId,
10125  const char *initdb_comment)
10126 {
10127  DumpOptions *dopt = fout->dopt;
10129  int ncomments;
10130 
10131  /* do nothing, if --no-comments is supplied */
10132  if (dopt->no_comments)
10133  return;
10134 
10135  /* Comments are schema not data ... except LO comments are data */
10136  if (strcmp(type, "LARGE OBJECT") != 0)
10137  {
10138  if (dopt->dataOnly)
10139  return;
10140  }
10141  else
10142  {
10143  /* We do dump LO comments in binary-upgrade mode */
10144  if (dopt->schemaOnly && !dopt->binary_upgrade)
10145  return;
10146  }
10147 
10148  /* Search for comments associated with catalogId, using table */
10149  ncomments = findComments(catalogId.tableoid, catalogId.oid,
10150  &comments);
10151 
10152  /* Is there one matching the subid? */
10153  while (ncomments > 0)
10154  {
10155  if (comments->objsubid == subid)
10156  break;
10157  comments++;
10158  ncomments--;
10159  }
10160 
10161  if (initdb_comment != NULL)
10162  {
10163  static CommentItem empty_comment = {.descr = ""};
10164 
10165  /*
10166  * initdb creates this object with a comment. Skip dumping the
10167  * initdb-provided comment, which would complicate matters for
10168  * non-superuser use of pg_dump. When the DBA has removed initdb's
10169  * comment, replicate that.
10170  */
10171  if (ncomments == 0)
10172  {
10173  comments = &empty_comment;
10174  ncomments = 1;
10175  }
10176  else if (strcmp(comments->descr, initdb_comment) == 0)
10177  ncomments = 0;
10178  }
10179 
10180  /* If a comment exists, build COMMENT ON statement */
10181  if (ncomments > 0)
10182  {
10183  PQExpBuffer query = createPQExpBuffer();
10185 
10186  appendPQExpBuffer(query, "COMMENT ON %s ", type);
10187  if (namespace && *namespace)
10188  appendPQExpBuffer(query, "%s.", fmtId(namespace));
10189  appendPQExpBuffer(query, "%s IS ", name);
10190  appendStringLiteralAH(query, comments->descr, fout);
10191  appendPQExpBufferStr(query, ";\n");
10192 
10193  appendPQExpBuffer(tag, "%s %s", type, name);
10194 
10195  /*
10196  * We mark comments as SECTION_NONE because they really belong in the
10197  * same section as their parent, whether that is pre-data or
10198  * post-data.
10199  */
10201  ARCHIVE_OPTS(.tag = tag->data,
10202  .namespace = namespace,
10203  .owner = owner,
10204  .description = "COMMENT",
10205  .section = SECTION_NONE,
10206  .createStmt = query->data,
10207  .deps = &dumpId,
10208  .nDeps = 1));
10209 
10210  destroyPQExpBuffer(query);
10211  destroyPQExpBuffer(tag);
10212  }
10213 }
10214 
10215 /*
10216  * dumpComment --
10217  *
10218  * Typical simplification of the above function.
10219  */
10220 static inline void
10221 dumpComment(Archive *fout, const char *type,
10222  const char *name, const char *namespace,
10223  const char *owner, CatalogId catalogId,
10224  int subid, DumpId dumpId)
10225 {
10226  dumpCommentExtended(fout, type, name, namespace, owner,
10227  catalogId, subid, dumpId, NULL);
10228 }
10229 
10230 /*
10231  * dumpTableComment --
10232  *
10233  * As above, but dump comments for both the specified table (or view)
10234  * and its columns.
10235  */
10236 static void
10237 dumpTableComment(Archive *fout, const TableInfo *tbinfo,
10238  const char *reltypename)
10239 {
10240  DumpOptions *dopt = fout->dopt;
10242  int ncomments;
10243  PQExpBuffer query;
10244  PQExpBuffer tag;
10245 
10246  /* do nothing, if --no-comments is supplied */
10247  if (dopt->no_comments)
10248  return;
10249 
10250  /* Comments are SCHEMA not data */
10251  if (dopt->dataOnly)
10252  return;
10253 
10254  /* Search for comments associated with relation, using table */
10256  tbinfo->dobj.catId.oid,
10257  &comments);
10258 
10259  /* If comments exist, build COMMENT ON statements */
10260  if (ncomments <= 0)
10261  return;
10262 
10263  query = createPQExpBuffer();
10264  tag = createPQExpBuffer();
10265 
10266  while (ncomments > 0)
10267  {
10268  const char *descr = comments->descr;
10269  int objsubid = comments->objsubid;
10270 
10271  if (objsubid == 0)
10272  {
10273  resetPQExpBuffer(tag);
10274  appendPQExpBuffer(tag, "%s %s", reltypename,
10275  fmtId(tbinfo->dobj.name));
10276 
10277  resetPQExpBuffer(query);
10278  appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
10279  fmtQualifiedDumpable(tbinfo));
10280  appendStringLiteralAH(query, descr, fout);
10281  appendPQExpBufferStr(query, ";\n");
10282 
10284  ARCHIVE_OPTS(.tag = tag->data,
10285  .namespace = tbinfo->dobj.namespace->dobj.name,
10286  .owner = tbinfo->rolname,
10287  .description = "COMMENT",
10288  .section = SECTION_NONE,
10289  .createStmt = query->data,
10290  .deps = &(tbinfo->dobj.dumpId),
10291  .nDeps = 1));
10292  }
10293  else if (objsubid > 0 && objsubid <= tbinfo->numatts)
10294  {
10295  resetPQExpBuffer(tag);
10296  appendPQExpBuffer(tag, "COLUMN %s.",
10297  fmtId(tbinfo->dobj.name));
10298  appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
10299 
10300  resetPQExpBuffer(query);
10301  appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
10302  fmtQualifiedDumpable(tbinfo));
10303  appendPQExpBuffer(query, "%s IS ",
10304  fmtId(tbinfo->attnames[objsubid - 1]));
10305  appendStringLiteralAH(query, descr, fout);
10306  appendPQExpBufferStr(query, ";\n");
10307 
10309  ARCHIVE_OPTS(.tag = tag->data,
10310  .namespace = tbinfo->dobj.namespace->dobj.name,
10311  .owner = tbinfo->rolname,
10312  .description = "COMMENT",
10313  .section = SECTION_NONE,
10314  .createStmt = query->data,
10315  .deps = &(tbinfo->dobj.dumpId),
10316  .nDeps = 1));
10317  }
10318 
10319  comments++;
10320  ncomments--;
10321  }
10322 
10323  destroyPQExpBuffer(query);
10324  destroyPQExpBuffer(tag);
10325 }
10326 
10327 /*
10328  * findComments --
10329  *
10330  * Find the comment(s), if any, associated with the given object. All the
10331  * objsubid values associated with the given classoid/objoid are found with
10332  * one search.
10333  */
10334 static int
10335 findComments(Oid classoid, Oid objoid, CommentItem **items)
10336 {
10337  CommentItem *middle = NULL;
10338  CommentItem *low;
10339  CommentItem *high;
10340  int nmatch;
10341 
10342  /*
10343  * Do binary search to find some item matching the object.
10344  */
10345  low = &comments[0];
10346  high = &comments[ncomments - 1];
10347  while (low <= high)
10348  {
10349  middle = low + (high - low) / 2;
10350 
10351  if (classoid < middle->classoid)
10352  high = middle - 1;
10353  else if (classoid > middle->classoid)
10354  low = middle + 1;
10355  else if (objoid < middle->objoid)
10356  high = middle - 1;
10357  else if (objoid > middle->objoid)
10358  low = middle + 1;
10359  else
10360  break; /* found a match */
10361  }
10362 
10363  if (low > high) /* no matches */
10364  {
10365  *items = NULL;
10366  return 0;
10367  }
10368 
10369  /*
10370  * Now determine how many items match the object. The search loop
10371  * invariant still holds: only items between low and high inclusive could
10372  * match.
10373  */
10374  nmatch = 1;
10375  while (middle > low)
10376  {
10377  if (classoid != middle[-1].classoid ||
10378  objoid != middle[-1].objoid)
10379  break;
10380  middle--;
10381  nmatch++;
10382  }
10383 
10384  *items = middle;
10385 
10386  middle += nmatch;
10387  while (middle <= high)
10388  {
10389  if (classoid != middle->classoid ||
10390  objoid != middle->objoid)
10391  break;
10392  middle++;
10393  nmatch++;
10394  }
10395 
10396  return nmatch;
10397 }
10398 
10399 /*
10400  * collectComments --
10401  *
10402  * Construct a table of all comments available for database objects;
10403  * also set the has-comment component flag for each relevant object.
10404  *
10405  * We used to do per-object queries for the comments, but it's much faster
10406  * to pull them all over at once, and on most databases the memory cost
10407  * isn't high.
10408  *
10409  * The table is sorted by classoid/objid/objsubid for speed in lookup.
10410  */
10411 static void
10413 {
10414  PGresult *res;
10415  PQExpBuffer query;
10416  int i_description;
10417  int i_classoid;
10418  int i_objoid;
10419  int i_objsubid;
10420  int ntups;
10421  int i;
10422  DumpableObject *dobj;
10423 
10424  query = createPQExpBuffer();
10425 
10426  appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
10427  "FROM pg_catalog.pg_description "
10428  "ORDER BY classoid, objoid, objsubid");
10429 
10430  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10431 
10432  /* Construct lookup table containing OIDs in numeric form */
10433 
10434  i_description = PQfnumber(res, "description");
10435  i_classoid = PQfnumber(res, "classoid");
10436  i_objoid = PQfnumber(res, "objoid");
10437  i_objsubid = PQfnumber(res, "objsubid");
10438 
10439  ntups = PQntuples(res);
10440 
10441  comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
10442  ncomments = 0;
10443  dobj = NULL;
10444 
10445  for (i = 0; i < ntups; i++)
10446  {
10447  CatalogId objId;
10448  int subid;
10449 
10450  objId.tableoid = atooid(PQgetvalue(res, i, i_classoid));
10451  objId.oid = atooid(PQgetvalue(res, i, i_objoid));
10452  subid = atoi(PQgetvalue(res, i, i_objsubid));
10453 
10454  /* We needn't remember comments that don't match any dumpable object */
10455  if (dobj == NULL ||
10456  dobj->catId.tableoid != objId.tableoid ||
10457  dobj->catId.oid != objId.oid)
10458  dobj = findObjectByCatalogId(objId);
10459  if (dobj == NULL)
10460  continue;
10461 
10462  /*
10463  * Comments on columns of composite types are linked to the type's
10464  * pg_class entry, but we need to set the DUMP_COMPONENT_COMMENT flag
10465  * in the type's own DumpableObject.
10466  */
10467  if (subid != 0 && dobj->objType == DO_TABLE &&
10468  ((TableInfo *) dobj)->relkind == RELKIND_COMPOSITE_TYPE)
10469  {
10470  TypeInfo *cTypeInfo;
10471 
10472  cTypeInfo = findTypeByOid(((TableInfo *) dobj)->reltype);
10473  if (cTypeInfo)
10474  cTypeInfo->dobj.components |= DUMP_COMPONENT_COMMENT;
10475  }
10476  else
10477  dobj->components |= DUMP_COMPONENT_COMMENT;
10478 
10479  comments[ncomments].descr = pg_strdup(PQgetvalue(res, i, i_description));
10481  comments[ncomments].objoid = objId.oid;
10482  comments[ncomments].objsubid = subid;
10483  ncomments++;
10484  }
10485 
10486  PQclear(res);
10487  destroyPQExpBuffer(query);
10488 }
10489 
10490 /*
10491  * dumpDumpableObject
10492  *
10493  * This routine and its subsidiaries are responsible for creating
10494  * ArchiveEntries (TOC objects) for each object to be dumped.
10495  */
10496 static void
10498 {
10499  /*
10500  * Clear any dump-request bits for components that don't exist for this
10501  * object. (This makes it safe to initially use DUMP_COMPONENT_ALL as the
10502  * request for every kind of object.)
10503  */
10504  dobj->dump &= dobj->components;
10505 
10506  /* Now, short-circuit if there's nothing to be done here. */
10507  if (dobj->dump == 0)
10508  return;
10509 
10510  switch (dobj->objType)
10511  {
10512  case DO_NAMESPACE:
10513  dumpNamespace(fout, (const NamespaceInfo *) dobj);
10514  break;
10515  case DO_EXTENSION:
10516  dumpExtension(fout, (const ExtensionInfo *) dobj);
10517  break;
10518  case DO_TYPE:
10519  dumpType(fout, (const TypeInfo *) dobj);
10520  break;
10521  case DO_SHELL_TYPE:
10522  dumpShellType(fout, (const ShellTypeInfo *) dobj);
10523  break;
10524  case DO_FUNC:
10525  dumpFunc(fout, (const FuncInfo *) dobj);
10526  break;
10527  case DO_AGG:
10528  dumpAgg(fout, (const AggInfo *) dobj);
10529  break;
10530  case DO_OPERATOR:
10531  dumpOpr(fout, (const OprInfo *) dobj);
10532  break;
10533  case DO_ACCESS_METHOD:
10534  dumpAccessMethod(fout, (const AccessMethodInfo *) dobj);
10535  break;
10536  case DO_OPCLASS:
10537  dumpOpclass(fout, (const OpclassInfo *) dobj);
10538  break;
10539  case DO_OPFAMILY:
10540  dumpOpfamily(fout, (const OpfamilyInfo *) dobj);
10541  break;
10542  case DO_COLLATION:
10543  dumpCollation(fout, (const CollInfo *) dobj);
10544  break;
10545  case DO_CONVERSION:
10546  dumpConversion(fout, (const ConvInfo *) dobj);
10547  break;
10548  case DO_TABLE:
10549  dumpTable(fout, (const TableInfo *) dobj);
10550  break;
10551  case DO_TABLE_ATTACH:
10552  dumpTableAttach(fout, (const TableAttachInfo *) dobj);
10553  break;
10554  case DO_ATTRDEF:
10555  dumpAttrDef(fout, (const AttrDefInfo *) dobj);
10556  break;
10557  case DO_INDEX:
10558  dumpIndex(fout, (const IndxInfo *) dobj);
10559  break;
10560  case DO_INDEX_ATTACH:
10561  dumpIndexAttach(fout, (const IndexAttachInfo *) dobj);
10562  break;
10563  case DO_STATSEXT:
10564  dumpStatisticsExt(fout, (const StatsExtInfo *) dobj);
10565  break;
10566  case DO_REFRESH_MATVIEW:
10567  refreshMatViewData(fout, (const TableDataInfo *) dobj);
10568  break;
10569  case DO_RULE:
10570  dumpRule(fout, (const RuleInfo *) dobj);
10571  break;
10572  case DO_TRIGGER:
10573  dumpTrigger(fout, (const TriggerInfo *) dobj);
10574  break;
10575  case DO_EVENT_TRIGGER:
10576  dumpEventTrigger(fout, (const EventTriggerInfo *) dobj);
10577  break;
10578  case DO_CONSTRAINT:
10579  dumpConstraint(fout, (const ConstraintInfo *) dobj);
10580  break;
10581  case DO_FK_CONSTRAINT:
10582  dumpConstraint(fout, (const ConstraintInfo *) dobj);
10583  break;
10584  case DO_PROCLANG:
10585  dumpProcLang(fout, (const ProcLangInfo *) dobj);
10586  break;
10587  case DO_CAST:
10588  dumpCast(fout, (const CastInfo *) dobj);
10589  break;
10590  case DO_TRANSFORM:
10591  dumpTransform(fout, (const TransformInfo *) dobj);
10592  break;
10593  case DO_SEQUENCE_SET:
10594  dumpSequenceData(fout, (const TableDataInfo *) dobj);
10595  break;
10596  case DO_TABLE_DATA:
10597  dumpTableData(fout, (const TableDataInfo *) dobj);
10598  break;
10599  case DO_DUMMY_TYPE:
10600  /* table rowtypes and array types are never dumped separately */
10601  break;
10602  case DO_TSPARSER:
10603  dumpTSParser(fout, (const TSParserInfo *) dobj);
10604  break;
10605  case DO_TSDICT:
10606  dumpTSDictionary(fout, (const TSDictInfo *) dobj);
10607  break;
10608  case DO_TSTEMPLATE:
10609  dumpTSTemplate(fout, (const TSTemplateInfo *) dobj);
10610  break;
10611  case DO_TSCONFIG:
10612  dumpTSConfig(fout, (const TSConfigInfo *) dobj);
10613  break;
10614  case DO_FDW:
10615  dumpForeignDataWrapper(fout, (const FdwInfo *) dobj);
10616  break;
10617  case DO_FOREIGN_SERVER:
10618  dumpForeignServer(fout, (const ForeignServerInfo *) dobj);
10619  break;
10620  case DO_DEFAULT_ACL:
10621  dumpDefaultACL(fout, (const DefaultACLInfo *) dobj);
10622  break;
10623  case DO_LARGE_OBJECT:
10624  dumpLO(fout, (const LoInfo *) dobj);
10625  break;
10626  case DO_LARGE_OBJECT_DATA:
10627  if (dobj->dump & DUMP_COMPONENT_DATA)
10628  {
10629  TocEntry *te;
10630 
10631  te = ArchiveEntry(fout, dobj->catId, dobj->dumpId,
10632  ARCHIVE_OPTS(.tag = dobj->name,
10633  .description = "BLOBS",
10634  .section = SECTION_DATA,
10635  .dumpFn = dumpLOs));
10636 
10637  /*
10638  * Set the TocEntry's dataLength in case we are doing a
10639  * parallel dump and want to order dump jobs by table size.
10640  * (We need some size estimate for every TocEntry with a
10641  * DataDumper function.) We don't currently have any cheap
10642  * way to estimate the size of LOs, but it doesn't matter;
10643  * let's just set the size to a large value so parallel dumps
10644  * will launch this job first. If there's lots of LOs, we
10645  * win, and if there aren't, we don't lose much. (If you want
10646  * to improve on this, really what you should be thinking
10647  * about is allowing LO dumping to be parallelized, not just
10648  * getting a smarter estimate for the single TOC entry.)
10649  */
10650  te->dataLength = INT_MAX;
10651  }
10652  break;
10653  case DO_POLICY:
10654  dumpPolicy(fout, (const PolicyInfo *) dobj);
10655  break;
10656  case DO_PUBLICATION:
10657  dumpPublication(fout, (const PublicationInfo *) dobj);
10658  break;
10659  case DO_PUBLICATION_REL:
10660  dumpPublicationTable(fout, (const PublicationRelInfo *) dobj);
10661  break;
10664  (const PublicationSchemaInfo *) dobj);
10665  break;
10666  case DO_SUBSCRIPTION:
10667  dumpSubscription(fout, (const SubscriptionInfo *) dobj);
10668  break;
10669  case DO_SUBSCRIPTION_REL:
10670  dumpSubscriptionTable(fout, (const SubRelInfo *) dobj);
10671  break;
10672  case DO_PRE_DATA_BOUNDARY:
10673  case DO_POST_DATA_BOUNDARY:
10674  /* never dumped, nothing to do */
10675  break;
10676  }
10677 }
10678 
10679 /*
10680  * dumpNamespace
10681  * writes out to fout the queries to recreate a user-defined namespace
10682  */
10683 static void
10684 dumpNamespace(Archive *fout, const NamespaceInfo *nspinfo)
10685 {
10686  DumpOptions *dopt = fout->dopt;
10687  PQExpBuffer q;
10688  PQExpBuffer delq;
10689  char *qnspname;
10690 
10691  /* Do nothing in data-only dump */
10692  if (dopt->dataOnly)
10693  return;
10694 
10695  q = createPQExpBuffer();
10696  delq = createPQExpBuffer();
10697 
10698  qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
10699 
10700  if (nspinfo->create)
10701  {
10702  appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
10703  appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
10704  }
10705  else
10706  {
10707  /* see selectDumpableNamespace() */
10708  appendPQExpBufferStr(delq,
10709  "-- *not* dropping schema, since initdb creates it\n");
10711  "-- *not* creating schema, since initdb creates it\n");
10712  }
10713 
10714  if (dopt->binary_upgrade)
10716  "SCHEMA", qnspname, NULL);
10717 
10718  if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10719  ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
10720  ARCHIVE_OPTS(.tag = nspinfo->dobj.name,
10721  .owner = nspinfo->rolname,
10722  .description = "SCHEMA",
10723  .section = SECTION_PRE_DATA,
10724  .createStmt = q->data,
10725  .dropStmt = delq->data));
10726 
10727  /* Dump Schema Comments and Security Labels */
10728  if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10729  {
10730  const char *initdb_comment = NULL;
10731 
10732  if (!nspinfo->create && strcmp(qnspname, "public") == 0)
10733  initdb_comment = "standard public schema";
10734  dumpCommentExtended(fout, "SCHEMA", qnspname,
10735  NULL, nspinfo->rolname,
10736  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId,
10737  initdb_comment);
10738  }
10739 
10740  if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10741  dumpSecLabel(fout, "SCHEMA", qnspname,
10742  NULL, nspinfo->rolname,
10743  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
10744 
10745  if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
10746  dumpACL(fout, nspinfo->dobj.dumpId, InvalidDumpId, "SCHEMA",
10747  qnspname, NULL, NULL,
10748  nspinfo->rolname, &nspinfo->dacl);
10749 
10750  free(qnspname);
10751 
10752  destroyPQExpBuffer(q);
10753  destroyPQExpBuffer(delq);
10754 }
10755 
10756 /*
10757  * dumpExtension
10758  * writes out to fout the queries to recreate an extension
10759  */
10760 static void
10761 dumpExtension(Archive *fout, const ExtensionInfo *extinfo)
10762 {
10763  DumpOptions *dopt = fout->dopt;
10764  PQExpBuffer q;
10765  PQExpBuffer delq;
10766  char *qextname;
10767 
10768  /* Do nothing in data-only dump */
10769  if (dopt->dataOnly)
10770  return;
10771 
10772  q = createPQExpBuffer();
10773  delq = createPQExpBuffer();
10774 
10775  qextname = pg_strdup(fmtId(extinfo->dobj.name));
10776 
10777  appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
10778 
10779  if (!dopt->binary_upgrade)
10780  {
10781  /*
10782  * In a regular dump, we simply create the extension, intentionally
10783  * not specifying a version, so that the destination installation's
10784  * default version is used.
10785  *
10786  * Use of IF NOT EXISTS here is unlike our behavior for other object
10787  * types; but there are various scenarios in which it's convenient to
10788  * manually create the desired extension before restoring, so we
10789  * prefer to allow it to exist already.
10790  */
10791  appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
10792  qextname, fmtId(extinfo->namespace));
10793  }
10794  else
10795  {
10796  /*
10797  * In binary-upgrade mode, it's critical to reproduce the state of the
10798  * database exactly, so our procedure is to create an empty extension,
10799  * restore all the contained objects normally, and add them to the
10800  * extension one by one. This function performs just the first of
10801  * those steps. binary_upgrade_extension_member() takes care of
10802  * adding member objects as they're created.
10803  */
10804  int i;
10805  int n;
10806 
10807  appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
10808 
10809  /*
10810  * We unconditionally create the extension, so we must drop it if it
10811  * exists. This could happen if the user deleted 'plpgsql' and then
10812  * readded it, causing its oid to be greater than g_last_builtin_oid.
10813  */
10814  appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
10815 
10817  "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
10818  appendStringLiteralAH(q, extinfo->dobj.name, fout);
10819  appendPQExpBufferStr(q, ", ");
10820  appendStringLiteralAH(q, extinfo->namespace, fout);
10821  appendPQExpBufferStr(q, ", ");
10822  appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
10823  appendStringLiteralAH(q, extinfo->extversion, fout);
10824  appendPQExpBufferStr(q, ", ");
10825 
10826  /*
10827  * Note that we're pushing extconfig (an OID array) back into
10828  * pg_extension exactly as-is. This is OK because pg_class OIDs are
10829  * preserved in binary upgrade.
10830  */
10831  if (strlen(extinfo->extconfig) > 2)
10832  appendStringLiteralAH(q, extinfo->extconfig, fout);
10833  else
10834  appendPQExpBufferStr(q, "NULL");
10835  appendPQExpBufferStr(q, ", ");
10836  if (strlen(extinfo->extcondition) > 2)
10837  appendStringLiteralAH(q, extinfo->extcondition, fout);
10838  else
10839  appendPQExpBufferStr(q, "NULL");
10840  appendPQExpBufferStr(q, ", ");
10841  appendPQExpBufferStr(q, "ARRAY[");
10842  n = 0;
10843  for (i = 0; i < extinfo->dobj.nDeps; i++)
10844  {
10845  DumpableObject *extobj;
10846 
10847  extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10848  if (extobj && extobj->objType == DO_EXTENSION)
10849  {
10850  if (n++ > 0)
10851  appendPQExpBufferChar(q, ',');
10852  appendStringLiteralAH(q, extobj->name, fout);
10853  }
10854  }
10855  appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10856  appendPQExpBufferStr(q, ");\n");
10857  }
10858 
10859  if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10860  ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10861  ARCHIVE_OPTS(.tag = extinfo->dobj.name,
10862  .description = "EXTENSION",
10863  .section = SECTION_PRE_DATA,
10864  .createStmt = q->data,
10865  .dropStmt = delq->data));
10866 
10867  /* Dump Extension Comments and Security Labels */
10868  if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10869  dumpComment(fout, "EXTENSION", qextname,
10870  NULL, "",
10871  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10872 
10873  if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10874  dumpSecLabel(fout, "EXTENSION", qextname,
10875  NULL, "",
10876  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10877 
10878  free(qextname);
10879 
10880  destroyPQExpBuffer(q);
10881  destroyPQExpBuffer(delq);
10882 }
10883 
10884 /*
10885  * dumpType
10886  * writes out to fout the queries to recreate a user-defined type
10887  */
10888 static void
10889 dumpType(Archive *fout, const TypeInfo *tyinfo)
10890 {
10891  DumpOptions *dopt = fout->dopt;
10892 
10893  /* Do nothing in data-only dump */
10894  if (dopt->dataOnly)
10895  return;
10896 
10897  /* Dump out in proper style */
10898  if (tyinfo->typtype == TYPTYPE_BASE)
10899  dumpBaseType(fout, tyinfo);
10900  else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10901  dumpDomain(fout, tyinfo);
10902  else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10903  dumpCompositeType(fout, tyinfo);
10904  else if (tyinfo->typtype == TYPTYPE_ENUM)
10905  dumpEnumType(fout, tyinfo);
10906  else if (tyinfo->typtype == TYPTYPE_RANGE)
10907  dumpRangeType(fout, tyinfo);
10908  else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10909  dumpUndefinedType(fout, tyinfo);
10910  else
10911  pg_log_warning("typtype of data type \"%s\" appears to be invalid",
10912  tyinfo->dobj.name);
10913 }
10914 
10915 /*
10916  * dumpEnumType
10917  * writes out to fout the queries to recreate a user-defined enum type
10918  */
10919 static void
10920 dumpEnumType(Archive *fout, const TypeInfo *tyinfo)
10921 {
10922  DumpOptions *dopt = fout->dopt;
10924  PQExpBuffer delq = createPQExpBuffer();
10925  PQExpBuffer query = createPQExpBuffer();
10926  PGresult *res;
10927  int num,
10928  i;
10929  Oid enum_oid;
10930  char *qtypname;
10931  char *qualtypname;
10932  char *label;
10933  int i_enumlabel;
10934  int i_oid;
10935 
10936  if (!fout->is_prepared[PREPQUERY_DUMPENUMTYPE])
10937  {
10938  /* Set up query for enum-specific details */
10939  appendPQExpBufferStr(query,
10940  "PREPARE dumpEnumType(pg_catalog.oid) AS\n"
10941  "SELECT oid, enumlabel "
10942  "FROM pg_catalog.pg_enum "
10943  "WHERE enumtypid = $1 "
10944  "ORDER BY enumsortorder");
10945 
10946  ExecuteSqlStatement(fout, query->data);
10947 
10948  fout->is_prepared[PREPQUERY_DUMPENUMTYPE] = true;
10949  }
10950 
10951  printfPQExpBuffer(query,
10952  "EXECUTE dumpEnumType('%u')",
10953  tyinfo->dobj.catId.oid);
10954 
10955  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10956 
10957  num = PQntuples(res);
10958 
10959  qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10960  qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10961 
10962  /*
10963  * CASCADE shouldn't be required here as for normal types since the I/O
10964  * functions are generic and do not get dropped.
10965  */
10966  appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10967 
10968  if (dopt->binary_upgrade)
10970  tyinfo->dobj.catId.oid,
10971  false, false);
10972 
10973  appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10974  qualtypname);
10975 
10976  if (!dopt->binary_upgrade)
10977  {
10978  i_enumlabel = PQfnumber(res, "enumlabel");
10979 
10980  /* Labels with server-assigned oids */
10981  for (i = 0; i < num; i++)
10982  {
10983  label = PQgetvalue(res, i, i_enumlabel);
10984  if (i > 0)
10985  appendPQExpBufferChar(q, ',');
10986  appendPQExpBufferStr(q, "\n ");
10987  appendStringLiteralAH(q, label, fout);
10988  }
10989  }
10990 
10991  appendPQExpBufferStr(q, "\n);\n");
10992 
10993  if (dopt->binary_upgrade)
10994  {
10995  i_oid = PQfnumber(res, "oid");
10996  i_enumlabel = PQfnumber(res, "enumlabel");
10997 
10998  /* Labels with dump-assigned (preserved) oids */
10999  for (i = 0; i < num; i++)
11000  {
11001  enum_oid = atooid(PQgetvalue(res, i, i_oid));
11002  label = PQgetvalue(res, i, i_enumlabel);
11003 
11004  if (i == 0)
11005  appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
11007  "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
11008  enum_oid);
11009  appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
11010  appendStringLiteralAH(q, label, fout);
11011  appendPQExpBufferStr(q, ";\n\n");
11012  }
11013  }
11014 
11015  if (dopt->binary_upgrade)
11017  "TYPE", qtypname,
11018  tyinfo->dobj.namespace->dobj.name);
11019 
11020  if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11021  ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11022  ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11023  .namespace = tyinfo->dobj.namespace->dobj.name,
11024  .owner = tyinfo->rolname,
11025  .description = "TYPE",
11026  .section = SECTION_PRE_DATA,
11027  .createStmt = q->data,
11028  .dropStmt = delq->data));
11029 
11030  /* Dump Type Comments and Security Labels */
11031  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11032  dumpComment(fout, "TYPE", qtypname,
11033  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11034  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11035 
11036  if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11037  dumpSecLabel(fout, "TYPE", qtypname,
11038  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11039  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11040 
11041  if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11042  dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11043  qtypname, NULL,
11044  tyinfo->dobj.namespace->dobj.name,
11045  tyinfo->rolname, &tyinfo->dacl);
11046 
11047  PQclear(res);
11048  destroyPQExpBuffer(q);
11049  destroyPQExpBuffer(delq);
11050  destroyPQExpBuffer(query);
11051  free(qtypname);
11052  free(qualtypname);
11053 }
11054 
11055 /*
11056  * dumpRangeType
11057  * writes out to fout the queries to recreate a user-defined range type
11058  */
11059 static void
11060 dumpRangeType(Archive *fout, const TypeInfo *tyinfo)
11061 {
11062  DumpOptions *dopt = fout->dopt;
11064  PQExpBuffer delq = createPQExpBuffer();
11065  PQExpBuffer query = createPQExpBuffer();
11066  PGresult *res;
11067  Oid collationOid;
11068  char *qtypname;
11069  char *qualtypname;
11070  char *procname;
11071 
11073  {
11074  /* Set up query for range-specific details */
11075  appendPQExpBufferStr(query,
11076  "PREPARE dumpRangeType(pg_catalog.oid) AS\n");
11077 
11078  appendPQExpBufferStr(query,
11079  "SELECT ");
11080 
11081  if (fout->remoteVersion >= 140000)
11082  appendPQExpBufferStr(query,
11083  "pg_catalog.format_type(rngmultitypid, NULL) AS rngmultitype, ");
11084  else
11085  appendPQExpBufferStr(query,
11086  "NULL AS rngmultitype, ");
11087 
11088  appendPQExpBufferStr(query,
11089  "pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
11090  "opc.opcname AS opcname, "
11091  "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
11092  " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
11093  "opc.opcdefault, "
11094  "CASE WHEN rngcollation = st.typcollation THEN 0 "
11095  " ELSE rngcollation END AS collation, "
11096  "rngcanonical, rngsubdiff "
11097  "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
11098  " pg_catalog.pg_opclass opc "
11099  "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
11100  "rngtypid = $1");
11101 
11102  ExecuteSqlStatement(fout, query->data);
11103 
11104  fout->is_prepared[PREPQUERY_DUMPRANGETYPE] = true;
11105  }
11106 
11107  printfPQExpBuffer(query,
11108  "EXECUTE dumpRangeType('%u')",
11109  tyinfo->dobj.catId.oid);
11110 
11111  res = ExecuteSqlQueryForSingleRow(fout, query->data);
11112 
11113  qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11114  qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11115 
11116  /*
11117  * CASCADE shouldn't be required here as for normal types since the I/O
11118  * functions are generic and do not get dropped.
11119  */
11120  appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11121 
11122  if (dopt->binary_upgrade)
11124  tyinfo->dobj.catId.oid,
11125  false, true);
11126 
11127  appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
11128  qualtypname);
11129 
11130  appendPQExpBuffer(q, "\n subtype = %s",
11131  PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
11132 
11133  if (!PQgetisnull(res, 0, PQfnumber(res, "rngmultitype")))
11134  appendPQExpBuffer(q, ",\n multirange_type_name = %s",
11135  PQgetvalue(res, 0, PQfnumber(res, "rngmultitype")));
11136 
11137  /* print subtype_opclass only if not default for subtype */
11138  if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
11139  {
11140  char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
11141  char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
11142 
11143  appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
11144  fmtId(nspname));
11145  appendPQExpBufferStr(q, fmtId(opcname));
11146  }
11147 
11148  collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
11149  if (OidIsValid(collationOid))
11150  {
11151  CollInfo *coll = findCollationByOid(collationOid);
11152 
11153  if (coll)
11154  appendPQExpBuffer(q, ",\n collation = %s",
11155  fmtQualifiedDumpable(coll));
11156  }
11157 
11158  procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
11159  if (strcmp(procname, "-") != 0)
11160  appendPQExpBuffer(q, ",\n canonical = %s", procname);
11161 
11162  procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
11163  if (strcmp(procname, "-") != 0)
11164  appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
11165 
11166  appendPQExpBufferStr(q, "\n);\n");
11167 
11168  if (dopt->binary_upgrade)
11170  "TYPE", qtypname,
11171  tyinfo->dobj.namespace->dobj.name);
11172 
11173  if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11174  ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11175  ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11176  .namespace = tyinfo->dobj.namespace->dobj.name,
11177  .owner = tyinfo->rolname,
11178  .description = "TYPE",
11179  .section = SECTION_PRE_DATA,
11180  .createStmt = q->data,
11181  .dropStmt = delq->data));
11182 
11183  /* Dump Type Comments and Security Labels */
11184  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11185  dumpComment(fout, "TYPE", qtypname,
11186  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11187  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11188 
11189  if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11190  dumpSecLabel(fout, "TYPE", qtypname,
11191  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11192  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11193 
11194  if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11195  dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11196  qtypname, NULL,
11197  tyinfo->dobj.namespace->dobj.name,
11198  tyinfo->rolname, &tyinfo->dacl);
11199 
11200  PQclear(res);
11201  destroyPQExpBuffer(q);
11202  destroyPQExpBuffer(delq);
11203  destroyPQExpBuffer(query);
11204  free(qtypname);
11205  free(qualtypname);
11206 }
11207 
11208 /*
11209  * dumpUndefinedType
11210  * writes out to fout the queries to recreate a !typisdefined type
11211  *
11212  * This is a shell type, but we use different terminology to distinguish
11213  * this case from where we have to emit a shell type definition to break
11214  * circular dependencies. An undefined type shouldn't ever have anything
11215  * depending on it.
11216  */
11217 static void
11218 dumpUndefinedType(Archive *fout, const TypeInfo *tyinfo)
11219 {
11220  DumpOptions *dopt = fout->dopt;
11222  PQExpBuffer delq = createPQExpBuffer();
11223  char *qtypname;
11224  char *qualtypname;
11225 
11226  qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11227  qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11228 
11229  appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11230 
11231  if (dopt->binary_upgrade)
11233  tyinfo->dobj.catId.oid,
11234  false, false);
11235 
11236  appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11237  qualtypname);
11238 
11239  if (dopt->binary_upgrade)
11241  "TYPE", qtypname,
11242  tyinfo->dobj.namespace->dobj.name);
11243 
11244  if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11245  ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11246  ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11247  .namespace = tyinfo->dobj.namespace->dobj.name,
11248  .owner = tyinfo->rolname,
11249  .description = "TYPE",
11250  .section = SECTION_PRE_DATA,
11251  .createStmt = q->data,
11252  .dropStmt = delq->data));
11253 
11254  /* Dump Type Comments and Security Labels */
11255  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11256  dumpComment(fout, "TYPE", qtypname,
11257  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11258  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11259 
11260  if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11261  dumpSecLabel(fout, "TYPE", qtypname,
11262  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11263  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11264 
11265  if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11266  dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11267  qtypname, NULL,
11268  tyinfo->dobj.namespace->dobj.name,
11269  tyinfo->rolname, &tyinfo->dacl);
11270 
11271  destroyPQExpBuffer(q);
11272  destroyPQExpBuffer(delq);
11273  free(qtypname);
11274  free(qualtypname);
11275 }
11276 
11277 /*
11278  * dumpBaseType
11279  * writes out to fout the queries to recreate a user-defined base type
11280  */
11281 static void
11282 dumpBaseType(Archive *fout, const TypeInfo *tyinfo)
11283 {
11284  DumpOptions *dopt = fout->dopt;
11286  PQExpBuffer delq = createPQExpBuffer();
11287  PQExpBuffer query = createPQExpBuffer();
11288  PGresult *res;
11289  char *qtypname;
11290  char *qualtypname;
11291  char *typlen;
11292  char *typinput;
11293  char *typoutput;
11294  char *typreceive;
11295  char *typsend;
11296  char *typmodin;
11297  char *typmodout;
11298  char *typanalyze;
11299  char *typsubscript;
11300  Oid typreceiveoid;
11301  Oid typsendoid;
11302  Oid typmodinoid;
11303  Oid typmodoutoid;
11304  Oid typanalyzeoid;
11305  Oid typsubscriptoid;
11306  char *typcategory;
11307  char *typispreferred;
11308  char *typdelim;
11309  char *typbyval;
11310  char *typalign;
11311  char *typstorage;
11312  char *typcollatable;
11313  char *typdefault;
11314  bool typdefault_is_literal = false;
11315 
11316  if (!fout->is_prepared[PREPQUERY_DUMPBASETYPE])
11317  {
11318  /* Set up query for type-specific details */
11319  appendPQExpBufferStr(query,
11320  "PREPARE dumpBaseType(pg_catalog.oid) AS\n"
11321  "SELECT typlen, "
11322  "typinput, typoutput, typreceive, typsend, "
11323  "typreceive::pg_catalog.oid AS typreceiveoid, "
11324  "typsend::pg_catalog.oid AS typsendoid, "
11325  "typanalyze, "
11326  "typanalyze::pg_catalog.oid AS typanalyzeoid, "
11327  "typdelim, typbyval, typalign, typstorage, "
11328  "typmodin, typmodout, "
11329  "typmodin::pg_catalog.oid AS typmodinoid, "
11330  "typmodout::pg_catalog.oid AS typmodoutoid, "
11331  "typcategory, typispreferred, "
11332  "(typcollation <> 0) AS typcollatable, "
11333  "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault, ");
11334 
11335  if (fout->remoteVersion >= 140000)
11336  appendPQExpBufferStr(query,
11337  "typsubscript, "
11338  "typsubscript::pg_catalog.oid AS typsubscriptoid ");
11339  else
11340  appendPQExpBufferStr(query,
11341  "'-' AS typsubscript, 0 AS typsubscriptoid ");
11342 
11343  appendPQExpBufferStr(query, "FROM pg_catalog.pg_type "
11344  "WHERE oid = $1");
11345 
11346  ExecuteSqlStatement(fout, query->data);
11347 
11348  fout->is_prepared[PREPQUERY_DUMPBASETYPE] = true;
11349  }
11350 
11351  printfPQExpBuffer(query,
11352  "EXECUTE dumpBaseType('%u')",
11353  tyinfo->dobj.catId.oid);
11354 
11355  res = ExecuteSqlQueryForSingleRow(fout, query->data);
11356 
11357  typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
11358  typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
11359  typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
11360  typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
11361  typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
11362  typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
11363  typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
11364  typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
11365  typsubscript = PQgetvalue(res, 0, PQfnumber(res, "typsubscript"));
11366  typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
11367  typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
11368  typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
11369  typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
11370  typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
11371  typsubscriptoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsubscriptoid")));
11372  typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
11373  typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
11374  typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
11375  typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
11376  typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
11377  typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
11378  typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
11379  if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
11380  typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
11381  else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
11382  {
11383  typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
11384  typdefault_is_literal = true; /* it needs quotes */
11385  }
11386  else
11387  typdefault = NULL;
11388 
11389  qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11390  qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11391 
11392  /*
11393  * The reason we include CASCADE is that the circular dependency between
11394  * the type and its I/O functions makes it impossible to drop the type any
11395  * other way.
11396  */
11397  appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
11398 
11399  /*
11400  * We might already have a shell type, but setting pg_type_oid is
11401  * harmless, and in any case we'd better set the array type OID.
11402  */
11403  if (dopt->binary_upgrade)
11405  tyinfo->dobj.catId.oid,
11406  false, false);
11407 
11409  "CREATE TYPE %s (\n"
11410  " INTERNALLENGTH = %s",
11411  qualtypname,
11412  (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
11413 
11414  /* regproc result is sufficiently quoted already */
11415  appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
11416  appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
11417  if (OidIsValid(typreceiveoid))
11418  appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
11419  if (OidIsValid(typsendoid))
11420  appendPQExpBuffer(q, ",\n SEND = %s", typsend);
11421  if (OidIsValid(typmodinoid))
11422  appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
11423  if (OidIsValid(typmodoutoid))
11424  appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
11425  if (OidIsValid(typanalyzeoid))
11426  appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
11427 
11428  if (strcmp(typcollatable, "t") == 0)
11429  appendPQExpBufferStr(q, ",\n COLLATABLE = true");
11430 
11431  if (typdefault != NULL)
11432  {
11433  appendPQExpBufferStr(q, ",\n DEFAULT = ");
11434  if (typdefault_is_literal)
11435  appendStringLiteralAH(q, typdefault, fout);
11436  else
11437  appendPQExpBufferStr(q, typdefault);
11438  }
11439 
11440  if (OidIsValid(typsubscriptoid))
11441  appendPQExpBuffer(q, ",\n SUBSCRIPT = %s", typsubscript);
11442 
11443  if (OidIsValid(tyinfo->typelem))
11444  appendPQExpBuffer(q, ",\n ELEMENT = %s",
11445  getFormattedTypeName(fout, tyinfo->typelem,
11446  zeroIsError));
11447 
11448  if (strcmp(typcategory, "U") != 0)
11449  {
11450  appendPQExpBufferStr(q, ",\n CATEGORY = ");
11451  appendStringLiteralAH(q, typcategory, fout);
11452  }
11453 
11454  if (strcmp(typispreferred, "t") == 0)
11455  appendPQExpBufferStr(q, ",\n PREFERRED = true");
11456 
11457  if (typdelim && strcmp(typdelim, ",") != 0)
11458  {
11459  appendPQExpBufferStr(q, ",\n DELIMITER = ");
11460  appendStringLiteralAH(q, typdelim, fout);
11461  }
11462 
11463  if (*typalign == TYPALIGN_CHAR)
11464  appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
11465  else if (*typalign == TYPALIGN_SHORT)
11466  appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
11467  else if (*typalign == TYPALIGN_INT)
11468  appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
11469  else if (*typalign == TYPALIGN_DOUBLE)
11470  appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
11471 
11472  if (*typstorage == TYPSTORAGE_PLAIN)
11473  appendPQExpBufferStr(q, ",\n STORAGE = plain");
11474  else if (*typstorage == TYPSTORAGE_EXTERNAL)
11475  appendPQExpBufferStr(q, ",\n STORAGE = external");
11476  else if (*typstorage == TYPSTORAGE_EXTENDED)
11477  appendPQExpBufferStr(q, ",\n STORAGE = extended");
11478  else if (*typstorage == TYPSTORAGE_MAIN)
11479  appendPQExpBufferStr(q, ",\n STORAGE = main");
11480 
11481  if (strcmp(typbyval, "t") == 0)
11482  appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
11483 
11484  appendPQExpBufferStr(q, "\n);\n");
11485 
11486  if (dopt->binary_upgrade)
11488  "TYPE", qtypname,
11489  tyinfo->dobj.namespace->dobj.name);
11490 
11491  if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11492  ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11493  ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11494  .namespace = tyinfo->dobj.namespace->dobj.name,
11495  .owner = tyinfo->rolname,
11496  .description = "TYPE",
11497  .section = SECTION_PRE_DATA,
11498  .createStmt = q->data,
11499  .dropStmt = delq->data));
11500 
11501  /* Dump Type Comments and Security Labels */
11502  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11503  dumpComment(fout, "TYPE", qtypname,
11504  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11505  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11506 
11507  if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11508  dumpSecLabel(fout, "TYPE", qtypname,
11509  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11510  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11511 
11512  if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11513  dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11514  qtypname, NULL,
11515  tyinfo->dobj.namespace->dobj.name,
11516  tyinfo->rolname, &tyinfo->dacl);
11517 
11518  PQclear(res);
11519  destroyPQExpBuffer(q);
11520  destroyPQExpBuffer(delq);
11521  destroyPQExpBuffer(query);
11522  free(qtypname);
11523  free(qualtypname);
11524 }
11525 
11526 /*
11527  * dumpDomain
11528  * writes out to fout the queries to recreate a user-defined domain
11529  */
11530 static void
11531 dumpDomain(Archive *fout, const TypeInfo *tyinfo)
11532 {
11533  DumpOptions *dopt = fout->dopt;
11535  PQExpBuffer delq = createPQExpBuffer();
11536  PQExpBuffer query = createPQExpBuffer();
11537  PGresult *res;
11538  int i;
11539  char *qtypname;
11540  char *qualtypname;
11541  char *typnotnull;
11542  char *typdefn;
11543  char *typdefault;
11544  Oid typcollation;
11545  bool typdefault_is_literal = false;
11546 
11547  if (!fout->is_prepared[PREPQUERY_DUMPDOMAIN])
11548  {
11549  /* Set up query for domain-specific details */
11550  appendPQExpBufferStr(query,
11551  "PREPARE dumpDomain(pg_catalog.oid) AS\n");
11552 
11553  appendPQExpBufferStr(query, "SELECT t.typnotnull, "
11554  "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
11555  "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
11556  "t.typdefault, "
11557  "CASE WHEN t.typcollation <> u.typcollation "
11558  "THEN t.typcollation ELSE 0 END AS typcollation "
11559  "FROM pg_catalog.pg_type t "
11560  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
11561  "WHERE t.oid = $1");
11562 
11563  ExecuteSqlStatement(fout, query->data);
11564 
11565  fout->is_prepared[PREPQUERY_DUMPDOMAIN] = true;
11566  }
11567 
11568  printfPQExpBuffer(query,
11569  "EXECUTE dumpDomain('%u')",
11570  tyinfo->dobj.catId.oid);
11571 
11572  res = ExecuteSqlQueryForSingleRow(fout, query->data);
11573 
11574  typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
11575  typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
11576  if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
11577  typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
11578  else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
11579  {
11580  typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
11581  typdefault_is_literal = true; /* it needs quotes */
11582  }
11583  else
11584  typdefault = NULL;
11585  typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
11586 
11587  if (dopt->binary_upgrade)
11589  tyinfo->dobj.catId.oid,
11590  true, /* force array type */
11591  false); /* force multirange type */
11592 
11593  qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11594  qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11595 
11597  "CREATE DOMAIN %s AS %s",
11598  qualtypname,
11599  typdefn);
11600 
11601  /* Print collation only if different from base type's collation */
11602  if (OidIsValid(typcollation))
11603  {
11604  CollInfo *coll;
11605 
11606  coll = findCollationByOid(typcollation);
11607  if (coll)
11608  appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
11609  }
11610 
11611  if (typnotnull[0] == 't')
11612  appendPQExpBufferStr(q, " NOT NULL");
11613 
11614  if (typdefault != NULL)
11615  {
11616  appendPQExpBufferStr(q, " DEFAULT ");
11617  if (typdefault_is_literal)
11618  appendStringLiteralAH(q, typdefault, fout);
11619  else
11620  appendPQExpBufferStr(q, typdefault);
11621  }
11622 
11623  PQclear(res);
11624 
11625  /*
11626  * Add any CHECK constraints for the domain
11627  */
11628  for (i = 0; i < tyinfo->nDomChecks; i++)
11629  {
11630  ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
11631 
11632  if (!domcheck->separate)
11633  appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
11634  fmtId(domcheck->dobj.name), domcheck->condef);
11635  }
11636 
11637  appendPQExpBufferStr(q, ";\n");
11638 
11639  appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
11640 
11641  if (dopt->binary_upgrade)
11643  "DOMAIN", qtypname,
11644  tyinfo->dobj.namespace->dobj.name);
11645 
11646  if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11647  ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11648  ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11649  .namespace = tyinfo->dobj.namespace->dobj.name,
11650  .owner = tyinfo->rolname,
11651  .description = "DOMAIN",
11652  .section = SECTION_PRE_DATA,
11653  .createStmt = q->data,
11654  .dropStmt = delq->data));
11655 
11656  /* Dump Domain Comments and Security Labels */
11657  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11658  dumpComment(fout, "DOMAIN", qtypname,
11659  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11660  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11661 
11662  if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11663  dumpSecLabel(fout, "DOMAIN", qtypname,
11664  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11665  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11666 
11667  if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11668  dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11669  qtypname, NULL,
11670  tyinfo->dobj.namespace->dobj.name,
11671  tyinfo->rolname, &tyinfo->dacl);
11672 
11673  /* Dump any per-constraint comments */
11674  for (i = 0; i < tyinfo->nDomChecks; i++)
11675  {
11676  ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
11677  PQExpBuffer conprefix = createPQExpBuffer();
11678 
11679  appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
11680  fmtId(domcheck->dobj.name));
11681 
11682  if (domcheck->dobj.dump & DUMP_COMPONENT_COMMENT)
11683  dumpComment(fout, conprefix->data, qtypname,
11684  tyinfo->dobj.namespace->dobj.name,
11685  tyinfo->rolname,
11686  domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
11687 
11688  destroyPQExpBuffer(conprefix);
11689  }
11690 
11691  destroyPQExpBuffer(q);
11692  destroyPQExpBuffer(delq);
11693  destroyPQExpBuffer(query);
11694  free(qtypname);
11695  free(qualtypname);
11696 }
11697 
11698 /*
11699  * dumpCompositeType
11700  * writes out to fout the queries to recreate a user-defined stand-alone
11701  * composite type
11702  */
11703 static void
11704 dumpCompositeType(Archive *fout, const TypeInfo *tyinfo)
11705 {
11706  DumpOptions *dopt = fout->dopt;
11708  PQExpBuffer dropped = createPQExpBuffer();
11709  PQExpBuffer delq = createPQExpBuffer();
11710  PQExpBuffer query = createPQExpBuffer();
11711  PGresult *res;
11712  char *qtypname;
11713  char *qualtypname;
11714  int ntups;
11715  int i_attname;
11716  int i_atttypdefn;
11717  int i_attlen;
11718  int i_attalign;
11719  int i_attisdropped;
11720  int i_attcollation;
11721  int i;
11722  int actual_atts;
11723 
11725  {
11726  /*
11727  * Set up query for type-specific details.
11728  *
11729  * Since we only want to dump COLLATE clauses for attributes whose
11730  * collation is different from their type's default, we use a CASE
11731  * here to suppress uninteresting attcollations cheaply. atttypid
11732  * will be 0 for dropped columns; collation does not matter for those.
11733  */
11734  appendPQExpBufferStr(query,
11735  "PREPARE dumpCompositeType(pg_catalog.oid) AS\n"
11736  "SELECT a.attname, a.attnum, "
11737  "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
11738  "a.attlen, a.attalign, a.attisdropped, "
11739  "CASE WHEN a.attcollation <> at.typcollation "
11740  "THEN a.attcollation ELSE 0 END AS attcollation "
11741  "FROM pg_catalog.pg_type ct "
11742  "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
11743  "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
11744  "WHERE ct.oid = $1 "
11745  "ORDER BY a.attnum");
11746 
11747  ExecuteSqlStatement(fout, query->data);
11748 
11750  }
11751 
11752  printfPQExpBuffer(query,
11753  "EXECUTE dumpCompositeType('%u')",
11754  tyinfo->dobj.catId.oid);
11755 
11756  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11757 
11758  ntups = PQntuples(res);
11759 
11760  i_attname = PQfnumber(res, "attname");
11761  i_atttypdefn = PQfnumber(res, "atttypdefn");
11762  i_attlen = PQfnumber(res, "attlen");
11763  i_attalign = PQfnumber(res, "attalign");
11764  i_attisdropped = PQfnumber(res, "attisdropped");
11765  i_attcollation = PQfnumber(res, "attcollation");
11766 
11767  if (dopt->binary_upgrade)
11768  {
11770  tyinfo->dobj.catId.oid,
11771  false, false);
11772  binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
11773  }
11774 
11775  qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11776  qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11777 
11778  appendPQExpBuffer(q, "CREATE TYPE %s AS (",
11779  qualtypname);
11780 
11781  actual_atts = 0;
11782  for (i = 0; i < ntups; i++)
11783  {
11784  char *attname;
11785  char *atttypdefn;
11786  char *attlen;
11787  char *attalign;
11788  bool attisdropped;
11789  Oid attcollation;
11790 
11791  attname = PQgetvalue(res, i, i_attname);
11792  atttypdefn = PQgetvalue(res, i, i_atttypdefn);
11793  attlen = PQgetvalue(res, i, i_attlen);
11794  attalign = PQgetvalue(res, i, i_attalign);
11795  attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
11796  attcollation = atooid(PQgetvalue(res, i, i_attcollation));
11797 
11798  if (attisdropped && !dopt->binary_upgrade)
11799  continue;
11800 
11801  /* Format properly if not first attr */
11802  if (actual_atts++ > 0)
11803  appendPQExpBufferChar(q, ',');
11804  appendPQExpBufferStr(q, "\n\t");
11805 
11806  if (!attisdropped)
11807  {
11808  appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
11809 
11810  /* Add collation if not default for the column type */
11811  if (OidIsValid(attcollation))
11812  {
11813  CollInfo *coll;
11814 
11815  coll = findCollationByOid(attcollation);
11816  if (coll)
11817  appendPQExpBuffer(q, " COLLATE %s",
11818  fmtQualifiedDumpable(coll));
11819  }
11820  }
11821  else
11822  {
11823  /*
11824  * This is a dropped attribute and we're in binary_upgrade mode.
11825  * Insert a placeholder for it in the CREATE TYPE command, and set
11826  * length and alignment with direct UPDATE to the catalogs
11827  * afterwards. See similar code in dumpTableSchema().
11828  */
11829  appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11830 
11831  /* stash separately for insertion after the CREATE TYPE */
11832  appendPQExpBufferStr(dropped,
11833  "\n-- For binary upgrade, recreate dropped column.\n");
11834  appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11835  "SET attlen = %s, "
11836  "attalign = '%s', attbyval = false\n"
11837  "WHERE attname = ", attlen, attalign);
11838  appendStringLiteralAH(dropped, attname, fout);
11839  appendPQExpBufferStr(dropped, "\n AND attrelid = ");
11840  appendStringLiteralAH(dropped, qualtypname, fout);
11841  appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11842 
11843  appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11844  qualtypname);
11845  appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11846  fmtId(attname));
11847  }
11848  }
11849  appendPQExpBufferStr(q, "\n);\n");
11850  appendPQExpBufferStr(q, dropped->data);
11851 
11852  appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11853 
11854  if (dopt->binary_upgrade)
11856  "TYPE", qtypname,
11857  tyinfo->dobj.namespace->dobj.name);
11858 
11859  if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11860  ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11861  ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11862  .namespace = tyinfo->dobj.namespace->dobj.name,
11863  .owner = tyinfo->rolname,
11864  .description = "TYPE",
11865  .section = SECTION_PRE_DATA,
11866  .createStmt = q->data,
11867  .dropStmt = delq->data));
11868 
11869 
11870  /* Dump Type Comments and Security Labels */
11871  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11872  dumpComment(fout, "TYPE", qtypname,
11873  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11874  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11875 
11876  if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11877  dumpSecLabel(fout, "TYPE", qtypname,
11878  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11879  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11880 
11881  if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11882  dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11883  qtypname, NULL,
11884  tyinfo->dobj.namespace->dobj.name,
11885  tyinfo->rolname, &tyinfo->dacl);
11886 
11887  /* Dump any per-column comments */
11888  if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11889  dumpCompositeTypeColComments(fout, tyinfo, res);
11890 
11891  PQclear(res);
11892  destroyPQExpBuffer(q);
11893  destroyPQExpBuffer(dropped);
11894  destroyPQExpBuffer(delq);
11895  destroyPQExpBuffer(query);
11896  free(qtypname);
11897  free(qualtypname);
11898 }
11899 
11900 /*
11901  * dumpCompositeTypeColComments
11902  * writes out to fout the queries to recreate comments on the columns of
11903  * a user-defined stand-alone composite type.
11904  *
11905  * The caller has already made a query to collect the names and attnums
11906  * of the type's columns, so we just pass that result into here rather
11907  * than reading them again.
11908  */
11909 static void
11911  PGresult *res)
11912 {
11914  int ncomments;
11915  PQExpBuffer query;
11916  PQExpBuffer target;
11917  int i;
11918  int ntups;
11919  int i_attname;
11920  int i_attnum;
11921  int i_attisdropped;
11922 
11923  /* do nothing, if --no-comments is supplied */
11924  if (fout->dopt->no_comments)
11925  return;
11926 
11927  /* Search for comments associated with type's pg_class OID */
11928  ncomments = findComments(RelationRelationId, tyinfo->typrelid,
11929  &comments);
11930 
11931  /* If no comments exist, we're done */
11932  if (ncomments <= 0)
11933  return;
11934 
11935  /* Build COMMENT ON statements */
11936  query = createPQExpBuffer();
11937  target = createPQExpBuffer();
11938 
11939  ntups = PQntuples(res);
11940  i_attnum = PQfnumber(res, "attnum");
11941  i_attname = PQfnumber(res, "attname");
11942  i_attisdropped = PQfnumber(res, "attisdropped");
11943  while (ncomments > 0)
11944  {
11945  const char *attname;
11946 
11947  attname = NULL;
11948  for (i = 0; i < ntups; i++)
11949  {
11950  if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
11951  PQgetvalue(res, i, i_attisdropped)[0] != 't')
11952  {
11953  attname = PQgetvalue(res, i, i_attname);
11954  break;
11955  }
11956  }
11957  if (attname) /* just in case we don't find it */
11958  {
11959  const char *descr = comments->descr;
11960 
11961  resetPQExpBuffer(target);
11962  appendPQExpBuffer(target, "COLUMN %s.",
11963  fmtId(tyinfo->dobj.name));
11965 
11966  resetPQExpBuffer(query);
11967  appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11968  fmtQualifiedDumpable(tyinfo));
11969  appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11970  appendStringLiteralAH(query, descr, fout);
11971  appendPQExpBufferStr(query, ";\n");
11972 
11974  ARCHIVE_OPTS(.tag = target->data,
11975  .namespace = tyinfo->dobj.namespace->dobj.name,
11976  .owner = tyinfo->rolname,
11977  .description = "COMMENT",
11978  .section = SECTION_NONE,
11979  .createStmt = query->data,
11980  .deps = &(tyinfo->dobj.dumpId),
11981  .nDeps = 1));
11982  }
11983 
11984  comments++;
11985  ncomments--;
11986  }
11987 
11988  destroyPQExpBuffer(query);
11989  destroyPQExpBuffer(target);
11990 }
11991 
11992 /*
11993  * dumpShellType
11994  * writes out to fout the queries to create a shell type
11995  *
11996  * We dump a shell definition in advance of the I/O functions for the type.
11997  */
11998 static void
11999 dumpShellType(Archive *fout, const ShellTypeInfo *stinfo)
12000 {
12001  DumpOptions *dopt = fout->dopt;
12002  PQExpBuffer q;
12003 
12004  /* Do nothing in data-only dump */
12005  if (dopt->dataOnly)
12006  return;
12007 
12008  q = createPQExpBuffer();
12009 
12010  /*
12011  * Note the lack of a DROP command for the shell type; any required DROP
12012  * is driven off the base type entry, instead. This interacts with
12013  * _printTocEntry()'s use of the presence of a DROP command to decide
12014  * whether an entry needs an ALTER OWNER command. We don't want to alter
12015  * the shell type's owner immediately on creation; that should happen only
12016  * after it's filled in, otherwise the backend complains.
12017  */
12018 
12019  if (dopt->binary_upgrade)
12021  stinfo->baseType->dobj.catId.oid,
12022  false, false);
12023 
12024  appendPQExpBuffer(q, "CREATE TYPE %s;\n",
12025  fmtQualifiedDumpable(stinfo));
12026 
12027  if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12028  ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
12029  ARCHIVE_OPTS(.tag = stinfo->dobj.name,
12030  .namespace = stinfo->dobj.namespace->dobj.name,
12031  .owner = stinfo->baseType->rolname,
12032  .description = "SHELL TYPE",
12033  .section = SECTION_PRE_DATA,
12034  .createStmt = q->data));
12035 
12036  destroyPQExpBuffer(q);
12037 }
12038 
12039 /*
12040  * dumpProcLang
12041  * writes out to fout the queries to recreate a user-defined
12042  * procedural language
12043  */
12044 static void
12045 dumpProcLang(Archive *fout, const ProcLangInfo *plang)
12046 {
12047  DumpOptions *dopt = fout->dopt;
12048  PQExpBuffer defqry;
12049  PQExpBuffer delqry;
12050  bool useParams;
12051  char *qlanname;
12052  FuncInfo *funcInfo;
12053  FuncInfo *inlineInfo = NULL;
12054  FuncInfo *validatorInfo = NULL;
12055 
12056  /* Do nothing in data-only dump */
12057  if (dopt->dataOnly)
12058  return;
12059 
12060  /*
12061  * Try to find the support function(s). It is not an error if we don't
12062  * find them --- if the functions are in the pg_catalog schema, as is
12063  * standard in 8.1 and up, then we won't have loaded them. (In this case
12064  * we will emit a parameterless CREATE LANGUAGE command, which will
12065  * require PL template knowledge in the backend to reload.)
12066  */
12067 
12068  funcInfo = findFuncByOid(plang->lanplcallfoid);
12069  if (funcInfo != NULL && !funcInfo->dobj.dump)
12070  funcInfo = NULL; /* treat not-dumped same as not-found */
12071 
12072  if (OidIsValid(plang->laninline))
12073  {
12074  inlineInfo = findFuncByOid(plang->laninline);
12075  if (inlineInfo != NULL && !inlineInfo->dobj.dump)
12076  inlineInfo = NULL;
12077  }
12078 
12079  if (OidIsValid(plang->lanvalidator))
12080  {
12081  validatorInfo = findFuncByOid(plang->lanvalidator);
12082  if (validatorInfo != NULL && !validatorInfo->dobj.dump)
12083  validatorInfo = NULL;
12084  }
12085 
12086  /*
12087  * If the functions are dumpable then emit a complete CREATE LANGUAGE with
12088  * parameters. Otherwise, we'll write a parameterless command, which will
12089  * be interpreted as CREATE EXTENSION.
12090  */
12091  useParams = (funcInfo != NULL &&
12092  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
12093  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
12094 
12095  defqry = createPQExpBuffer();
12096  delqry = createPQExpBuffer();
12097 
12098  qlanname = pg_strdup(fmtId(plang->dobj.name));
12099 
12100  appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
12101  qlanname);
12102 
12103  if (useParams)
12104  {
12105  appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
12106  plang->lanpltrusted ? "TRUSTED " : "",
12107  qlanname);
12108  appendPQExpBuffer(defqry, " HANDLER %s",
12109  fmtQualifiedDumpable(funcInfo));
12110  if (OidIsValid(plang->laninline))
12111  appendPQExpBuffer(defqry, " INLINE %s",
12112  fmtQualifiedDumpable(inlineInfo));
12113  if (OidIsValid(plang->lanvalidator))
12114  appendPQExpBuffer(defqry, " VALIDATOR %s",
12115  fmtQualifiedDumpable(validatorInfo));
12116  }
12117  else
12118  {
12119  /*
12120  * If not dumping parameters, then use CREATE OR REPLACE so that the
12121  * command will not fail if the language is preinstalled in the target
12122  * database.
12123  *
12124  * Modern servers will interpret this as CREATE EXTENSION IF NOT
12125  * EXISTS; perhaps we should emit that instead? But it might just add
12126  * confusion.
12127  */
12128  appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
12129  qlanname);
12130  }
12131  appendPQExpBufferStr(defqry, ";\n");
12132 
12133  if (dopt->binary_upgrade)
12134  binary_upgrade_extension_member(defqry, &plang->dobj,
12135  "LANGUAGE", qlanname, NULL);
12136 
12137  if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
12138  ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
12139  ARCHIVE_OPTS(.tag = plang->dobj.name,
12140  .owner = plang->lanowner,
12141  .description = "PROCEDURAL LANGUAGE",
12142  .section = SECTION_PRE_DATA,
12143  .createStmt = defqry->data,
12144  .dropStmt = delqry->data,
12145  ));
12146 
12147  /* Dump Proc Lang Comments and Security Labels */
12148  if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
12149  dumpComment(fout, "LANGUAGE", qlanname,
12150  NULL, plang->lanowner,
12151  plang->dobj.catId, 0, plang->dobj.dumpId);
12152 
12153  if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
12154  dumpSecLabel(fout, "LANGUAGE", qlanname,
12155  NULL, plang->lanowner,
12156  plang->dobj.catId, 0, plang->dobj.dumpId);
12157 
12158  if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
12159  dumpACL(fout, plang->dobj.dumpId, InvalidDumpId, "LANGUAGE",
12160  qlanname, NULL, NULL,
12161  plang->lanowner, &plang->dacl);
12162 
12163  free(qlanname);
12164 
12165  destroyPQExpBuffer(defqry);
12166  destroyPQExpBuffer(delqry);
12167 }
12168 
12169 /*
12170  * format_function_arguments: generate function name and argument list
12171  *
12172  * This is used when we can rely on pg_get_function_arguments to format
12173  * the argument list. Note, however, that pg_get_function_arguments
12174  * does not special-case zero-argument aggregates.
12175  */
12176 static char *
12177 format_function_arguments(const FuncInfo *finfo, const char *funcargs, bool is_agg)
12178 {
12180 
12181  initPQExpBuffer(&fn);
12182  appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
12183  if (is_agg && finfo->nargs == 0)
12184  appendPQExpBufferStr(&fn, "(*)");
12185  else
12186  appendPQExpBuffer(&fn, "(%s)", funcargs);
12187  return fn.data;
12188 }
12189 
12190 /*
12191  * format_function_signature: generate function name and argument list
12192  *
12193  * Only a minimal list of input argument types is generated; this is
12194  * sufficient to reference the function, but not to define it.
12195  *
12196  * If honor_quotes is false then the function name is never quoted.
12197  * This is appropriate for use in TOC tags, but not in SQL commands.
12198  */
12199 static char *
12200 format_function_signature(Archive *fout, const FuncInfo *finfo, bool honor_quotes)
12201 {
12203  int j;
12204 
12205  initPQExpBuffer(&fn);
12206  if (honor_quotes)
12207  appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
12208  else
12209  appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
12210  for (j = 0; j < finfo->nargs; j++)
12211  {
12212  if (j > 0)
12213  appendPQExpBufferStr(&fn, ", ");
12214 
12216  getFormattedTypeName(fout, finfo->argtypes[j],
12217  zeroIsError));
12218  }
12219  appendPQExpBufferChar(&fn, ')');
12220  return fn.data;
12221 }
12222 
12223 
12224 /*
12225  * dumpFunc:
12226  * dump out one function
12227  */
12228 static void
12229 dumpFunc(Archive *fout, const FuncInfo *finfo)
12230 {
12231  DumpOptions *dopt = fout->dopt;
12232  PQExpBuffer query;
12233  PQExpBuffer q;
12234  PQExpBuffer delqry;
12235  PQExpBuffer asPart;
12236  PGresult *res;
12237  char *funcsig; /* identity signature */
12238  char *funcfullsig = NULL; /* full signature */
12239  char *funcsig_tag;
12240  char *qual_funcsig;
12241  char *proretset;
12242  char *prosrc;
12243  char *probin;
12244  char *prosqlbody;
12245  char *funcargs;
12246  char *funciargs;
12247  char *funcresult;
12248  char *protrftypes;
12249  char *prokind;
12250  char *provolatile;
12251  char *proisstrict;
12252  char *prosecdef;
12253  char *proleakproof;
12254  char *proconfig;
12255  char *procost;
12256  char *prorows;
12257  char *prosupport;
12258  char *proparallel;
12259  char *lanname;
12260  char **configitems = NULL;
12261  int nconfigitems = 0;
12262  const char *keyword;
12263 
12264  /* Do nothing in data-only dump */
12265  if (dopt->dataOnly)
12266  return;
12267 
12268  query = createPQExpBuffer();
12269  q = createPQExpBuffer();
12270  delqry = createPQExpBuffer();
12271  asPart = createPQExpBuffer();
12272 
12273  if (!fout->is_prepared[PREPQUERY_DUMPFUNC])
12274  {
12275  /* Set up query for function-specific details */
12276  appendPQExpBufferStr(query,
12277  "PREPARE dumpFunc(pg_catalog.oid) AS\n");
12278 
12279  appendPQExpBufferStr(query,
12280  "SELECT\n"
12281  "proretset,\n"
12282  "prosrc,\n"
12283  "probin,\n"
12284  "provolatile,\n"
12285  "proisstrict,\n"
12286  "prosecdef,\n"
12287  "lanname,\n"
12288  "proconfig,\n"
12289  "procost,\n"
12290  "prorows,\n"
12291  "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs,\n"
12292  "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs,\n"
12293  "pg_catalog.pg_get_function_result(p.oid) AS funcresult,\n"
12294  "proleakproof,\n");
12295 
12296  if (fout->remoteVersion >= 90500)
12297  appendPQExpBufferStr(query,
12298  "array_to_string(protrftypes, ' ') AS protrftypes,\n");
12299  else
12300  appendPQExpBufferStr(query,
12301  "NULL AS protrftypes,\n");
12302 
12303  if (fout->remoteVersion >= 90600)
12304  appendPQExpBufferStr(query,
12305  "proparallel,\n");
12306  else
12307  appendPQExpBufferStr(query,
12308  "'u' AS proparallel,\n");
12309 
12310  if (fout->remoteVersion >= 110000)
12311  appendPQExpBufferStr(query,
12312  "prokind,\n");
12313  else
12314  appendPQExpBufferStr(query,
12315  "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind,\n");
12316 
12317  if (fout->remoteVersion >= 120000)
12318  appendPQExpBufferStr(query,
12319  "prosupport,\n");
12320  else
12321  appendPQExpBufferStr(query,
12322  "'-' AS prosupport,\n");
12323 
12324  if (fout->remoteVersion >= 140000)
12325  appendPQExpBufferStr(query,
12326  "pg_get_function_sqlbody(p.oid) AS prosqlbody\n");
12327  else
12328  appendPQExpBufferStr(query,
12329  "NULL AS prosqlbody\n");
12330 
12331  appendPQExpBufferStr(query,
12332  "FROM pg_catalog.pg_proc p, pg_catalog.pg_language l\n"
12333  "WHERE p.oid = $1 "
12334  "AND l.oid = p.prolang");
12335 
12336  ExecuteSqlStatement(fout, query->data);
12337 
12338  fout->is_prepared[PREPQUERY_DUMPFUNC] = true;
12339  }
12340 
12341  printfPQExpBuffer(query,
12342  "EXECUTE dumpFunc('%u')",
12343  finfo->dobj.catId.oid);
12344 
12345  res = ExecuteSqlQueryForSingleRow(fout, query->data);
12346 
12347  proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
12348  if (PQgetisnull(res, 0, PQfnumber(res, "prosqlbody")))
12349  {
12350  prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
12351  probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
12352  prosqlbody = NULL;
12353  }
12354  else
12355  {
12356  prosrc = NULL;
12357  probin = NULL;
12358  prosqlbody = PQgetvalue(res, 0, PQfnumber(res, "prosqlbody"));
12359  }
12360  funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
12361  funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
12362  funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
12363  protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
12364  prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
12365  provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
12366  proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
12367  prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
12368  proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
12369  proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
12370  procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
12371  prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
12372  prosupport = PQgetvalue(res, 0, PQfnumber(res, "prosupport"));
12373  proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
12374  lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
12375 
12376  /*
12377  * See backend/commands/functioncmds.c for details of how the 'AS' clause
12378  * is used.
12379  */
12380  if (prosqlbody)
12381  {
12382  appendPQExpBufferStr(asPart, prosqlbody);
12383  }
12384  else if (probin[0] != '\0')
12385  {
12386  appendPQExpBufferStr(asPart, "AS ");
12387  appendStringLiteralAH(asPart, probin, fout);
12388  if (prosrc[0] != '\0')
12389  {
12390  appendPQExpBufferStr(asPart, ", ");
12391 
12392  /*
12393  * where we have bin, use dollar quoting if allowed and src
12394  * contains quote or backslash; else use regular quoting.
12395  */
12396  if (dopt->disable_dollar_quoting ||
12397  (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
12398  appendStringLiteralAH(asPart, prosrc, fout);
12399  else
12400  appendStringLiteralDQ(asPart, prosrc, NULL);
12401  }
12402  }
12403  else
12404  {
12405  appendPQExpBufferStr(asPart, "AS ");
12406  /* with no bin, dollar quote src unconditionally if allowed */
12407  if (dopt->disable_dollar_quoting)
12408  appendStringLiteralAH(asPart, prosrc, fout);
12409  else
12410  appendStringLiteralDQ(asPart, prosrc, NULL);
12411  }
12412 
12413  if (*proconfig)
12414  {
12415  if (!parsePGArray(proconfig, &configitems, &nconfigitems))
12416  pg_fatal("could not parse %s array", "proconfig");
12417  }
12418  else
12419  {
12420  configitems = NULL;
12421  nconfigitems = 0;
12422  }
12423 
12424  funcfullsig = format_function_arguments(finfo, funcargs, false);
12425  funcsig = format_function_arguments(finfo, funciargs, false);
12426 
12427  funcsig_tag = format_function_signature(fout, finfo, false);
12428 
12429  qual_funcsig = psprintf("%s.%s",
12430  fmtId(finfo->dobj.namespace->dobj.name),
12431  funcsig);
12432 
12433  if (prokind[0] == PROKIND_PROCEDURE)
12434  keyword = "PROCEDURE";
12435  else
12436  keyword = "FUNCTION"; /* works for window functions too */
12437 
12438  appendPQExpBuffer(delqry, "DROP %s %s;\n",
12439  keyword, qual_funcsig);
12440 
12441  appendPQExpBuffer(q, "CREATE %s %s.%s",
12442  keyword,
12443  fmtId(finfo->dobj.namespace->dobj.name),
12444  funcfullsig ? funcfullsig :
12445  funcsig);
12446 
12447  if (prokind[0] == PROKIND_PROCEDURE)
12448  /* no result type to output */ ;
12449  else if (funcresult)
12450  appendPQExpBuffer(q, " RETURNS %s", funcresult);
12451  else
12452  appendPQExpBuffer(q, " RETURNS %s%s",
12453  (proretset[0] == 't') ? "SETOF " : "",
12454  getFormattedTypeName(fout, finfo->prorettype,
12455  zeroIsError));
12456 
12457  appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
12458 
12459  if (*protrftypes)
12460  {
12461  Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
12462  int i;
12463 
12464  appendPQExpBufferStr(q, " TRANSFORM ");
12465  parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
12466  for (i = 0; typeids[i]; i++)
12467  {
12468  if (i != 0)
12469  appendPQExpBufferStr(q, ", ");
12470  appendPQExpBuffer(q, "FOR TYPE %s",
12471  getFormattedTypeName(fout, typeids[i], zeroAsNone));
12472  }
12473  }
12474 
12475  if (prokind[0] == PROKIND_WINDOW)
12476  appendPQExpBufferStr(q, " WINDOW");
12477 
12478  if (provolatile[0] != PROVOLATILE_VOLATILE)
12479  {
12480  if (provolatile[0] == PROVOLATILE_IMMUTABLE)
12481  appendPQExpBufferStr(q, " IMMUTABLE");
12482  else if (provolatile[0] == PROVOLATILE_STABLE)
12483  appendPQExpBufferStr(q, " STABLE");
12484  else if (provolatile[0] != PROVOLATILE_VOLATILE)
12485  pg_fatal("unrecognized provolatile value for function \"%s\"",
12486  finfo->dobj.name);
12487  }
12488 
12489  if (proisstrict[0] == 't')
12490  appendPQExpBufferStr(q, " STRICT");
12491 
12492  if (prosecdef[0] == 't')
12493  appendPQExpBufferStr(q, " SECURITY DEFINER");
12494 
12495  if (proleakproof[0] == 't')
12496  appendPQExpBufferStr(q, " LEAKPROOF");
12497 
12498  /*
12499  * COST and ROWS are emitted only if present and not default, so as not to
12500  * break backwards-compatibility of the dump without need. Keep this code
12501  * in sync with the defaults in functioncmds.c.
12502  */
12503  if (strcmp(procost, "0") != 0)
12504  {
12505  if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
12506  {
12507  /* default cost is 1 */
12508  if (strcmp(procost, "1") != 0)
12509  appendPQExpBuffer(q, " COST %s", procost);
12510  }
12511  else
12512  {
12513  /* default cost is 100 */
12514  if (strcmp(procost, "100") != 0)
12515  appendPQExpBuffer(q, " COST %s", procost);
12516  }
12517  }
12518  if (proretset[0] == 't' &&
12519  strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
12520  appendPQExpBuffer(q, " ROWS %s", prorows);
12521 
12522  if (strcmp(prosupport, "-") != 0)
12523  {
12524  /* We rely on regprocout to provide quoting and qualification */
12525  appendPQExpBuffer(q, " SUPPORT %s", prosupport);
12526  }
12527 
12528  if (proparallel[0] != PROPARALLEL_UNSAFE)
12529  {
12530  if (proparallel[0] == PROPARALLEL_SAFE)
12531  appendPQExpBufferStr(q, " PARALLEL SAFE");
12532  else if (proparallel[0] == PROPARALLEL_RESTRICTED)
12533  appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
12534  else if (proparallel[0] != PROPARALLEL_UNSAFE)
12535  pg_fatal("unrecognized proparallel value for function \"%s\"",
12536  finfo->dobj.name);
12537  }
12538 
12539  for (int i = 0; i < nconfigitems; i++)
12540  {
12541  /* we feel free to scribble on configitems[] here */
12542  char *configitem = configitems[i];
12543  char *pos;
12544 
12545  pos = strchr(configitem, '=');
12546  if (pos == NULL)
12547  continue;
12548  *pos++ = '\0';
12549  appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
12550 
12551  /*
12552  * Variables that are marked GUC_LIST_QUOTE were already fully quoted
12553  * by flatten_set_variable_args() before they were put into the
12554  * proconfig array. However, because the quoting rules used there
12555  * aren't exactly like SQL's, we have to break the list value apart
12556  * and then quote the elements as string literals. (The elements may
12557  * be double-quoted as-is, but we can't just feed them to the SQL
12558  * parser; it would do the wrong thing with elements that are
12559  * zero-length or longer than NAMEDATALEN.)
12560  *
12561  * Variables that are not so marked should just be emitted as simple
12562  * string literals. If the variable is not known to
12563  * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
12564  * to use GUC_LIST_QUOTE for extension variables.
12565  */
12566  if (variable_is_guc_list_quote(configitem))
12567  {
12568  char **namelist;
12569  char **nameptr;
12570 
12571  /* Parse string into list of identifiers */
12572  /* this shouldn't fail really */
12573  if (SplitGUCList(pos, ',', &namelist))
12574  {
12575  for (nameptr = namelist; *nameptr; nameptr++)
12576  {
12577  if (nameptr != namelist)
12578  appendPQExpBufferStr(q, ", ");
12579  appendStringLiteralAH(q, *nameptr, fout);
12580  }
12581  }
12582  pg_free(namelist);
12583  }
12584  else
12585  appendStringLiteralAH(q, pos, fout);
12586  }
12587 
12588  appendPQExpBuffer(q, "\n %s;\n", asPart->data);
12589 
12590  append_depends_on_extension(fout, q, &finfo->dobj,
12591  "pg_catalog.pg_proc", keyword,
12592  qual_funcsig);
12593 
12594  if (dopt->binary_upgrade)
12596  keyword, funcsig,
12597  finfo->dobj.namespace->dobj.name);
12598 
12599  if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12600  ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12601  ARCHIVE_OPTS(.tag = funcsig_tag,
12602  .namespace = finfo->dobj.namespace->dobj.name,
12603  .owner = finfo->rolname,
12604  .description = keyword,
12605  .section = finfo->postponed_def ?
12607  .createStmt = q->data,
12608  .dropStmt = delqry->data));
12609 
12610  /* Dump Function Comments and Security Labels */
12611  if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12612  dumpComment(fout, keyword, funcsig,
12613  finfo->dobj.namespace->dobj.name, finfo->rolname,
12614  finfo->dobj.catId, 0, finfo->dobj.dumpId);
12615 
12616  if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12617  dumpSecLabel(fout, keyword, funcsig,
12618  finfo->dobj.namespace->dobj.name, finfo->rolname,
12619  finfo->dobj.catId, 0, finfo->dobj.dumpId);
12620 
12621  if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12622  dumpACL(fout, finfo->dobj.dumpId, InvalidDumpId, keyword,
12623  funcsig, NULL,
12624  finfo->dobj.namespace->dobj.name,
12625  finfo->rolname, &finfo->dacl);
12626 
12627  PQclear(res);
12628 
12629  destroyPQExpBuffer(query);
12630  destroyPQExpBuffer(q);
12631  destroyPQExpBuffer(delqry);
12632  destroyPQExpBuffer(asPart);
12633  free(funcsig);
12634  free(funcfullsig);
12635  free(funcsig_tag);
12636  free(qual_funcsig);
12637  free(configitems);
12638 }
12639 
12640 
12641 /*
12642  * Dump a user-defined cast
12643  */
12644 static void
12645 dumpCast(Archive *fout, const CastInfo *cast)
12646 {
12647  DumpOptions *dopt = fout->dopt;
12648  PQExpBuffer defqry;
12649  PQExpBuffer delqry;
12650  PQExpBuffer labelq;
12651  PQExpBuffer castargs;
12652  FuncInfo *funcInfo = NULL;
12653  const char *sourceType;
12654  const char *targetType;
12655 
12656  /* Do nothing in data-only dump */
12657  if (dopt->dataOnly)
12658  return;
12659 
12660  /* Cannot dump if we don't have the cast function's info */
12661  if (OidIsValid(cast->castfunc))
12662  {
12663  funcInfo = findFuncByOid(cast->castfunc);
12664  if (funcInfo == NULL)
12665  pg_fatal("could not find function definition for function with OID %u",
12666  cast->castfunc);
12667  }
12668 
12669  defqry = createPQExpBuffer();
12670  delqry = createPQExpBuffer();
12671  labelq = createPQExpBuffer();
12672  castargs = createPQExpBuffer();
12673 
12674  sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12675  targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12676  appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12677  sourceType, targetType);
12678 
12679  appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12680  sourceType, targetType);
12681 
12682  switch (cast->castmethod)
12683  {
12684  case COERCION_METHOD_BINARY:
12685  appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12686  break;
12687  case COERCION_METHOD_INOUT:
12688  appendPQExpBufferStr(defqry, "WITH INOUT");
12689  break;
12690  case COERCION_METHOD_FUNCTION:
12691  if (funcInfo)
12692  {
12693  char *fsig = format_function_signature(fout, funcInfo, true);
12694 
12695  /*
12696  * Always qualify the function name (format_function_signature
12697  * won't qualify it).
12698  */
12699  appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12700  fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12701  free(fsig);
12702  }
12703  else
12704  pg_log_warning("bogus value in pg_cast.castfunc or pg_cast.castmethod field");
12705  break;
12706  default:
12707  pg_log_warning("bogus value in pg_cast.castmethod field");
12708  }
12709 
12710  if (cast->castcontext == 'a')
12711  appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12712  else if (cast->castcontext == 'i')
12713  appendPQExpBufferStr(defqry, " AS IMPLICIT");
12714  appendPQExpBufferStr(defqry, ";\n");
12715 
12716  appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12717  sourceType, targetType);
12718 
12719  appendPQExpBuffer(castargs, "(%s AS %s)",
12720  sourceType, targetType);
12721 
12722  if (dopt->binary_upgrade)
12723  binary_upgrade_extension_member(defqry, &cast->dobj,
12724  "CAST", castargs->data, NULL);
12725 
12726  if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12727  ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12728  ARCHIVE_OPTS(.tag = labelq->data,
12729  .description = "CAST",
12730  .section = SECTION_PRE_DATA,
12731  .createStmt = defqry->data,
12732  .dropStmt = delqry->data));
12733 
12734  /* Dump Cast Comments */
12735  if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12736  dumpComment(fout, "CAST", castargs->data,
12737  NULL, "",
12738  cast->dobj.catId, 0, cast->dobj.dumpId);
12739 
12740  destroyPQExpBuffer(defqry);
12741  destroyPQExpBuffer(delqry);
12742  destroyPQExpBuffer(labelq);
12743  destroyPQExpBuffer(castargs);
12744 }
12745 
12746 /*
12747  * Dump a transform
12748  */
12749 static void
12750 dumpTransform(Archive *fout, const TransformInfo *transform)
12751 {
12752  DumpOptions *dopt = fout->dopt;
12753  PQExpBuffer defqry;
12754  PQExpBuffer delqry;
12755  PQExpBuffer labelq;
12756  PQExpBuffer transformargs;
12757  FuncInfo *fromsqlFuncInfo = NULL;
12758  FuncInfo *tosqlFuncInfo = NULL;
12759  char *lanname;
12760  const char *transformType;
12761 
12762  /* Do nothing in data-only dump */
12763  if (dopt->dataOnly)
12764  return;
12765 
12766  /* Cannot dump if we don't have the transform functions' info */
12767  if (OidIsValid(transform->trffromsql))
12768  {
12769  fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12770  if (fromsqlFuncInfo == NULL)
12771  pg_fatal("could not find function definition for function with OID %u",
12772  transform->trffromsql);
12773  }
12774  if (OidIsValid(transform->trftosql))
12775  {
12776  tosqlFuncInfo = findFuncByOid(transform->trftosql);
12777  if (tosqlFuncInfo == NULL)
12778  pg_fatal("could not find function definition for function with OID %u",
12779  transform->trftosql);
12780  }
12781 
12782  defqry = createPQExpBuffer();
12783  delqry = createPQExpBuffer();
12784  labelq = createPQExpBuffer();
12785  transformargs = createPQExpBuffer();
12786 
12787  lanname = get_language_name(fout, transform->trflang);
12788  transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12789 
12790  appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12791  transformType, lanname);
12792 
12793  appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12794  transformType, lanname);
12795 
12796  if (!transform->trffromsql && !transform->trftosql)
12797  pg_log_warning("bogus transform definition, at least one of trffromsql and trftosql should be nonzero");
12798 
12799  if (transform->trffromsql)
12800  {
12801  if (fromsqlFuncInfo)
12802  {
12803  char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12804 
12805  /*
12806  * Always qualify the function name (format_function_signature
12807  * won't qualify it).
12808  */
12809  appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12810  fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12811  free(fsig);
12812  }
12813  else
12814  pg_log_warning("bogus value in pg_transform.trffromsql field");
12815  }
12816 
12817  if (transform->trftosql)
12818  {
12819  if (transform->trffromsql)
12820  appendPQExpBufferStr(defqry, ", ");
12821 
12822  if (tosqlFuncInfo)
12823  {
12824  char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12825 
12826  /*
12827  * Always qualify the function name (format_function_signature
12828  * won't qualify it).
12829  */
12830  appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12831  fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12832  free(fsig);
12833  }
12834  else
12835  pg_log_warning("bogus value in pg_transform.trftosql field");
12836  }
12837 
12838  appendPQExpBufferStr(defqry, ");\n");
12839 
12840  appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12841  transformType, lanname);
12842 
12843  appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12844  transformType, lanname);
12845 
12846  if (dopt->binary_upgrade)
12847  binary_upgrade_extension_member(defqry, &transform->dobj,
12848  "TRANSFORM", transformargs->data, NULL);
12849 
12850  if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12851  ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12852  ARCHIVE_OPTS(.tag = labelq->data,
12853  .description = "TRANSFORM",
12854  .section = SECTION_PRE_DATA,
12855  .createStmt = defqry->data,
12856  .dropStmt = delqry->data,
12857  .deps = transform->dobj.dependencies,
12858  .nDeps = transform->dobj.nDeps));
12859 
12860  /* Dump Transform Comments */
12861  if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12862  dumpComment(fout, "TRANSFORM", transformargs->data,
12863  NULL, "",
12864  transform->dobj.catId, 0, transform->dobj.dumpId);
12865 
12866  free(lanname);
12867  destroyPQExpBuffer(defqry);
12868  destroyPQExpBuffer(delqry);
12869  destroyPQExpBuffer(labelq);
12870  destroyPQExpBuffer(transformargs);
12871 }
12872 
12873 
12874 /*
12875  * dumpOpr
12876  * write out a single operator definition
12877  */
12878 static void
12879 dumpOpr(Archive *fout, const OprInfo *oprinfo)
12880 {
12881  DumpOptions *dopt = fout->dopt;
12882  PQExpBuffer query;
12883  PQExpBuffer q;
12884  PQExpBuffer delq;
12886  PQExpBuffer details;
12887  PGresult *res;
12888  int i_oprkind;
12889  int i_oprcode;
12890  int i_oprleft;
12891  int i_oprright;
12892  int i_oprcom;
12893  int i_oprnegate;
12894  int i_oprrest;
12895  int i_oprjoin;
12896  int i_oprcanmerge;
12897  int i_oprcanhash;
12898  char *oprkind;
12899  char *oprcode;
12900  char *oprleft;
12901  char *oprright;
12902  char *oprcom;
12903  char *oprnegate;
12904  char *oprrest;
12905  char *oprjoin;
12906  char *oprcanmerge;
12907  char *oprcanhash;
12908  char *oprregproc;
12909  char *oprref;
12910 
12911  /* Do nothing in data-only dump */
12912  if (dopt->dataOnly)
12913  return;
12914 
12915  /*
12916  * some operators are invalid because they were the result of user
12917  * defining operators before commutators exist
12918  */
12919  if (!OidIsValid(oprinfo->oprcode))
12920  return;
12921 
12922  query = createPQExpBuffer();
12923  q = createPQExpBuffer();
12924  delq = createPQExpBuffer();
12926  details = createPQExpBuffer();
12927 
12928  if (!fout->is_prepared[PREPQUERY_DUMPOPR])
12929  {
12930  /* Set up query for operator-specific details */
12931  appendPQExpBufferStr(query,
12932  "PREPARE dumpOpr(pg_catalog.oid) AS\n"
12933  "SELECT oprkind, "
12934  "oprcode::pg_catalog.regprocedure, "
12935  "oprleft::pg_catalog.regtype, "
12936  "oprright::pg_catalog.regtype, "
12937  "oprcom, "
12938  "oprnegate, "
12939  "oprrest::pg_catalog.regprocedure, "
12940  "oprjoin::pg_catalog.regprocedure, "
12941  "oprcanmerge, oprcanhash "
12942  "FROM pg_catalog.pg_operator "
12943  "WHERE oid = $1");
12944 
12945  ExecuteSqlStatement(fout, query->data);
12946 
12947  fout->is_prepared[PREPQUERY_DUMPOPR] = true;
12948  }
12949 
12950  printfPQExpBuffer(query,
12951  "EXECUTE dumpOpr('%u')",
12952  oprinfo->dobj.catId.oid);
12953 
12954  res = ExecuteSqlQueryForSingleRow(fout, query->data);
12955 
12956  i_oprkind = PQfnumber(res, "oprkind");
12957  i_oprcode = PQfnumber(res, "oprcode");
12958  i_oprleft = PQfnumber(res, "oprleft");
12959  i_oprright = PQfnumber(res, "oprright");
12960  i_oprcom = PQfnumber(res, "oprcom");
12961  i_oprnegate = PQfnumber(res, "oprnegate");
12962  i_oprrest = PQfnumber(res, "oprrest");
12963  i_oprjoin = PQfnumber(res, "oprjoin");
12964  i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12965  i_oprcanhash = PQfnumber(res, "oprcanhash");
12966 
12967  oprkind = PQgetvalue(res, 0, i_oprkind);
12968  oprcode = PQgetvalue(res, 0, i_oprcode);
12969  oprleft = PQgetvalue(res, 0, i_oprleft);
12970  oprright = PQgetvalue(res, 0, i_oprright);
12971  oprcom = PQgetvalue(res, 0, i_oprcom);
12972  oprnegate = PQgetvalue(res, 0, i_oprnegate);
12973  oprrest = PQgetvalue(res, 0, i_oprrest);
12974  oprjoin = PQgetvalue(res, 0, i_oprjoin);
12975  oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12976  oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12977 
12978  /* In PG14 upwards postfix operator support does not exist anymore. */
12979  if (strcmp(oprkind, "r") == 0)
12980  pg_log_warning("postfix operators are not supported anymore (operator \"%s\")",
12981  oprcode);
12982 
12983  oprregproc = convertRegProcReference(oprcode);
12984  if (oprregproc)
12985  {
12986  appendPQExpBuffer(details, " FUNCTION = %s", oprregproc);
12987  free(oprregproc);
12988  }
12989 
12990  appendPQExpBuffer(oprid, "%s (",
12991  oprinfo->dobj.name);
12992 
12993  /*
12994  * right unary means there's a left arg and left unary means there's a
12995  * right arg. (Although the "r" case is dead code for PG14 and later,
12996  * continue to support it in case we're dumping from an old server.)
12997  */
12998  if (strcmp(oprkind, "r") == 0 ||
12999  strcmp(oprkind, "b") == 0)
13000  {
13001  appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
13002  appendPQExpBufferStr(oprid, oprleft);
13003  }
13004  else
13005  appendPQExpBufferStr(oprid, "NONE");
13006 
13007  if (strcmp(oprkind, "l") == 0 ||
13008  strcmp(oprkind, "b") == 0)
13009  {
13010  appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
13011  appendPQExpBuffer(oprid, ", %s)", oprright);
13012  }
13013  else
13014  appendPQExpBufferStr(oprid, ", NONE)");
13015 
13016  oprref = getFormattedOperatorName(oprcom);
13017  if (oprref)
13018  {
13019  appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
13020  free(oprref);
13021  }
13022 
13023  oprref = getFormattedOperatorName(oprnegate);
13024  if (oprref)
13025  {
13026  appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
13027  free(oprref);
13028  }
13029 
13030  if (strcmp(oprcanmerge, "t") == 0)
13031  appendPQExpBufferStr(details, ",\n MERGES");
13032 
13033  if (strcmp(oprcanhash, "t") == 0)
13034  appendPQExpBufferStr(details, ",\n HASHES");
13035 
13036  oprregproc = convertRegProcReference(oprrest);
13037  if (oprregproc)
13038  {
13039  appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
13040  free(oprregproc);
13041  }
13042 
13043  oprregproc = convertRegProcReference(oprjoin);
13044  if (oprregproc)
13045  {
13046  appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
13047  free(oprregproc);
13048  }
13049 
13050  appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
13051  fmtId(oprinfo->dobj.namespace->dobj.name),
13052  oprid->data);
13053 
13054  appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
13055  fmtId(oprinfo->dobj.namespace->dobj.name),
13056  oprinfo->dobj.name, details->data);
13057 
13058  if (dopt->binary_upgrade)
13060  "OPERATOR", oprid->data,
13061  oprinfo->dobj.namespace->dobj.name);
13062 
13063  if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13064  ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
13065  ARCHIVE_OPTS(.tag = oprinfo->dobj.name,
13066  .namespace = oprinfo->dobj.namespace->dobj.name,
13067  .owner = oprinfo->rolname,
13068  .description = "OPERATOR",
13069  .section = SECTION_PRE_DATA,
13070  .createStmt = q->data,
13071  .dropStmt = delq->data));
13072 
13073  /* Dump Operator Comments */
13074  if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13075  dumpComment(fout, "OPERATOR", oprid->data,
13076  oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
13077  oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
13078 
13079  PQclear(res);
13080 
13081  destroyPQExpBuffer(query);
13082  destroyPQExpBuffer(q);
13083  destroyPQExpBuffer(delq);
13085  destroyPQExpBuffer(details);
13086 }
13087 
13088 /*
13089  * Convert a function reference obtained from pg_operator
13090  *
13091  * Returns allocated string of what to print, or NULL if function references
13092  * is InvalidOid. Returned string is expected to be free'd by the caller.
13093  *
13094  * The input is a REGPROCEDURE display; we have to strip the argument-types
13095  * part.
13096  */
13097 static char *
13098 convertRegProcReference(const char *proc)
13099 {
13100  char *name;
13101  char *paren;
13102  bool inquote;
13103 
13104  /* In all cases "-" means a null reference */
13105  if (strcmp(proc, "-") == 0)
13106  return NULL;
13107 
13108  name = pg_strdup(proc);
13109  /* find non-double-quoted left paren */
13110  inquote = false;
13111  for (paren = name; *paren; paren++)
13112  {
13113  if (*paren == '(' && !inquote)
13114  {
13115  *paren = '\0';
13116  break;
13117  }
13118  if (*paren == '"')
13119  inquote = !inquote;
13120  }
13121  return name;
13122 }
13123 
13124 /*
13125  * getFormattedOperatorName - retrieve the operator name for the
13126  * given operator OID (presented in string form).
13127  *
13128  * Returns an allocated string, or NULL if the given OID is invalid.
13129  * Caller is responsible for free'ing result string.
13130  *
13131  * What we produce has the format "OPERATOR(schema.oprname)". This is only
13132  * useful in commands where the operator's argument types can be inferred from
13133  * context. We always schema-qualify the name, though. The predecessor to
13134  * this code tried to skip the schema qualification if possible, but that led
13135  * to wrong results in corner cases, such as if an operator and its negator
13136  * are in different schemas.
13137  */
13138 static char *
13139 getFormattedOperatorName(const char *oproid)
13140 {
13141  OprInfo *oprInfo;
13142 
13143  /* In all cases "0" means a null reference */
13144  if (strcmp(oproid, "0") == 0)
13145  return NULL;
13146 
13147  oprInfo = findOprByOid(atooid(oproid));
13148  if (oprInfo == NULL)
13149  {
13150  pg_log_warning("could not find operator with OID %s",
13151  oproid);
13152  return NULL;
13153  }
13154 
13155  return psprintf("OPERATOR(%s.%s)",
13156  fmtId(oprInfo->dobj.namespace->dobj.name),
13157  oprInfo->dobj.name);
13158 }
13159 
13160 /*
13161  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
13162  *
13163  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
13164  * argument lists of these functions are predetermined. Note that the
13165  * caller should ensure we are in the proper schema, because the results
13166  * are search path dependent!
13167  */
13168 static char *
13170 {
13171  char *result;
13172  char query[128];
13173  PGresult *res;
13174 
13175  snprintf(query, sizeof(query),
13176  "SELECT '%u'::pg_catalog.regproc", funcOid);
13177  res = ExecuteSqlQueryForSingleRow(fout, query);
13178 
13179  result = pg_strdup(PQgetvalue(res, 0, 0));
13180 
13181  PQclear(res);
13182 
13183  return result;
13184 }
13185 
13186 /*
13187  * dumpAccessMethod
13188  * write out a single access method definition
13189  */
13190 static void
13192 {
13193  DumpOptions *dopt = fout->dopt;
13194  PQExpBuffer q;
13195  PQExpBuffer delq;
13196  char *qamname;
13197 
13198  /* Do nothing in data-only dump */
13199  if (dopt->dataOnly)
13200  return;
13201 
13202  q = createPQExpBuffer();
13203  delq = createPQExpBuffer();
13204 
13205  qamname = pg_strdup(fmtId(aminfo->dobj.name));
13206 
13207  appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
13208 
13209  switch (aminfo->amtype)
13210  {
13211  case AMTYPE_INDEX:
13212  appendPQExpBufferStr(q, "TYPE INDEX ");
13213  break;
13214  case AMTYPE_TABLE:
13215  appendPQExpBufferStr(q, "TYPE TABLE ");
13216  break;
13217  default:
13218  pg_log_warning("invalid type \"%c\" of access method \"%s\"",
13219  aminfo->amtype, qamname);
13220  destroyPQExpBuffer(q);
13221  destroyPQExpBuffer(delq);
13222  free(qamname);
13223  return;
13224  }
13225 
13226  appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
13227 
13228  appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
13229  qamname);
13230 
13231  if (dopt->binary_upgrade)
13233  "ACCESS METHOD", qamname, NULL);
13234 
13235  if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13236  ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
13237  ARCHIVE_OPTS(.tag = aminfo->dobj.name,
13238  .description = "ACCESS METHOD",
13239  .section = SECTION_PRE_DATA,
13240  .createStmt = q->data,
13241  .dropStmt = delq->data));
13242 
13243  /* Dump Access Method Comments */
13244  if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13245  dumpComment(fout, "ACCESS METHOD", qamname,
13246  NULL, "",
13247  aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
13248 
13249  destroyPQExpBuffer(q);
13250  destroyPQExpBuffer(delq);
13251  free(qamname);
13252 }
13253 
13254 /*
13255  * dumpOpclass
13256  * write out a single operator class definition
13257  */
13258 static void
13259 dumpOpclass(Archive *fout, const OpclassInfo *opcinfo)
13260 {
13261  DumpOptions *dopt = fout->dopt;
13262  PQExpBuffer query;
13263  PQExpBuffer q;
13264  PQExpBuffer delq;
13265  PQExpBuffer nameusing;
13266  PGresult *res;
13267  int ntups;
13268  int i_opcintype;
13269  int i_opckeytype;
13270  int i_opcdefault;
13271  int i_opcfamily;
13272  int i_opcfamilyname;
13273  int i_opcfamilynsp;
13274  int i_amname;
13275  int i_amopstrategy;
13276  int i_amopopr;
13277  int i_sortfamily;
13278  int i_sortfamilynsp;
13279  int i_amprocnum;
13280  int i_amproc;
13281  int i_amproclefttype;
13282  int i_amprocrighttype;
13283  char *opcintype;
13284  char *opckeytype;
13285  char *opcdefault;
13286  char *opcfamily;
13287  char *opcfamilyname;
13288  char *opcfamilynsp;
13289  char *amname;
13290  char *amopstrategy;
13291  char *amopopr;
13292  char *sortfamily;
13293  char *sortfamilynsp;
13294  char *amprocnum;
13295  char *amproc;
13296  char *amproclefttype;
13297  char *amprocrighttype;
13298  bool needComma;
13299  int i;
13300 
13301  /* Do nothing in data-only dump */
13302  if (dopt->dataOnly)
13303  return;
13304 
13305  query = createPQExpBuffer();
13306  q = createPQExpBuffer();
13307  delq = createPQExpBuffer();
13308  nameusing = createPQExpBuffer();
13309 
13310  /* Get additional fields from the pg_opclass row */
13311  appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
13312  "opckeytype::pg_catalog.regtype, "
13313  "opcdefault, opcfamily, "
13314  "opfname AS opcfamilyname, "
13315  "nspname AS opcfamilynsp, "
13316  "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
13317  "FROM pg_catalog.pg_opclass c "
13318  "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
13319  "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13320  "WHERE c.oid = '%u'::pg_catalog.oid",
13321  opcinfo->dobj.catId.oid);
13322 
13323  res = ExecuteSqlQueryForSingleRow(fout, query->data);
13324 
13325  i_opcintype = PQfnumber(res, "opcintype");
13326  i_opckeytype = PQfnumber(res, "opckeytype");
13327  i_opcdefault = PQfnumber(res, "opcdefault");
13328  i_opcfamily = PQfnumber(res, "opcfamily");
13329  i_opcfamilyname = PQfnumber(res, "opcfamilyname");
13330  i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
13331  i_amname = PQfnumber(res, "amname");
13332 
13333  /* opcintype may still be needed after we PQclear res */
13334  opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
13335  opckeytype = PQgetvalue(res, 0, i_opckeytype);
13336  opcdefault = PQgetvalue(res, 0, i_opcdefault);
13337  /* opcfamily will still be needed after we PQclear res */
13338  opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
13339  opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
13340  opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
13341  /* amname will still be needed after we PQclear res */
13342  amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13343 
13344  appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
13345  fmtQualifiedDumpable(opcinfo));
13346  appendPQExpBuffer(delq, " USING %s;\n",
13347  fmtId(amname));
13348 
13349  /* Build the fixed portion of the CREATE command */
13350  appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
13351  fmtQualifiedDumpable(opcinfo));
13352  if (strcmp(opcdefault, "t") == 0)
13353  appendPQExpBufferStr(q, "DEFAULT ");
13354  appendPQExpBuffer(q, "FOR TYPE %s USING %s",
13355  opcintype,
13356  fmtId(amname));
13357  if (strlen(opcfamilyname) > 0)
13358  {
13359  appendPQExpBufferStr(q, " FAMILY ");
13360  appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
13361  appendPQExpBufferStr(q, fmtId(opcfamilyname));
13362  }
13363  appendPQExpBufferStr(q, " AS\n ");
13364 
13365  needComma = false;
13366 
13367  if (strcmp(opckeytype, "-") != 0)
13368  {
13369  appendPQExpBuffer(q, "STORAGE %s",
13370  opckeytype);
13371  needComma = true;
13372  }
13373 
13374  PQclear(res);
13375 
13376  /*
13377  * Now fetch and print the OPERATOR entries (pg_amop rows).
13378  *
13379  * Print only those opfamily members that are tied to the opclass by
13380  * pg_depend entries.
13381  */
13382  resetPQExpBuffer(query);
13383  appendPQExpBuffer(query, "SELECT amopstrategy, "
13384  "amopopr::pg_catalog.regoperator, "
13385  "opfname AS sortfamily, "
13386  "nspname AS sortfamilynsp "
13387  "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13388  "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13389  "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13390  "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13391  "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13392  "AND refobjid = '%u'::pg_catalog.oid "
13393  "AND amopfamily = '%s'::pg_catalog.oid "
13394  "ORDER BY amopstrategy",
13395  opcinfo->dobj.catId.oid,
13396  opcfamily);
13397 
13398  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13399 
13400  ntups = PQntuples(res);
13401 
13402  i_amopstrategy = PQfnumber(res, "amopstrategy");
13403  i_amopopr = PQfnumber(res, "amopopr");
13404  i_sortfamily = PQfnumber(res, "sortfamily");
13405  i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
13406 
13407  for (i = 0; i < ntups; i++)
13408  {
13409  amopstrategy = PQgetvalue(res, i, i_amopstrategy);
13410  amopopr = PQgetvalue(res, i, i_amopopr);
13411  sortfamily = PQgetvalue(res, i, i_sortfamily);
13412  sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
13413 
13414  if (needComma)
13415  appendPQExpBufferStr(q, " ,\n ");
13416 
13417  appendPQExpBuffer(q, "OPERATOR %s %s",
13418  amopstrategy, amopopr);
13419 
13420  if (strlen(sortfamily) > 0)
13421  {
13422  appendPQExpBufferStr(q, " FOR ORDER BY ");
13423  appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13424  appendPQExpBufferStr(q, fmtId(sortfamily));
13425  }
13426 
13427  needComma = true;
13428  }
13429 
13430  PQclear(res);
13431 
13432  /*
13433  * Now fetch and print the FUNCTION entries (pg_amproc rows).
13434  *
13435  * Print only those opfamily members that are tied to the opclass by
13436  * pg_depend entries.
13437  *
13438  * We print the amproclefttype/amprocrighttype even though in most cases
13439  * the backend could deduce the right values, because of the corner case
13440  * of a btree sort support function for a cross-type comparison.
13441  */
13442  resetPQExpBuffer(query);
13443 
13444  appendPQExpBuffer(query, "SELECT amprocnum, "
13445  "amproc::pg_catalog.regprocedure, "
13446  "amproclefttype::pg_catalog.regtype, "
13447  "amprocrighttype::pg_catalog.regtype "
13448  "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13449  "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13450  "AND refobjid = '%u'::pg_catalog.oid "
13451  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13452  "AND objid = ap.oid "
13453  "ORDER BY amprocnum",
13454  opcinfo->dobj.catId.oid);
13455 
13456  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13457 
13458  ntups = PQntuples(res);
13459 
13460  i_amprocnum = PQfnumber(res, "amprocnum");
13461  i_amproc = PQfnumber(res, "amproc");
13462  i_amproclefttype = PQfnumber(res, "amproclefttype");
13463  i_amprocrighttype = PQfnumber(res, "amprocrighttype");
13464 
13465  for (i = 0; i < ntups; i++)
13466  {
13467  amprocnum = PQgetvalue(res, i, i_amprocnum);
13468  amproc = PQgetvalue(res, i, i_amproc);
13469  amproclefttype = PQgetvalue(res, i, i_amproclefttype);
13470  amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
13471 
13472  if (needComma)
13473  appendPQExpBufferStr(q, " ,\n ");
13474 
13475  appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
13476 
13477  if (*amproclefttype && *amprocrighttype)
13478  appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13479 
13480  appendPQExpBuffer(q, " %s", amproc);
13481 
13482  needComma = true;
13483  }
13484 
13485  PQclear(res);
13486 
13487  /*
13488  * If needComma is still false it means we haven't added anything after
13489  * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13490  * clause with the same datatype. This isn't sanctioned by the
13491  * documentation, but actually DefineOpClass will treat it as a no-op.
13492  */
13493  if (!needComma)
13494  appendPQExpBuffer(q, "STORAGE %s", opcintype);
13495 
13496  appendPQExpBufferStr(q, ";\n");
13497 
13498  appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13499  appendPQExpBuffer(nameusing, " USING %s",
13500  fmtId(amname));
13501 
13502  if (dopt->binary_upgrade)
13504  "OPERATOR CLASS", nameusing->data,
13505  opcinfo->dobj.namespace->dobj.name);
13506 
13507  if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13508  ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13509  ARCHIVE_OPTS(.tag = opcinfo->dobj.name,
13510  .namespace = opcinfo->dobj.namespace->dobj.name,
13511  .owner = opcinfo->rolname,
13512  .description = "OPERATOR CLASS",
13513  .section = SECTION_PRE_DATA,
13514  .createStmt = q->data,
13515  .dropStmt = delq->data));
13516 
13517  /* Dump Operator Class Comments */
13518  if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13519  dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13520  opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13521  opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13522 
13523  free(opcintype);
13524  free(opcfamily);
13525  free(amname);
13526  destroyPQExpBuffer(query);
13527  destroyPQExpBuffer(q);
13528  destroyPQExpBuffer(delq);
13529  destroyPQExpBuffer(nameusing);
13530 }
13531 
13532 /*
13533  * dumpOpfamily
13534  * write out a single operator family definition
13535  *
13536  * Note: this also dumps any "loose" operator members that aren't bound to a
13537  * specific opclass within the opfamily.
13538  */
13539 static void
13540 dumpOpfamily(Archive *fout, const OpfamilyInfo *opfinfo)
13541 {
13542  DumpOptions *dopt = fout->dopt;
13543  PQExpBuffer query;
13544  PQExpBuffer q;
13545  PQExpBuffer delq;
13546  PQExpBuffer nameusing;
13547  PGresult *res;
13548  PGresult *res_ops;
13549  PGresult *res_procs;
13550  int ntups;
13551  int i_amname;
13552  int i_amopstrategy;
13553  int i_amopopr;
13554  int i_sortfamily;
13555  int i_sortfamilynsp;
13556  int i_amprocnum;
13557  int i_amproc;
13558  int i_amproclefttype;
13559  int i_amprocrighttype;
13560  char *amname;
13561  char *amopstrategy;
13562  char *amopopr;
13563  char *sortfamily;
13564  char *sortfamilynsp;
13565  char *amprocnum;
13566  char *amproc;
13567  char *amproclefttype;
13568  char *amprocrighttype;
13569  bool needComma;
13570  int i;
13571 
13572  /* Do nothing in data-only dump */
13573  if (dopt->dataOnly)
13574  return;
13575 
13576  query = createPQExpBuffer();
13577  q = createPQExpBuffer();
13578  delq = createPQExpBuffer();
13579  nameusing = createPQExpBuffer();
13580 
13581  /*
13582  * Fetch only those opfamily members that are tied directly to the
13583  * opfamily by pg_depend entries.
13584  */
13585  appendPQExpBuffer(query, "SELECT amopstrategy, "
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);
13599 
13600  res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13601 
13602  resetPQExpBuffer(query);
13603 
13604  appendPQExpBuffer(query, "SELECT amprocnum, "
13605  "amproc::pg_catalog.regprocedure, "
13606  "amproclefttype::pg_catalog.regtype, "
13607  "amprocrighttype::pg_catalog.regtype "
13608  "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13609  "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13610  "AND refobjid = '%u'::pg_catalog.oid "
13611  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13612  "AND objid = ap.oid "
13613  "ORDER BY amprocnum",
13614  opfinfo->dobj.catId.oid);
13615 
13616  res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13617 
13618  /* Get additional fields from the pg_opfamily row */
13619  resetPQExpBuffer(query);
13620 
13621  appendPQExpBuffer(query, "SELECT "
13622  "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13623  "FROM pg_catalog.pg_opfamily "
13624  "WHERE oid = '%u'::pg_catalog.oid",
13625  opfinfo->dobj.catId.oid);
13626 
13627  res = ExecuteSqlQueryForSingleRow(fout, query->data);
13628 
13629  i_amname = PQfnumber(res, "amname");
13630 
13631  /* amname will still be needed after we PQclear res */
13632  amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13633 
13634  appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13635  fmtQualifiedDumpable(opfinfo));
13636  appendPQExpBuffer(delq, " USING %s;\n",
13637  fmtId(amname));
13638 
13639  /* Build the fixed portion of the CREATE command */
13640  appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13641  fmtQualifiedDumpable(opfinfo));
13642  appendPQExpBuffer(q, " USING %s;\n",
13643  fmtId(amname));
13644 
13645  PQclear(res);
13646 
13647  /* Do we need an ALTER to add loose members? */
13648  if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13649  {
13650  appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13651  fmtQualifiedDumpable(opfinfo));
13652  appendPQExpBuffer(q, " USING %s ADD\n ",
13653  fmtId(amname));
13654 
13655  needComma = false;
13656 
13657  /*
13658  * Now fetch and print the OPERATOR entries (pg_amop rows).
13659  */
13660  ntups = PQntuples(res_ops);
13661 
13662  i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13663  i_amopopr = PQfnumber(res_ops, "amopopr");
13664  i_sortfamily = PQfnumber(res_ops, "sortfamily");
13665  i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13666 
13667  for (i = 0; i < ntups; i++)
13668  {
13669  amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13670  amopopr = PQgetvalue(res_ops, i, i_amopopr);
13671  sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13672  sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13673 
13674  if (needComma)
13675  appendPQExpBufferStr(q, " ,\n ");
13676 
13677  appendPQExpBuffer(q, "OPERATOR %s %s",
13678  amopstrategy, amopopr);
13679 
13680  if (strlen(sortfamily) > 0)
13681  {
13682  appendPQExpBufferStr(q, " FOR ORDER BY ");
13683  appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13684  appendPQExpBufferStr(q, fmtId(sortfamily));
13685  }
13686 
13687  needComma = true;
13688  }
13689 
13690  /*
13691  * Now fetch and print the FUNCTION entries (pg_amproc rows).
13692  */
13693  ntups = PQntuples(res_procs);
13694 
13695  i_amprocnum = PQfnumber(res_procs, "amprocnum");
13696  i_amproc = PQfnumber(res_procs, "amproc");
13697  i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13698  i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13699 
13700  for (i = 0; i < ntups; i++)
13701  {
13702  amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13703  amproc = PQgetvalue(res_procs, i, i_amproc);
13704  amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13705  amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13706 
13707  if (needComma)
13708  appendPQExpBufferStr(q, " ,\n ");
13709 
13710  appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13711  amprocnum, amproclefttype, amprocrighttype,
13712  amproc);
13713 
13714  needComma = true;
13715  }
13716 
13717  appendPQExpBufferStr(q, ";\n");
13718  }
13719 
13720  appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13721  appendPQExpBuffer(nameusing, " USING %s",
13722  fmtId(amname));
13723 
13724  if (dopt->binary_upgrade)
13726  "OPERATOR FAMILY", nameusing->data,
13727  opfinfo->dobj.namespace->dobj.name);
13728 
13729  if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13730  ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13731  ARCHIVE_OPTS(.tag = opfinfo->dobj.name,
13732  .namespace = opfinfo->dobj.namespace->dobj.name,
13733  .owner = opfinfo->rolname,
13734  .description = "OPERATOR FAMILY",
13735  .section = SECTION_PRE_DATA,
13736  .createStmt = q->data,
13737  .dropStmt = delq->data));
13738 
13739  /* Dump Operator Family Comments */
13740  if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13741  dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13742  opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13743  opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13744 
13745  free(amname);
13746  PQclear(res_ops);
13747  PQclear(res_procs);
13748  destroyPQExpBuffer(query);
13749  destroyPQExpBuffer(q);
13750  destroyPQExpBuffer(delq);
13751  destroyPQExpBuffer(nameusing);
13752 }
13753 
13754 /*
13755  * dumpCollation
13756  * write out a single collation definition
13757  */
13758 static void
13759 dumpCollation(Archive *fout, const CollInfo *collinfo)
13760 {
13761  DumpOptions *dopt = fout->dopt;
13762  PQExpBuffer query;
13763  PQExpBuffer q;
13764  PQExpBuffer delq;
13765  char *qcollname;
13766  PGresult *res;
13767  int i_collprovider;
13768  int i_collisdeterministic;
13769  int i_collcollate;
13770  int i_collctype;
13771  int i_colllocale;
13772  int i_collicurules;
13773  const char *collprovider;
13774  const char *collcollate;
13775  const char *collctype;
13776  const char *colllocale;
13777  const char *collicurules;
13778 
13779  /* Do nothing in data-only dump */
13780  if (dopt->dataOnly)
13781  return;
13782 
13783  query = createPQExpBuffer();
13784  q = createPQExpBuffer();
13785  delq = createPQExpBuffer();
13786 
13787  qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13788 
13789  /* Get collation-specific details */
13790  appendPQExpBufferStr(query, "SELECT ");
13791 
13792  if (fout->remoteVersion >= 100000)
13793  appendPQExpBufferStr(query,
13794  "collprovider, "
13795  "collversion, ");
13796  else
13797  appendPQExpBufferStr(query,
13798  "'c' AS collprovider, "
13799  "NULL AS collversion, ");
13800 
13801  if (fout->remoteVersion >= 120000)
13802  appendPQExpBufferStr(query,
13803  "collisdeterministic, ");
13804  else
13805  appendPQExpBufferStr(query,
13806  "true AS collisdeterministic, ");
13807 
13808  if (fout->remoteVersion >= 170000)
13809  appendPQExpBufferStr(query,
13810  "colllocale, ");
13811  else if (fout->remoteVersion >= 150000)
13812  appendPQExpBufferStr(query,
13813  "colliculocale AS colllocale, ");
13814  else
13815  appendPQExpBufferStr(query,
13816  "NULL AS colllocale, ");
13817 
13818  if (fout->remoteVersion >= 160000)
13819  appendPQExpBufferStr(query,
13820  "collicurules, ");
13821  else
13822  appendPQExpBufferStr(query,
13823  "NULL AS collicurules, ");
13824 
13825  appendPQExpBuffer(query,
13826  "collcollate, "
13827  "collctype "
13828  "FROM pg_catalog.pg_collation c "
13829  "WHERE c.oid = '%u'::pg_catalog.oid",
13830  collinfo->dobj.catId.oid);
13831 
13832  res = ExecuteSqlQueryForSingleRow(fout, query->data);
13833 
13834  i_collprovider = PQfnumber(res, "collprovider");
13835  i_collisdeterministic = PQfnumber(res, "collisdeterministic");
13836  i_collcollate = PQfnumber(res, "collcollate");
13837  i_collctype = PQfnumber(res, "collctype");
13838  i_colllocale = PQfnumber(res, "colllocale");
13839  i_collicurules = PQfnumber(res, "collicurules");
13840 
13841  collprovider = PQgetvalue(res, 0, i_collprovider);
13842 
13843  if (!PQgetisnull(res, 0, i_collcollate))
13844  collcollate = PQgetvalue(res, 0, i_collcollate);
13845  else
13846  collcollate = NULL;
13847 
13848  if (!PQgetisnull(res, 0, i_collctype))
13849  collctype = PQgetvalue(res, 0, i_collctype);
13850  else
13851  collctype = NULL;
13852 
13853  /*
13854  * Before version 15, collcollate and collctype were of type NAME and
13855  * non-nullable. Treat empty strings as NULL for consistency.
13856  */
13857  if (fout->remoteVersion < 150000)
13858  {
13859  if (collcollate[0] == '\0')
13860  collcollate = NULL;
13861  if (collctype[0] == '\0')
13862  collctype = NULL;
13863  }
13864 
13865  if (!PQgetisnull(res, 0, i_colllocale))
13866  colllocale = PQgetvalue(res, 0, i_colllocale);
13867  else
13868  colllocale = NULL;
13869 
13870  if (!PQgetisnull(res, 0, i_collicurules))
13871  collicurules = PQgetvalue(res, 0, i_collicurules);
13872  else
13873  collicurules = NULL;
13874 
13875  appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13876  fmtQualifiedDumpable(collinfo));
13877 
13878  appendPQExpBuffer(q, "CREATE COLLATION %s (",
13879  fmtQualifiedDumpable(collinfo));
13880 
13881  appendPQExpBufferStr(q, "provider = ");
13882  if (collprovider[0] == 'b')
13883  appendPQExpBufferStr(q, "builtin");
13884  else if (collprovider[0] == 'c')
13885  appendPQExpBufferStr(q, "libc");
13886  else if (collprovider[0] == 'i')
13887  appendPQExpBufferStr(q, "icu");
13888  else if (collprovider[0] == 'd')
13889  /* to allow dumping pg_catalog; not accepted on input */
13890  appendPQExpBufferStr(q, "default");
13891  else
13892  pg_fatal("unrecognized collation provider: %s",
13893  collprovider);
13894 
13895  if (strcmp(PQgetvalue(res, 0, i_collisdeterministic), "f") == 0)
13896  appendPQExpBufferStr(q, ", deterministic = false");
13897 
13898  if (collprovider[0] == 'd')
13899  {
13900  if (collcollate || collctype || colllocale || collicurules)
13901  pg_log_warning("invalid collation \"%s\"", qcollname);
13902 
13903  /* no locale -- the default collation cannot be reloaded anyway */
13904  }
13905  else if (collprovider[0] == 'b')
13906  {
13907  if (collcollate || collctype || !colllocale || collicurules)
13908  pg_log_warning("invalid collation \"%s\"", qcollname);
13909 
13910  appendPQExpBufferStr(q, ", locale = ");
13911  appendStringLiteralAH(q, colllocale ? colllocale : "",
13912  fout);
13913  }
13914  else if (collprovider[0] == 'i')
13915  {
13916  if (fout->remoteVersion >= 150000)
13917  {
13918  if (collcollate || collctype || !colllocale)
13919  pg_log_warning("invalid collation \"%s\"", qcollname);
13920 
13921  appendPQExpBufferStr(q, ", locale = ");
13922  appendStringLiteralAH(q, colllocale ? colllocale : "",
13923  fout);
13924  }
13925  else
13926  {
13927  if (!collcollate || !collctype || colllocale ||
13928  strcmp(collcollate, collctype) != 0)
13929  pg_log_warning("invalid collation \"%s\"", qcollname);
13930 
13931  appendPQExpBufferStr(q, ", locale = ");
13932  appendStringLiteralAH(q, collcollate ? collcollate : "", fout);
13933  }
13934 
13935  if (collicurules)
13936  {
13937  appendPQExpBufferStr(q, ", rules = ");
13938  appendStringLiteralAH(q, collicurules ? collicurules : "", fout);
13939  }
13940  }
13941  else if (collprovider[0] == 'c')
13942  {
13943  if (colllocale || collicurules || !collcollate || !collctype)
13944  pg_log_warning("invalid collation \"%s\"", qcollname);
13945 
13946  if (collcollate && collctype && strcmp(collcollate, collctype) == 0)
13947  {
13948  appendPQExpBufferStr(q, ", locale = ");
13949  appendStringLiteralAH(q, collcollate ? collcollate : "", fout);
13950  }
13951  else
13952  {
13953  appendPQExpBufferStr(q, ", lc_collate = ");
13954  appendStringLiteralAH(q, collcollate ? collcollate : "", fout);
13955  appendPQExpBufferStr(q, ", lc_ctype = ");
13956  appendStringLiteralAH(q, collctype ? collctype : "", fout);
13957  }
13958  }
13959  else
13960  pg_fatal("unrecognized collation provider: %s", collprovider);
13961 
13962  /*
13963  * For binary upgrade, carry over the collation version. For normal
13964  * dump/restore, omit the version, so that it is computed upon restore.
13965  */
13966  if (dopt->binary_upgrade)
13967  {
13968  int i_collversion;
13969 
13970  i_collversion = PQfnumber(res, "collversion");
13971  if (!PQgetisnull(res, 0, i_collversion))
13972  {
13973  appendPQExpBufferStr(q, ", version = ");
13975  PQgetvalue(res, 0, i_collversion),
13976  fout);
13977  }
13978  }
13979 
13980  appendPQExpBufferStr(q, ");\n");
13981 
13982  if (dopt->binary_upgrade)
13983  binary_upgrade_extension_member(q, &collinfo->dobj,
13984  "COLLATION", qcollname,
13985  collinfo->dobj.namespace->dobj.name);
13986 
13987  if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13988  ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13989  ARCHIVE_OPTS(.tag = collinfo->dobj.name,
13990  .namespace = collinfo->dobj.namespace->dobj.name,
13991  .owner = collinfo->rolname,
13992  .description = "COLLATION",
13993  .section = SECTION_PRE_DATA,
13994  .createStmt = q->data,
13995  .dropStmt = delq->data));
13996 
13997  /* Dump Collation Comments */
13998  if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13999  dumpComment(fout, "COLLATION", qcollname,
14000  collinfo->dobj.namespace->dobj.name, collinfo->rolname,
14001  collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
14002 
14003  PQclear(res);
14004 
14005  destroyPQExpBuffer(query);
14006  destroyPQExpBuffer(q);
14007  destroyPQExpBuffer(delq);
14008  free(qcollname);
14009 }
14010 
14011 /*
14012  * dumpConversion
14013  * write out a single conversion definition
14014  */
14015 static void
14016 dumpConversion(Archive *fout, const ConvInfo *convinfo)
14017 {
14018  DumpOptions *dopt = fout->dopt;
14019  PQExpBuffer query;
14020  PQExpBuffer q;
14021  PQExpBuffer delq;
14022  char *qconvname;
14023  PGresult *res;
14024  int i_conforencoding;
14025  int i_contoencoding;
14026  int i_conproc;
14027  int i_condefault;
14028  const char *conforencoding;
14029  const char *contoencoding;
14030  const char *conproc;
14031  bool condefault;
14032 
14033  /* Do nothing in data-only dump */
14034  if (dopt->dataOnly)
14035  return;
14036 
14037  query = createPQExpBuffer();
14038  q = createPQExpBuffer();
14039  delq = createPQExpBuffer();
14040 
14041  qconvname = pg_strdup(fmtId(convinfo->dobj.name));
14042 
14043  /* Get conversion-specific details */
14044  appendPQExpBuffer(query, "SELECT "
14045  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
14046  "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
14047  "conproc, condefault "
14048  "FROM pg_catalog.pg_conversion c "
14049  "WHERE c.oid = '%u'::pg_catalog.oid",
14050  convinfo->dobj.catId.oid);
14051 
14052  res = ExecuteSqlQueryForSingleRow(fout, query->data);
14053 
14054  i_conforencoding = PQfnumber(res, "conforencoding");
14055  i_contoencoding = PQfnumber(res, "contoencoding");
14056  i_conproc = PQfnumber(res, "conproc");
14057  i_condefault = PQfnumber(res, "condefault");
14058 
14059  conforencoding = PQgetvalue(res, 0, i_conforencoding);
14060  contoencoding = PQgetvalue(res, 0, i_contoencoding);
14061  conproc = PQgetvalue(res, 0, i_conproc);
14062  condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
14063 
14064  appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
14065  fmtQualifiedDumpable(convinfo));
14066 
14067  appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
14068  (condefault) ? "DEFAULT " : "",
14069  fmtQualifiedDumpable(convinfo));
14070  appendStringLiteralAH(q, conforencoding, fout);
14071  appendPQExpBufferStr(q, " TO ");
14072  appendStringLiteralAH(q, contoencoding, fout);
14073  /* regproc output is already sufficiently quoted */
14074  appendPQExpBuffer(q, " FROM %s;\n", conproc);
14075 
14076  if (dopt->binary_upgrade)
14077  binary_upgrade_extension_member(q, &convinfo->dobj,
14078  "CONVERSION", qconvname,
14079  convinfo->dobj.namespace->dobj.name);
14080 
14081  if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14082  ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
14083  ARCHIVE_OPTS(.tag = convinfo->dobj.name,
14084  .namespace = convinfo->dobj.namespace->dobj.name,
14085  .owner = convinfo->rolname,
14086  .description = "CONVERSION",
14087  .section = SECTION_PRE_DATA,
14088  .createStmt = q->data,
14089  .dropStmt = delq->data));
14090 
14091  /* Dump Conversion Comments */
14092  if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14093  dumpComment(fout, "CONVERSION", qconvname,
14094  convinfo->dobj.namespace->dobj.name, convinfo->rolname,
14095  convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
14096 
14097  PQclear(res);
14098 
14099  destroyPQExpBuffer(query);
14100  destroyPQExpBuffer(q);
14101  destroyPQExpBuffer(delq);
14102  free(qconvname);
14103 }
14104 
14105 /*
14106  * format_aggregate_signature: generate aggregate name and argument list
14107  *
14108  * The argument type names are qualified if needed. The aggregate name
14109  * is never qualified.
14110  */
14111 static char *
14112 format_aggregate_signature(const AggInfo *agginfo, Archive *fout, bool honor_quotes)
14113 {
14115  int j;
14116 
14117  initPQExpBuffer(&buf);
14118  if (honor_quotes)
14119  appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
14120  else
14121  appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
14122 
14123  if (agginfo->aggfn.nargs == 0)
14124  appendPQExpBufferStr(&buf, "(*)");
14125  else
14126  {
14127  appendPQExpBufferChar(&buf, '(');
14128  for (j = 0; j < agginfo->aggfn.nargs; j++)
14129  appendPQExpBuffer(&buf, "%s%s",
14130  (j > 0) ? ", " : "",
14131  getFormattedTypeName(fout,
14132  agginfo->aggfn.argtypes[j],
14133  zeroIsError));
14134  appendPQExpBufferChar(&buf, ')');
14135  }
14136  return buf.data;
14137 }
14138 
14139 /*
14140  * dumpAgg
14141  * write out a single aggregate definition
14142  */
14143 static void
14144 dumpAgg(Archive *fout, const AggInfo *agginfo)
14145 {
14146  DumpOptions *dopt = fout->dopt;
14147  PQExpBuffer query;
14148  PQExpBuffer q;
14149  PQExpBuffer delq;
14150  PQExpBuffer details;
14151  char *aggsig; /* identity signature */
14152  char *aggfullsig = NULL; /* full signature */
14153  char *aggsig_tag;
14154  PGresult *res;
14155  int i_agginitval;
14156  int i_aggminitval;
14157  const char *aggtransfn;
14158  const char *aggfinalfn;
14159  const char *aggcombinefn;
14160  const char *aggserialfn;
14161  const char *aggdeserialfn;
14162  const char *aggmtransfn;
14163  const char *aggminvtransfn;
14164  const char *aggmfinalfn;
14165  bool aggfinalextra;
14166  bool aggmfinalextra;
14167  char aggfinalmodify;
14168  char aggmfinalmodify;
14169  const char *aggsortop;
14170  char *aggsortconvop;
14171  char aggkind;
14172  const char *aggtranstype;
14173  const char *aggtransspace;
14174  const char *aggmtranstype;
14175  const char *aggmtransspace;
14176  const char *agginitval;
14177  const char *aggminitval;
14178  const char *proparallel;
14179  char defaultfinalmodify;
14180 
14181  /* Do nothing in data-only dump */
14182  if (dopt->dataOnly)
14183  return;
14184 
14185  query = createPQExpBuffer();
14186  q = createPQExpBuffer();
14187  delq = createPQExpBuffer();
14188  details = createPQExpBuffer();
14189 
14190  if (!fout->is_prepared[PREPQUERY_DUMPAGG])
14191  {
14192  /* Set up query for aggregate-specific details */
14193  appendPQExpBufferStr(query,
14194  "PREPARE dumpAgg(pg_catalog.oid) AS\n");
14195 
14196  appendPQExpBufferStr(query,
14197  "SELECT "
14198  "aggtransfn,\n"
14199  "aggfinalfn,\n"
14200  "aggtranstype::pg_catalog.regtype,\n"
14201  "agginitval,\n"
14202  "aggsortop,\n"
14203  "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs,\n"
14204  "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs,\n");
14205 
14206  if (fout->remoteVersion >= 90400)
14207  appendPQExpBufferStr(query,
14208  "aggkind,\n"
14209  "aggmtransfn,\n"
14210  "aggminvtransfn,\n"
14211  "aggmfinalfn,\n"
14212  "aggmtranstype::pg_catalog.regtype,\n"
14213  "aggfinalextra,\n"
14214  "aggmfinalextra,\n"
14215  "aggtransspace,\n"
14216  "aggmtransspace,\n"
14217  "aggminitval,\n");
14218  else
14219  appendPQExpBufferStr(query,
14220  "'n' AS aggkind,\n"
14221  "'-' AS aggmtransfn,\n"
14222  "'-' AS aggminvtransfn,\n"
14223  "'-' AS aggmfinalfn,\n"
14224  "0 AS aggmtranstype,\n"
14225  "false AS aggfinalextra,\n"
14226  "false AS aggmfinalextra,\n"
14227  "0 AS aggtransspace,\n"
14228  "0 AS aggmtransspace,\n"
14229  "NULL AS aggminitval,\n");
14230 
14231  if (fout->remoteVersion >= 90600)
14232  appendPQExpBufferStr(query,
14233  "aggcombinefn,\n"
14234  "aggserialfn,\n"
14235  "aggdeserialfn,\n"
14236  "proparallel,\n");
14237  else
14238  appendPQExpBufferStr(query,
14239  "'-' AS aggcombinefn,\n"
14240  "'-' AS aggserialfn,\n"
14241  "'-' AS aggdeserialfn,\n"
14242  "'u' AS proparallel,\n");
14243 
14244  if (fout->remoteVersion >= 110000)
14245  appendPQExpBufferStr(query,
14246  "aggfinalmodify,\n"
14247  "aggmfinalmodify\n");
14248  else
14249  appendPQExpBufferStr(query,
14250  "'0' AS aggfinalmodify,\n"
14251  "'0' AS aggmfinalmodify\n");
14252 
14253  appendPQExpBufferStr(query,
14254  "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14255  "WHERE a.aggfnoid = p.oid "
14256  "AND p.oid = $1");
14257 
14258  ExecuteSqlStatement(fout, query->data);
14259 
14260  fout->is_prepared[PREPQUERY_DUMPAGG] = true;
14261  }
14262 
14263  printfPQExpBuffer(query,
14264  "EXECUTE dumpAgg('%u')",
14265  agginfo->aggfn.dobj.catId.oid);
14266 
14267  res = ExecuteSqlQueryForSingleRow(fout, query->data);
14268 
14269  i_agginitval = PQfnumber(res, "agginitval");
14270  i_aggminitval = PQfnumber(res, "aggminitval");
14271 
14272  aggtransfn = PQgetvalue(res, 0, PQfnumber(res, "aggtransfn"));
14273  aggfinalfn = PQgetvalue(res, 0, PQfnumber(res, "aggfinalfn"));
14274  aggcombinefn = PQgetvalue(res, 0, PQfnumber(res, "aggcombinefn"));
14275  aggserialfn = PQgetvalue(res, 0, PQfnumber(res, "aggserialfn"));
14276  aggdeserialfn = PQgetvalue(res, 0, PQfnumber(res, "aggdeserialfn"));
14277  aggmtransfn = PQgetvalue(res, 0, PQfnumber(res, "aggmtransfn"));
14278  aggminvtransfn = PQgetvalue(res, 0, PQfnumber(res, "aggminvtransfn"));
14279  aggmfinalfn = PQgetvalue(res, 0, PQfnumber(res, "aggmfinalfn"));
14280  aggfinalextra = (PQgetvalue(res, 0, PQfnumber(res, "aggfinalextra"))[0] == 't');
14281  aggmfinalextra = (PQgetvalue(res, 0, PQfnumber(res, "aggmfinalextra"))[0] == 't');
14282  aggfinalmodify = PQgetvalue(res, 0, PQfnumber(res, "aggfinalmodify"))[0];
14283  aggmfinalmodify = PQgetvalue(res, 0, PQfnumber(res, "aggmfinalmodify"))[0];
14284  aggsortop = PQgetvalue(res, 0, PQfnumber(res, "aggsortop"));
14285  aggkind = PQgetvalue(res, 0, PQfnumber(res, "aggkind"))[0];
14286  aggtranstype = PQgetvalue(res, 0, PQfnumber(res, "aggtranstype"));
14287  aggtransspace = PQgetvalue(res, 0, PQfnumber(res, "aggtransspace"));
14288  aggmtranstype = PQgetvalue(res, 0, PQfnumber(res, "aggmtranstype"));
14289  aggmtransspace = PQgetvalue(res, 0, PQfnumber(res, "aggmtransspace"));
14290  agginitval = PQgetvalue(res, 0, i_agginitval);
14291  aggminitval = PQgetvalue(res, 0, i_aggminitval);
14292  proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
14293 
14294  {
14295  char *funcargs;
14296  char *funciargs;
14297 
14298  funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
14299  funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
14300  aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
14301  aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
14302  }
14303 
14304  aggsig_tag = format_aggregate_signature(agginfo, fout, false);
14305 
14306  /* identify default modify flag for aggkind (must match DefineAggregate) */
14307  defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
14308  /* replace omitted flags for old versions */
14309  if (aggfinalmodify == '0')
14310  aggfinalmodify = defaultfinalmodify;
14311  if (aggmfinalmodify == '0')
14312  aggmfinalmodify = defaultfinalmodify;
14313 
14314  /* regproc and regtype output is already sufficiently quoted */
14315  appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
14316  aggtransfn, aggtranstype);
14317 
14318  if (strcmp(aggtransspace, "0") != 0)
14319  {
14320  appendPQExpBuffer(details, ",\n SSPACE = %s",
14321  aggtransspace);
14322  }
14323 
14324  if (!PQgetisnull(res, 0, i_agginitval))
14325  {
14326  appendPQExpBufferStr(details, ",\n INITCOND = ");
14327  appendStringLiteralAH(details, agginitval, fout);
14328  }
14329 
14330  if (strcmp(aggfinalfn, "-") != 0)
14331  {
14332  appendPQExpBuffer(details, ",\n FINALFUNC = %s",
14333  aggfinalfn);
14334  if (aggfinalextra)
14335  appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
14336  if (aggfinalmodify != defaultfinalmodify)
14337  {
14338  switch (aggfinalmodify)
14339  {
14340  case AGGMODIFY_READ_ONLY:
14341  appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
14342  break;
14343  case AGGMODIFY_SHAREABLE:
14344  appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
14345  break;
14346  case AGGMODIFY_READ_WRITE:
14347  appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
14348  break;
14349  default:
14350  pg_fatal("unrecognized aggfinalmodify value for aggregate \"%s\"",
14351  agginfo->aggfn.dobj.name);
14352  break;
14353  }
14354  }
14355  }
14356 
14357  if (strcmp(aggcombinefn, "-") != 0)
14358  appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
14359 
14360  if (strcmp(aggserialfn, "-") != 0)
14361  appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
14362 
14363  if (strcmp(aggdeserialfn, "-") != 0)
14364  appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
14365 
14366  if (strcmp(aggmtransfn, "-") != 0)
14367  {
14368  appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
14369  aggmtransfn,
14370  aggminvtransfn,
14371  aggmtranstype);
14372  }
14373 
14374  if (strcmp(aggmtransspace, "0") != 0)
14375  {
14376  appendPQExpBuffer(details, ",\n MSSPACE = %s",
14377  aggmtransspace);
14378  }
14379 
14380  if (!PQgetisnull(res, 0, i_aggminitval))
14381  {
14382  appendPQExpBufferStr(details, ",\n MINITCOND = ");
14383  appendStringLiteralAH(details, aggminitval, fout);
14384  }
14385 
14386  if (strcmp(aggmfinalfn, "-") != 0)
14387  {
14388  appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
14389  aggmfinalfn);
14390  if (aggmfinalextra)
14391  appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
14392  if (aggmfinalmodify != defaultfinalmodify)
14393  {
14394  switch (aggmfinalmodify)
14395  {
14396  case AGGMODIFY_READ_ONLY:
14397  appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
14398  break;
14399  case AGGMODIFY_SHAREABLE:
14400  appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
14401  break;
14402  case AGGMODIFY_READ_WRITE:
14403  appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
14404  break;
14405  default:
14406  pg_fatal("unrecognized aggmfinalmodify value for aggregate \"%s\"",
14407  agginfo->aggfn.dobj.name);
14408  break;
14409  }
14410  }
14411  }
14412 
14413  aggsortconvop = getFormattedOperatorName(aggsortop);
14414  if (aggsortconvop)
14415  {
14416  appendPQExpBuffer(details, ",\n SORTOP = %s",
14417  aggsortconvop);
14418  free(aggsortconvop);
14419  }
14420 
14421  if (aggkind == AGGKIND_HYPOTHETICAL)
14422  appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
14423 
14424  if (proparallel[0] != PROPARALLEL_UNSAFE)
14425  {
14426  if (proparallel[0] == PROPARALLEL_SAFE)
14427  appendPQExpBufferStr(details, ",\n PARALLEL = safe");
14428  else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14429  appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
14430  else if (proparallel[0] != PROPARALLEL_UNSAFE)
14431  pg_fatal("unrecognized proparallel value for function \"%s\"",
14432  agginfo->aggfn.dobj.name);
14433  }
14434 
14435  appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14436  fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14437  aggsig);
14438 
14439  appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14440  fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14441  aggfullsig ? aggfullsig : aggsig, details->data);
14442 
14443  if (dopt->binary_upgrade)
14444  binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14445  "AGGREGATE", aggsig,
14446  agginfo->aggfn.dobj.namespace->dobj.name);
14447 
14448  if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14449  ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14450  agginfo->aggfn.dobj.dumpId,
14451  ARCHIVE_OPTS(.tag = aggsig_tag,
14452  .namespace = agginfo->aggfn.dobj.namespace->dobj.name,
14453  .owner = agginfo->aggfn.rolname,
14454  .description = "AGGREGATE",
14455  .section = SECTION_PRE_DATA,
14456  .createStmt = q->data,
14457  .dropStmt = delq->data));
14458 
14459  /* Dump Aggregate Comments */
14460  if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14461  dumpComment(fout, "AGGREGATE", aggsig,
14462  agginfo->aggfn.dobj.namespace->dobj.name,
14463  agginfo->aggfn.rolname,
14464  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14465 
14466  if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14467  dumpSecLabel(fout, "AGGREGATE", aggsig,
14468  agginfo->aggfn.dobj.namespace->dobj.name,
14469  agginfo->aggfn.rolname,
14470  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14471 
14472  /*
14473  * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14474  * command look like a function's GRANT; in particular this affects the
14475  * syntax for zero-argument aggregates and ordered-set aggregates.
14476  */
14477  free(aggsig);
14478 
14479  aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14480 
14481  if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14482  dumpACL(fout, agginfo->aggfn.dobj.dumpId, InvalidDumpId,
14483  "FUNCTION", aggsig, NULL,
14484  agginfo->aggfn.dobj.namespace->dobj.name,
14485  agginfo->aggfn.rolname, &agginfo->aggfn.dacl);
14486 
14487  free(aggsig);
14488  free(aggfullsig);
14489  free(aggsig_tag);
14490 
14491  PQclear(res);
14492 
14493  destroyPQExpBuffer(query);
14494  destroyPQExpBuffer(q);
14495  destroyPQExpBuffer(delq);
14496  destroyPQExpBuffer(details);
14497 }
14498 
14499 /*
14500  * dumpTSParser
14501  * write out a single text search parser
14502  */
14503 static void
14504 dumpTSParser(Archive *fout, const TSParserInfo *prsinfo)
14505 {
14506  DumpOptions *dopt = fout->dopt;
14507  PQExpBuffer q;
14508  PQExpBuffer delq;
14509  char *qprsname;
14510 
14511  /* Do nothing in data-only dump */
14512  if (dopt->dataOnly)
14513  return;
14514 
14515  q = createPQExpBuffer();
14516  delq = createPQExpBuffer();
14517 
14518  qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14519 
14520  appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14521  fmtQualifiedDumpable(prsinfo));
14522 
14523  appendPQExpBuffer(q, " START = %s,\n",
14524  convertTSFunction(fout, prsinfo->prsstart));
14525  appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14526  convertTSFunction(fout, prsinfo->prstoken));
14527  appendPQExpBuffer(q, " END = %s,\n",
14528  convertTSFunction(fout, prsinfo->prsend));
14529  if (prsinfo->prsheadline != InvalidOid)
14530  appendPQExpBuffer(q, " HEADLINE = %s,\n",
14531  convertTSFunction(fout, prsinfo->prsheadline));
14532  appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14533  convertTSFunction(fout, prsinfo->prslextype));
14534 
14535  appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14536  fmtQualifiedDumpable(prsinfo));
14537 
14538  if (dopt->binary_upgrade)
14540  "TEXT SEARCH PARSER", qprsname,
14541  prsinfo->dobj.namespace->dobj.name);
14542 
14543  if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14544  ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14545  ARCHIVE_OPTS(.tag = prsinfo->dobj.name,
14546  .namespace = prsinfo->dobj.namespace->dobj.name,
14547  .description = "TEXT SEARCH PARSER",
14548  .section = SECTION_PRE_DATA,
14549  .createStmt = q->data,
14550  .dropStmt = delq->data));
14551 
14552  /* Dump Parser Comments */
14553  if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14554  dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14555  prsinfo->dobj.namespace->dobj.name, "",
14556  prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14557 
14558  destroyPQExpBuffer(q);
14559  destroyPQExpBuffer(delq);
14560  free(qprsname);
14561 }
14562 
14563 /*
14564  * dumpTSDictionary
14565  * write out a single text search dictionary
14566  */
14567 static void
14568 dumpTSDictionary(Archive *fout, const TSDictInfo *dictinfo)
14569 {
14570  DumpOptions *dopt = fout->dopt;
14571  PQExpBuffer q;
14572  PQExpBuffer delq;
14573  PQExpBuffer query;
14574  char *qdictname;
14575  PGresult *res;
14576  char *nspname;
14577  char *tmplname;
14578 
14579  /* Do nothing in data-only dump */
14580  if (dopt->dataOnly)
14581  return;
14582 
14583  q = createPQExpBuffer();
14584  delq = createPQExpBuffer();
14585  query = createPQExpBuffer();
14586 
14587  qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14588 
14589  /* Fetch name and namespace of the dictionary's template */
14590  appendPQExpBuffer(query, "SELECT nspname, tmplname "
14591  "FROM pg_ts_template p, pg_namespace n "
14592  "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14593  dictinfo->dicttemplate);
14594  res = ExecuteSqlQueryForSingleRow(fout, query->data);
14595  nspname = PQgetvalue(res, 0, 0);
14596  tmplname = PQgetvalue(res, 0, 1);
14597 
14598  appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14599  fmtQualifiedDumpable(dictinfo));
14600 
14601  appendPQExpBufferStr(q, " TEMPLATE = ");
14602  appendPQExpBuffer(q, "%s.", fmtId(nspname));
14603  appendPQExpBufferStr(q, fmtId(tmplname));
14604 
14605  PQclear(res);
14606 
14607  /* the dictinitoption can be dumped straight into the command */
14608  if (dictinfo->dictinitoption)
14609  appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14610 
14611  appendPQExpBufferStr(q, " );\n");
14612 
14613  appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14614  fmtQualifiedDumpable(dictinfo));
14615 
14616  if (dopt->binary_upgrade)
14617  binary_upgrade_extension_member(q, &dictinfo->dobj,
14618  "TEXT SEARCH DICTIONARY", qdictname,
14619  dictinfo->dobj.namespace->dobj.name);
14620 
14621  if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14622  ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14623  ARCHIVE_OPTS(.tag = dictinfo->dobj.name,
14624  .namespace = dictinfo->dobj.namespace->dobj.name,
14625  .owner = dictinfo->rolname,
14626  .description = "TEXT SEARCH DICTIONARY",
14627  .section = SECTION_PRE_DATA,
14628  .createStmt = q->data,
14629  .dropStmt = delq->data));
14630 
14631  /* Dump Dictionary Comments */
14632  if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14633  dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14634  dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14635  dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14636 
14637  destroyPQExpBuffer(q);
14638  destroyPQExpBuffer(delq);
14639  destroyPQExpBuffer(query);
14640  free(qdictname);
14641 }
14642 
14643 /*
14644  * dumpTSTemplate
14645  * write out a single text search template
14646  */
14647 static void
14648 dumpTSTemplate(Archive *fout, const TSTemplateInfo *tmplinfo)
14649 {
14650  DumpOptions *dopt = fout->dopt;
14651  PQExpBuffer q;
14652  PQExpBuffer delq;
14653  char *qtmplname;
14654 
14655  /* Do nothing in data-only dump */
14656  if (dopt->dataOnly)
14657  return;
14658 
14659  q = createPQExpBuffer();
14660  delq = createPQExpBuffer();
14661 
14662  qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14663 
14664  appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14665  fmtQualifiedDumpable(tmplinfo));
14666 
14667  if (tmplinfo->tmplinit != InvalidOid)
14668  appendPQExpBuffer(q, " INIT = %s,\n",
14669  convertTSFunction(fout, tmplinfo->tmplinit));
14670  appendPQExpBuffer(q, " LEXIZE = %s );\n",
14671  convertTSFunction(fout, tmplinfo->tmpllexize));
14672 
14673  appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14674  fmtQualifiedDumpable(tmplinfo));
14675 
14676  if (dopt->binary_upgrade)
14677  binary_upgrade_extension_member(q, &tmplinfo->dobj,
14678  "TEXT SEARCH TEMPLATE", qtmplname,
14679  tmplinfo->dobj.namespace->dobj.name);
14680 
14681  if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14682  ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14683  ARCHIVE_OPTS(.tag = tmplinfo->dobj.name,
14684  .namespace = tmplinfo->dobj.namespace->dobj.name,
14685  .description = "TEXT SEARCH TEMPLATE",
14686  .section = SECTION_PRE_DATA,
14687  .createStmt = q->data,
14688  .dropStmt = delq->data));
14689 
14690  /* Dump Template Comments */
14691  if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14692  dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14693  tmplinfo->dobj.namespace->dobj.name, "",
14694  tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14695 
14696  destroyPQExpBuffer(q);
14697  destroyPQExpBuffer(delq);
14698  free(qtmplname);
14699 }
14700 
14701 /*
14702  * dumpTSConfig
14703  * write out a single text search configuration
14704  */
14705 static void
14706 dumpTSConfig(Archive *fout, const TSConfigInfo *cfginfo)
14707 {
14708  DumpOptions *dopt = fout->dopt;
14709  PQExpBuffer q;
14710  PQExpBuffer delq;
14711  PQExpBuffer query;
14712  char *qcfgname;
14713  PGresult *res;
14714  char *nspname;
14715  char *prsname;
14716  int ntups,
14717  i;
14718  int i_tokenname;
14719  int i_dictname;
14720 
14721  /* Do nothing in data-only dump */
14722  if (dopt->dataOnly)
14723  return;
14724 
14725  q = createPQExpBuffer();
14726  delq = createPQExpBuffer();
14727  query = createPQExpBuffer();
14728 
14729  qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14730 
14731  /* Fetch name and namespace of the config's parser */
14732  appendPQExpBuffer(query, "SELECT nspname, prsname "
14733  "FROM pg_ts_parser p, pg_namespace n "
14734  "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14735  cfginfo->cfgparser);
14736  res = ExecuteSqlQueryForSingleRow(fout, query->data);
14737  nspname = PQgetvalue(res, 0, 0);
14738  prsname = PQgetvalue(res, 0, 1);
14739 
14740  appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14741  fmtQualifiedDumpable(cfginfo));
14742 
14743  appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14744  appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14745 
14746  PQclear(res);
14747 
14748  resetPQExpBuffer(query);
14749  appendPQExpBuffer(query,
14750  "SELECT\n"
14751  " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14752  " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14753  " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14754  "FROM pg_catalog.pg_ts_config_map AS m\n"
14755  "WHERE m.mapcfg = '%u'\n"
14756  "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14757  cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14758 
14759  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14760  ntups = PQntuples(res);
14761 
14762  i_tokenname = PQfnumber(res, "tokenname");
14763  i_dictname = PQfnumber(res, "dictname");
14764 
14765  for (i = 0; i < ntups; i++)
14766  {
14767  char *tokenname = PQgetvalue(res, i, i_tokenname);
14768  char *dictname = PQgetvalue(res, i, i_dictname);
14769 
14770  if (i == 0 ||
14771  strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14772  {
14773  /* starting a new token type, so start a new command */
14774  if (i > 0)
14775  appendPQExpBufferStr(q, ";\n");
14776  appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14777  fmtQualifiedDumpable(cfginfo));
14778  /* tokenname needs quoting, dictname does NOT */
14779  appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14780  fmtId(tokenname), dictname);
14781  }
14782  else
14783  appendPQExpBuffer(q, ", %s", dictname);
14784  }
14785 
14786  if (ntups > 0)
14787  appendPQExpBufferStr(q, ";\n");
14788 
14789  PQclear(res);
14790 
14791  appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14792  fmtQualifiedDumpable(cfginfo));
14793 
14794  if (dopt->binary_upgrade)
14796  "TEXT SEARCH CONFIGURATION", qcfgname,
14797  cfginfo->dobj.namespace->dobj.name);
14798 
14799  if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14800  ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14801  ARCHIVE_OPTS(.tag = cfginfo->dobj.name,
14802  .namespace = cfginfo->dobj.namespace->dobj.name,
14803  .owner = cfginfo->rolname,
14804  .description = "TEXT SEARCH CONFIGURATION",
14805  .section = SECTION_PRE_DATA,
14806  .createStmt = q->data,
14807  .dropStmt = delq->data));
14808 
14809  /* Dump Configuration Comments */
14810  if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14811  dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14812  cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14813  cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14814 
14815  destroyPQExpBuffer(q);
14816  destroyPQExpBuffer(delq);
14817  destroyPQExpBuffer(query);
14818  free(qcfgname);
14819 }
14820 
14821 /*
14822  * dumpForeignDataWrapper
14823  * write out a single foreign-data wrapper definition
14824  */
14825 static void
14827 {
14828  DumpOptions *dopt = fout->dopt;
14829  PQExpBuffer q;
14830  PQExpBuffer delq;
14831  char *qfdwname;
14832 
14833  /* Do nothing in data-only dump */
14834  if (dopt->dataOnly)
14835  return;
14836 
14837  q = createPQExpBuffer();
14838  delq = createPQExpBuffer();
14839 
14840  qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14841 
14842  appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14843  qfdwname);
14844 
14845  if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14846  appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14847 
14848  if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14849  appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14850 
14851  if (strlen(fdwinfo->fdwoptions) > 0)
14852  appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14853 
14854  appendPQExpBufferStr(q, ";\n");
14855 
14856  appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14857  qfdwname);
14858 
14859  if (dopt->binary_upgrade)
14861  "FOREIGN DATA WRAPPER", qfdwname,
14862  NULL);
14863 
14864  if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14865  ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14866  ARCHIVE_OPTS(.tag = fdwinfo->dobj.name,
14867  .owner = fdwinfo->rolname,
14868  .description = "FOREIGN DATA WRAPPER",
14869  .section = SECTION_PRE_DATA,
14870  .createStmt = q->data,
14871  .dropStmt = delq->data));
14872 
14873  /* Dump Foreign Data Wrapper Comments */
14874  if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14875  dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14876  NULL, fdwinfo->rolname,
14877  fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14878 
14879  /* Handle the ACL */
14880  if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14881  dumpACL(fout, fdwinfo->dobj.dumpId, InvalidDumpId,
14882  "FOREIGN DATA WRAPPER", qfdwname, NULL,
14883  NULL, fdwinfo->rolname, &fdwinfo->dacl);
14884 
14885  free(qfdwname);
14886 
14887  destroyPQExpBuffer(q);
14888  destroyPQExpBuffer(delq);
14889 }
14890 
14891 /*
14892  * dumpForeignServer
14893  * write out a foreign server definition
14894  */
14895 static void
14897 {
14898  DumpOptions *dopt = fout->dopt;
14899  PQExpBuffer q;
14900  PQExpBuffer delq;
14901  PQExpBuffer query;
14902  PGresult *res;
14903  char *qsrvname;
14904  char *fdwname;
14905 
14906  /* Do nothing in data-only dump */
14907  if (dopt->dataOnly)
14908  return;
14909 
14910  q = createPQExpBuffer();
14911  delq = createPQExpBuffer();
14912  query = createPQExpBuffer();
14913 
14914  qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14915 
14916  /* look up the foreign-data wrapper */
14917  appendPQExpBuffer(query, "SELECT fdwname "
14918  "FROM pg_foreign_data_wrapper w "
14919  "WHERE w.oid = '%u'",
14920  srvinfo->srvfdw);
14921  res = ExecuteSqlQueryForSingleRow(fout, query->data);
14922  fdwname = PQgetvalue(res, 0, 0);
14923 
14924  appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14925  if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14926  {
14927  appendPQExpBufferStr(q, " TYPE ");
14928  appendStringLiteralAH(q, srvinfo->srvtype, fout);
14929  }
14930  if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14931  {
14932  appendPQExpBufferStr(q, " VERSION ");
14933  appendStringLiteralAH(q, srvinfo->srvversion, fout);
14934  }
14935 
14936  appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14937  appendPQExpBufferStr(q, fmtId(fdwname));
14938 
14939  if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14940  appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
14941 
14942  appendPQExpBufferStr(q, ";\n");
14943 
14944  appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14945  qsrvname);
14946 
14947  if (dopt->binary_upgrade)
14949  "SERVER", qsrvname, NULL);
14950 
14951  if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14952  ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14953  ARCHIVE_OPTS(.tag = srvinfo->dobj.name,
14954  .owner = srvinfo->rolname,
14955  .description = "SERVER",
14956  .section = SECTION_PRE_DATA,
14957  .createStmt = q->data,
14958  .dropStmt = delq->data));
14959 
14960  /* Dump Foreign Server Comments */
14961  if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14962  dumpComment(fout, "SERVER", qsrvname,
14963  NULL, srvinfo->rolname,
14964  srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14965 
14966  /* Handle the ACL */
14967  if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14968  dumpACL(fout, srvinfo->dobj.dumpId, InvalidDumpId,
14969  "FOREIGN SERVER", qsrvname, NULL,
14970  NULL, srvinfo->rolname, &srvinfo->dacl);
14971 
14972  /* Dump user mappings */
14973  if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14974  dumpUserMappings(fout,
14975  srvinfo->dobj.name, NULL,
14976  srvinfo->rolname,
14977  srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14978 
14979  PQclear(res);
14980 
14981  free(qsrvname);
14982 
14983  destroyPQExpBuffer(q);
14984  destroyPQExpBuffer(delq);
14985  destroyPQExpBuffer(query);
14986 }
14987 
14988 /*
14989  * dumpUserMappings
14990  *
14991  * This routine is used to dump any user mappings associated with the
14992  * server handed to this routine. Should be called after ArchiveEntry()
14993  * for the server.
14994  */
14995 static void
14997  const char *servername, const char *namespace,
14998  const char *owner,
14999  CatalogId catalogId, DumpId dumpId)
15000 {
15001  PQExpBuffer q;
15002  PQExpBuffer delq;
15003  PQExpBuffer query;
15004  PQExpBuffer tag;
15005  PGresult *res;
15006  int ntups;
15007  int i_usename;
15008  int i_umoptions;
15009  int i;
15010 
15011  q = createPQExpBuffer();
15012  tag = createPQExpBuffer();
15013  delq = createPQExpBuffer();
15014  query = createPQExpBuffer();
15015 
15016  /*
15017  * We read from the publicly accessible view pg_user_mappings, so as not
15018  * to fail if run by a non-superuser. Note that the view will show
15019  * umoptions as null if the user hasn't got privileges for the associated
15020  * server; this means that pg_dump will dump such a mapping, but with no
15021  * OPTIONS clause. A possible alternative is to skip such mappings
15022  * altogether, but it's not clear that that's an improvement.
15023  */
15024  appendPQExpBuffer(query,
15025  "SELECT usename, "
15026  "array_to_string(ARRAY("
15027  "SELECT quote_ident(option_name) || ' ' || "
15028  "quote_literal(option_value) "
15029  "FROM pg_options_to_table(umoptions) "
15030  "ORDER BY option_name"
15031  "), E',\n ') AS umoptions "
15032  "FROM pg_user_mappings "
15033  "WHERE srvid = '%u' "
15034  "ORDER BY usename",
15035  catalogId.oid);
15036 
15037  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15038 
15039  ntups = PQntuples(res);
15040  i_usename = PQfnumber(res, "usename");
15041  i_umoptions = PQfnumber(res, "umoptions");
15042 
15043  for (i = 0; i < ntups; i++)
15044  {
15045  char *usename;
15046  char *umoptions;
15047 
15048  usename = PQgetvalue(res, i, i_usename);
15049  umoptions = PQgetvalue(res, i, i_umoptions);
15050 
15051  resetPQExpBuffer(q);
15052  appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
15053  appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
15054 
15055  if (umoptions && strlen(umoptions) > 0)
15056  appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
15057 
15058  appendPQExpBufferStr(q, ";\n");
15059 
15060  resetPQExpBuffer(delq);
15061  appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
15062  appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
15063 
15064  resetPQExpBuffer(tag);
15065  appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
15066  usename, servername);
15067 
15069  ARCHIVE_OPTS(.tag = tag->data,
15070  .namespace = namespace,
15071  .owner = owner,
15072  .description = "USER MAPPING",
15073  .section = SECTION_PRE_DATA,
15074  .createStmt = q->data,
15075  .dropStmt = delq->data));
15076  }
15077 
15078  PQclear(res);
15079 
15080  destroyPQExpBuffer(query);
15081  destroyPQExpBuffer(delq);
15082  destroyPQExpBuffer(tag);
15083  destroyPQExpBuffer(q);
15084 }
15085 
15086 /*
15087  * Write out default privileges information
15088  */
15089 static void
15090 dumpDefaultACL(Archive *fout, const DefaultACLInfo *daclinfo)
15091 {
15092  DumpOptions *dopt = fout->dopt;
15093  PQExpBuffer q;
15094  PQExpBuffer tag;
15095  const char *type;
15096 
15097  /* Do nothing in data-only dump, or if we're skipping ACLs */
15098  if (dopt->dataOnly || dopt->aclsSkip)
15099  return;
15100 
15101  q = createPQExpBuffer();
15102  tag = createPQExpBuffer();
15103 
15104  switch (daclinfo->defaclobjtype)
15105  {
15106  case DEFACLOBJ_RELATION:
15107  type = "TABLES";
15108  break;
15109  case DEFACLOBJ_SEQUENCE:
15110  type = "SEQUENCES";
15111  break;
15112  case DEFACLOBJ_FUNCTION:
15113  type = "FUNCTIONS";
15114  break;
15115  case DEFACLOBJ_TYPE:
15116  type = "TYPES";
15117  break;
15118  case DEFACLOBJ_NAMESPACE:
15119  type = "SCHEMAS";
15120  break;
15121  default:
15122  /* shouldn't get here */
15123  pg_fatal("unrecognized object type in default privileges: %d",
15124  (int) daclinfo->defaclobjtype);
15125  type = ""; /* keep compiler quiet */
15126  }
15127 
15128  appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
15129 
15130  /* build the actual command(s) for this tuple */
15132  daclinfo->dobj.namespace != NULL ?
15133  daclinfo->dobj.namespace->dobj.name : NULL,
15134  daclinfo->dacl.acl,
15135  daclinfo->dacl.acldefault,
15136  daclinfo->defaclrole,
15137  fout->remoteVersion,
15138  q))
15139  pg_fatal("could not parse default ACL list (%s)",
15140  daclinfo->dacl.acl);
15141 
15142  if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
15143  ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
15144  ARCHIVE_OPTS(.tag = tag->data,
15145  .namespace = daclinfo->dobj.namespace ?
15146  daclinfo->dobj.namespace->dobj.name : NULL,
15147  .owner = daclinfo->defaclrole,
15148  .description = "DEFAULT ACL",
15149  .section = SECTION_POST_DATA,
15150  .createStmt = q->data));
15151 
15152  destroyPQExpBuffer(tag);
15153  destroyPQExpBuffer(q);
15154 }
15155 
15156 /*----------
15157  * Write out grant/revoke information
15158  *
15159  * 'objDumpId' is the dump ID of the underlying object.
15160  * 'altDumpId' can be a second dumpId that the ACL entry must also depend on,
15161  * or InvalidDumpId if there is no need for a second dependency.
15162  * 'type' must be one of
15163  * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
15164  * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
15165  * 'name' is the formatted name of the object. Must be quoted etc. already.
15166  * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
15167  * (Currently we assume that subname is only provided for table columns.)
15168  * 'nspname' is the namespace the object is in (NULL if none).
15169  * 'owner' is the owner, NULL if there is no owner (for languages).
15170  * 'dacl' is the DumpableAcl struct for the object.
15171  *
15172  * Returns the dump ID assigned to the ACL TocEntry, or InvalidDumpId if
15173  * no ACL entry was created.
15174  *----------
15175  */
15176 static DumpId
15177 dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId,
15178  const char *type, const char *name, const char *subname,
15179  const char *nspname, const char *owner,
15180  const DumpableAcl *dacl)
15181 {
15182  DumpId aclDumpId = InvalidDumpId;
15183  DumpOptions *dopt = fout->dopt;
15184  const char *acls = dacl->acl;
15185  const char *acldefault = dacl->acldefault;
15186  char privtype = dacl->privtype;
15187  const char *initprivs = dacl->initprivs;
15188  const char *baseacls;
15189  PQExpBuffer sql;
15190 
15191  /* Do nothing if ACL dump is not enabled */
15192  if (dopt->aclsSkip)
15193  return InvalidDumpId;
15194 
15195  /* --data-only skips ACLs *except* large object ACLs */
15196  if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
15197  return InvalidDumpId;
15198 
15199  sql = createPQExpBuffer();
15200 
15201  /*
15202  * In binary upgrade mode, we don't run an extension's script but instead
15203  * dump out the objects independently and then recreate them. To preserve
15204  * any initial privileges which were set on extension objects, we need to
15205  * compute the set of GRANT and REVOKE commands necessary to get from the
15206  * default privileges of an object to its initial privileges as recorded
15207  * in pg_init_privs.
15208  *
15209  * At restore time, we apply these commands after having called
15210  * binary_upgrade_set_record_init_privs(true). That tells the backend to
15211  * copy the results into pg_init_privs. This is how we preserve the
15212  * contents of that catalog across binary upgrades.
15213  */
15214  if (dopt->binary_upgrade && privtype == 'e' &&
15215  initprivs && *initprivs != '\0')
15216  {
15217  appendPQExpBufferStr(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
15218  if (!buildACLCommands(name, subname, nspname, type,
15219  initprivs, acldefault, owner,
15220  "", fout->remoteVersion, sql))
15221  pg_fatal("could not parse initial ACL list (%s) or default (%s) for object \"%s\" (%s)",
15222  initprivs, acldefault, name, type);
15223  appendPQExpBufferStr(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
15224  }
15225 
15226  /*
15227  * Now figure the GRANT and REVOKE commands needed to get to the object's
15228  * actual current ACL, starting from the initprivs if given, else from the
15229  * object-type-specific default. Also, while buildACLCommands will assume
15230  * that a NULL/empty acls string means it needn't do anything, what that
15231  * actually represents is the object-type-specific default; so we need to
15232  * substitute the acldefault string to get the right results in that case.
15233  */
15234  if (initprivs && *initprivs != '\0')
15235  {
15236  baseacls = initprivs;
15237  if (acls == NULL || *acls == '\0')
15238  acls = acldefault;
15239  }
15240  else
15241  baseacls = acldefault;
15242 
15243  if (!buildACLCommands(name, subname, nspname, type,
15244  acls, baseacls, owner,
15245  "", fout->remoteVersion, sql))
15246  pg_fatal("could not parse ACL list (%s) or default (%s) for object \"%s\" (%s)",
15247  acls, baseacls, name, type);
15248 
15249  if (sql->len > 0)
15250  {
15252  DumpId aclDeps[2];
15253  int nDeps = 0;
15254 
15255  if (subname)
15256  appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
15257  else
15258  appendPQExpBuffer(tag, "%s %s", type, name);
15259 
15260  aclDeps[nDeps++] = objDumpId;
15261  if (altDumpId != InvalidDumpId)
15262  aclDeps[nDeps++] = altDumpId;
15263 
15264  aclDumpId = createDumpId();
15265 
15266  ArchiveEntry(fout, nilCatalogId, aclDumpId,
15267  ARCHIVE_OPTS(.tag = tag->data,
15268  .namespace = nspname,
15269  .owner = owner,
15270  .description = "ACL",
15271  .section = SECTION_NONE,
15272  .createStmt = sql->data,
15273  .deps = aclDeps,
15274  .nDeps = nDeps));
15275 
15276  destroyPQExpBuffer(tag);
15277  }
15278 
15279  destroyPQExpBuffer(sql);
15280 
15281  return aclDumpId;
15282 }
15283 
15284 /*
15285  * dumpSecLabel
15286  *
15287  * This routine is used to dump any security labels associated with the
15288  * object handed to this routine. The routine takes the object type
15289  * and object name (ready to print, except for schema decoration), plus
15290  * the namespace and owner of the object (for labeling the ArchiveEntry),
15291  * plus catalog ID and subid which are the lookup key for pg_seclabel,
15292  * plus the dump ID for the object (for setting a dependency).
15293  * If a matching pg_seclabel entry is found, it is dumped.
15294  *
15295  * Note: although this routine takes a dumpId for dependency purposes,
15296  * that purpose is just to mark the dependency in the emitted dump file
15297  * for possible future use by pg_restore. We do NOT use it for determining
15298  * ordering of the label in the dump file, because this routine is called
15299  * after dependency sorting occurs. This routine should be called just after
15300  * calling ArchiveEntry() for the specified object.
15301  */
15302 static void
15303 dumpSecLabel(Archive *fout, const char *type, const char *name,
15304  const char *namespace, const char *owner,
15305  CatalogId catalogId, int subid, DumpId dumpId)
15306 {
15307  DumpOptions *dopt = fout->dopt;
15308  SecLabelItem *labels;
15309  int nlabels;
15310  int i;
15311  PQExpBuffer query;
15312 
15313  /* do nothing, if --no-security-labels is supplied */
15314  if (dopt->no_security_labels)
15315  return;
15316 
15317  /*
15318  * Security labels are schema not data ... except large object labels are
15319  * data
15320  */
15321  if (strcmp(type, "LARGE OBJECT") != 0)
15322  {
15323  if (dopt->dataOnly)
15324  return;
15325  }
15326  else
15327  {
15328  /* We do dump large object security labels in binary-upgrade mode */
15329  if (dopt->schemaOnly && !dopt->binary_upgrade)
15330  return;
15331  }
15332 
15333  /* Search for security labels associated with catalogId, using table */
15334  nlabels = findSecLabels(catalogId.tableoid, catalogId.oid, &labels);
15335 
15336  query = createPQExpBuffer();
15337 
15338  for (i = 0; i < nlabels; i++)
15339  {
15340  /*
15341  * Ignore label entries for which the subid doesn't match.
15342  */
15343  if (labels[i].objsubid != subid)
15344  continue;
15345 
15346  appendPQExpBuffer(query,
15347  "SECURITY LABEL FOR %s ON %s ",
15348  fmtId(labels[i].provider), type);
15349  if (namespace && *namespace)
15350  appendPQExpBuffer(query, "%s.", fmtId(namespace));
15351  appendPQExpBuffer(query, "%s IS ", name);
15352  appendStringLiteralAH(query, labels[i].label, fout);
15353  appendPQExpBufferStr(query, ";\n");
15354  }
15355 
15356  if (query->len > 0)
15357  {
15359 
15360  appendPQExpBuffer(tag, "%s %s", type, name);
15362  ARCHIVE_OPTS(.tag = tag->data,
15363  .namespace = namespace,
15364  .owner = owner,
15365  .description = "SECURITY LABEL",
15366  .section = SECTION_NONE,
15367  .createStmt = query->data,
15368  .deps = &dumpId,
15369  .nDeps = 1));
15370  destroyPQExpBuffer(tag);
15371  }
15372 
15373  destroyPQExpBuffer(query);
15374 }
15375 
15376 /*
15377  * dumpTableSecLabel
15378  *
15379  * As above, but dump security label for both the specified table (or view)
15380  * and its columns.
15381  */
15382 static void
15383 dumpTableSecLabel(Archive *fout, const TableInfo *tbinfo, const char *reltypename)
15384 {
15385  DumpOptions *dopt = fout->dopt;
15386  SecLabelItem *labels;
15387  int nlabels;
15388  int i;
15389  PQExpBuffer query;
15390  PQExpBuffer target;
15391 
15392  /* do nothing, if --no-security-labels is supplied */
15393  if (dopt->no_security_labels)
15394  return;
15395 
15396  /* SecLabel are SCHEMA not data */
15397  if (dopt->dataOnly)
15398  return;
15399 
15400  /* Search for comments associated with relation, using table */
15401  nlabels = findSecLabels(tbinfo->dobj.catId.tableoid,
15402  tbinfo->dobj.catId.oid,
15403  &labels);
15404 
15405  /* If security labels exist, build SECURITY LABEL statements */
15406  if (nlabels <= 0)
15407  return;
15408 
15409  query = createPQExpBuffer();
15410  target = createPQExpBuffer();
15411 
15412  for (i = 0; i < nlabels; i++)
15413  {
15414  const char *colname;
15415  const char *provider = labels[i].provider;
15416  const char *label = labels[i].label;
15417  int objsubid = labels[i].objsubid;
15418 
15419  resetPQExpBuffer(target);
15420  if (objsubid == 0)
15421  {
15422  appendPQExpBuffer(target, "%s %s", reltypename,
15423  fmtQualifiedDumpable(tbinfo));
15424  }
15425  else
15426  {
15427  colname = getAttrName(objsubid, tbinfo);
15428  /* first fmtXXX result must be consumed before calling again */
15429  appendPQExpBuffer(target, "COLUMN %s",
15430  fmtQualifiedDumpable(tbinfo));
15431  appendPQExpBuffer(target, ".%s", fmtId(colname));
15432  }
15433  appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
15434  fmtId(provider), target->data);
15435  appendStringLiteralAH(query, label, fout);
15436  appendPQExpBufferStr(query, ";\n");
15437  }
15438  if (query->len > 0)
15439  {
15440  resetPQExpBuffer(target);
15441  appendPQExpBuffer(target, "%s %s", reltypename,
15442  fmtId(tbinfo->dobj.name));
15444  ARCHIVE_OPTS(.tag = target->data,
15445  .namespace = tbinfo->dobj.namespace->dobj.name,
15446  .owner = tbinfo->rolname,
15447  .description = "SECURITY LABEL",
15448  .section = SECTION_NONE,
15449  .createStmt = query->data,
15450  .deps = &(tbinfo->dobj.dumpId),
15451  .nDeps = 1));
15452  }
15453  destroyPQExpBuffer(query);
15454  destroyPQExpBuffer(target);
15455 }
15456 
15457 /*
15458  * findSecLabels
15459  *
15460  * Find the security label(s), if any, associated with the given object.
15461  * All the objsubid values associated with the given classoid/objoid are
15462  * found with one search.
15463  */
15464 static int
15465 findSecLabels(Oid classoid, Oid objoid, SecLabelItem **items)
15466 {
15467  SecLabelItem *middle = NULL;
15468  SecLabelItem *low;
15469  SecLabelItem *high;
15470  int nmatch;
15471 
15472  if (nseclabels <= 0) /* no labels, so no match is possible */
15473  {
15474  *items = NULL;
15475  return 0;
15476  }
15477 
15478  /*
15479  * Do binary search to find some item matching the object.
15480  */
15481  low = &seclabels[0];
15482  high = &seclabels[nseclabels - 1];
15483  while (low <= high)
15484  {
15485  middle = low + (high - low) / 2;
15486 
15487  if (classoid < middle->classoid)
15488  high = middle - 1;
15489  else if (classoid > middle->classoid)
15490  low = middle + 1;
15491  else if (objoid < middle->objoid)
15492  high = middle - 1;
15493  else if (objoid > middle->objoid)
15494  low = middle + 1;
15495  else
15496  break; /* found a match */
15497  }
15498 
15499  if (low > high) /* no matches */
15500  {
15501  *items = NULL;
15502  return 0;
15503  }
15504 
15505  /*
15506  * Now determine how many items match the object. The search loop
15507  * invariant still holds: only items between low and high inclusive could
15508  * match.
15509  */
15510  nmatch = 1;
15511  while (middle > low)
15512  {
15513  if (classoid != middle[-1].classoid ||
15514  objoid != middle[-1].objoid)
15515  break;
15516  middle--;
15517  nmatch++;
15518  }
15519 
15520  *items = middle;
15521 
15522  middle += nmatch;
15523  while (middle <= high)
15524  {
15525  if (classoid != middle->classoid ||
15526  objoid != middle->objoid)
15527  break;
15528  middle++;
15529  nmatch++;
15530  }
15531 
15532  return nmatch;
15533 }
15534 
15535 /*
15536  * collectSecLabels
15537  *
15538  * Construct a table of all security labels available for database objects;
15539  * also set the has-seclabel component flag for each relevant object.
15540  *
15541  * The table is sorted by classoid/objid/objsubid for speed in lookup.
15542  */
15543 static void
15545 {
15546  PGresult *res;
15547  PQExpBuffer query;
15548  int i_label;
15549  int i_provider;
15550  int i_classoid;
15551  int i_objoid;
15552  int i_objsubid;
15553  int ntups;
15554  int i;
15555  DumpableObject *dobj;
15556 
15557  query = createPQExpBuffer();
15558 
15559  appendPQExpBufferStr(query,
15560  "SELECT label, provider, classoid, objoid, objsubid "
15561  "FROM pg_catalog.pg_seclabel "
15562  "ORDER BY classoid, objoid, objsubid");
15563 
15564  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15565 
15566  /* Construct lookup table containing OIDs in numeric form */
15567  i_label = PQfnumber(res, "label");
15568  i_provider = PQfnumber(res, "provider");
15569  i_classoid = PQfnumber(res, "classoid");
15570  i_objoid = PQfnumber(res, "objoid");
15571  i_objsubid = PQfnumber(res, "objsubid");
15572 
15573  ntups = PQntuples(res);
15574 
15575  seclabels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15576  nseclabels = 0;
15577  dobj = NULL;
15578 
15579  for (i = 0; i < ntups; i++)
15580  {
15581  CatalogId objId;
15582  int subid;
15583 
15584  objId.tableoid = atooid(PQgetvalue(res, i, i_classoid));
15585  objId.oid = atooid(PQgetvalue(res, i, i_objoid));
15586  subid = atoi(PQgetvalue(res, i, i_objsubid));
15587 
15588  /* We needn't remember labels that don't match any dumpable object */
15589  if (dobj == NULL ||
15590  dobj->catId.tableoid != objId.tableoid ||
15591  dobj->catId.oid != objId.oid)
15592  dobj = findObjectByCatalogId(objId);
15593  if (dobj == NULL)
15594  continue;
15595 
15596  /*
15597  * Labels on columns of composite types are linked to the type's
15598  * pg_class entry, but we need to set the DUMP_COMPONENT_SECLABEL flag
15599  * in the type's own DumpableObject.
15600  */
15601  if (subid != 0 && dobj->objType == DO_TABLE &&
15602  ((TableInfo *) dobj)->relkind == RELKIND_COMPOSITE_TYPE)
15603  {
15604  TypeInfo *cTypeInfo;
15605 
15606  cTypeInfo = findTypeByOid(((TableInfo *) dobj)->reltype);
15607  if (cTypeInfo)
15608  cTypeInfo->dobj.components |= DUMP_COMPONENT_SECLABEL;
15609  }
15610  else
15611  dobj->components |= DUMP_COMPONENT_SECLABEL;
15612 
15616  seclabels[nseclabels].objoid = objId.oid;
15617  seclabels[nseclabels].objsubid = subid;
15618  nseclabels++;
15619  }
15620 
15621  PQclear(res);
15622  destroyPQExpBuffer(query);
15623 }
15624 
15625 /*
15626  * dumpTable
15627  * write out to fout the declarations (not data) of a user-defined table
15628  */
15629 static void
15630 dumpTable(Archive *fout, const TableInfo *tbinfo)
15631 {
15632  DumpOptions *dopt = fout->dopt;
15633  DumpId tableAclDumpId = InvalidDumpId;
15634  char *namecopy;
15635 
15636  /* Do nothing in data-only dump */
15637  if (dopt->dataOnly)
15638  return;
15639 
15640  if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15641  {
15642  if (tbinfo->relkind == RELKIND_SEQUENCE)
15643  dumpSequence(fout, tbinfo);
15644  else
15645  dumpTableSchema(fout, tbinfo);
15646  }
15647 
15648  /* Handle the ACL here */
15649  namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15650  if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15651  {
15652  const char *objtype =
15653  (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15654 
15655  tableAclDumpId =
15656  dumpACL(fout, tbinfo->dobj.dumpId, InvalidDumpId,
15657  objtype, namecopy, NULL,
15658  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15659  &tbinfo->dacl);
15660  }
15661 
15662  /*
15663  * Handle column ACLs, if any. Note: we pull these with a separate query
15664  * rather than trying to fetch them during getTableAttrs, so that we won't
15665  * miss ACLs on system columns. Doing it this way also allows us to dump
15666  * ACLs for catalogs that we didn't mark "interesting" back in getTables.
15667  */
15668  if ((tbinfo->dobj.dump & DUMP_COMPONENT_ACL) && tbinfo->hascolumnACLs)
15669  {
15670  PQExpBuffer query = createPQExpBuffer();
15671  PGresult *res;
15672  int i;
15673 
15675  {
15676  /* Set up query for column ACLs */
15677  appendPQExpBufferStr(query,
15678  "PREPARE getColumnACLs(pg_catalog.oid) AS\n");
15679 
15680  if (fout->remoteVersion >= 90600)
15681  {
15682  /*
15683  * In principle we should call acldefault('c', relowner) to
15684  * get the default ACL for a column. However, we don't
15685  * currently store the numeric OID of the relowner in
15686  * TableInfo. We could convert the owner name using regrole,
15687  * but that creates a risk of failure due to concurrent role
15688  * renames. Given that the default ACL for columns is empty
15689  * and is likely to stay that way, it's not worth extra cycles
15690  * and risk to avoid hard-wiring that knowledge here.
15691  */
15692  appendPQExpBufferStr(query,
15693  "SELECT at.attname, "
15694  "at.attacl, "
15695  "'{}' AS acldefault, "
15696  "pip.privtype, pip.initprivs "
15697  "FROM pg_catalog.pg_attribute at "
15698  "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15699  "(at.attrelid = pip.objoid "
15700  "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15701  "AND at.attnum = pip.objsubid) "
15702  "WHERE at.attrelid = $1 AND "
15703  "NOT at.attisdropped "
15704  "AND (at.attacl IS NOT NULL OR pip.initprivs IS NOT NULL) "
15705  "ORDER BY at.attnum");
15706  }
15707  else
15708  {
15709  appendPQExpBufferStr(query,
15710  "SELECT attname, attacl, '{}' AS acldefault, "
15711  "NULL AS privtype, NULL AS initprivs "
15712  "FROM pg_catalog.pg_attribute "
15713  "WHERE attrelid = $1 AND NOT attisdropped "
15714  "AND attacl IS NOT NULL "
15715  "ORDER BY attnum");
15716  }
15717 
15718  ExecuteSqlStatement(fout, query->data);
15719 
15720  fout->is_prepared[PREPQUERY_GETCOLUMNACLS] = true;
15721  }
15722 
15723  printfPQExpBuffer(query,
15724  "EXECUTE getColumnACLs('%u')",
15725  tbinfo->dobj.catId.oid);
15726 
15727  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15728 
15729  for (i = 0; i < PQntuples(res); i++)
15730  {
15731  char *attname = PQgetvalue(res, i, 0);
15732  char *attacl = PQgetvalue(res, i, 1);
15733  char *acldefault = PQgetvalue(res, i, 2);
15734  char privtype = *(PQgetvalue(res, i, 3));
15735  char *initprivs = PQgetvalue(res, i, 4);
15736  DumpableAcl coldacl;
15737  char *attnamecopy;
15738 
15739  coldacl.acl = attacl;
15740  coldacl.acldefault = acldefault;
15741  coldacl.privtype = privtype;
15742  coldacl.initprivs = initprivs;
15743  attnamecopy = pg_strdup(fmtId(attname));
15744 
15745  /*
15746  * Column's GRANT type is always TABLE. Each column ACL depends
15747  * on the table-level ACL, since we can restore column ACLs in
15748  * parallel but the table-level ACL has to be done first.
15749  */
15750  dumpACL(fout, tbinfo->dobj.dumpId, tableAclDumpId,
15751  "TABLE", namecopy, attnamecopy,
15752  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15753  &coldacl);
15754  free(attnamecopy);
15755  }
15756  PQclear(res);
15757  destroyPQExpBuffer(query);
15758  }
15759 
15760  free(namecopy);
15761 }
15762 
15763 /*
15764  * Create the AS clause for a view or materialized view. The semicolon is
15765  * stripped because a materialized view must add a WITH NO DATA clause.
15766  *
15767  * This returns a new buffer which must be freed by the caller.
15768  */
15769 static PQExpBuffer
15770 createViewAsClause(Archive *fout, const TableInfo *tbinfo)
15771 {
15772  PQExpBuffer query = createPQExpBuffer();
15773  PQExpBuffer result = createPQExpBuffer();
15774  PGresult *res;
15775  int len;
15776 
15777  /* Fetch the view definition */
15778  appendPQExpBuffer(query,
15779  "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15780  tbinfo->dobj.catId.oid);
15781 
15782  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15783 
15784  if (PQntuples(res) != 1)
15785  {
15786  if (PQntuples(res) < 1)
15787  pg_fatal("query to obtain definition of view \"%s\" returned no data",
15788  tbinfo->dobj.name);
15789  else
15790  pg_fatal("query to obtain definition of view \"%s\" returned more than one definition",
15791  tbinfo->dobj.name);
15792  }
15793 
15794  len = PQgetlength(res, 0, 0);
15795 
15796  if (len == 0)
15797  pg_fatal("definition of view \"%s\" appears to be empty (length zero)",
15798  tbinfo->dobj.name);
15799 
15800  /* Strip off the trailing semicolon so that other things may follow. */
15801  Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15802  appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15803 
15804  PQclear(res);
15805  destroyPQExpBuffer(query);
15806 
15807  return result;
15808 }
15809 
15810 /*
15811  * Create a dummy AS clause for a view. This is used when the real view
15812  * definition has to be postponed because of circular dependencies.
15813  * We must duplicate the view's external properties -- column names and types
15814  * (including collation) -- so that it works for subsequent references.
15815  *
15816  * This returns a new buffer which must be freed by the caller.
15817  */
15818 static PQExpBuffer
15820 {
15821  PQExpBuffer result = createPQExpBuffer();
15822  int j;
15823 
15824  appendPQExpBufferStr(result, "SELECT");
15825 
15826  for (j = 0; j < tbinfo->numatts; j++)
15827  {
15828  if (j > 0)
15829  appendPQExpBufferChar(result, ',');
15830  appendPQExpBufferStr(result, "\n ");
15831 
15832  appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15833 
15834  /*
15835  * Must add collation if not default for the type, because CREATE OR
15836  * REPLACE VIEW won't change it
15837  */
15838  if (OidIsValid(tbinfo->attcollation[j]))
15839  {
15840  CollInfo *coll;
15841 
15842  coll = findCollationByOid(tbinfo->attcollation[j]);
15843  if (coll)
15844  appendPQExpBuffer(result, " COLLATE %s",
15845  fmtQualifiedDumpable(coll));
15846  }
15847 
15848  appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15849  }
15850 
15851  return result;
15852 }
15853 
15854 /*
15855  * dumpTableSchema
15856  * write the declaration (not data) of one user-defined table or view
15857  */
15858 static void
15859 dumpTableSchema(Archive *fout, const TableInfo *tbinfo)
15860 {
15861  DumpOptions *dopt = fout->dopt;
15863  PQExpBuffer delq = createPQExpBuffer();
15864  char *qrelname;
15865  char *qualrelname;
15866  int numParents;
15867  TableInfo **parents;
15868  int actual_atts; /* number of attrs in this CREATE statement */
15869  const char *reltypename;
15870  char *storage;
15871  int j,
15872  k;
15873 
15874  /* We had better have loaded per-column details about this table */
15875  Assert(tbinfo->interesting);
15876 
15877  qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15878  qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15879 
15880  if (tbinfo->hasoids)
15881  pg_log_warning("WITH OIDS is not supported anymore (table \"%s\")",
15882  qrelname);
15883 
15884  if (dopt->binary_upgrade)
15885  binary_upgrade_set_type_oids_by_rel(fout, q, tbinfo);
15886 
15887  /* Is it a table or a view? */
15888  if (tbinfo->relkind == RELKIND_VIEW)
15889  {
15890  PQExpBuffer result;
15891 
15892  /*
15893  * Note: keep this code in sync with the is_view case in dumpRule()
15894  */
15895 
15896  reltypename = "VIEW";
15897 
15898  appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15899 
15900  if (dopt->binary_upgrade)
15902  tbinfo->dobj.catId.oid, false);
15903 
15904  appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15905 
15906  if (tbinfo->dummy_view)
15907  result = createDummyViewAsClause(fout, tbinfo);
15908  else
15909  {
15910  if (nonemptyReloptions(tbinfo->reloptions))
15911  {
15912  appendPQExpBufferStr(q, " WITH (");
15913  appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15914  appendPQExpBufferChar(q, ')');
15915  }
15916  result = createViewAsClause(fout, tbinfo);
15917  }
15918  appendPQExpBuffer(q, " AS\n%s", result->data);
15919  destroyPQExpBuffer(result);
15920 
15921  if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15922  appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15923  appendPQExpBufferStr(q, ";\n");
15924  }
15925  else
15926  {
15927  char *partkeydef = NULL;
15928  char *ftoptions = NULL;
15929  char *srvname = NULL;
15930  char *foreign = "";
15931 
15932  /*
15933  * Set reltypename, and collect any relkind-specific data that we
15934  * didn't fetch during getTables().
15935  */
15936  switch (tbinfo->relkind)
15937  {
15938  case RELKIND_PARTITIONED_TABLE:
15939  {
15940  PQExpBuffer query = createPQExpBuffer();
15941  PGresult *res;
15942 
15943  reltypename = "TABLE";
15944 
15945  /* retrieve partition key definition */
15946  appendPQExpBuffer(query,
15947  "SELECT pg_get_partkeydef('%u')",
15948  tbinfo->dobj.catId.oid);
15949  res = ExecuteSqlQueryForSingleRow(fout, query->data);
15950  partkeydef = pg_strdup(PQgetvalue(res, 0, 0));
15951  PQclear(res);
15952  destroyPQExpBuffer(query);
15953  break;
15954  }
15955  case RELKIND_FOREIGN_TABLE:
15956  {
15957  PQExpBuffer query = createPQExpBuffer();
15958  PGresult *res;
15959  int i_srvname;
15960  int i_ftoptions;
15961 
15962  reltypename = "FOREIGN TABLE";
15963 
15964  /* retrieve name of foreign server and generic options */
15965  appendPQExpBuffer(query,
15966  "SELECT fs.srvname, "
15967  "pg_catalog.array_to_string(ARRAY("
15968  "SELECT pg_catalog.quote_ident(option_name) || "
15969  "' ' || pg_catalog.quote_literal(option_value) "
15970  "FROM pg_catalog.pg_options_to_table(ftoptions) "
15971  "ORDER BY option_name"
15972  "), E',\n ') AS ftoptions "
15973  "FROM pg_catalog.pg_foreign_table ft "
15974  "JOIN pg_catalog.pg_foreign_server fs "
15975  "ON (fs.oid = ft.ftserver) "
15976  "WHERE ft.ftrelid = '%u'",
15977  tbinfo->dobj.catId.oid);
15978  res = ExecuteSqlQueryForSingleRow(fout, query->data);
15979  i_srvname = PQfnumber(res, "srvname");
15980  i_ftoptions = PQfnumber(res, "ftoptions");
15981  srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15982  ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15983  PQclear(res);
15984  destroyPQExpBuffer(query);
15985 
15986  foreign = "FOREIGN ";
15987  break;
15988  }
15989  case RELKIND_MATVIEW:
15990  reltypename = "MATERIALIZED VIEW";
15991  break;
15992  default:
15993  reltypename = "TABLE";
15994  break;
15995  }
15996 
15997  numParents = tbinfo->numParents;
15998  parents = tbinfo->parents;
15999 
16000  appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
16001 
16002  if (dopt->binary_upgrade)
16004  tbinfo->dobj.catId.oid, false);
16005 
16006  appendPQExpBuffer(q, "CREATE %s%s %s",
16007  tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
16008  "UNLOGGED " : "",
16009  reltypename,
16010  qualrelname);
16011 
16012  /*
16013  * Attach to type, if reloftype; except in case of a binary upgrade,
16014  * we dump the table normally and attach it to the type afterward.
16015  */
16016  if (OidIsValid(tbinfo->reloftype) && !dopt->binary_upgrade)
16017  appendPQExpBuffer(q, " OF %s",
16018  getFormattedTypeName(fout, tbinfo->reloftype,
16019  zeroIsError));
16020 
16021  if (tbinfo->relkind != RELKIND_MATVIEW)
16022  {
16023  /* Dump the attributes */
16024  actual_atts = 0;
16025  for (j = 0; j < tbinfo->numatts; j++)
16026  {
16027  /*
16028  * Normally, dump if it's locally defined in this table, and
16029  * not dropped. But for binary upgrade, we'll dump all the
16030  * columns, and then fix up the dropped and nonlocal cases
16031  * below.
16032  */
16033  if (shouldPrintColumn(dopt, tbinfo, j))
16034  {
16035  bool print_default;
16036  bool print_notnull;
16037 
16038  /*
16039  * Default value --- suppress if to be printed separately
16040  * or not at all.
16041  */
16042  print_default = (tbinfo->attrdefs[j] != NULL &&
16043  tbinfo->attrdefs[j]->dobj.dump &&
16044  !tbinfo->attrdefs[j]->separate);
16045 
16046  /*
16047  * Not Null constraint --- suppress unless it is locally
16048  * defined, except if partition, or in binary-upgrade case
16049  * where that won't work.
16050  */
16051  print_notnull =
16052  (tbinfo->notnull_constrs[j] != NULL &&
16053  (!tbinfo->notnull_inh[j] || tbinfo->ispartition ||
16054  dopt->binary_upgrade));
16055 
16056  /*
16057  * Skip column if fully defined by reloftype, except in
16058  * binary upgrade
16059  */
16060  if (OidIsValid(tbinfo->reloftype) &&
16061  !print_default && !print_notnull &&
16062  !dopt->binary_upgrade)
16063  continue;
16064 
16065  /* Format properly if not first attr */
16066  if (actual_atts == 0)
16067  appendPQExpBufferStr(q, " (");
16068  else
16069  appendPQExpBufferChar(q, ',');
16070  appendPQExpBufferStr(q, "\n ");
16071  actual_atts++;
16072 
16073  /* Attribute name */
16074  appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
16075 
16076  if (tbinfo->attisdropped[j])
16077  {
16078  /*
16079  * ALTER TABLE DROP COLUMN clears
16080  * pg_attribute.atttypid, so we will not have gotten a
16081  * valid type name; insert INTEGER as a stopgap. We'll
16082  * clean things up later.
16083  */
16084  appendPQExpBufferStr(q, " INTEGER /* dummy */");
16085  /* and skip to the next column */
16086  continue;
16087  }
16088 
16089  /*
16090  * Attribute type; print it except when creating a typed
16091  * table ('OF type_name'), but in binary-upgrade mode,
16092  * print it in that case too.
16093  */
16094  if (dopt->binary_upgrade || !OidIsValid(tbinfo->reloftype))
16095  {
16096  appendPQExpBuffer(q, " %s",
16097  tbinfo->atttypnames[j]);
16098  }
16099 
16100  if (print_default)
16101  {
16102  if (tbinfo->attgenerated[j] == ATTRIBUTE_GENERATED_STORED)
16103  appendPQExpBuffer(q, " GENERATED ALWAYS AS (%s) STORED",
16104  tbinfo->attrdefs[j]->adef_expr);
16105  else
16106  appendPQExpBuffer(q, " DEFAULT %s",
16107  tbinfo->attrdefs[j]->adef_expr);
16108  }
16109 
16110 
16111  if (print_notnull)
16112  {
16113  if (tbinfo->notnull_constrs[j][0] == '\0')
16114  appendPQExpBufferStr(q, " NOT NULL");
16115  else
16116  appendPQExpBuffer(q, " CONSTRAINT %s NOT NULL",
16117  fmtId(tbinfo->notnull_constrs[j]));
16118 
16119  if (tbinfo->notnull_noinh[j])
16120  appendPQExpBufferStr(q, " NO INHERIT");
16121  }
16122 
16123  /* Add collation if not default for the type */
16124  if (OidIsValid(tbinfo->attcollation[j]))
16125  {
16126  CollInfo *coll;
16127 
16128  coll = findCollationByOid(tbinfo->attcollation[j]);
16129  if (coll)
16130  appendPQExpBuffer(q, " COLLATE %s",
16131  fmtQualifiedDumpable(coll));
16132  }
16133  }
16134  }
16135 
16136  /*
16137  * Add non-inherited CHECK constraints, if any.
16138  *
16139  * For partitions, we need to include check constraints even if
16140  * they're not defined locally, because the ALTER TABLE ATTACH
16141  * PARTITION that we'll emit later expects the constraint to be
16142  * there. (No need to fix conislocal: ATTACH PARTITION does that)
16143  */
16144  for (j = 0; j < tbinfo->ncheck; j++)
16145  {
16146  ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16147 
16148  if (constr->separate ||
16149  (!constr->conislocal && !tbinfo->ispartition))
16150  continue;
16151 
16152  if (actual_atts == 0)
16153  appendPQExpBufferStr(q, " (\n ");
16154  else
16155  appendPQExpBufferStr(q, ",\n ");
16156 
16157  appendPQExpBuffer(q, "CONSTRAINT %s ",
16158  fmtId(constr->dobj.name));
16159  appendPQExpBufferStr(q, constr->condef);
16160 
16161  actual_atts++;
16162  }
16163 
16164  if (actual_atts)
16165  appendPQExpBufferStr(q, "\n)");
16166  else if (!(OidIsValid(tbinfo->reloftype) && !dopt->binary_upgrade))
16167  {
16168  /*
16169  * No attributes? we must have a parenthesized attribute list,
16170  * even though empty, when not using the OF TYPE syntax.
16171  */
16172  appendPQExpBufferStr(q, " (\n)");
16173  }
16174 
16175  /*
16176  * Emit the INHERITS clause (not for partitions), except in
16177  * binary-upgrade mode.
16178  */
16179  if (numParents > 0 && !tbinfo->ispartition &&
16180  !dopt->binary_upgrade)
16181  {
16182  appendPQExpBufferStr(q, "\nINHERITS (");
16183  for (k = 0; k < numParents; k++)
16184  {
16185  TableInfo *parentRel = parents[k];
16186 
16187  if (k > 0)
16188  appendPQExpBufferStr(q, ", ");
16190  }
16191  appendPQExpBufferChar(q, ')');
16192  }
16193 
16194  if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
16195  appendPQExpBuffer(q, "\nPARTITION BY %s", partkeydef);
16196 
16197  if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
16198  appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
16199  }
16200 
16201  if (nonemptyReloptions(tbinfo->reloptions) ||
16203  {
16204  bool addcomma = false;
16205 
16206  appendPQExpBufferStr(q, "\nWITH (");
16207  if (nonemptyReloptions(tbinfo->reloptions))
16208  {
16209  addcomma = true;
16210  appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
16211  }
16212  if (nonemptyReloptions(tbinfo->toast_reloptions))
16213  {
16214  if (addcomma)
16215  appendPQExpBufferStr(q, ", ");
16216  appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
16217  fout);
16218  }
16219  appendPQExpBufferChar(q, ')');
16220  }
16221 
16222  /* Dump generic options if any */
16223  if (ftoptions && ftoptions[0])
16224  appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
16225 
16226  /*
16227  * For materialized views, create the AS clause just like a view. At
16228  * this point, we always mark the view as not populated.
16229  */
16230  if (tbinfo->relkind == RELKIND_MATVIEW)
16231  {
16232  PQExpBuffer result;
16233 
16234  result = createViewAsClause(fout, tbinfo);
16235  appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
16236  result->data);
16237  destroyPQExpBuffer(result);
16238  }
16239  else
16240  appendPQExpBufferStr(q, ";\n");
16241 
16242  /* Materialized views can depend on extensions */
16243  if (tbinfo->relkind == RELKIND_MATVIEW)
16244  append_depends_on_extension(fout, q, &tbinfo->dobj,
16245  "pg_catalog.pg_class",
16246  "MATERIALIZED VIEW",
16247  qualrelname);
16248 
16249  /*
16250  * in binary upgrade mode, update the catalog with any missing values
16251  * that might be present.
16252  */
16253  if (dopt->binary_upgrade)
16254  {
16255  for (j = 0; j < tbinfo->numatts; j++)
16256  {
16257  if (tbinfo->attmissingval[j][0] != '\0')
16258  {
16259  appendPQExpBufferStr(q, "\n-- set missing value.\n");
16261  "SELECT pg_catalog.binary_upgrade_set_missing_value(");
16262  appendStringLiteralAH(q, qualrelname, fout);
16263  appendPQExpBufferStr(q, "::pg_catalog.regclass,");
16264  appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16265  appendPQExpBufferChar(q, ',');
16266  appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
16267  appendPQExpBufferStr(q, ");\n\n");
16268  }
16269  }
16270  }
16271 
16272  /*
16273  * To create binary-compatible heap files, we have to ensure the same
16274  * physical column order, including dropped columns, as in the
16275  * original. Therefore, we create dropped columns above and drop them
16276  * here, also updating their attlen/attalign values so that the
16277  * dropped column can be skipped properly. (We do not bother with
16278  * restoring the original attbyval setting.) Also, inheritance
16279  * relationships are set up by doing ALTER TABLE INHERIT rather than
16280  * using an INHERITS clause --- the latter would possibly mess up the
16281  * column order. That also means we have to take care about setting
16282  * attislocal correctly, plus fix up any inherited CHECK constraints.
16283  * Analogously, we set up typed tables using ALTER TABLE / OF here.
16284  *
16285  * We process foreign and partitioned tables here, even though they
16286  * lack heap storage, because they can participate in inheritance
16287  * relationships and we want this stuff to be consistent across the
16288  * inheritance tree. We can exclude indexes, toast tables, sequences
16289  * and matviews, even though they have storage, because we don't
16290  * support altering or dropping columns in them, nor can they be part
16291  * of inheritance trees.
16292  */
16293  if (dopt->binary_upgrade &&
16294  (tbinfo->relkind == RELKIND_RELATION ||
16295  tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
16296  tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
16297  {
16298  for (j = 0; j < tbinfo->numatts; j++)
16299  {
16300  if (tbinfo->attisdropped[j])
16301  {
16302  appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
16303  appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
16304  "SET attlen = %d, "
16305  "attalign = '%c', attbyval = false\n"
16306  "WHERE attname = ",
16307  tbinfo->attlen[j],
16308  tbinfo->attalign[j]);
16309  appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16310  appendPQExpBufferStr(q, "\n AND attrelid = ");
16311  appendStringLiteralAH(q, qualrelname, fout);
16312  appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16313 
16314  if (tbinfo->relkind == RELKIND_RELATION ||
16315  tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
16316  appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16317  qualrelname);
16318  else
16319  appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
16320  qualrelname);
16321  appendPQExpBuffer(q, "DROP COLUMN %s;\n",
16322  fmtId(tbinfo->attnames[j]));
16323  }
16324  else if (!tbinfo->attislocal[j])
16325  {
16326  appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
16327  appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
16328  "SET attislocal = false\n"
16329  "WHERE attname = ");
16330  appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16331  appendPQExpBufferStr(q, "\n AND attrelid = ");
16332  appendStringLiteralAH(q, qualrelname, fout);
16333  appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16334 
16335  /*
16336  * If a not-null constraint comes from inheritance, reset
16337  * conislocal. The inhcount is fixed later.
16338  */
16339  if (tbinfo->notnull_constrs[j] != NULL &&
16340  !tbinfo->notnull_throwaway[j] &&
16341  tbinfo->notnull_inh[j] &&
16342  !tbinfo->ispartition)
16343  {
16344  appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
16345  "SET conislocal = false\n"
16346  "WHERE contype = 'n' AND conrelid = ");
16347  appendStringLiteralAH(q, qualrelname, fout);
16348  appendPQExpBufferStr(q, "::pg_catalog.regclass AND\n"
16349  "conname = ");
16350  appendStringLiteralAH(q, tbinfo->notnull_constrs[j], fout);
16351  appendPQExpBufferStr(q, ";\n");
16352  }
16353  }
16354  }
16355 
16356  /*
16357  * Add inherited CHECK constraints, if any.
16358  *
16359  * For partitions, they were already dumped, and conislocal
16360  * doesn't need fixing.
16361  */
16362  for (k = 0; k < tbinfo->ncheck; k++)
16363  {
16364  ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
16365 
16366  if (constr->separate || constr->conislocal || tbinfo->ispartition)
16367  continue;
16368 
16369  appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
16370  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ADD CONSTRAINT %s %s;\n",
16371  foreign, qualrelname,
16372  fmtId(constr->dobj.name),
16373  constr->condef);
16374  appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
16375  "SET conislocal = false\n"
16376  "WHERE contype = 'c' AND conname = ");
16377  appendStringLiteralAH(q, constr->dobj.name, fout);
16378  appendPQExpBufferStr(q, "\n AND conrelid = ");
16379  appendStringLiteralAH(q, qualrelname, fout);
16380  appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16381  }
16382 
16383  if (numParents > 0 && !tbinfo->ispartition)
16384  {
16385  appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance this way.\n");
16386  for (k = 0; k < numParents; k++)
16387  {
16388  TableInfo *parentRel = parents[k];
16389 
16390  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s INHERIT %s;\n", foreign,
16391  qualrelname,
16392  fmtQualifiedDumpable(parentRel));
16393  }
16394  }
16395 
16396  if (OidIsValid(tbinfo->reloftype))
16397  {
16398  appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
16399  appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
16400  qualrelname,
16401  getFormattedTypeName(fout, tbinfo->reloftype,
16402  zeroIsError));
16403  }
16404  }
16405 
16406  /*
16407  * In binary_upgrade mode, arrange to restore the old relfrozenxid and
16408  * relminmxid of all vacuumable relations. (While vacuum.c processes
16409  * TOAST tables semi-independently, here we see them only as children
16410  * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
16411  * child toast table is handled below.)
16412  */
16413  if (dopt->binary_upgrade &&
16414  (tbinfo->relkind == RELKIND_RELATION ||
16415  tbinfo->relkind == RELKIND_MATVIEW))
16416  {
16417  appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
16418  appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16419  "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16420  "WHERE oid = ",
16421  tbinfo->frozenxid, tbinfo->minmxid);
16422  appendStringLiteralAH(q, qualrelname, fout);
16423  appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16424 
16425  if (tbinfo->toast_oid)
16426  {
16427  /*
16428  * The toast table will have the same OID at restore, so we
16429  * can safely target it by OID.
16430  */
16431  appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
16432  appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16433  "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16434  "WHERE oid = '%u';\n",
16435  tbinfo->toast_frozenxid,
16436  tbinfo->toast_minmxid, tbinfo->toast_oid);
16437  }
16438  }
16439 
16440  /*
16441  * In binary_upgrade mode, restore matviews' populated status by
16442  * poking pg_class directly. This is pretty ugly, but we can't use
16443  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
16444  * matview is not populated even though this matview is; in any case,
16445  * we want to transfer the matview's heap storage, not run REFRESH.
16446  */
16447  if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
16448  tbinfo->relispopulated)
16449  {
16450  appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
16451  appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
16452  "SET relispopulated = 't'\n"
16453  "WHERE oid = ");
16454  appendStringLiteralAH(q, qualrelname, fout);
16455  appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16456  }
16457 
16458  /*
16459  * Dump additional per-column properties that we can't handle in the
16460  * main CREATE TABLE command.
16461  */
16462  for (j = 0; j < tbinfo->numatts; j++)
16463  {
16464  /* None of this applies to dropped columns */
16465  if (tbinfo->attisdropped[j])
16466  continue;
16467 
16468  /*
16469  * If we didn't dump the column definition explicitly above, and
16470  * it is not-null and did not inherit that property from a parent,
16471  * we have to mark it separately.
16472  */
16473  if (!shouldPrintColumn(dopt, tbinfo, j) &&
16474  tbinfo->notnull_constrs[j] != NULL &&
16475  (!tbinfo->notnull_inh[j] && !tbinfo->ispartition && !dopt->binary_upgrade))
16476  {
16477  /* No constraint name desired? */
16478  if (tbinfo->notnull_constrs[j][0] == '\0')
16480  "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET NOT NULL;\n",
16481  foreign, qualrelname,
16482  fmtId(tbinfo->attnames[j]));
16483  else
16485  "ALTER %sTABLE ONLY %s ADD CONSTRAINT %s NOT NULL %s;\n",
16486  foreign, qualrelname,
16487  tbinfo->notnull_constrs[j],
16488  fmtId(tbinfo->attnames[j]));
16489  }
16490 
16491  /*
16492  * Dump per-column statistics information. We only issue an ALTER
16493  * TABLE statement if the attstattarget entry for this column is
16494  * not the default value.
16495  */
16496  if (tbinfo->attstattarget[j] >= 0)
16497  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET STATISTICS %d;\n",
16498  foreign, qualrelname,
16499  fmtId(tbinfo->attnames[j]),
16500  tbinfo->attstattarget[j]);
16501 
16502  /*
16503  * Dump per-column storage information. The statement is only
16504  * dumped if the storage has been changed from the type's default.
16505  */
16506  if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
16507  {
16508  switch (tbinfo->attstorage[j])
16509  {
16510  case TYPSTORAGE_PLAIN:
16511  storage = "PLAIN";
16512  break;
16513  case TYPSTORAGE_EXTERNAL:
16514  storage = "EXTERNAL";
16515  break;
16516  case TYPSTORAGE_EXTENDED:
16517  storage = "EXTENDED";
16518  break;
16519  case TYPSTORAGE_MAIN:
16520  storage = "MAIN";
16521  break;
16522  default:
16523  storage = NULL;
16524  }
16525 
16526  /*
16527  * Only dump the statement if it's a storage type we recognize
16528  */
16529  if (storage != NULL)
16530  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET STORAGE %s;\n",
16531  foreign, qualrelname,
16532  fmtId(tbinfo->attnames[j]),
16533  storage);
16534  }
16535 
16536  /*
16537  * Dump per-column compression, if it's been set.
16538  */
16539  if (!dopt->no_toast_compression)
16540  {
16541  const char *cmname;
16542 
16543  switch (tbinfo->attcompression[j])
16544  {
16545  case 'p':
16546  cmname = "pglz";
16547  break;
16548  case 'l':
16549  cmname = "lz4";
16550  break;
16551  default:
16552  cmname = NULL;
16553  break;
16554  }
16555 
16556  if (cmname != NULL)
16557  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET COMPRESSION %s;\n",
16558  foreign, qualrelname,
16559  fmtId(tbinfo->attnames[j]),
16560  cmname);
16561  }
16562 
16563  /*
16564  * Dump per-column attributes.
16565  */
16566  if (tbinfo->attoptions[j][0] != '\0')
16567  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET (%s);\n",
16568  foreign, qualrelname,
16569  fmtId(tbinfo->attnames[j]),
16570  tbinfo->attoptions[j]);
16571 
16572  /*
16573  * Dump per-column fdw options.
16574  */
16575  if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16576  tbinfo->attfdwoptions[j][0] != '\0')
16578  "ALTER FOREIGN TABLE %s ALTER COLUMN %s OPTIONS (\n"
16579  " %s\n"
16580  ");\n",
16581  qualrelname,
16582  fmtId(tbinfo->attnames[j]),
16583  tbinfo->attfdwoptions[j]);
16584  } /* end loop over columns */
16585 
16586  free(partkeydef);
16587  free(ftoptions);
16588  free(srvname);
16589  }
16590 
16591  /*
16592  * dump properties we only have ALTER TABLE syntax for
16593  */
16594  if ((tbinfo->relkind == RELKIND_RELATION ||
16595  tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16596  tbinfo->relkind == RELKIND_MATVIEW) &&
16597  tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16598  {
16599  if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16600  {
16601  /* nothing to do, will be set when the index is dumped */
16602  }
16603  else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16604  {
16605  appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16606  qualrelname);
16607  }
16608  else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16609  {
16610  appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16611  qualrelname);
16612  }
16613  }
16614 
16615  if (tbinfo->forcerowsec)
16616  appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16617  qualrelname);
16618 
16619  if (dopt->binary_upgrade)
16621  reltypename, qrelname,
16622  tbinfo->dobj.namespace->dobj.name);
16623 
16624  if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16625  {
16626  char *tablespace = NULL;
16627  char *tableam = NULL;
16628 
16629  /*
16630  * _selectTablespace() relies on tablespace-enabled objects in the
16631  * default tablespace to have a tablespace of "" (empty string) versus
16632  * non-tablespace-enabled objects to have a tablespace of NULL.
16633  * getTables() sets tbinfo->reltablespace to "" for the default
16634  * tablespace (not NULL).
16635  */
16636  if (RELKIND_HAS_TABLESPACE(tbinfo->relkind))
16637  tablespace = tbinfo->reltablespace;
16638 
16639  if (RELKIND_HAS_TABLE_AM(tbinfo->relkind))
16640  tableam = tbinfo->amname;
16641 
16642  ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16643  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
16644  .namespace = tbinfo->dobj.namespace->dobj.name,
16645  .tablespace = tablespace,
16646  .tableam = tableam,
16647  .owner = tbinfo->rolname,
16648  .description = reltypename,
16649  .section = tbinfo->postponed_def ?
16651  .createStmt = q->data,
16652  .dropStmt = delq->data));
16653  }
16654 
16655  /* Dump Table Comments */
16656  if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16657  dumpTableComment(fout, tbinfo, reltypename);
16658 
16659  /* Dump Table Security Labels */
16660  if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16661  dumpTableSecLabel(fout, tbinfo, reltypename);
16662 
16663  /* Dump comments on inlined table constraints */
16664  for (j = 0; j < tbinfo->ncheck; j++)
16665  {
16666  ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16667 
16668  if (constr->separate || !constr->conislocal)
16669  continue;
16670 
16671  if (constr->dobj.dump & DUMP_COMPONENT_COMMENT)
16672  dumpTableConstraintComment(fout, constr);
16673  }
16674 
16675  destroyPQExpBuffer(q);
16676  destroyPQExpBuffer(delq);
16677  free(qrelname);
16678  free(qualrelname);
16679 }
16680 
16681 /*
16682  * dumpTableAttach
16683  * write to fout the commands to attach a child partition
16684  *
16685  * Child partitions are always made by creating them separately
16686  * and then using ATTACH PARTITION, rather than using
16687  * CREATE TABLE ... PARTITION OF. This is important for preserving
16688  * any possible discrepancy in column layout, to allow assigning the
16689  * correct tablespace if different, and so that it's possible to restore
16690  * a partition without restoring its parent. (You'll get an error from
16691  * the ATTACH PARTITION command, but that can be ignored, or skipped
16692  * using "pg_restore -L" if you prefer.) The last point motivates
16693  * treating ATTACH PARTITION as a completely separate ArchiveEntry
16694  * rather than emitting it within the child partition's ArchiveEntry.
16695  */
16696 static void
16697 dumpTableAttach(Archive *fout, const TableAttachInfo *attachinfo)
16698 {
16699  DumpOptions *dopt = fout->dopt;
16700  PQExpBuffer q;
16701  PGresult *res;
16702  char *partbound;
16703 
16704  /* Do nothing in data-only dump */
16705  if (dopt->dataOnly)
16706  return;
16707 
16708  q = createPQExpBuffer();
16709 
16711  {
16712  /* Set up query for partbound details */
16714  "PREPARE dumpTableAttach(pg_catalog.oid) AS\n");
16715 
16717  "SELECT pg_get_expr(c.relpartbound, c.oid) "
16718  "FROM pg_class c "
16719  "WHERE c.oid = $1");
16720 
16721  ExecuteSqlStatement(fout, q->data);
16722 
16723  fout->is_prepared[PREPQUERY_DUMPTABLEATTACH] = true;
16724  }
16725 
16727  "EXECUTE dumpTableAttach('%u')",
16728  attachinfo->partitionTbl->dobj.catId.oid);
16729 
16730  res = ExecuteSqlQueryForSingleRow(fout, q->data);
16731  partbound = PQgetvalue(res, 0, 0);
16732 
16733  /* Perform ALTER TABLE on the parent */
16735  "ALTER TABLE ONLY %s ",
16736  fmtQualifiedDumpable(attachinfo->parentTbl));
16738  "ATTACH PARTITION %s %s;\n",
16739  fmtQualifiedDumpable(attachinfo->partitionTbl),
16740  partbound);
16741 
16742  /*
16743  * There is no point in creating a drop query as the drop is done by table
16744  * drop. (If you think to change this, see also _printTocEntry().)
16745  * Although this object doesn't really have ownership as such, set the
16746  * owner field anyway to ensure that the command is run by the correct
16747  * role at restore time.
16748  */
16749  ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16750  ARCHIVE_OPTS(.tag = attachinfo->dobj.name,
16751  .namespace = attachinfo->dobj.namespace->dobj.name,
16752  .owner = attachinfo->partitionTbl->rolname,
16753  .description = "TABLE ATTACH",
16754  .section = SECTION_PRE_DATA,
16755  .createStmt = q->data));
16756 
16757  PQclear(res);
16758  destroyPQExpBuffer(q);
16759 }
16760 
16761 /*
16762  * dumpAttrDef --- dump an attribute's default-value declaration
16763  */
16764 static void
16765 dumpAttrDef(Archive *fout, const AttrDefInfo *adinfo)
16766 {
16767  DumpOptions *dopt = fout->dopt;
16768  TableInfo *tbinfo = adinfo->adtable;
16769  int adnum = adinfo->adnum;
16770  PQExpBuffer q;
16771  PQExpBuffer delq;
16772  char *qualrelname;
16773  char *tag;
16774  char *foreign;
16775 
16776  /* Do nothing in data-only dump */
16777  if (dopt->dataOnly)
16778  return;
16779 
16780  /* Skip if not "separate"; it was dumped in the table's definition */
16781  if (!adinfo->separate)
16782  return;
16783 
16784  q = createPQExpBuffer();
16785  delq = createPQExpBuffer();
16786 
16787  qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16788 
16789  foreign = tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "";
16790 
16792  "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET DEFAULT %s;\n",
16793  foreign, qualrelname, fmtId(tbinfo->attnames[adnum - 1]),
16794  adinfo->adef_expr);
16795 
16796  appendPQExpBuffer(delq, "ALTER %sTABLE %s ALTER COLUMN %s DROP DEFAULT;\n",
16797  foreign, qualrelname,
16798  fmtId(tbinfo->attnames[adnum - 1]));
16799 
16800  tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16801 
16802  if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16803  ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16804  ARCHIVE_OPTS(.tag = tag,
16805  .namespace = tbinfo->dobj.namespace->dobj.name,
16806  .owner = tbinfo->rolname,
16807  .description = "DEFAULT",
16808  .section = SECTION_PRE_DATA,
16809  .createStmt = q->data,
16810  .dropStmt = delq->data));
16811 
16812  free(tag);
16813  destroyPQExpBuffer(q);
16814  destroyPQExpBuffer(delq);
16815  free(qualrelname);
16816 }
16817 
16818 /*
16819  * getAttrName: extract the correct name for an attribute
16820  *
16821  * The array tblInfo->attnames[] only provides names of user attributes;
16822  * if a system attribute number is supplied, we have to fake it.
16823  * We also do a little bit of bounds checking for safety's sake.
16824  */
16825 static const char *
16826 getAttrName(int attrnum, const TableInfo *tblInfo)
16827 {
16828  if (attrnum > 0 && attrnum <= tblInfo->numatts)
16829  return tblInfo->attnames[attrnum - 1];
16830  switch (attrnum)
16831  {
16833  return "ctid";
16835  return "xmin";
16837  return "cmin";
16839  return "xmax";
16841  return "cmax";
16843  return "tableoid";
16844  }
16845  pg_fatal("invalid column number %d for table \"%s\"",
16846  attrnum, tblInfo->dobj.name);
16847  return NULL; /* keep compiler quiet */
16848 }
16849 
16850 /*
16851  * dumpIndex
16852  * write out to fout a user-defined index
16853  */
16854 static void
16855 dumpIndex(Archive *fout, const IndxInfo *indxinfo)
16856 {
16857  DumpOptions *dopt = fout->dopt;
16858  TableInfo *tbinfo = indxinfo->indextable;
16859  bool is_constraint = (indxinfo->indexconstraint != 0);
16860  PQExpBuffer q;
16861  PQExpBuffer delq;
16862  char *qindxname;
16863  char *qqindxname;
16864 
16865  /* Do nothing in data-only dump */
16866  if (dopt->dataOnly)
16867  return;
16868 
16869  q = createPQExpBuffer();
16870  delq = createPQExpBuffer();
16871 
16872  qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16873  qqindxname = pg_strdup(fmtQualifiedDumpable(indxinfo));
16874 
16875  /*
16876  * If there's an associated constraint, don't dump the index per se, but
16877  * do dump any comment for it. (This is safe because dependency ordering
16878  * will have ensured the constraint is emitted first.) Note that the
16879  * emitted comment has to be shown as depending on the constraint, not the
16880  * index, in such cases.
16881  */
16882  if (!is_constraint)
16883  {
16884  char *indstatcols = indxinfo->indstatcols;
16885  char *indstatvals = indxinfo->indstatvals;
16886  char **indstatcolsarray = NULL;
16887  char **indstatvalsarray = NULL;
16888  int nstatcols = 0;
16889  int nstatvals = 0;
16890 
16891  if (dopt->binary_upgrade)
16893  indxinfo->dobj.catId.oid, true);
16894 
16895  /* Plain secondary index */
16896  appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16897 
16898  /*
16899  * Append ALTER TABLE commands as needed to set properties that we
16900  * only have ALTER TABLE syntax for. Keep this in sync with the
16901  * similar code in dumpConstraint!
16902  */
16903 
16904  /* If the index is clustered, we need to record that. */
16905  if (indxinfo->indisclustered)
16906  {
16907  appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16908  fmtQualifiedDumpable(tbinfo));
16909  /* index name is not qualified in this syntax */
16910  appendPQExpBuffer(q, " ON %s;\n",
16911  qindxname);
16912  }
16913 
16914  /*
16915  * If the index has any statistics on some of its columns, generate
16916  * the associated ALTER INDEX queries.
16917  */
16918  if (strlen(indstatcols) != 0 || strlen(indstatvals) != 0)
16919  {
16920  int j;
16921 
16922  if (!parsePGArray(indstatcols, &indstatcolsarray, &nstatcols))
16923  pg_fatal("could not parse index statistic columns");
16924  if (!parsePGArray(indstatvals, &indstatvalsarray, &nstatvals))
16925  pg_fatal("could not parse index statistic values");
16926  if (nstatcols != nstatvals)
16927  pg_fatal("mismatched number of columns and values for index statistics");
16928 
16929  for (j = 0; j < nstatcols; j++)
16930  {
16931  appendPQExpBuffer(q, "ALTER INDEX %s ", qqindxname);
16932 
16933  /*
16934  * Note that this is a column number, so no quotes should be
16935  * used.
16936  */
16937  appendPQExpBuffer(q, "ALTER COLUMN %s ",
16938  indstatcolsarray[j]);
16939  appendPQExpBuffer(q, "SET STATISTICS %s;\n",
16940  indstatvalsarray[j]);
16941  }
16942  }
16943 
16944  /* Indexes can depend on extensions */
16945  append_depends_on_extension(fout, q, &indxinfo->dobj,
16946  "pg_catalog.pg_class",
16947  "INDEX", qqindxname);
16948 
16949  /* If the index defines identity, we need to record that. */
16950  if (indxinfo->indisreplident)
16951  {
16952  appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16953  fmtQualifiedDumpable(tbinfo));
16954  /* index name is not qualified in this syntax */
16955  appendPQExpBuffer(q, " INDEX %s;\n",
16956  qindxname);
16957  }
16958 
16959  appendPQExpBuffer(delq, "DROP INDEX %s;\n", qqindxname);
16960 
16961  if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16962  ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16963  ARCHIVE_OPTS(.tag = indxinfo->dobj.name,
16964  .namespace = tbinfo->dobj.namespace->dobj.name,
16965  .tablespace = indxinfo->tablespace,
16966  .owner = tbinfo->rolname,
16967  .description = "INDEX",
16968  .section = SECTION_POST_DATA,
16969  .createStmt = q->data,
16970  .dropStmt = delq->data));
16971 
16972  free(indstatcolsarray);
16973  free(indstatvalsarray);
16974  }
16975 
16976  /* Dump Index Comments */
16977  if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16978  dumpComment(fout, "INDEX", qindxname,
16979  tbinfo->dobj.namespace->dobj.name,
16980  tbinfo->rolname,
16981  indxinfo->dobj.catId, 0,
16982  is_constraint ? indxinfo->indexconstraint :
16983  indxinfo->dobj.dumpId);
16984 
16985  destroyPQExpBuffer(q);
16986  destroyPQExpBuffer(delq);
16987  free(qindxname);
16988  free(qqindxname);
16989 }
16990 
16991 /*
16992  * dumpIndexAttach
16993  * write out to fout a partitioned-index attachment clause
16994  */
16995 static void
16996 dumpIndexAttach(Archive *fout, const IndexAttachInfo *attachinfo)
16997 {
16998  /* Do nothing in data-only dump */
16999  if (fout->dopt->dataOnly)
17000  return;
17001 
17002  if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
17003  {
17005 
17006  appendPQExpBuffer(q, "ALTER INDEX %s ",
17007  fmtQualifiedDumpable(attachinfo->parentIdx));
17008  appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
17009  fmtQualifiedDumpable(attachinfo->partitionIdx));
17010 
17011  /*
17012  * There is no point in creating a drop query as the drop is done by
17013  * index drop. (If you think to change this, see also
17014  * _printTocEntry().) Although this object doesn't really have
17015  * ownership as such, set the owner field anyway to ensure that the
17016  * command is run by the correct role at restore time.
17017  */
17018  ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
17019  ARCHIVE_OPTS(.tag = attachinfo->dobj.name,
17020  .namespace = attachinfo->dobj.namespace->dobj.name,
17021  .owner = attachinfo->parentIdx->indextable->rolname,
17022  .description = "INDEX ATTACH",
17023  .section = SECTION_POST_DATA,
17024  .createStmt = q->data));
17025 
17026  destroyPQExpBuffer(q);
17027  }
17028 }
17029 
17030 /*
17031  * dumpStatisticsExt
17032  * write out to fout an extended statistics object
17033  */
17034 static void
17035 dumpStatisticsExt(Archive *fout, const StatsExtInfo *statsextinfo)
17036 {
17037  DumpOptions *dopt = fout->dopt;
17038  PQExpBuffer q;
17039  PQExpBuffer delq;
17040  PQExpBuffer query;
17041  char *qstatsextname;
17042  PGresult *res;
17043  char *stxdef;
17044 
17045  /* Do nothing in data-only dump */
17046  if (dopt->dataOnly)
17047  return;
17048 
17049  q = createPQExpBuffer();
17050  delq = createPQExpBuffer();
17051  query = createPQExpBuffer();
17052 
17053  qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
17054 
17055  appendPQExpBuffer(query, "SELECT "
17056  "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
17057  statsextinfo->dobj.catId.oid);
17058 
17059  res = ExecuteSqlQueryForSingleRow(fout, query->data);
17060 
17061  stxdef = PQgetvalue(res, 0, 0);
17062 
17063  /* Result of pg_get_statisticsobjdef is complete except for semicolon */
17064  appendPQExpBuffer(q, "%s;\n", stxdef);
17065 
17066  /*
17067  * We only issue an ALTER STATISTICS statement if the stxstattarget entry
17068  * for this statistics object is not the default value.
17069  */
17070  if (statsextinfo->stattarget >= 0)
17071  {
17072  appendPQExpBuffer(q, "ALTER STATISTICS %s ",
17073  fmtQualifiedDumpable(statsextinfo));
17074  appendPQExpBuffer(q, "SET STATISTICS %d;\n",
17075  statsextinfo->stattarget);
17076  }
17077 
17078  appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
17079  fmtQualifiedDumpable(statsextinfo));
17080 
17081  if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17082  ArchiveEntry(fout, statsextinfo->dobj.catId,
17083  statsextinfo->dobj.dumpId,
17084  ARCHIVE_OPTS(.tag = statsextinfo->dobj.name,
17085  .namespace = statsextinfo->dobj.namespace->dobj.name,
17086  .owner = statsextinfo->rolname,
17087  .description = "STATISTICS",
17088  .section = SECTION_POST_DATA,
17089  .createStmt = q->data,
17090  .dropStmt = delq->data));
17091 
17092  /* Dump Statistics Comments */
17093  if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17094  dumpComment(fout, "STATISTICS", qstatsextname,
17095  statsextinfo->dobj.namespace->dobj.name,
17096  statsextinfo->rolname,
17097  statsextinfo->dobj.catId, 0,
17098  statsextinfo->dobj.dumpId);
17099 
17100  PQclear(res);
17101  destroyPQExpBuffer(q);
17102  destroyPQExpBuffer(delq);
17103  destroyPQExpBuffer(query);
17104  free(qstatsextname);
17105 }
17106 
17107 /*
17108  * dumpConstraint
17109  * write out to fout a user-defined constraint
17110  */
17111 static void
17112 dumpConstraint(Archive *fout, const ConstraintInfo *coninfo)
17113 {
17114  DumpOptions *dopt = fout->dopt;
17115  TableInfo *tbinfo = coninfo->contable;
17116  PQExpBuffer q;
17117  PQExpBuffer delq;
17118  char *tag = NULL;
17119  char *foreign;
17120 
17121  /* Do nothing in data-only dump */
17122  if (dopt->dataOnly)
17123  return;
17124 
17125  q = createPQExpBuffer();
17126  delq = createPQExpBuffer();
17127 
17128  foreign = tbinfo &&
17129  tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "";
17130 
17131  if (coninfo->contype == 'p' ||
17132  coninfo->contype == 'u' ||
17133  coninfo->contype == 'x')
17134  {
17135  /* Index-related constraint */
17136  IndxInfo *indxinfo;
17137  int k;
17138 
17139  indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
17140 
17141  if (indxinfo == NULL)
17142  pg_fatal("missing index for constraint \"%s\"",
17143  coninfo->dobj.name);
17144 
17145  if (dopt->binary_upgrade)
17147  indxinfo->dobj.catId.oid, true);
17148 
17149  appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s\n", foreign,
17150  fmtQualifiedDumpable(tbinfo));
17151  appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
17152  fmtId(coninfo->dobj.name));
17153 
17154  if (coninfo->condef)
17155  {
17156  /* pg_get_constraintdef should have provided everything */
17157  appendPQExpBuffer(q, "%s;\n", coninfo->condef);
17158  }
17159  else
17160  {
17162  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
17163 
17164  /*
17165  * PRIMARY KEY constraints should not be using NULLS NOT DISTINCT
17166  * indexes. Being able to create this was fixed, but we need to
17167  * make the index distinct in order to be able to restore the
17168  * dump.
17169  */
17170  if (indxinfo->indnullsnotdistinct && coninfo->contype != 'p')
17171  appendPQExpBufferStr(q, " NULLS NOT DISTINCT");
17172  appendPQExpBufferStr(q, " (");
17173  for (k = 0; k < indxinfo->indnkeyattrs; k++)
17174  {
17175  int indkey = (int) indxinfo->indkeys[k];
17176  const char *attname;
17177 
17178  if (indkey == InvalidAttrNumber)
17179  break;
17180  attname = getAttrName(indkey, tbinfo);
17181 
17182  appendPQExpBuffer(q, "%s%s",
17183  (k == 0) ? "" : ", ",
17184  fmtId(attname));
17185  }
17186  if (coninfo->conperiod)
17187  appendPQExpBufferStr(q, " WITHOUT OVERLAPS");
17188 
17189  if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
17190  appendPQExpBufferStr(q, ") INCLUDE (");
17191 
17192  for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
17193  {
17194  int indkey = (int) indxinfo->indkeys[k];
17195  const char *attname;
17196 
17197  if (indkey == InvalidAttrNumber)
17198  break;
17199  attname = getAttrName(indkey, tbinfo);
17200 
17201  appendPQExpBuffer(q, "%s%s",
17202  (k == indxinfo->indnkeyattrs) ? "" : ", ",
17203  fmtId(attname));
17204  }
17205 
17206  appendPQExpBufferChar(q, ')');
17207 
17208  if (nonemptyReloptions(indxinfo->indreloptions))
17209  {
17210  appendPQExpBufferStr(q, " WITH (");
17211  appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
17212  appendPQExpBufferChar(q, ')');
17213  }
17214 
17215  if (coninfo->condeferrable)
17216  {
17217  appendPQExpBufferStr(q, " DEFERRABLE");
17218  if (coninfo->condeferred)
17219  appendPQExpBufferStr(q, " INITIALLY DEFERRED");
17220  }
17221 
17222  appendPQExpBufferStr(q, ";\n");
17223  }
17224 
17225  /*
17226  * Append ALTER TABLE commands as needed to set properties that we
17227  * only have ALTER TABLE syntax for. Keep this in sync with the
17228  * similar code in dumpIndex!
17229  */
17230 
17231  /* Drop any not-null constraints that were added to support the PK */
17232  if (coninfo->contype == 'p')
17233  for (int i = 0; i < tbinfo->numatts; i++)
17234  if (tbinfo->notnull_throwaway[i])
17235  appendPQExpBuffer(q, "\nALTER TABLE ONLY %s DROP CONSTRAINT %s;",
17236  fmtQualifiedDumpable(tbinfo),
17237  tbinfo->notnull_constrs[i]);
17238 
17239  /* If the index is clustered, we need to record that. */
17240  if (indxinfo->indisclustered)
17241  {
17242  appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
17243  fmtQualifiedDumpable(tbinfo));
17244  /* index name is not qualified in this syntax */
17245  appendPQExpBuffer(q, " ON %s;\n",
17246  fmtId(indxinfo->dobj.name));
17247  }
17248 
17249  /* If the index defines identity, we need to record that. */
17250  if (indxinfo->indisreplident)
17251  {
17252  appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
17253  fmtQualifiedDumpable(tbinfo));
17254  /* index name is not qualified in this syntax */
17255  appendPQExpBuffer(q, " INDEX %s;\n",
17256  fmtId(indxinfo->dobj.name));
17257  }
17258 
17259  /* Indexes can depend on extensions */
17260  append_depends_on_extension(fout, q, &indxinfo->dobj,
17261  "pg_catalog.pg_class", "INDEX",
17262  fmtQualifiedDumpable(indxinfo));
17263 
17264  appendPQExpBuffer(delq, "ALTER %sTABLE ONLY %s ", foreign,
17265  fmtQualifiedDumpable(tbinfo));
17266  appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17267  fmtId(coninfo->dobj.name));
17268 
17269  tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17270 
17271  if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17272  ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17273  ARCHIVE_OPTS(.tag = tag,
17274  .namespace = tbinfo->dobj.namespace->dobj.name,
17275  .tablespace = indxinfo->tablespace,
17276  .owner = tbinfo->rolname,
17277  .description = "CONSTRAINT",
17278  .section = SECTION_POST_DATA,
17279  .createStmt = q->data,
17280  .dropStmt = delq->data));
17281  }
17282  else if (coninfo->contype == 'f')
17283  {
17284  char *only;
17285 
17286  /*
17287  * Foreign keys on partitioned tables are always declared as
17288  * inheriting to partitions; for all other cases, emit them as
17289  * applying ONLY directly to the named table, because that's how they
17290  * work for regular inherited tables.
17291  */
17292  only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
17293 
17294  /*
17295  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
17296  * current table data is not processed
17297  */
17298  appendPQExpBuffer(q, "ALTER %sTABLE %s%s\n", foreign,
17299  only, fmtQualifiedDumpable(tbinfo));
17300  appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17301  fmtId(coninfo->dobj.name),
17302  coninfo->condef);
17303 
17304  appendPQExpBuffer(delq, "ALTER %sTABLE %s%s ", foreign,
17305  only, fmtQualifiedDumpable(tbinfo));
17306  appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17307  fmtId(coninfo->dobj.name));
17308 
17309  tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17310 
17311  if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17312  ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17313  ARCHIVE_OPTS(.tag = tag,
17314  .namespace = tbinfo->dobj.namespace->dobj.name,
17315  .owner = tbinfo->rolname,
17316  .description = "FK CONSTRAINT",
17317  .section = SECTION_POST_DATA,
17318  .createStmt = q->data,
17319  .dropStmt = delq->data));
17320  }
17321  else if (coninfo->contype == 'c' && tbinfo)
17322  {
17323  /* CHECK constraint on a table */
17324 
17325  /* Ignore if not to be dumped separately, or if it was inherited */
17326  if (coninfo->separate && coninfo->conislocal)
17327  {
17328  /* not ONLY since we want it to propagate to children */
17329  appendPQExpBuffer(q, "ALTER %sTABLE %s\n", foreign,
17330  fmtQualifiedDumpable(tbinfo));
17331  appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17332  fmtId(coninfo->dobj.name),
17333  coninfo->condef);
17334 
17335  appendPQExpBuffer(delq, "ALTER %sTABLE %s ", foreign,
17336  fmtQualifiedDumpable(tbinfo));
17337  appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17338  fmtId(coninfo->dobj.name));
17339 
17340  tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17341 
17342  if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17343  ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17344  ARCHIVE_OPTS(.tag = tag,
17345  .namespace = tbinfo->dobj.namespace->dobj.name,
17346  .owner = tbinfo->rolname,
17347  .description = "CHECK CONSTRAINT",
17348  .section = SECTION_POST_DATA,
17349  .createStmt = q->data,
17350  .dropStmt = delq->data));
17351  }
17352  }
17353  else if (coninfo->contype == 'c' && tbinfo == NULL)
17354  {
17355  /* CHECK constraint on a domain */
17356  TypeInfo *tyinfo = coninfo->condomain;
17357 
17358  /* Ignore if not to be dumped separately */
17359  if (coninfo->separate)
17360  {
17361  appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
17362  fmtQualifiedDumpable(tyinfo));
17363  appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17364  fmtId(coninfo->dobj.name),
17365  coninfo->condef);
17366 
17367  appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
17368  fmtQualifiedDumpable(tyinfo));
17369  appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17370  fmtId(coninfo->dobj.name));
17371 
17372  tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
17373 
17374  if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17375  ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17376  ARCHIVE_OPTS(.tag = tag,
17377  .namespace = tyinfo->dobj.namespace->dobj.name,
17378  .owner = tyinfo->rolname,
17379  .description = "CHECK CONSTRAINT",
17380  .section = SECTION_POST_DATA,
17381  .createStmt = q->data,
17382  .dropStmt = delq->data));
17383  }
17384  }
17385  else
17386  {
17387  pg_fatal("unrecognized constraint type: %c",
17388  coninfo->contype);
17389  }
17390 
17391  /* Dump Constraint Comments --- only works for table constraints */
17392  if (tbinfo && coninfo->separate &&
17393  coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17394  dumpTableConstraintComment(fout, coninfo);
17395 
17396  free(tag);
17397  destroyPQExpBuffer(q);
17398  destroyPQExpBuffer(delq);
17399 }
17400 
17401 /*
17402  * dumpTableConstraintComment --- dump a constraint's comment if any
17403  *
17404  * This is split out because we need the function in two different places
17405  * depending on whether the constraint is dumped as part of CREATE TABLE
17406  * or as a separate ALTER command.
17407  */
17408 static void
17410 {
17411  TableInfo *tbinfo = coninfo->contable;
17412  PQExpBuffer conprefix = createPQExpBuffer();
17413  char *qtabname;
17414 
17415  qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17416 
17417  appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
17418  fmtId(coninfo->dobj.name));
17419 
17420  if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17421  dumpComment(fout, conprefix->data, qtabname,
17422  tbinfo->dobj.namespace->dobj.name,
17423  tbinfo->rolname,
17424  coninfo->dobj.catId, 0,
17425  coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
17426 
17427  destroyPQExpBuffer(conprefix);
17428  free(qtabname);
17429 }
17430 
17431 /*
17432  * dumpSequence
17433  * write the declaration (not data) of one user-defined sequence
17434  */
17435 static void
17436 dumpSequence(Archive *fout, const TableInfo *tbinfo)
17437 {
17438  DumpOptions *dopt = fout->dopt;
17439  PGresult *res;
17440  char *startv,
17441  *incby,
17442  *maxv,
17443  *minv,
17444  *cache,
17445  *seqtype;
17446  bool cycled;
17447  bool is_ascending;
17448  int64 default_minv,
17449  default_maxv;
17450  char bufm[32],
17451  bufx[32];
17452  PQExpBuffer query = createPQExpBuffer();
17453  PQExpBuffer delqry = createPQExpBuffer();
17454  char *qseqname;
17455  TableInfo *owning_tab = NULL;
17456 
17457  qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
17458 
17459  if (fout->remoteVersion >= 100000)
17460  {
17461  appendPQExpBuffer(query,
17462  "SELECT format_type(seqtypid, NULL), "
17463  "seqstart, seqincrement, "
17464  "seqmax, seqmin, "
17465  "seqcache, seqcycle "
17466  "FROM pg_catalog.pg_sequence "
17467  "WHERE seqrelid = '%u'::oid",
17468  tbinfo->dobj.catId.oid);
17469  }
17470  else
17471  {
17472  /*
17473  * Before PostgreSQL 10, sequence metadata is in the sequence itself.
17474  *
17475  * Note: it might seem that 'bigint' potentially needs to be
17476  * schema-qualified, but actually that's a keyword.
17477  */
17478  appendPQExpBuffer(query,
17479  "SELECT 'bigint' AS sequence_type, "
17480  "start_value, increment_by, max_value, min_value, "
17481  "cache_value, is_cycled FROM %s",
17482  fmtQualifiedDumpable(tbinfo));
17483  }
17484 
17485  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17486 
17487  if (PQntuples(res) != 1)
17488  pg_fatal(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17489  "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17490  PQntuples(res)),
17491  tbinfo->dobj.name, PQntuples(res));
17492 
17493  seqtype = PQgetvalue(res, 0, 0);
17494  startv = PQgetvalue(res, 0, 1);
17495  incby = PQgetvalue(res, 0, 2);
17496  maxv = PQgetvalue(res, 0, 3);
17497  minv = PQgetvalue(res, 0, 4);
17498  cache = PQgetvalue(res, 0, 5);
17499  cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
17500 
17501  /* Calculate default limits for a sequence of this type */
17502  is_ascending = (incby[0] != '-');
17503  if (strcmp(seqtype, "smallint") == 0)
17504  {
17505  default_minv = is_ascending ? 1 : PG_INT16_MIN;
17506  default_maxv = is_ascending ? PG_INT16_MAX : -1;
17507  }
17508  else if (strcmp(seqtype, "integer") == 0)
17509  {
17510  default_minv = is_ascending ? 1 : PG_INT32_MIN;
17511  default_maxv = is_ascending ? PG_INT32_MAX : -1;
17512  }
17513  else if (strcmp(seqtype, "bigint") == 0)
17514  {
17515  default_minv = is_ascending ? 1 : PG_INT64_MIN;
17516  default_maxv = is_ascending ? PG_INT64_MAX : -1;
17517  }
17518  else
17519  {
17520  pg_fatal("unrecognized sequence type: %s", seqtype);
17521  default_minv = default_maxv = 0; /* keep compiler quiet */
17522  }
17523 
17524  /*
17525  * 64-bit strtol() isn't very portable, so convert the limits to strings
17526  * and compare that way.
17527  */
17528  snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
17529  snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
17530 
17531  /* Don't print minv/maxv if they match the respective default limit */
17532  if (strcmp(minv, bufm) == 0)
17533  minv = NULL;
17534  if (strcmp(maxv, bufx) == 0)
17535  maxv = NULL;
17536 
17537  /*
17538  * Identity sequences are not to be dropped separately.
17539  */
17540  if (!tbinfo->is_identity_sequence)
17541  {
17542  appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
17543  fmtQualifiedDumpable(tbinfo));
17544  }
17545 
17546  resetPQExpBuffer(query);
17547 
17548  if (dopt->binary_upgrade)
17549  {
17551  tbinfo->dobj.catId.oid, false);
17552 
17553  /*
17554  * In older PG versions a sequence will have a pg_type entry, but v14
17555  * and up don't use that, so don't attempt to preserve the type OID.
17556  */
17557  }
17558 
17559  if (tbinfo->is_identity_sequence)
17560  {
17561  owning_tab = findTableByOid(tbinfo->owning_tab);
17562 
17563  appendPQExpBuffer(query,
17564  "ALTER TABLE %s ",
17565  fmtQualifiedDumpable(owning_tab));
17566  appendPQExpBuffer(query,
17567  "ALTER COLUMN %s ADD GENERATED ",
17568  fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17569  if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
17570  appendPQExpBufferStr(query, "ALWAYS");
17571  else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
17572  appendPQExpBufferStr(query, "BY DEFAULT");
17573  appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
17574  fmtQualifiedDumpable(tbinfo));
17575  }
17576  else
17577  {
17578  appendPQExpBuffer(query,
17579  "CREATE %sSEQUENCE %s\n",
17580  tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
17581  "UNLOGGED " : "",
17582  fmtQualifiedDumpable(tbinfo));
17583 
17584  if (strcmp(seqtype, "bigint") != 0)
17585  appendPQExpBuffer(query, " AS %s\n", seqtype);
17586  }
17587 
17588  appendPQExpBuffer(query, " START WITH %s\n", startv);
17589 
17590  appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
17591 
17592  if (minv)
17593  appendPQExpBuffer(query, " MINVALUE %s\n", minv);
17594  else
17595  appendPQExpBufferStr(query, " NO MINVALUE\n");
17596 
17597  if (maxv)
17598  appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
17599  else
17600  appendPQExpBufferStr(query, " NO MAXVALUE\n");
17601 
17602  appendPQExpBuffer(query,
17603  " CACHE %s%s",
17604  cache, (cycled ? "\n CYCLE" : ""));
17605 
17606  if (tbinfo->is_identity_sequence)
17607  {
17608  appendPQExpBufferStr(query, "\n);\n");
17609  if (tbinfo->relpersistence != owning_tab->relpersistence)
17610  appendPQExpBuffer(query,
17611  "ALTER SEQUENCE %s SET %s;\n",
17612  fmtQualifiedDumpable(tbinfo),
17613  tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
17614  "UNLOGGED" : "LOGGED");
17615  }
17616  else
17617  appendPQExpBufferStr(query, ";\n");
17618 
17619  /* binary_upgrade: no need to clear TOAST table oid */
17620 
17621  if (dopt->binary_upgrade)
17622  binary_upgrade_extension_member(query, &tbinfo->dobj,
17623  "SEQUENCE", qseqname,
17624  tbinfo->dobj.namespace->dobj.name);
17625 
17626  if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17627  ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
17628  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17629  .namespace = tbinfo->dobj.namespace->dobj.name,
17630  .owner = tbinfo->rolname,
17631  .description = "SEQUENCE",
17632  .section = SECTION_PRE_DATA,
17633  .createStmt = query->data,
17634  .dropStmt = delqry->data));
17635 
17636  /*
17637  * If the sequence is owned by a table column, emit the ALTER for it as a
17638  * separate TOC entry immediately following the sequence's own entry. It's
17639  * OK to do this rather than using full sorting logic, because the
17640  * dependency that tells us it's owned will have forced the table to be
17641  * created first. We can't just include the ALTER in the TOC entry
17642  * because it will fail if we haven't reassigned the sequence owner to
17643  * match the table's owner.
17644  *
17645  * We need not schema-qualify the table reference because both sequence
17646  * and table must be in the same schema.
17647  */
17648  if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
17649  {
17650  owning_tab = findTableByOid(tbinfo->owning_tab);
17651 
17652  if (owning_tab == NULL)
17653  pg_fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
17654  tbinfo->owning_tab, tbinfo->dobj.catId.oid);
17655 
17656  if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
17657  {
17658  resetPQExpBuffer(query);
17659  appendPQExpBuffer(query, "ALTER SEQUENCE %s",
17660  fmtQualifiedDumpable(tbinfo));
17661  appendPQExpBuffer(query, " OWNED BY %s",
17662  fmtQualifiedDumpable(owning_tab));
17663  appendPQExpBuffer(query, ".%s;\n",
17664  fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17665 
17666  if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17668  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17669  .namespace = tbinfo->dobj.namespace->dobj.name,
17670  .owner = tbinfo->rolname,
17671  .description = "SEQUENCE OWNED BY",
17672  .section = SECTION_PRE_DATA,
17673  .createStmt = query->data,
17674  .deps = &(tbinfo->dobj.dumpId),
17675  .nDeps = 1));
17676  }
17677  }
17678 
17679  /* Dump Sequence Comments and Security Labels */
17680  if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17681  dumpComment(fout, "SEQUENCE", qseqname,
17682  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17683  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17684 
17685  if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
17686  dumpSecLabel(fout, "SEQUENCE", qseqname,
17687  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17688  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17689 
17690  PQclear(res);
17691 
17692  destroyPQExpBuffer(query);
17693  destroyPQExpBuffer(delqry);
17694  free(qseqname);
17695 }
17696 
17697 /*
17698  * dumpSequenceData
17699  * write the data of one user-defined sequence
17700  */
17701 static void
17703 {
17704  TableInfo *tbinfo = tdinfo->tdtable;
17705  PGresult *res;
17706  char *last;
17707  bool called;
17708  PQExpBuffer query = createPQExpBuffer();
17709 
17710  appendPQExpBuffer(query,
17711  "SELECT last_value, is_called FROM %s",
17712  fmtQualifiedDumpable(tbinfo));
17713 
17714  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17715 
17716  if (PQntuples(res) != 1)
17717  pg_fatal(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17718  "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17719  PQntuples(res)),
17720  tbinfo->dobj.name, PQntuples(res));
17721 
17722  last = PQgetvalue(res, 0, 0);
17723  called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17724 
17725  resetPQExpBuffer(query);
17726  appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17727  appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
17728  appendPQExpBuffer(query, ", %s, %s);\n",
17729  last, (called ? "true" : "false"));
17730 
17731  if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17733  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17734  .namespace = tbinfo->dobj.namespace->dobj.name,
17735  .owner = tbinfo->rolname,
17736  .description = "SEQUENCE SET",
17737  .section = SECTION_DATA,
17738  .createStmt = query->data,
17739  .deps = &(tbinfo->dobj.dumpId),
17740  .nDeps = 1));
17741 
17742  PQclear(res);
17743 
17744  destroyPQExpBuffer(query);
17745 }
17746 
17747 /*
17748  * dumpTrigger
17749  * write the declaration of one user-defined table trigger
17750  */
17751 static void
17752 dumpTrigger(Archive *fout, const TriggerInfo *tginfo)
17753 {
17754  DumpOptions *dopt = fout->dopt;
17755  TableInfo *tbinfo = tginfo->tgtable;
17756  PQExpBuffer query;
17757  PQExpBuffer delqry;
17758  PQExpBuffer trigprefix;
17759  PQExpBuffer trigidentity;
17760  char *qtabname;
17761  char *tag;
17762 
17763  /* Do nothing in data-only dump */
17764  if (dopt->dataOnly)
17765  return;
17766 
17767  query = createPQExpBuffer();
17768  delqry = createPQExpBuffer();
17769  trigprefix = createPQExpBuffer();
17770  trigidentity = createPQExpBuffer();
17771 
17772  qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17773 
17774  appendPQExpBuffer(trigidentity, "%s ", fmtId(tginfo->dobj.name));
17775  appendPQExpBuffer(trigidentity, "ON %s", fmtQualifiedDumpable(tbinfo));
17776 
17777  appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17778  appendPQExpBuffer(delqry, "DROP TRIGGER %s;\n", trigidentity->data);
17779 
17780  /* Triggers can depend on extensions */
17781  append_depends_on_extension(fout, query, &tginfo->dobj,
17782  "pg_catalog.pg_trigger", "TRIGGER",
17783  trigidentity->data);
17784 
17785  if (tginfo->tgispartition)
17786  {
17787  Assert(tbinfo->ispartition);
17788 
17789  /*
17790  * Partition triggers only appear here because their 'tgenabled' flag
17791  * differs from its parent's. The trigger is created already, so
17792  * remove the CREATE and replace it with an ALTER. (Clear out the
17793  * DROP query too, so that pg_dump --create does not cause errors.)
17794  */
17795  resetPQExpBuffer(query);
17796  resetPQExpBuffer(delqry);
17797  appendPQExpBuffer(query, "\nALTER %sTABLE %s ",
17798  tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "",
17799  fmtQualifiedDumpable(tbinfo));
17800  switch (tginfo->tgenabled)
17801  {
17802  case 'f':
17803  case 'D':
17804  appendPQExpBufferStr(query, "DISABLE");
17805  break;
17806  case 't':
17807  case 'O':
17808  appendPQExpBufferStr(query, "ENABLE");
17809  break;
17810  case 'R':
17811  appendPQExpBufferStr(query, "ENABLE REPLICA");
17812  break;
17813  case 'A':
17814  appendPQExpBufferStr(query, "ENABLE ALWAYS");
17815  break;
17816  }
17817  appendPQExpBuffer(query, " TRIGGER %s;\n",
17818  fmtId(tginfo->dobj.name));
17819  }
17820  else if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17821  {
17822  appendPQExpBuffer(query, "\nALTER %sTABLE %s ",
17823  tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "",
17824  fmtQualifiedDumpable(tbinfo));
17825  switch (tginfo->tgenabled)
17826  {
17827  case 'D':
17828  case 'f':
17829  appendPQExpBufferStr(query, "DISABLE");
17830  break;
17831  case 'A':
17832  appendPQExpBufferStr(query, "ENABLE ALWAYS");
17833  break;
17834  case 'R':
17835  appendPQExpBufferStr(query, "ENABLE REPLICA");
17836  break;
17837  default:
17838  appendPQExpBufferStr(query, "ENABLE");
17839  break;
17840  }
17841  appendPQExpBuffer(query, " TRIGGER %s;\n",
17842  fmtId(tginfo->dobj.name));
17843  }
17844 
17845  appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17846  fmtId(tginfo->dobj.name));
17847 
17848  tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17849 
17850  if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17851  ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17852  ARCHIVE_OPTS(.tag = tag,
17853  .namespace = tbinfo->dobj.namespace->dobj.name,
17854  .owner = tbinfo->rolname,
17855  .description = "TRIGGER",
17856  .section = SECTION_POST_DATA,
17857  .createStmt = query->data,
17858  .dropStmt = delqry->data));
17859 
17860  if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17861  dumpComment(fout, trigprefix->data, qtabname,
17862  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17863  tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17864 
17865  free(tag);
17866  destroyPQExpBuffer(query);
17867  destroyPQExpBuffer(delqry);
17868  destroyPQExpBuffer(trigprefix);
17869  destroyPQExpBuffer(trigidentity);
17870  free(qtabname);
17871 }
17872 
17873 /*
17874  * dumpEventTrigger
17875  * write the declaration of one user-defined event trigger
17876  */
17877 static void
17879 {
17880  DumpOptions *dopt = fout->dopt;
17881  PQExpBuffer query;
17882  PQExpBuffer delqry;
17883  char *qevtname;
17884 
17885  /* Do nothing in data-only dump */
17886  if (dopt->dataOnly)
17887  return;
17888 
17889  query = createPQExpBuffer();
17890  delqry = createPQExpBuffer();
17891 
17892  qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17893 
17894  appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17895  appendPQExpBufferStr(query, qevtname);
17896  appendPQExpBufferStr(query, " ON ");
17897  appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17898 
17899  if (strcmp("", evtinfo->evttags) != 0)
17900  {
17901  appendPQExpBufferStr(query, "\n WHEN TAG IN (");
17902  appendPQExpBufferStr(query, evtinfo->evttags);
17903  appendPQExpBufferChar(query, ')');
17904  }
17905 
17906  appendPQExpBufferStr(query, "\n EXECUTE FUNCTION ");
17907  appendPQExpBufferStr(query, evtinfo->evtfname);
17908  appendPQExpBufferStr(query, "();\n");
17909 
17910  if (evtinfo->evtenabled != 'O')
17911  {
17912  appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17913  qevtname);
17914  switch (evtinfo->evtenabled)
17915  {
17916  case 'D':
17917  appendPQExpBufferStr(query, "DISABLE");
17918  break;
17919  case 'A':
17920  appendPQExpBufferStr(query, "ENABLE ALWAYS");
17921  break;
17922  case 'R':
17923  appendPQExpBufferStr(query, "ENABLE REPLICA");
17924  break;
17925  default:
17926  appendPQExpBufferStr(query, "ENABLE");
17927  break;
17928  }
17929  appendPQExpBufferStr(query, ";\n");
17930  }
17931 
17932  appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17933  qevtname);
17934 
17935  if (dopt->binary_upgrade)
17936  binary_upgrade_extension_member(query, &evtinfo->dobj,
17937  "EVENT TRIGGER", qevtname, NULL);
17938 
17939  if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17940  ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17941  ARCHIVE_OPTS(.tag = evtinfo->dobj.name,
17942  .owner = evtinfo->evtowner,
17943  .description = "EVENT TRIGGER",
17944  .section = SECTION_POST_DATA,
17945  .createStmt = query->data,
17946  .dropStmt = delqry->data));
17947 
17948  if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17949  dumpComment(fout, "EVENT TRIGGER", qevtname,
17950  NULL, evtinfo->evtowner,
17951  evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17952 
17953  destroyPQExpBuffer(query);
17954  destroyPQExpBuffer(delqry);
17955  free(qevtname);
17956 }
17957 
17958 /*
17959  * dumpRule
17960  * Dump a rule
17961  */
17962 static void
17963 dumpRule(Archive *fout, const RuleInfo *rinfo)
17964 {
17965  DumpOptions *dopt = fout->dopt;
17966  TableInfo *tbinfo = rinfo->ruletable;
17967  bool is_view;
17968  PQExpBuffer query;
17969  PQExpBuffer cmd;
17970  PQExpBuffer delcmd;
17971  PQExpBuffer ruleprefix;
17972  char *qtabname;
17973  PGresult *res;
17974  char *tag;
17975 
17976  /* Do nothing in data-only dump */
17977  if (dopt->dataOnly)
17978  return;
17979 
17980  /*
17981  * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17982  * we do not want to dump it as a separate object.
17983  */
17984  if (!rinfo->separate)
17985  return;
17986 
17987  /*
17988  * If it's an ON SELECT rule, we want to print it as a view definition,
17989  * instead of a rule.
17990  */
17991  is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17992 
17993  query = createPQExpBuffer();
17994  cmd = createPQExpBuffer();
17995  delcmd = createPQExpBuffer();
17996  ruleprefix = createPQExpBuffer();
17997 
17998  qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17999 
18000  if (is_view)
18001  {
18002  PQExpBuffer result;
18003 
18004  /*
18005  * We need OR REPLACE here because we'll be replacing a dummy view.
18006  * Otherwise this should look largely like the regular view dump code.
18007  */
18008  appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
18009  fmtQualifiedDumpable(tbinfo));
18010  if (nonemptyReloptions(tbinfo->reloptions))
18011  {
18012  appendPQExpBufferStr(cmd, " WITH (");
18013  appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
18014  appendPQExpBufferChar(cmd, ')');
18015  }
18016  result = createViewAsClause(fout, tbinfo);
18017  appendPQExpBuffer(cmd, " AS\n%s", result->data);
18018  destroyPQExpBuffer(result);
18019  if (tbinfo->checkoption != NULL)
18020  appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
18021  tbinfo->checkoption);
18022  appendPQExpBufferStr(cmd, ";\n");
18023  }
18024  else
18025  {
18026  /* In the rule case, just print pg_get_ruledef's result verbatim */
18027  appendPQExpBuffer(query,
18028  "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
18029  rinfo->dobj.catId.oid);
18030 
18031  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18032 
18033  if (PQntuples(res) != 1)
18034  pg_fatal("query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
18035  rinfo->dobj.name, tbinfo->dobj.name);
18036 
18037  printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
18038 
18039  PQclear(res);
18040  }
18041 
18042  /*
18043  * Add the command to alter the rules replication firing semantics if it
18044  * differs from the default.
18045  */
18046  if (rinfo->ev_enabled != 'O')
18047  {
18048  appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
18049  switch (rinfo->ev_enabled)
18050  {
18051  case 'A':
18052  appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
18053  fmtId(rinfo->dobj.name));
18054  break;
18055  case 'R':
18056  appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
18057  fmtId(rinfo->dobj.name));
18058  break;
18059  case 'D':
18060  appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
18061  fmtId(rinfo->dobj.name));
18062  break;
18063  }
18064  }
18065 
18066  if (is_view)
18067  {
18068  /*
18069  * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
18070  * REPLACE VIEW to replace the rule with something with minimal
18071  * dependencies.
18072  */
18073  PQExpBuffer result;
18074 
18075  appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
18076  fmtQualifiedDumpable(tbinfo));
18077  result = createDummyViewAsClause(fout, tbinfo);
18078  appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
18079  destroyPQExpBuffer(result);
18080  }
18081  else
18082  {
18083  appendPQExpBuffer(delcmd, "DROP RULE %s ",
18084  fmtId(rinfo->dobj.name));
18085  appendPQExpBuffer(delcmd, "ON %s;\n",
18086  fmtQualifiedDumpable(tbinfo));
18087  }
18088 
18089  appendPQExpBuffer(ruleprefix, "RULE %s ON",
18090  fmtId(rinfo->dobj.name));
18091 
18092  tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
18093 
18094  if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
18095  ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
18096  ARCHIVE_OPTS(.tag = tag,
18097  .namespace = tbinfo->dobj.namespace->dobj.name,
18098  .owner = tbinfo->rolname,
18099  .description = "RULE",
18100  .section = SECTION_POST_DATA,
18101  .createStmt = cmd->data,
18102  .dropStmt = delcmd->data));
18103 
18104  /* Dump rule comments */
18105  if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
18106  dumpComment(fout, ruleprefix->data, qtabname,
18107  tbinfo->dobj.namespace->dobj.name,
18108  tbinfo->rolname,
18109  rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
18110 
18111  free(tag);
18112  destroyPQExpBuffer(query);
18113  destroyPQExpBuffer(cmd);
18114  destroyPQExpBuffer(delcmd);
18115  destroyPQExpBuffer(ruleprefix);
18116  free(qtabname);
18117 }
18118 
18119 /*
18120  * getExtensionMembership --- obtain extension membership data
18121  *
18122  * We need to identify objects that are extension members as soon as they're
18123  * loaded, so that we can correctly determine whether they need to be dumped.
18124  * Generally speaking, extension member objects will get marked as *not* to
18125  * be dumped, as they will be recreated by the single CREATE EXTENSION
18126  * command. However, in binary upgrade mode we still need to dump the members
18127  * individually.
18128  */
18129 void
18131  int numExtensions)
18132 {
18133  PQExpBuffer query;
18134  PGresult *res;
18135  int ntups,
18136  i;
18137  int i_classid,
18138  i_objid,
18139  i_refobjid;
18140  ExtensionInfo *ext;
18141 
18142  /* Nothing to do if no extensions */
18143  if (numExtensions == 0)
18144  return;
18145 
18146  query = createPQExpBuffer();
18147 
18148  /* refclassid constraint is redundant but may speed the search */
18149  appendPQExpBufferStr(query, "SELECT "
18150  "classid, objid, refobjid "
18151  "FROM pg_depend "
18152  "WHERE refclassid = 'pg_extension'::regclass "
18153  "AND deptype = 'e' "
18154  "ORDER BY 3");
18155 
18156  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18157 
18158  ntups = PQntuples(res);
18159 
18160  i_classid = PQfnumber(res, "classid");
18161  i_objid = PQfnumber(res, "objid");
18162  i_refobjid = PQfnumber(res, "refobjid");
18163 
18164  /*
18165  * Since we ordered the SELECT by referenced ID, we can expect that
18166  * multiple entries for the same extension will appear together; this
18167  * saves on searches.
18168  */
18169  ext = NULL;
18170 
18171  for (i = 0; i < ntups; i++)
18172  {
18173  CatalogId objId;
18174  Oid extId;
18175 
18176  objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
18177  objId.oid = atooid(PQgetvalue(res, i, i_objid));
18178  extId = atooid(PQgetvalue(res, i, i_refobjid));
18179 
18180  if (ext == NULL ||
18181  ext->dobj.catId.oid != extId)
18182  ext = findExtensionByOid(extId);
18183 
18184  if (ext == NULL)
18185  {
18186  /* shouldn't happen */
18187  pg_log_warning("could not find referenced extension %u", extId);
18188  continue;
18189  }
18190 
18191  recordExtensionMembership(objId, ext);
18192  }
18193 
18194  PQclear(res);
18195 
18196  destroyPQExpBuffer(query);
18197 }
18198 
18199 /*
18200  * processExtensionTables --- deal with extension configuration tables
18201  *
18202  * There are two parts to this process:
18203  *
18204  * 1. Identify and create dump records for extension configuration tables.
18205  *
18206  * Extensions can mark tables as "configuration", which means that the user
18207  * is able and expected to modify those tables after the extension has been
18208  * loaded. For these tables, we dump out only the data- the structure is
18209  * expected to be handled at CREATE EXTENSION time, including any indexes or
18210  * foreign keys, which brings us to-
18211  *
18212  * 2. Record FK dependencies between configuration tables.
18213  *
18214  * Due to the FKs being created at CREATE EXTENSION time and therefore before
18215  * the data is loaded, we have to work out what the best order for reloading
18216  * the data is, to avoid FK violations when the tables are restored. This is
18217  * not perfect- we can't handle circular dependencies and if any exist they
18218  * will cause an invalid dump to be produced (though at least all of the data
18219  * is included for a user to manually restore). This is currently documented
18220  * but perhaps we can provide a better solution in the future.
18221  */
18222 void
18224  int numExtensions)
18225 {
18226  DumpOptions *dopt = fout->dopt;
18227  PQExpBuffer query;
18228  PGresult *res;
18229  int ntups,
18230  i;
18231  int i_conrelid,
18232  i_confrelid;
18233 
18234  /* Nothing to do if no extensions */
18235  if (numExtensions == 0)
18236  return;
18237 
18238  /*
18239  * Identify extension configuration tables and create TableDataInfo
18240  * objects for them, ensuring their data will be dumped even though the
18241  * tables themselves won't be.
18242  *
18243  * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
18244  * user data in a configuration table is treated like schema data. This
18245  * seems appropriate since system data in a config table would get
18246  * reloaded by CREATE EXTENSION. If the extension is not listed in the
18247  * list of extensions to be included, none of its data is dumped.
18248  */
18249  for (i = 0; i < numExtensions; i++)
18250  {
18251  ExtensionInfo *curext = &(extinfo[i]);
18252  char *extconfig = curext->extconfig;
18253  char *extcondition = curext->extcondition;
18254  char **extconfigarray = NULL;
18255  char **extconditionarray = NULL;
18256  int nconfigitems = 0;
18257  int nconditionitems = 0;
18258 
18259  /*
18260  * Check if this extension is listed as to include in the dump. If
18261  * not, any table data associated with it is discarded.
18262  */
18263  if (extension_include_oids.head != NULL &&
18265  curext->dobj.catId.oid))
18266  continue;
18267 
18268  if (strlen(extconfig) != 0 || strlen(extcondition) != 0)
18269  {
18270  int j;
18271 
18272  if (!parsePGArray(extconfig, &extconfigarray, &nconfigitems))
18273  pg_fatal("could not parse %s array", "extconfig");
18274  if (!parsePGArray(extcondition, &extconditionarray, &nconditionitems))
18275  pg_fatal("could not parse %s array", "extcondition");
18276  if (nconfigitems != nconditionitems)
18277  pg_fatal("mismatched number of configurations and conditions for extension");
18278 
18279  for (j = 0; j < nconfigitems; j++)
18280  {
18281  TableInfo *configtbl;
18282  Oid configtbloid = atooid(extconfigarray[j]);
18283  bool dumpobj =
18285 
18286  configtbl = findTableByOid(configtbloid);
18287  if (configtbl == NULL)
18288  continue;
18289 
18290  /*
18291  * Tables of not-to-be-dumped extensions shouldn't be dumped
18292  * unless the table or its schema is explicitly included
18293  */
18294  if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
18295  {
18296  /* check table explicitly requested */
18297  if (table_include_oids.head != NULL &&
18299  configtbloid))
18300  dumpobj = true;
18301 
18302  /* check table's schema explicitly requested */
18303  if (configtbl->dobj.namespace->dobj.dump &
18305  dumpobj = true;
18306  }
18307 
18308  /* check table excluded by an exclusion switch */
18309  if (table_exclude_oids.head != NULL &&
18311  configtbloid))
18312  dumpobj = false;
18313 
18314  /* check schema excluded by an exclusion switch */
18316  configtbl->dobj.namespace->dobj.catId.oid))
18317  dumpobj = false;
18318 
18319  if (dumpobj)
18320  {
18321  makeTableDataInfo(dopt, configtbl);
18322  if (configtbl->dataObj != NULL)
18323  {
18324  if (strlen(extconditionarray[j]) > 0)
18325  configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
18326  }
18327  }
18328  }
18329  }
18330  if (extconfigarray)
18331  free(extconfigarray);
18332  if (extconditionarray)
18333  free(extconditionarray);
18334  }
18335 
18336  /*
18337  * Now that all the TableDataInfo objects have been created for all the
18338  * extensions, check their FK dependencies and register them to try and
18339  * dump the data out in an order that they can be restored in.
18340  *
18341  * Note that this is not a problem for user tables as their FKs are
18342  * recreated after the data has been loaded.
18343  */
18344 
18345  query = createPQExpBuffer();
18346 
18347  printfPQExpBuffer(query,
18348  "SELECT conrelid, confrelid "
18349  "FROM pg_constraint "
18350  "JOIN pg_depend ON (objid = confrelid) "
18351  "WHERE contype = 'f' "
18352  "AND refclassid = 'pg_extension'::regclass "
18353  "AND classid = 'pg_class'::regclass;");
18354 
18355  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18356  ntups = PQntuples(res);
18357 
18358  i_conrelid = PQfnumber(res, "conrelid");
18359  i_confrelid = PQfnumber(res, "confrelid");
18360 
18361  /* Now get the dependencies and register them */
18362  for (i = 0; i < ntups; i++)
18363  {
18364  Oid conrelid,
18365  confrelid;
18366  TableInfo *reftable,
18367  *contable;
18368 
18369  conrelid = atooid(PQgetvalue(res, i, i_conrelid));
18370  confrelid = atooid(PQgetvalue(res, i, i_confrelid));
18371  contable = findTableByOid(conrelid);
18372  reftable = findTableByOid(confrelid);
18373 
18374  if (reftable == NULL ||
18375  reftable->dataObj == NULL ||
18376  contable == NULL ||
18377  contable->dataObj == NULL)
18378  continue;
18379 
18380  /*
18381  * Make referencing TABLE_DATA object depend on the referenced table's
18382  * TABLE_DATA object.
18383  */
18384  addObjectDependency(&contable->dataObj->dobj,
18385  reftable->dataObj->dobj.dumpId);
18386  }
18387  PQclear(res);
18388  destroyPQExpBuffer(query);
18389 }
18390 
18391 /*
18392  * getDependencies --- obtain available dependency data
18393  */
18394 static void
18396 {
18397  PQExpBuffer query;
18398  PGresult *res;
18399  int ntups,
18400  i;
18401  int i_classid,
18402  i_objid,
18403  i_refclassid,
18404  i_refobjid,
18405  i_deptype;
18406  DumpableObject *dobj,
18407  *refdobj;
18408 
18409  pg_log_info("reading dependency data");
18410 
18411  query = createPQExpBuffer();
18412 
18413  /*
18414  * Messy query to collect the dependency data we need. Note that we
18415  * ignore the sub-object column, so that dependencies of or on a column
18416  * look the same as dependencies of or on a whole table.
18417  *
18418  * PIN dependencies aren't interesting, and EXTENSION dependencies were
18419  * already processed by getExtensionMembership.
18420  */
18421  appendPQExpBufferStr(query, "SELECT "
18422  "classid, objid, refclassid, refobjid, deptype "
18423  "FROM pg_depend "
18424  "WHERE deptype != 'p' AND deptype != 'e'\n");
18425 
18426  /*
18427  * Since we don't treat pg_amop entries as separate DumpableObjects, we
18428  * have to translate their dependencies into dependencies of their parent
18429  * opfamily. Ignore internal dependencies though, as those will point to
18430  * their parent opclass, which we needn't consider here (and if we did,
18431  * it'd just result in circular dependencies). Also, "loose" opfamily
18432  * entries will have dependencies on their parent opfamily, which we
18433  * should drop since they'd likewise become useless self-dependencies.
18434  * (But be sure to keep deps on *other* opfamilies; see amopsortfamily.)
18435  */
18436  appendPQExpBufferStr(query, "UNION ALL\n"
18437  "SELECT 'pg_opfamily'::regclass AS classid, amopfamily AS objid, refclassid, refobjid, deptype "
18438  "FROM pg_depend d, pg_amop o "
18439  "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18440  "classid = 'pg_amop'::regclass AND objid = o.oid "
18441  "AND NOT (refclassid = 'pg_opfamily'::regclass AND amopfamily = refobjid)\n");
18442 
18443  /* Likewise for pg_amproc entries */
18444  appendPQExpBufferStr(query, "UNION ALL\n"
18445  "SELECT 'pg_opfamily'::regclass AS classid, amprocfamily AS objid, refclassid, refobjid, deptype "
18446  "FROM pg_depend d, pg_amproc p "
18447  "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18448  "classid = 'pg_amproc'::regclass AND objid = p.oid "
18449  "AND NOT (refclassid = 'pg_opfamily'::regclass AND amprocfamily = refobjid)\n");
18450 
18451  /* Sort the output for efficiency below */
18452  appendPQExpBufferStr(query, "ORDER BY 1,2");
18453 
18454  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18455 
18456  ntups = PQntuples(res);
18457 
18458  i_classid = PQfnumber(res, "classid");
18459  i_objid = PQfnumber(res, "objid");
18460  i_refclassid = PQfnumber(res, "refclassid");
18461  i_refobjid = PQfnumber(res, "refobjid");
18462  i_deptype = PQfnumber(res, "deptype");
18463 
18464  /*
18465  * Since we ordered the SELECT by referencing ID, we can expect that
18466  * multiple entries for the same object will appear together; this saves
18467  * on searches.
18468  */
18469  dobj = NULL;
18470 
18471  for (i = 0; i < ntups; i++)
18472  {
18473  CatalogId objId;
18474  CatalogId refobjId;
18475  char deptype;
18476 
18477  objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
18478  objId.oid = atooid(PQgetvalue(res, i, i_objid));
18479  refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
18480  refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
18481  deptype = *(PQgetvalue(res, i, i_deptype));
18482 
18483  if (dobj == NULL ||
18484  dobj->catId.tableoid != objId.tableoid ||
18485  dobj->catId.oid != objId.oid)
18486  dobj = findObjectByCatalogId(objId);
18487 
18488  /*
18489  * Failure to find objects mentioned in pg_depend is not unexpected,
18490  * since for example we don't collect info about TOAST tables.
18491  */
18492  if (dobj == NULL)
18493  {
18494 #ifdef NOT_USED
18495  pg_log_warning("no referencing object %u %u",
18496  objId.tableoid, objId.oid);
18497 #endif
18498  continue;
18499  }
18500 
18501  refdobj = findObjectByCatalogId(refobjId);
18502 
18503  if (refdobj == NULL)
18504  {
18505 #ifdef NOT_USED
18506  pg_log_warning("no referenced object %u %u",
18507  refobjId.tableoid, refobjId.oid);
18508 #endif
18509  continue;
18510  }
18511 
18512  /*
18513  * For 'x' dependencies, mark the object for later; we still add the
18514  * normal dependency, for possible ordering purposes. Currently
18515  * pg_dump_sort.c knows to put extensions ahead of all object types
18516  * that could possibly depend on them, but this is safer.
18517  */
18518  if (deptype == 'x')
18519  dobj->depends_on_ext = true;
18520 
18521  /*
18522  * Ordinarily, table rowtypes have implicit dependencies on their
18523  * tables. However, for a composite type the implicit dependency goes
18524  * the other way in pg_depend; which is the right thing for DROP but
18525  * it doesn't produce the dependency ordering we need. So in that one
18526  * case, we reverse the direction of the dependency.
18527  */
18528  if (deptype == 'i' &&
18529  dobj->objType == DO_TABLE &&
18530  refdobj->objType == DO_TYPE)
18531  addObjectDependency(refdobj, dobj->dumpId);
18532  else
18533  /* normal case */
18534  addObjectDependency(dobj, refdobj->dumpId);
18535  }
18536 
18537  PQclear(res);
18538 
18539  destroyPQExpBuffer(query);
18540 }
18541 
18542 
18543 /*
18544  * createBoundaryObjects - create dummy DumpableObjects to represent
18545  * dump section boundaries.
18546  */
18547 static DumpableObject *
18549 {
18550  DumpableObject *dobjs;
18551 
18552  dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
18553 
18554  dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
18555  dobjs[0].catId = nilCatalogId;
18556  AssignDumpId(dobjs + 0);
18557  dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
18558 
18559  dobjs[1].objType = DO_POST_DATA_BOUNDARY;
18560  dobjs[1].catId = nilCatalogId;
18561  AssignDumpId(dobjs + 1);
18562  dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
18563 
18564  return dobjs;
18565 }
18566 
18567 /*
18568  * addBoundaryDependencies - add dependencies as needed to enforce the dump
18569  * section boundaries.
18570  */
18571 static void
18573  DumpableObject *boundaryObjs)
18574 {
18575  DumpableObject *preDataBound = boundaryObjs + 0;
18576  DumpableObject *postDataBound = boundaryObjs + 1;
18577  int i;
18578 
18579  for (i = 0; i < numObjs; i++)
18580  {
18581  DumpableObject *dobj = dobjs[i];
18582 
18583  /*
18584  * The classification of object types here must match the SECTION_xxx
18585  * values assigned during subsequent ArchiveEntry calls!
18586  */
18587  switch (dobj->objType)
18588  {
18589  case DO_NAMESPACE:
18590  case DO_EXTENSION:
18591  case DO_TYPE:
18592  case DO_SHELL_TYPE:
18593  case DO_FUNC:
18594  case DO_AGG:
18595  case DO_OPERATOR:
18596  case DO_ACCESS_METHOD:
18597  case DO_OPCLASS:
18598  case DO_OPFAMILY:
18599  case DO_COLLATION:
18600  case DO_CONVERSION:
18601  case DO_TABLE:
18602  case DO_TABLE_ATTACH:
18603  case DO_ATTRDEF:
18604  case DO_PROCLANG:
18605  case DO_CAST:
18606  case DO_DUMMY_TYPE:
18607  case DO_TSPARSER:
18608  case DO_TSDICT:
18609  case DO_TSTEMPLATE:
18610  case DO_TSCONFIG:
18611  case DO_FDW:
18612  case DO_FOREIGN_SERVER:
18613  case DO_TRANSFORM:
18614  case DO_LARGE_OBJECT:
18615  /* Pre-data objects: must come before the pre-data boundary */
18616  addObjectDependency(preDataBound, dobj->dumpId);
18617  break;
18618  case DO_TABLE_DATA:
18619  case DO_SEQUENCE_SET:
18620  case DO_LARGE_OBJECT_DATA:
18621  /* Data objects: must come between the boundaries */
18622  addObjectDependency(dobj, preDataBound->dumpId);
18623  addObjectDependency(postDataBound, dobj->dumpId);
18624  break;
18625  case DO_INDEX:
18626  case DO_INDEX_ATTACH:
18627  case DO_STATSEXT:
18628  case DO_REFRESH_MATVIEW:
18629  case DO_TRIGGER:
18630  case DO_EVENT_TRIGGER:
18631  case DO_DEFAULT_ACL:
18632  case DO_POLICY:
18633  case DO_PUBLICATION:
18634  case DO_PUBLICATION_REL:
18636  case DO_SUBSCRIPTION:
18637  case DO_SUBSCRIPTION_REL:
18638  /* Post-data objects: must come after the post-data boundary */
18639  addObjectDependency(dobj, postDataBound->dumpId);
18640  break;
18641  case DO_RULE:
18642  /* Rules are post-data, but only if dumped separately */
18643  if (((RuleInfo *) dobj)->separate)
18644  addObjectDependency(dobj, postDataBound->dumpId);
18645  break;
18646  case DO_CONSTRAINT:
18647  case DO_FK_CONSTRAINT:
18648  /* Constraints are post-data, but only if dumped separately */
18649  if (((ConstraintInfo *) dobj)->separate)
18650  addObjectDependency(dobj, postDataBound->dumpId);
18651  break;
18652  case DO_PRE_DATA_BOUNDARY:
18653  /* nothing to do */
18654  break;
18655  case DO_POST_DATA_BOUNDARY:
18656  /* must come after the pre-data boundary */
18657  addObjectDependency(dobj, preDataBound->dumpId);
18658  break;
18659  }
18660  }
18661 }
18662 
18663 
18664 /*
18665  * BuildArchiveDependencies - create dependency data for archive TOC entries
18666  *
18667  * The raw dependency data obtained by getDependencies() is not terribly
18668  * useful in an archive dump, because in many cases there are dependency
18669  * chains linking through objects that don't appear explicitly in the dump.
18670  * For example, a view will depend on its _RETURN rule while the _RETURN rule
18671  * will depend on other objects --- but the rule will not appear as a separate
18672  * object in the dump. We need to adjust the view's dependencies to include
18673  * whatever the rule depends on that is included in the dump.
18674  *
18675  * Just to make things more complicated, there are also "special" dependencies
18676  * such as the dependency of a TABLE DATA item on its TABLE, which we must
18677  * not rearrange because pg_restore knows that TABLE DATA only depends on
18678  * its table. In these cases we must leave the dependencies strictly as-is
18679  * even if they refer to not-to-be-dumped objects.
18680  *
18681  * To handle this, the convention is that "special" dependencies are created
18682  * during ArchiveEntry calls, and an archive TOC item that has any such
18683  * entries will not be touched here. Otherwise, we recursively search the
18684  * DumpableObject data structures to build the correct dependencies for each
18685  * archive TOC item.
18686  */
18687 static void
18689 {
18690  ArchiveHandle *AH = (ArchiveHandle *) fout;
18691  TocEntry *te;
18692 
18693  /* Scan all TOC entries in the archive */
18694  for (te = AH->toc->next; te != AH->toc; te = te->next)
18695  {
18696  DumpableObject *dobj;
18697  DumpId *dependencies;
18698  int nDeps;
18699  int allocDeps;
18700 
18701  /* No need to process entries that will not be dumped */
18702  if (te->reqs == 0)
18703  continue;
18704  /* Ignore entries that already have "special" dependencies */
18705  if (te->nDeps > 0)
18706  continue;
18707  /* Otherwise, look up the item's original DumpableObject, if any */
18708  dobj = findObjectByDumpId(te->dumpId);
18709  if (dobj == NULL)
18710  continue;
18711  /* No work if it has no dependencies */
18712  if (dobj->nDeps <= 0)
18713  continue;
18714  /* Set up work array */
18715  allocDeps = 64;
18716  dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18717  nDeps = 0;
18718  /* Recursively find all dumpable dependencies */
18719  findDumpableDependencies(AH, dobj,
18720  &dependencies, &nDeps, &allocDeps);
18721  /* And save 'em ... */
18722  if (nDeps > 0)
18723  {
18724  dependencies = (DumpId *) pg_realloc(dependencies,
18725  nDeps * sizeof(DumpId));
18726  te->dependencies = dependencies;
18727  te->nDeps = nDeps;
18728  }
18729  else
18730  free(dependencies);
18731  }
18732 }
18733 
18734 /* Recursive search subroutine for BuildArchiveDependencies */
18735 static void
18737  DumpId **dependencies, int *nDeps, int *allocDeps)
18738 {
18739  int i;
18740 
18741  /*
18742  * Ignore section boundary objects: if we search through them, we'll
18743  * report lots of bogus dependencies.
18744  */
18745  if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18746  dobj->objType == DO_POST_DATA_BOUNDARY)
18747  return;
18748 
18749  for (i = 0; i < dobj->nDeps; i++)
18750  {
18751  DumpId depid = dobj->dependencies[i];
18752 
18753  if (TocIDRequired(AH, depid) != 0)
18754  {
18755  /* Object will be dumped, so just reference it as a dependency */
18756  if (*nDeps >= *allocDeps)
18757  {
18758  *allocDeps *= 2;
18759  *dependencies = (DumpId *) pg_realloc(*dependencies,
18760  *allocDeps * sizeof(DumpId));
18761  }
18762  (*dependencies)[*nDeps] = depid;
18763  (*nDeps)++;
18764  }
18765  else
18766  {
18767  /*
18768  * Object will not be dumped, so recursively consider its deps. We
18769  * rely on the assumption that sortDumpableObjects already broke
18770  * any dependency loops, else we might recurse infinitely.
18771  */
18772  DumpableObject *otherdobj = findObjectByDumpId(depid);
18773 
18774  if (otherdobj)
18775  findDumpableDependencies(AH, otherdobj,
18776  dependencies, nDeps, allocDeps);
18777  }
18778  }
18779 }
18780 
18781 
18782 /*
18783  * getFormattedTypeName - retrieve a nicely-formatted type name for the
18784  * given type OID.
18785  *
18786  * This does not guarantee to schema-qualify the output, so it should not
18787  * be used to create the target object name for CREATE or ALTER commands.
18788  *
18789  * Note that the result is cached and must not be freed by the caller.
18790  */
18791 static const char *
18793 {
18794  TypeInfo *typeInfo;
18795  char *result;
18796  PQExpBuffer query;
18797  PGresult *res;
18798 
18799  if (oid == 0)
18800  {
18801  if ((opts & zeroAsStar) != 0)
18802  return "*";
18803  else if ((opts & zeroAsNone) != 0)
18804  return "NONE";
18805  }
18806 
18807  /* see if we have the result cached in the type's TypeInfo record */
18808  typeInfo = findTypeByOid(oid);
18809  if (typeInfo && typeInfo->ftypname)
18810  return typeInfo->ftypname;
18811 
18812  query = createPQExpBuffer();
18813  appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18814  oid);
18815 
18816  res = ExecuteSqlQueryForSingleRow(fout, query->data);
18817 
18818  /* result of format_type is already quoted */
18819  result = pg_strdup(PQgetvalue(res, 0, 0));
18820 
18821  PQclear(res);
18822  destroyPQExpBuffer(query);
18823 
18824  /*
18825  * Cache the result for re-use in later requests, if possible. If we
18826  * don't have a TypeInfo for the type, the string will be leaked once the
18827  * caller is done with it ... but that case really should not happen, so
18828  * leaking if it does seems acceptable.
18829  */
18830  if (typeInfo)
18831  typeInfo->ftypname = result;
18832 
18833  return result;
18834 }
18835 
18836 /*
18837  * Return a column list clause for the given relation.
18838  *
18839  * Special case: if there are no undropped columns in the relation, return
18840  * "", not an invalid "()" column list.
18841  */
18842 static const char *
18844 {
18845  int numatts = ti->numatts;
18846  char **attnames = ti->attnames;
18847  bool *attisdropped = ti->attisdropped;
18848  char *attgenerated = ti->attgenerated;
18849  bool needComma;
18850  int i;
18851 
18852  appendPQExpBufferChar(buffer, '(');
18853  needComma = false;
18854  for (i = 0; i < numatts; i++)
18855  {
18856  if (attisdropped[i])
18857  continue;
18858  if (attgenerated[i])
18859  continue;
18860  if (needComma)
18861  appendPQExpBufferStr(buffer, ", ");
18862  appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18863  needComma = true;
18864  }
18865 
18866  if (!needComma)
18867  return ""; /* no undropped columns */
18868 
18869  appendPQExpBufferChar(buffer, ')');
18870  return buffer->data;
18871 }
18872 
18873 /*
18874  * Check if a reloptions array is nonempty.
18875  */
18876 static bool
18877 nonemptyReloptions(const char *reloptions)
18878 {
18879  /* Don't want to print it if it's just "{}" */
18880  return (reloptions != NULL && strlen(reloptions) > 2);
18881 }
18882 
18883 /*
18884  * Format a reloptions array and append it to the given buffer.
18885  *
18886  * "prefix" is prepended to the option names; typically it's "" or "toast.".
18887  */
18888 static void
18889 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18890  const char *prefix, Archive *fout)
18891 {
18892  bool res;
18893 
18894  res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18895  fout->std_strings);
18896  if (!res)
18897  pg_log_warning("could not parse %s array", "reloptions");
18898 }
18899 
18900 /*
18901  * read_dump_filters - retrieve object identifier patterns from file
18902  *
18903  * Parse the specified filter file for include and exclude patterns, and add
18904  * them to the relevant lists. If the filename is "-" then filters will be
18905  * read from STDIN rather than a file.
18906  */
18907 static void
18909 {
18910  FilterStateData fstate;
18911  char *objname;
18912  FilterCommandType comtype;
18913  FilterObjectType objtype;
18914 
18915  filter_init(&fstate, filename, exit_nicely);
18916 
18917  while (filter_read_item(&fstate, &objname, &comtype, &objtype))
18918  {
18919  if (comtype == FILTER_COMMAND_TYPE_INCLUDE)
18920  {
18921  switch (objtype)
18922  {
18924  break;
18931  pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
18932  "include",
18933  filter_object_type_name(objtype));
18934  exit_nicely(1);
18935  break; /* unreachable */
18936 
18939  break;
18942  break;
18945  dopt->include_everything = false;
18946  break;
18949  dopt->include_everything = false;
18950  break;
18953  objname);
18954  dopt->include_everything = false;
18955  break;
18956  }
18957  }
18958  else if (comtype == FILTER_COMMAND_TYPE_EXCLUDE)
18959  {
18960  switch (objtype)
18961  {
18963  break;
18970  pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
18971  "exclude",
18972  filter_object_type_name(objtype));
18973  exit_nicely(1);
18974  break;
18975 
18978  objname);
18979  break;
18982  objname);
18983  break;
18986  break;
18989  break;
18992  objname);
18993  break;
18994  }
18995  }
18996  else
18997  {
18998  Assert(comtype == FILTER_COMMAND_TYPE_NONE);
18999  Assert(objtype == FILTER_OBJECT_TYPE_NONE);
19000  }
19001 
19002  if (objname)
19003  free(objname);
19004  }
19005 
19006  filter_free(&fstate);
19007 }
Acl * acldefault(ObjectType objtype, Oid ownerId)
Definition: acl.c:778
#define InvalidAttrNumber
Definition: attnum.h:23
int lo_read(int fd, char *buf, int len)
Definition: be-fsstubs.c:154
void recordExtensionMembership(CatalogId catId, ExtensionInfo *ext)
Definition: common.c:1010
FuncInfo * findFuncByOid(Oid oid)
Definition: common.c:883
NamespaceInfo * findNamespaceByOid(Oid oid)
Definition: common.c:937
SubscriptionInfo * findSubscriptionByOid(Oid oid)
Definition: common.c:991
ExtensionInfo * findOwningExtension(CatalogId catalogId)
Definition: common.c:1034
TableInfo * getSchemaData(Archive *fout, int *numTablesPtr)
Definition: common.c:97
DumpableObject * findObjectByCatalogId(CatalogId catalogId)
Definition: common.c:743
void addObjectDependency(DumpableObject *dobj, DumpId refId)
Definition: common.c:783
DumpableObject * findObjectByDumpId(DumpId dumpId)
Definition: common.c:730
void parseOidArray(const char *str, Oid *array, int arraysize)
Definition: common.c:1058
TableInfo * findTableByOid(Oid oid)
Definition: common.c:828
DumpId createDumpId(void)
Definition: common.c:710
ExtensionInfo * findExtensionByOid(Oid oid)
Definition: common.c:955
void AssignDumpId(DumpableObject *dobj)
Definition: common.c:646
void getDumpableObjects(DumpableObject ***objs, int *numObjs)
Definition: common.c:762
CollInfo * findCollationByOid(Oid oid)
Definition: common.c:919
TypeInfo * findTypeByOid(Oid oid)
Definition: common.c:864
OprInfo * findOprByOid(Oid oid)
Definition: common.c:901
PublicationInfo * findPublicationByOid(Oid oid)
Definition: common.c:973
void on_exit_close_archive(Archive *AHX)
Definition: parallel.c:328
void init_parallel_dump_utils(void)
Definition: parallel.c:236
#define PG_MAX_JOBS
Definition: parallel.h:48
uint32 BlockNumber
Definition: block.h:31
static void cleanup(void)
Definition: bootstrap.c:682
static const gbtree_vinfo tinfo
Definition: btree_bit.c:109
unsigned int uint32
Definition: c.h:493
#define PG_INT32_MAX
Definition: c.h:576
#define ngettext(s, p, n)
Definition: c.h:1168
#define INT64_FORMAT
Definition: c.h:535
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1201
#define PG_INT16_MIN
Definition: c.h:572
#define CppAsString2(x)
Definition: c.h:314
#define PG_INT64_MAX
Definition: c.h:579
#define PG_INT64_MIN
Definition: c.h:578
#define PG_INT32_MIN
Definition: c.h:575
#define PG_INT16_MAX
Definition: c.h:573
#define OidIsValid(objectId)
Definition: c.h:762
int nspid
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:448
char * supports_compression(const pg_compress_specification compression_spec)
Definition: compress_io.c:88
bool parse_compress_algorithm(char *name, pg_compress_algorithm *algorithm)
Definition: compression.c:49
void parse_compress_specification(pg_compress_algorithm algorithm, char *specification, pg_compress_specification *result)
Definition: compression.c:107
char * validate_compress_specification(pg_compress_specification *spec)
Definition: compression.c:344
#define PG_COMPRESSION_OPTION_WORKERS
Definition: compression.h:29
pg_compress_algorithm
Definition: compression.h:22
@ PG_COMPRESSION_NONE
Definition: compression.h:23
void parse_compress_options(const char *option, char **algorithm, char **detail)
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:177
bool buildACLCommands(const char *name, const char *subname, const char *nspname, const char *type, const char *acls, const char *baseacls, const char *owner, const char *prefix, int remoteVersion, PQExpBuffer sql)
Definition: dumputils.c:64
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition: dumputils.c:637
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition: dumputils.c:823
bool buildDefaultACLCommands(const char *type, const char *nspname, const char *acls, const char *acldefault, const char *owner, int remoteVersion, PQExpBuffer sql)
Definition: dumputils.c:326
bool variable_is_guc_list_quote(const char *name)
Definition: dumputils.c:689
void quoteAclUserName(PQExpBuffer output, const char *input)
Definition: dumputils.c:544
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition: dumputils.c:655
#define _(x)
Definition: elog.c:90
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6913
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6794
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6948
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7036
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7044
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3847
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992
Oid PQftype(const PGresult *res, int field_num)
Definition: fe-exec.c:3679
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3371
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3441
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3527
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3836
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3549
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3861
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3449
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2038
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2778
int lo_close(PGconn *conn, int fd)
Definition: fe-lobj.c:96
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:57
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void pg_free(void *ptr)
Definition: fe_memutils.c:105
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
DataDirSyncMethod
Definition: file_utils.h:28
@ DATA_DIR_SYNC_METHOD_FSYNC
Definition: file_utils.h:29
void filter_init(FilterStateData *fstate, const char *filename, exit_function f_exit)
Definition: filter.c:37
void filter_free(FilterStateData *fstate)
Definition: filter.c:61
bool filter_read_item(FilterStateData *fstate, char **objname, FilterCommandType *comtype, FilterObjectType *objtype)
Definition: filter.c:388
void pg_log_filter_error(FilterStateData *fstate, const char *fmt,...)
Definition: filter.c:155
const char * filter_object_type_name(FilterObjectType fot)
Definition: filter.c:83
FilterObjectType
Definition: filter.h:48
@ FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN
Definition: filter.h:51
@ FILTER_OBJECT_TYPE_SCHEMA
Definition: filter.h:57
@ FILTER_OBJECT_TYPE_INDEX
Definition: filter.h:56
@ FILTER_OBJECT_TYPE_TRIGGER
Definition: filter.h:60
@ FILTER_OBJECT_TYPE_FOREIGN_DATA
Definition: filter.h:54
@ FILTER_OBJECT_TYPE_DATABASE
Definition: filter.h:52
@ FILTER_OBJECT_TYPE_FUNCTION
Definition: filter.h:55
@ FILTER_OBJECT_TYPE_TABLE_DATA
Definition: filter.h:50
@ FILTER_OBJECT_TYPE_NONE
Definition: filter.h:49
@ FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN
Definition: filter.h:59
@ FILTER_OBJECT_TYPE_EXTENSION
Definition: filter.h:53
@ FILTER_OBJECT_TYPE_TABLE
Definition: filter.h:58
FilterCommandType
Definition: filter.h:38
@ FILTER_COMMAND_TYPE_NONE
Definition: filter.h:39
@ FILTER_COMMAND_TYPE_EXCLUDE
Definition: filter.h:41
@ FILTER_COMMAND_TYPE_INCLUDE
Definition: filter.h:40
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:60
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
#define free(a)
Definition: header.h:65
#define comment
Definition: indent_codes.h:49
#define storage
Definition: indent_codes.h:68
long val
Definition: informix.c:664
static char * locale
Definition: initdb.c:140
static DataDirSyncMethod sync_method
Definition: initdb.c:170
int j
Definition: isn.c:74
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
static JitProviderCallbacks provider
Definition: jit.c:43
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:100
@ PGRES_COPY_OUT
Definition: libpq-fe.h:106
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103
#define INV_READ
Definition: libpq-fs.h:22
Assert(fmt[strlen(fmt) - 1] !='\n')
void pg_logging_increase_verbosity(void)
Definition: logging.c:182
void pg_logging_init(const char *argv0)
Definition: logging.c:83
void pg_logging_set_level(enum pg_log_level new_level)
Definition: logging.c:173
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
#define pg_log_info(...)
Definition: logging.h:124
@ PG_LOG_WARNING
Definition: logging.h:38
#define pg_log_error_detail(...)
Definition: logging.h:109
const char * progname
Definition: main.c:44
char * pstrdup(const char *in)
Definition: mcxt.c:1683
void * palloc(Size size)
Definition: mcxt.c:1304
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
bool parse_sync_method(const char *optarg, DataDirSyncMethod *sync_method)
Definition: option_utils.c:90
Oid oprid(Operator op)
Definition: parse_oper.c:238
static AmcheckOptions opts
Definition: pg_amcheck.c:111
NameData attname
Definition: pg_attribute.h:41
char attalign
Definition: pg_attribute.h:109
int16 attlen
Definition: pg_attribute.h:59
NameData rolname
Definition: pg_authid.h:34
void ConnectDatabase(Archive *AHX, const ConnParams *cparams, bool isReconnect)
Definition: pg_backup_db.c:110
@ SECTION_NONE
Definition: pg_backup.h:57
@ SECTION_POST_DATA
Definition: pg_backup.h:60
@ SECTION_PRE_DATA
Definition: pg_backup.h:58
@ SECTION_DATA
Definition: pg_backup.h:59
int DumpId
Definition: pg_backup.h:268
int EndLO(Archive *AHX, Oid oid)
void ProcessArchiveRestoreOptions(Archive *AHX)
#define InvalidDumpId
Definition: pg_backup.h:270
#define appendStringLiteralAH(buf, str, AH)
Definition: pg_backup.h:330
RestoreOptions * NewRestoreOptions(void)
int StartLO(Archive *AHX, Oid oid)
Archive * CreateArchive(const char *FileSpec, const ArchiveFormat fmt, const pg_compress_specification compression_spec, bool dosync, ArchiveMode mode, SetupWorkerPtrType setupDumpWorker, DataDirSyncMethod sync_method)
enum _archiveFormat ArchiveFormat
void CloseArchive(Archive *AHX)
@ archModeWrite
Definition: pg_backup.h:51
@ archModeAppend
Definition: pg_backup.h:50
@ PREPQUERY_DUMPFUNC
Definition: pg_backup.h:71
@ PREPQUERY_DUMPTABLEATTACH
Definition: pg_backup.h:74
@ PREPQUERY_DUMPBASETYPE
Definition: pg_backup.h:67
@ PREPQUERY_DUMPRANGETYPE
Definition: pg_backup.h:73
@ PREPQUERY_DUMPOPR
Definition: pg_backup.h:72
@ PREPQUERY_DUMPDOMAIN
Definition: pg_backup.h:69
@ NUM_PREP_QUERIES
Definition: pg_backup.h:77
@ PREPQUERY_DUMPCOMPOSITETYPE
Definition: pg_backup.h:68
@ PREPQUERY_DUMPAGG
Definition: pg_backup.h:66
@ PREPQUERY_GETCOLUMNACLS
Definition: pg_backup.h:75
@ PREPQUERY_GETDOMAINCONSTRAINTS
Definition: pg_backup.h:76
@ PREPQUERY_DUMPENUMTYPE
Definition: pg_backup.h:70
int archprintf(Archive *AH, const char *fmt,...) pg_attribute_printf(2
void SetArchiveOptions(Archive *AH, DumpOptions *dopt, RestoreOptions *ropt)
void RestoreArchive(Archive *AHX)
void archputs(const char *s, Archive *AH)
@ archUnknown
Definition: pg_backup.h:41
@ archTar
Definition: pg_backup.h:43
@ archCustom
Definition: pg_backup.h:42
@ archDirectory
Definition: pg_backup.h:45
@ archNull
Definition: pg_backup.h:44
void InitDumpOptions(DumpOptions *opts)
void WriteData(Archive *AHX, const void *data, size_t dLen)
int(* DataDumperPtr)(Archive *AH, const void *userArg)
Definition: pg_backup.h:276
int TocIDRequired(ArchiveHandle *AH, DumpId id)
TocEntry * ArchiveEntry(Archive *AHX, CatalogId catalogId, DumpId dumpId, ArchiveOpts *opts)
#define ARCHIVE_OPTS(...)
#define LOBBUFSIZE
void ExecuteSqlStatement(Archive *AHX, const char *query)
Definition: pg_backup_db.c:278
PGresult * ExecuteSqlQuery(Archive *AHX, const char *query, ExecStatusType status)
Definition: pg_backup_db.c:290
PGresult * ExecuteSqlQueryForSingleRow(Archive *fout, const char *query)
Definition: pg_backup_db.c:305
void set_dump_section(const char *arg, int *dumpSections)
void * arg
#define pg_fatal(...)
static char format
static char * label
static PgChecksumMode mode
Definition: pg_checksums.c:56
#define FUNC_MAX_ARGS
const void size_t len
char datlocprovider
Definition: pg_database.h:44
NameData datname
Definition: pg_database.h:35
int32 encoding
Definition: pg_database.h:41
bool datistemplate
Definition: pg_database.h:47
int32 datconnlimit
Definition: pg_database.h:59
static void expand_schema_name_patterns(Archive *fout, SimpleStringList *patterns, SimpleOidList *oids, bool strict_names)
Definition: pg_dump.c:1397
NamespaceInfo * getNamespaces(Archive *fout, int *numNamespaces)
Definition: pg_dump.c:5473
static const CatalogId nilCatalogId
Definition: pg_dump.c:139
static void dumpEncoding(Archive *AH)
Definition: pg_dump.c:3480
void getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
Definition: pg_dump.c:7639
static SimpleStringList schema_include_patterns
Definition: pg_dump.c:118
static void dumpAttrDef(Archive *fout, const AttrDefInfo *adinfo)
Definition: pg_dump.c:16765
static void selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
Definition: pg_dump.c:1949
static PQExpBuffer createDummyViewAsClause(Archive *fout, const TableInfo *tbinfo)
Definition: pg_dump.c:15819
static void dumpUserMappings(Archive *fout, const char *servername, const char *namespace, const char *owner, CatalogId catalogId, DumpId dumpId)
Definition: pg_dump.c:14996
static void dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo)
Definition: pg_dump.c:4510
static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs, DumpableObject *boundaryObjs)
Definition: pg_dump.c:18572
void getPublicationNamespaces(Archive *fout)
Definition: pg_dump.c:4291
static void dumpSearchPath(Archive *AH)
Definition: pg_dump.c:3529
static int ncomments
Definition: pg_dump.c:151
static void selectDumpableTable(TableInfo *tbinfo, Archive *fout)
Definition: pg_dump.c:1818
static DumpableObject * createBoundaryObjects(void)
Definition: pg_dump.c:18548
static char * convertTSFunction(Archive *fout, Oid funcOid)
Definition: pg_dump.c:13169
static void dumpDatabase(Archive *fout)
Definition: pg_dump.c:2970
static SimpleStringList table_include_patterns
Definition: pg_dump.c:123
static void append_depends_on_extension(Archive *fout, PQExpBuffer create, const DumpableObject *dobj, const char *catalog, const char *keyword, const char *objname)
Definition: pg_dump.c:5137
static Oid get_next_possible_free_pg_type_oid(Archive *fout, PQExpBuffer upgrade_query)
Definition: pg_dump.c:5182
static void dumpNamespace(Archive *fout, const NamespaceInfo *nspinfo)
Definition: pg_dump.c:10684
static bool forcePartitionRootLoad(const TableInfo *tbinfo)
Definition: pg_dump.c:2546
static void dumpCast(Archive *fout, const CastInfo *cast)
Definition: pg_dump.c:12645
static SimpleOidList schema_exclude_oids
Definition: pg_dump.c:121
static bool have_extra_float_digits
Definition: pg_dump.c:142
static void dumpIndex(Archive *fout, const IndxInfo *indxinfo)
Definition: pg_dump.c:16855
void getPartitioningInfo(Archive *fout)
Definition: pg_dump.c:7180
static void dumpBaseType(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:11282
OidOptions
Definition: pg_dump.c:96
@ zeroIsError
Definition: pg_dump.c:97
@ zeroAsStar
Definition: pg_dump.c:98
@ zeroAsNone
Definition: pg_dump.c:99
DefaultACLInfo * getDefaultACLs(Archive *fout, int *numDefaultACLs)
Definition: pg_dump.c:9821
static SimpleOidList extension_include_oids
Definition: pg_dump.c:137
static void dumpTSDictionary(Archive *fout, const TSDictInfo *dictinfo)
Definition: pg_dump.c:14568
static void dumpAgg(Archive *fout, const AggInfo *agginfo)
Definition: pg_dump.c:14144
static int extra_float_digits
Definition: pg_dump.c:143
static void dumpTableComment(Archive *fout, const TableInfo *tbinfo, const char *reltypename)
Definition: pg_dump.c:10237
static SimpleStringList extension_include_patterns
Definition: pg_dump.c:136
static void selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
Definition: pg_dump.c:1732
static void dumpTrigger(Archive *fout, const TriggerInfo *tginfo)
Definition: pg_dump.c:17752
static void binary_upgrade_set_type_oids_by_rel(Archive *fout, PQExpBuffer upgrade_buffer, const TableInfo *tbinfo)
Definition: pg_dump.c:5298
static void dumpTable(Archive *fout, const TableInfo *tbinfo)
Definition: pg_dump.c:15630
static SimpleStringList table_exclude_patterns
Definition: pg_dump.c:126
static PQExpBuffer createViewAsClause(Archive *fout, const TableInfo *tbinfo)
Definition: pg_dump.c:15770
static void dumpStatisticsExt(Archive *fout, const StatsExtInfo *statsextinfo)
Definition: pg_dump.c:17035
void getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
Definition: pg_dump.c:3806
static void dumpRangeType(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:11060
static void binary_upgrade_set_pg_class_oids(Archive *fout, PQExpBuffer upgrade_buffer, Oid pg_class_oid, bool is_index)
Definition: pg_dump.c:5310
void getExtensionMembership(Archive *fout, ExtensionInfo extinfo[], int numExtensions)
Definition: pg_dump.c:18130
static void dumpComment(Archive *fout, const char *type, const char *name, const char *namespace, const char *owner, CatalogId catalogId, int subid, DumpId dumpId)
Definition: pg_dump.c:10221
static char * getFormattedOperatorName(const char *oproid)
Definition: pg_dump.c:13139
ForeignServerInfo * getForeignServers(Archive *fout, int *numForeignServers)
Definition: pg_dump.c:9727
static char * format_function_signature(Archive *fout, const FuncInfo *finfo, bool honor_quotes)
Definition: pg_dump.c:12200
static int nseclabels
Definition: pg_dump.c:155
static pg_compress_algorithm compression_algorithm
Definition: pg_dump.c:110
static void dumpStdStrings(Archive *AH)
Definition: pg_dump.c:3505
static void dumpConstraint(Archive *fout, const ConstraintInfo *coninfo)
Definition: pg_dump.c:17112
static void dumpType(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:10889
static void dumpTableAttach(Archive *fout, const TableAttachInfo *attachinfo)
Definition: pg_dump.c:16697
AccessMethodInfo * getAccessMethods(Archive *fout, int *numAccessMethods)
Definition: pg_dump.c:6064
FdwInfo * getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
Definition: pg_dump.c:9637
FuncInfo * getFuncs(Archive *fout, int *numFuncs)
Definition: pg_dump.c:6416
static void help(const char *progname)
Definition: pg_dump.c:1069
static void dumpAccessMethod(Archive *fout, const AccessMethodInfo *aminfo)
Definition: pg_dump.c:13191
TSConfigInfo * getTSConfigurations(Archive *fout, int *numTSConfigs)
Definition: pg_dump.c:9572
int main(int argc, char **argv)
Definition: pg_dump.c:336
static void dumpOpr(Archive *fout, const OprInfo *oprinfo)
Definition: pg_dump.c:12879
static void selectDumpableStatisticsObject(StatsExtInfo *sobj, Archive *fout)
Definition: pg_dump.c:2061
static void selectDumpablePublicationObject(DumpableObject *dobj, Archive *fout)
Definition: pg_dump.c:2043
static void dumpSequenceData(Archive *fout, const TableDataInfo *tdinfo)
Definition: pg_dump.c:17702
static void dumpFunc(Archive *fout, const FuncInfo *finfo)
Definition: pg_dump.c:12229
static void selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
Definition: pg_dump.c:1902
static void BuildArchiveDependencies(Archive *fout)
Definition: pg_dump.c:18688
ConvInfo * getConversions(Archive *fout, int *numConversions)
Definition: pg_dump.c:5996
void getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
Definition: pg_dump.c:7061
static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo)
Definition: pg_dump.c:2740
static const char * getAttrName(int attrnum, const TableInfo *tblInfo)
Definition: pg_dump.c:16826
static void dumpForeignServer(Archive *fout, const ForeignServerInfo *srvinfo)
Definition: pg_dump.c:14896
static RoleNameItem * rolenames
Definition: pg_dump.c:146
static void collectRoleNames(Archive *fout)
Definition: pg_dump.c:9957
static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions, const char *prefix, Archive *fout)
Definition: pg_dump.c:18889
static void dumpTableData(Archive *fout, const TableDataInfo *tdinfo)
Definition: pg_dump.c:2574
static void prohibit_crossdb_refs(PGconn *conn, const char *dbname, const char *pattern)
Definition: pg_dump.c:1657
static bool dosync
Definition: pg_dump.c:103
static int dumpTableData_copy(Archive *fout, const void *dcontext)
Definition: pg_dump.c:2101
static const char * getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
Definition: pg_dump.c:18792
static void getDependencies(Archive *fout)
Definition: pg_dump.c:18395
static void buildMatViewRefreshDependencies(Archive *fout)
Definition: pg_dump.c:2814
static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout, PQExpBuffer upgrade_buffer, Oid pg_type_oid, bool force_array_type, bool include_multirange_type)
Definition: pg_dump.c:5213
#define DUMP_DEFAULT_ROWS_PER_INSERT
Definition: pg_dump.c:161
void getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
Definition: pg_dump.c:4378
static const char * getRoleName(const char *roleoid_str)
Definition: pg_dump.c:9921
AggInfo * getAggregates(Archive *fout, int *numAggs)
Definition: pg_dump.c:6269
static void dumpShellType(Archive *fout, const ShellTypeInfo *stinfo)
Definition: pg_dump.c:11999
static void refreshMatViewData(Archive *fout, const TableDataInfo *tdinfo)
Definition: pg_dump.c:2686
static int findComments(Oid classoid, Oid objoid, CommentItem **items)
Definition: pg_dump.c:10335
static SimpleStringList foreign_servers_include_patterns
Definition: pg_dump.c:133
static char * format_aggregate_signature(const AggInfo *agginfo, Archive *fout, bool honor_quotes)
Definition: pg_dump.c:14112
static void selectDumpableCast(CastInfo *cast, Archive *fout)
Definition: pg_dump.c:1924
static void dumpPublication(Archive *fout, const PublicationInfo *pubinfo)
Definition: pg_dump.c:4195
static char * get_language_name(Archive *fout, Oid langid)
Definition: pg_dump.c:8486
static void dumpPolicy(Archive *fout, const PolicyInfo *polinfo)
Definition: pg_dump.c:3973
void getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
Definition: pg_dump.c:7240
static void setupDumpWorker(Archive *AH)
Definition: pg_dump.c:1330
static void addConstrChildIdxDeps(DumpableObject *dobj, const IndxInfo *refidx)
Definition: pg_dump.c:7804
static int nrolenames
Definition: pg_dump.c:147
static int findSecLabels(Oid classoid, Oid objoid, SecLabelItem **items)
Definition: pg_dump.c:15465
static SimpleStringList table_include_patterns_and_children
Definition: pg_dump.c:124
static char * convertRegProcReference(const char *proc)
Definition: pg_dump.c:13098
static void getAdditionalACLs(Archive *fout)
Definition: pg_dump.c:9992
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4614
static void getTableDataFKConstraints(void)
Definition: pg_dump.c:2929
static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind)
Definition: pg_dump.c:2721
static SimpleOidList table_exclude_oids
Definition: pg_dump.c:128
static DumpId dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId, const char *type, const char *name, const char *subname, const char *nspname, const char *owner, const DumpableAcl *dacl)
Definition: pg_dump.c:15177
TSDictInfo * getTSDictionaries(Archive *fout, int *numTSDicts)
Definition: pg_dump.c:9435
InhInfo * getInherits(Archive *fout, int *numInherits)
Definition: pg_dump.c:7124
OpfamilyInfo * getOpfamilies(Archive *fout, int *numOpfamilies)
Definition: pg_dump.c:6201
static void dumpDomain(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:11531
void getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
Definition: pg_dump.c:8600
static void collectComments(Archive *fout)
Definition: pg_dump.c:10412
static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
Definition: pg_dump.c:7827
static void dumpOpfamily(Archive *fout, const OpfamilyInfo *opfinfo)
Definition: pg_dump.c:13540
static void dumpDefaultACL(Archive *fout, const DefaultACLInfo *daclinfo)
Definition: pg_dump.c:15090
void getSubscriptionTables(Archive *fout)
Definition: pg_dump.c:4827
static void selectDumpableObject(DumpableObject *dobj, Archive *fout)
Definition: pg_dump.c:2079
static void dumpTSTemplate(Archive *fout, const TSTemplateInfo *tmplinfo)
Definition: pg_dump.c:14648
static void dumpIndexAttach(Archive *fout, const IndexAttachInfo *attachinfo)
Definition: pg_dump.c:16996
static void dumpSubscriptionTable(Archive *fout, const SubRelInfo *subrinfo)
Definition: pg_dump.c:4913
static char * format_function_arguments(const FuncInfo *finfo, const char *funcargs, bool is_agg)
Definition: pg_dump.c:12177
static int strict_names
Definition: pg_dump.c:108
static void dumpTransform(Archive *fout, const TransformInfo *transform)
Definition: pg_dump.c:12750
static void dumpLO(Archive *fout, const LoInfo *loinfo)
Definition: pg_dump.c:3683
static void dumpPublicationTable(Archive *fout, const PublicationRelInfo *pubrinfo)
Definition: pg_dump.c:4553
static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer, const DumpableObject *dobj, const char *objtype, const char *objname, const char *objnamespace)
Definition: pg_dump.c:5426
static void dumpDumpableObject(Archive *fout, DumpableObject *dobj)
Definition: pg_dump.c:10497
static void getLOs(Archive *fout)
Definition: pg_dump.c:3591
static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf, const char *dbname, Oid dboid)
Definition: pg_dump.c:3436
static void setup_connection(Archive *AH, const char *dumpencoding, const char *dumpsnapshot, char *use_role)
Definition: pg_dump.c:1168
static void dumpTableConstraintComment(Archive *fout, const ConstraintInfo *coninfo)
Definition: pg_dump.c:17409
static void dumpUndefinedType(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:11218
static void selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
Definition: pg_dump.c:1982
static const char * fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
Definition: pg_dump.c:18843
PublicationInfo * getPublications(Archive *fout, int *numPublications)
Definition: pg_dump.c:4091
static void expand_table_name_patterns(Archive *fout, SimpleStringList *patterns, SimpleOidList *oids, bool strict_names, bool with_child_tables)
Definition: pg_dump.c:1561
static void findDumpableDependencies(ArchiveHandle *AH, const DumpableObject *dobj, DumpId **dependencies, int *nDeps, int *allocDeps)
Definition: pg_dump.c:18736
static void dumpTableSchema(Archive *fout, const TableInfo *tbinfo)
Definition: pg_dump.c:15859
static void dumpTSParser(Archive *fout, const TSParserInfo *prsinfo)
Definition: pg_dump.c:14504
static void expand_foreign_server_name_patterns(Archive *fout, SimpleStringList *patterns, SimpleOidList *oids)
Definition: pg_dump.c:1509
TSTemplateInfo * getTSTemplates(Archive *fout, int *numTSTemplates)
Definition: pg_dump.c:9507
static void dumpRule(Archive *fout, const RuleInfo *rinfo)
Definition: pg_dump.c:17963
static void dumpCompositeType(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:11704
ProcLangInfo * getProcLangs(Archive *fout, int *numProcLangs)
Definition: pg_dump.c:8303
static void dumpEnumType(Archive *fout, const TypeInfo *tyinfo)
Definition: pg_dump.c:10920
static void dumpExtension(Archive *fout, const ExtensionInfo *extinfo)
Definition: pg_dump.c:10761
#define fmtQualifiedDumpable(obj)
Definition: pg_dump.c:166
TypeInfo * getTypes(Archive *fout, int *numTypes)
Definition: pg_dump.c:5684
static bool nonemptyReloptions(const char *reloptions)
Definition: pg_dump.c:18877
static SimpleOidList table_include_oids
Definition: pg_dump.c:125
void getExtendedStatistics(Archive *fout)
Definition: pg_dump.c:7560
static NamespaceInfo * findNamespace(Oid nsoid)
Definition: pg_dump.c:5591
static char * get_synchronized_snapshot(Archive *fout)
Definition: pg_dump.c:1345
static int dumpLOs(Archive *fout, const void *arg)
Definition: pg_dump.c:3732
static void dumpSubscription(Archive *fout, const SubscriptionInfo *subinfo)
Definition: pg_dump.c:4982
void processExtensionTables(Archive *fout, ExtensionInfo extinfo[], int numExtensions)
Definition: pg_dump.c:18223
static void dumpEventTrigger(Archive *fout, const EventTriggerInfo *evtinfo)
Definition: pg_dump.c:17878
static void dumpCommentExtended(Archive *fout, const char *type, const char *name, const char *namespace, const char *owner, CatalogId catalogId, int subid, DumpId dumpId, const char *initdb_comment)
Definition: pg_dump.c:10121
static SimpleStringList tabledata_exclude_patterns
Definition: pg_dump.c:129
OpclassInfo * getOpclasses(Archive *fout, int *numOpclasses)
Definition: pg_dump.c:6135
static void dumpConversion(Archive *fout, const ConvInfo *convinfo)
Definition: pg_dump.c:14016
static void dumpForeignDataWrapper(Archive *fout, const FdwInfo *fdwinfo)
Definition: pg_dump.c:14826
CollInfo * getCollations(Archive *fout, int *numCollations)
Definition: pg_dump.c:5928
static void dumpProcLang(Archive *fout, const ProcLangInfo *plang)
Definition: pg_dump.c:12045
static void dumpSecLabel(Archive *fout, const char *type, const char *name, const char *namespace, const char *owner, CatalogId catalogId, int subid, DumpId dumpId)
Definition: pg_dump.c:15303
void getSubscriptions(Archive *fout)
Definition: pg_dump.c:4632
static void collectSecLabels(Archive *fout)
Definition: pg_dump.c:15544
static void selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
Definition: pg_dump.c:2010
static Oid g_last_builtin_oid
Definition: pg_dump.c:105
ExtensionInfo * getExtensions(Archive *fout, int *numExtensions)
Definition: pg_dump.c:5609
TSParserInfo * getTSParsers(Archive *fout, int *numTSParsers)
Definition: pg_dump.c:9355
TransformInfo * getTransforms(Archive *fout, int *numTransforms)
Definition: pg_dump.c:8509
void getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
Definition: pg_dump.c:8020
static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode)
Definition: pg_dump.c:1359
static void read_dump_filters(const char *filename, DumpOptions *dopt)
Definition: pg_dump.c:18908
static void dumpTSConfig(Archive *fout, const TSConfigInfo *cfginfo)
Definition: pg_dump.c:14706
OprInfo * getOperators(Archive *fout, int *numOprs)
Definition: pg_dump.c:5854
static SecLabelItem * seclabels
Definition: pg_dump.c:154
static SimpleStringList tabledata_exclude_patterns_and_children
Definition: pg_dump.c:130
static bool checkExtensionMembership(DumpableObject *dobj, Archive *fout)
Definition: pg_dump.c:1682
RuleInfo * getRules(Archive *fout, int *numRules)
Definition: pg_dump.c:7919
static CommentItem * comments
Definition: pg_dump.c:150
static int dumpTableData_insert(Archive *fout, const void *dcontext)
Definition: pg_dump.c:2260
static SimpleOidList tabledata_exclude_oids
Definition: pg_dump.c:131
EventTriggerInfo * getEventTriggers(Archive *fout, int *numEventTriggers)
Definition: pg_dump.c:8216
static SimpleStringList table_exclude_patterns_and_children
Definition: pg_dump.c:127
TableInfo * getTables(Archive *fout, int *numTables)
Definition: pg_dump.c:6615
static void dumpSequence(Archive *fout, const TableInfo *tbinfo)
Definition: pg_dump.c:17436
bool shouldPrintColumn(const DumpOptions *dopt, const TableInfo *tbinfo, int colno)
Definition: pg_dump.c:9337
static TableInfo * getRootTableInfo(const TableInfo *tbinfo)
Definition: pg_dump.c:2521
static SimpleOidList foreign_servers_include_oids
Definition: pg_dump.c:134
static void dumpCollation(Archive *fout, const CollInfo *collinfo)
Definition: pg_dump.c:13759
static void dumpTableSecLabel(Archive *fout, const TableInfo *tbinfo, const char *reltypename)
Definition: pg_dump.c:15383
CastInfo * getCasts(Archive *fout, int *numCasts)
Definition: pg_dump.c:8393
static void dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo, PGresult *res)
Definition: pg_dump.c:11910
static void expand_extension_name_patterns(Archive *fout, SimpleStringList *patterns, SimpleOidList *oids, bool strict_names)
Definition: pg_dump.c:1456
static void selectDumpableType(TypeInfo *tyinfo, Archive *fout)
Definition: pg_dump.c:1857
static SimpleOidList schema_include_oids
Definition: pg_dump.c:119
static void dumpOpclass(Archive *fout, const OpclassInfo *opcinfo)
Definition: pg_dump.c:13259
static SimpleStringList schema_exclude_patterns
Definition: pg_dump.c:120
#define DUMP_COMPONENT_COMMENT
Definition: pg_dump.h:99
#define DUMP_COMPONENT_DATA
Definition: pg_dump.h:98
#define DUMP_COMPONENT_USERMAP
Definition: pg_dump.h:103
#define DUMP_COMPONENT_POLICY
Definition: pg_dump.h:102
#define DUMP_COMPONENT_SECLABEL
Definition: pg_dump.h:100
#define DUMP_COMPONENT_ALL
Definition: pg_dump.h:104
#define DUMP_COMPONENT_ACL
Definition: pg_dump.h:101
#define DUMP_COMPONENT_NONE
Definition: pg_dump.h:96
#define DUMP_COMPONENTS_REQUIRING_LOCK
Definition: pg_dump.h:128
void sortDumpableObjects(DumpableObject **objs, int numObjs, DumpId preBoundaryId, DumpId postBoundaryId)
Definition: pg_dump_sort.c:322
#define DUMP_COMPONENT_DEFINITION
Definition: pg_dump.h:97
@ DO_EVENT_TRIGGER
Definition: pg_dump.h:79
@ DO_REFRESH_MATVIEW
Definition: pg_dump.h:80
@ DO_POLICY
Definition: pg_dump.h:81
@ DO_CAST
Definition: pg_dump.h:63
@ DO_FOREIGN_SERVER
Definition: pg_dump.h:72
@ DO_PRE_DATA_BOUNDARY
Definition: pg_dump.h:77
@ DO_PROCLANG
Definition: pg_dump.h:62
@ DO_TYPE
Definition: pg_dump.h:42
@ DO_INDEX
Definition: pg_dump.h:55
@ DO_COLLATION
Definition: pg_dump.h:50
@ DO_LARGE_OBJECT
Definition: pg_dump.h:75
@ DO_TSCONFIG
Definition: pg_dump.h:70
@ DO_OPERATOR
Definition: pg_dump.h:46
@ DO_FK_CONSTRAINT
Definition: pg_dump.h:61
@ DO_CONSTRAINT
Definition: pg_dump.h:60
@ DO_SUBSCRIPTION
Definition: pg_dump.h:85
@ DO_DEFAULT_ACL
Definition: pg_dump.h:73
@ DO_FDW
Definition: pg_dump.h:71
@ DO_SUBSCRIPTION_REL
Definition: pg_dump.h:86
@ DO_SEQUENCE_SET
Definition: pg_dump.h:65
@ DO_ATTRDEF
Definition: pg_dump.h:54
@ DO_PUBLICATION_REL
Definition: pg_dump.h:83
@ DO_TABLE_ATTACH
Definition: pg_dump.h:53
@ DO_OPCLASS
Definition: pg_dump.h:48
@ DO_INDEX_ATTACH
Definition: pg_dump.h:56
@ DO_TSTEMPLATE
Definition: pg_dump.h:69
@ DO_STATSEXT
Definition: pg_dump.h:57
@ DO_FUNC
Definition: pg_dump.h:44
@ DO_POST_DATA_BOUNDARY
Definition: pg_dump.h:78
@ DO_LARGE_OBJECT_DATA
Definition: pg_dump.h:76
@ DO_OPFAMILY
Definition: pg_dump.h:49
@ DO_TRANSFORM
Definition: pg_dump.h:74
@ DO_ACCESS_METHOD
Definition: pg_dump.h:47
@ DO_PUBLICATION_TABLE_IN_SCHEMA
Definition: pg_dump.h:84
@ DO_CONVERSION
Definition: pg_dump.h:51
@ DO_TRIGGER
Definition: pg_dump.h:59
@ DO_RULE
Definition: pg_dump.h:58
@ DO_DUMMY_TYPE
Definition: pg_dump.h:66
@ DO_TSDICT
Definition: pg_dump.h:68
@ DO_TSPARSER
Definition: pg_dump.h:67
@ DO_EXTENSION
Definition: pg_dump.h:41
@ DO_TABLE_DATA
Definition: pg_dump.h:64
@ DO_PUBLICATION
Definition: pg_dump.h:82
@ DO_TABLE
Definition: pg_dump.h:52
@ DO_NAMESPACE
Definition: pg_dump.h:40
@ DO_AGG
Definition: pg_dump.h:45
@ DO_SHELL_TYPE
Definition: pg_dump.h:43
void sortDumpableObjectsByTypeName(DumpableObject **objs, int numObjs)
Definition: pg_dump_sort.c:189
#define exit_nicely(code)
Definition: pg_dumpall.c:126
static char * filename
Definition: pg_dumpall.c:121
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define LOGICALREP_ORIGIN_ANY
NameData subname
#define LOGICALREP_TWOPHASE_STATE_DISABLED
static char * buf
Definition: pg_test_fsync.c:73
char typalign
Definition: pg_type.h:176
#define pg_encoding_to_char
Definition: pg_wchar.h:569
char * tablespace
Definition: pgbench.c:216
#define pg_log_warning(...)
Definition: pgfnames.c:24
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * get_progname(const char *argv0)
Definition: path.c:574
#define snprintf
Definition: port.h:238
#define printf(...)
Definition: port.h:244
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define atooid(x)
Definition: postgres_ext.h:42
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendBinaryPQExpBuffer(PQExpBuffer str, const char *data, size_t datalen)
Definition: pqexpbuffer.c:397
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
char * c
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Oid RelFileNumber
Definition: relpath.h:25
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
bool quote_all_identifiers
Definition: ruleutils.c:323
void simple_string_list_append(SimpleStringList *list, const char *val)
Definition: simple_list.c:63
bool simple_oid_list_member(SimpleOidList *list, Oid val)
Definition: simple_list.c:45
void simple_oid_list_append(SimpleOidList *list, Oid val)
Definition: simple_list.c:26
struct SimplePtrList SimplePtrList
char * dbname
Definition: streamutil.c:51
PGconn * conn
Definition: streamutil.c:54
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
void appendPGArray(PQExpBuffer buffer, const char *value)
Definition: string_utils.c:740
bool processSQLNamePattern(PGconn *conn, PQExpBuffer buf, const char *pattern, bool have_where, bool force_escape, const char *schemavar, const char *namevar, const char *altnamevar, const char *visibilityrule, PQExpBuffer dbnamebuf, int *dotcnt)
Definition: string_utils.c:891
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
bool parsePGArray(const char *atext, char ***itemarray, int *nitems)
Definition: string_utils.c:657
bool appendReloptionsArray(PQExpBuffer buffer, const char *reloptions, const char *prefix, int encoding, bool std_strings)
Definition: string_utils.c:804
void appendStringLiteralDQ(PQExpBuffer buf, const char *str, const char *dqprefix)
Definition: string_utils.c:331
int minRemoteVersion
Definition: pg_backup.h:220
int remoteVersion
Definition: pg_backup.h:217
DumpOptions * dopt
Definition: pg_backup.h:212
bool * is_prepared
Definition: pg_backup.h:239
char * searchpath
Definition: pg_backup.h:231
bool isStandby
Definition: pg_backup.h:218
int maxRemoteVersion
Definition: pg_backup.h:221
bool std_strings
Definition: pg_backup.h:228
int numWorkers
Definition: pg_backup.h:223
int encoding
Definition: pg_backup.h:227
char * use_role
Definition: pg_backup.h:232
char * sync_snapshot_id
Definition: pg_backup.h:224
int verbose
Definition: pg_backup.h:215
Oid tableoid
Definition: pg_backup.h:264
Oid classoid
Definition: pg_dump.c:81
Oid objoid
Definition: pg_dump.c:82
int objsubid
Definition: pg_dump.c:83
const char * descr
Definition: pg_dump.c:80
const char * rolename
Definition: pg_dump.c:75
Oid roleoid
Definition: pg_dump.c:74
const char * provider
Definition: pg_dump.c:88
Oid classoid
Definition: pg_dump.c:90
int objsubid
Definition: pg_dump.c:92
const char * label
Definition: pg_dump.c:89
Oid objoid
Definition: pg_dump.c:91
SimpleOidListCell * head
Definition: simple_list.h:28
struct SimplePtrListCell * next
Definition: simple_list.h:48
SimplePtrListCell * head
Definition: simple_list.h:54
char val[FLEXIBLE_ARRAY_MEMBER]
Definition: simple_list.h:37
struct SimpleStringListCell * next
Definition: simple_list.h:34
SimpleStringListCell * head
Definition: simple_list.h:42
const char * rolname
Definition: pg_dump.h:616
bool puballtables
Definition: pg_dump.h:617
bool pubtruncate
Definition: pg_dump.h:621
DumpableObject dobj
Definition: pg_dump.h:615
NamespaceInfo * pubschema
Definition: pg_dump.h:646
DumpableObject dobj
Definition: pg_dump.h:644
PublicationInfo * publication
Definition: pg_dump.h:645
DumpableObject dobj
Definition: pg_dump.h:684
char * srsublsn
Definition: pg_dump.h:688
SubscriptionInfo * subinfo
Definition: pg_dump.h:685
TableInfo * tblinfo
Definition: pg_dump.h:686
char srsubstate
Definition: pg_dump.h:687
char * suboriginremotelsn
Definition: pg_dump.h:668
char * suborigin
Definition: pg_dump.h:667
char * subbinary
Definition: pg_dump.h:657
const char * rolname
Definition: pg_dump.h:655
char * subrunasowner
Definition: pg_dump.h:662
char * subsynccommit
Definition: pg_dump.h:665
char * subpublications
Definition: pg_dump.h:666
char * subtwophasestate
Definition: pg_dump.h:659
char * subfailover
Definition: pg_dump.h:669
char * subenabled
Definition: pg_dump.h:656
char * substream
Definition: pg_dump.h:658
char * subpasswordrequired
Definition: pg_dump.h:661
char * subslotname
Definition: pg_dump.h:664
char * subdisableonerr
Definition: pg_dump.h:660
char * subconninfo
Definition: pg_dump.h:663
DumpableObject dobj
Definition: pg_dump.h:654
char * amhandler
Definition: pg_dump.h:253
DumpableObject dobj
Definition: pg_dump.h:251
struct _tocEntry * toc
DumpableObject dobj
Definition: pg_dump.h:380
char * adef_expr
Definition: pg_dump.h:383
TableInfo * adtable
Definition: pg_dump.h:381
bool separate
Definition: pg_dump.h:384
char castmethod
Definition: pg_dump.h:505
Oid casttarget
Definition: pg_dump.h:502
char castcontext
Definition: pg_dump.h:504
DumpableObject dobj
Definition: pg_dump.h:500
Oid castsource
Definition: pg_dump.h:501
Oid castfunc
Definition: pg_dump.h:503
Oid cfgparser
Definition: pg_dump.h:553
DumpableObject dobj
Definition: pg_dump.h:551
const char * rolname
Definition: pg_dump.h:552
const char * rolname
Definition: pg_dump.h:271
DumpableObject dobj
Definition: pg_dump.h:270
char * pgport
Definition: pg_backup.h:85
char * pghost
Definition: pg_backup.h:86
trivalue promptPassword
Definition: pg_backup.h:88
char * username
Definition: pg_backup.h:87
char * dbname
Definition: pg_backup.h:84
TypeInfo * condomain
Definition: pg_dump.h:475
TableInfo * contable
Definition: pg_dump.h:474
bool condeferred
Definition: pg_dump.h:481
bool conperiod
Definition: pg_dump.h:482
bool conislocal
Definition: pg_dump.h:483
DumpableObject dobj
Definition: pg_dump.h:473
DumpId conindex
Definition: pg_dump.h:479
bool condeferrable
Definition: pg_dump.h:480
char * condef
Definition: pg_dump.h:477
DumpableObject dobj
Definition: pg_dump.h:276
const char * rolname
Definition: pg_dump.h:277
DumpableObject dobj
Definition: pg_dump.h:579
DumpableAcl dacl
Definition: pg_dump.h:580
const char * defaclrole
Definition: pg_dump.h:581
char defaclobjtype
Definition: pg_dump.h:582
char * dictinitoption
Definition: pg_dump.h:539
DumpableObject dobj
Definition: pg_dump.h:536
const char * rolname
Definition: pg_dump.h:537
Oid dicttemplate
Definition: pg_dump.h:538
bool dataOnly
Definition: pg_backup.h:168
int dump_inserts
Definition: pg_backup.h:172
int no_toast_compression
Definition: pg_backup.h:182
int column_inserts
Definition: pg_backup.h:176
bool dontOutputLOs
Definition: pg_backup.h:198
int use_setsessauth
Definition: pg_backup.h:188
int outputCreateDB
Definition: pg_backup.h:196
bool include_everything
Definition: pg_backup.h:193
int sequence_data
Definition: pg_backup.h:202
int disable_dollar_quoting
Definition: pg_backup.h:175
bool outputLOs
Definition: pg_backup.h:197
int no_comments
Definition: pg_backup.h:178
int serializable_deferrable
Definition: pg_backup.h:184
int outputNoTableAm
Definition: pg_backup.h:186
int enable_row_security
Definition: pg_backup.h:189
char * outputSuperuser
Definition: pg_backup.h:200
int dumpSections
Definition: pg_backup.h:169
int no_security_labels
Definition: pg_backup.h:179
int no_unlogged_table_data
Definition: pg_backup.h:183
int no_publications
Definition: pg_backup.h:180
ConnParams cparams
Definition: pg_backup.h:162
const char * lockWaitTimeout
Definition: pg_backup.h:171
int no_subscriptions
Definition: pg_backup.h:181
bool aclsSkip
Definition: pg_backup.h:170
int load_via_partition_root
Definition: pg_backup.h:190
int outputClean
Definition: pg_backup.h:195
int do_nothing
Definition: pg_backup.h:203
int outputNoTablespaces
Definition: pg_backup.h:187
int disable_triggers
Definition: pg_backup.h:185
int outputNoOwner
Definition: pg_backup.h:199
bool schemaOnly
Definition: pg_backup.h:167
int binary_upgrade
Definition: pg_backup.h:164
char privtype
Definition: pg_dump.h:159
char * acldefault
Definition: pg_dump.h:157
char * acl
Definition: pg_dump.h:156
char * initprivs
Definition: pg_dump.h:160
DumpableAcl dacl
Definition: pg_dump.h:167
DumpComponents dump
Definition: pg_dump.h:139
char * name
Definition: pg_dump.h:138
DumpId * dependencies
Definition: pg_dump.h:145
DumpId dumpId
Definition: pg_dump.h:137
bool ext_member
Definition: pg_dump.h:143
DumpComponents components
Definition: pg_dump.h:142
DumpableObjectType objType
Definition: pg_dump.h:135
CatalogId catId
Definition: pg_dump.h:136
DumpComponents dump_contains
Definition: pg_dump.h:141
bool depends_on_ext
Definition: pg_dump.h:144
char * evtevent
Definition: pg_dump.h:456
char * evtfname
Definition: pg_dump.h:459
char evtenabled
Definition: pg_dump.h:460
char * evtname
Definition: pg_dump.h:455
const char * evtowner
Definition: pg_dump.h:457
char * evttags
Definition: pg_dump.h:458
DumpableObject dobj
Definition: pg_dump.h:454
bool relocatable
Definition: pg_dump.h:182
char * extversion
Definition: pg_dump.h:184
DumpableObject dobj
Definition: pg_dump.h:181
char * extcondition
Definition: pg_dump.h:186
char * extconfig
Definition: pg_dump.h:185
char * fdwhandler
Definition: pg_dump.h:561
const char * rolname
Definition: pg_dump.h:560
char * fdwvalidator
Definition: pg_dump.h:562
char * fdwoptions
Definition: pg_dump.h:563
DumpableAcl dacl
Definition: pg_dump.h:559
DumpableObject dobj
Definition: pg_dump.h:558
DumpableAcl dacl
Definition: pg_dump.h:569
char * srvoptions
Definition: pg_dump.h:574
DumpableObject dobj
Definition: pg_dump.h:568
const char * rolname
Definition: pg_dump.h:570
char * srvversion
Definition: pg_dump.h:573
bool postponed_def
Definition: pg_dump.h:231
Oid lang
Definition: pg_dump.h:227
const char * rolname
Definition: pg_dump.h:226
Oid * argtypes
Definition: pg_dump.h:229
Oid prorettype
Definition: pg_dump.h:230
DumpableObject dobj
Definition: pg_dump.h:224
int nargs
Definition: pg_dump.h:228
DumpableAcl dacl
Definition: pg_dump.h:225
IndxInfo * partitionIdx
Definition: pg_dump.h:421
DumpableObject dobj
Definition: pg_dump.h:419
IndxInfo * parentIdx
Definition: pg_dump.h:420
bool indisreplident
Definition: pg_dump.h:408
int indnkeyattrs
Definition: pg_dump.h:403
char * indstatvals
Definition: pg_dump.h:402
char * indstatcols
Definition: pg_dump.h:401
int indnattrs
Definition: pg_dump.h:404
TableInfo * indextable
Definition: pg_dump.h:397
Oid parentidx
Definition: pg_dump.h:410
Oid * indkeys
Definition: pg_dump.h:405
char * indreloptions
Definition: pg_dump.h:400
DumpId indexconstraint
Definition: pg_dump.h:414
bool indisclustered
Definition: pg_dump.h:407
SimplePtrList partattaches
Definition: pg_dump.h:411
char * tablespace
Definition: pg_dump.h:399
bool indnullsnotdistinct
Definition: pg_dump.h:409
char * indexdef
Definition: pg_dump.h:398
DumpableObject dobj
Definition: pg_dump.h:396
Oid inhparent
Definition: pg_dump.h:521
Oid inhrelid
Definition: pg_dump.h:520
const char * rolname
Definition: pg_dump.h:589
DumpableObject dobj
Definition: pg_dump.h:587
DumpableAcl dacl
Definition: pg_dump.h:588
DumpableObject dobj
Definition: pg_dump.h:172
DumpableAcl dacl
Definition: pg_dump.h:173
const char * rolname
Definition: pg_dump.h:176
DumpableObject dobj
Definition: pg_dump.h:258
const char * rolname
Definition: pg_dump.h:259
const char * rolname
Definition: pg_dump.h:265
DumpableObject dobj
Definition: pg_dump.h:264
DumpableObject dobj
Definition: pg_dump.h:243
char oprkind
Definition: pg_dump.h:245
Oid oprcode
Definition: pg_dump.h:246
const char * rolname
Definition: pg_dump.h:244
TableInfo * poltable
Definition: pg_dump.h:601
char * polqual
Definition: pg_dump.h:606
char polcmd
Definition: pg_dump.h:603
char * polroles
Definition: pg_dump.h:605
char * polwithcheck
Definition: pg_dump.h:607
DumpableObject dobj
Definition: pg_dump.h:600
bool polpermissive
Definition: pg_dump.h:604
char * polname
Definition: pg_dump.h:602
Oid lanvalidator
Definition: pg_dump.h:494
DumpableAcl dacl
Definition: pg_dump.h:490
DumpableObject dobj
Definition: pg_dump.h:489
Oid laninline
Definition: pg_dump.h:493
const char * lanowner
Definition: pg_dump.h:495
Oid lanplcallfoid
Definition: pg_dump.h:492
bool lanpltrusted
Definition: pg_dump.h:491
DumpableObject dobj
Definition: pg_dump.h:526
Oid prstoken
Definition: pg_dump.h:528
Oid prslextype
Definition: pg_dump.h:531
Oid prsheadline
Definition: pg_dump.h:530
Oid prsstart
Definition: pg_dump.h:527
Oid prsend
Definition: pg_dump.h:529
int include_everything
Definition: pg_backup.h:124
int suppressDumpWarnings
Definition: pg_backup.h:150
ConnParams cparams
Definition: pg_backup.h:144
pg_compress_specification compression_spec
Definition: pg_backup.h:148
int no_subscriptions
Definition: pg_backup.h:114
int disable_dollar_quoting
Definition: pg_backup.h:107
const char * filename
Definition: pg_backup.h:117
int no_security_labels
Definition: pg_backup.h:113
char * superuser
Definition: pg_backup.h:104
const char * lockWaitTimeout
Definition: pg_backup.h:123
int enable_row_security
Definition: pg_backup.h:155
int disable_triggers
Definition: pg_backup.h:100
DumpableObject dobj
Definition: pg_dump.h:434
bool separate
Definition: pg_dump.h:439
char ev_enabled
Definition: pg_dump.h:438
bool is_instead
Definition: pg_dump.h:437
TableInfo * ruletable
Definition: pg_dump.h:435
char ev_type
Definition: pg_dump.h:436
TypeInfo * baseType
Definition: pg_dump.h:219
DumpableObject dobj
Definition: pg_dump.h:217
TableInfo * stattable
Definition: pg_dump.h:428
int stattarget
Definition: pg_dump.h:429
const char * rolname
Definition: pg_dump.h:427
DumpableObject dobj
Definition: pg_dump.h:426
TableInfo * partitionTbl
Definition: pg_dump.h:375
DumpableObject dobj
Definition: pg_dump.h:373
TableInfo * parentTbl
Definition: pg_dump.h:374
TableInfo * tdtable
Definition: pg_dump.h:390
DumpableObject dobj
Definition: pg_dump.h:389
char * filtercond
Definition: pg_dump.h:391
char * attidentity
Definition: pg_dump.h:339
char * reltablespace
Definition: pg_dump.h:292
char ** notnull_constrs
Definition: pg_dump.h:349
int ncheck
Definition: pg_dump.h:308
bool ispartition
Definition: pg_dump.h:322
struct _indxInfo * indexes
Definition: pg_dump.h:365
bool * attislocal
Definition: pg_dump.h:343
DumpableObject dobj
Definition: pg_dump.h:285
bool is_identity_sequence
Definition: pg_dump.h:315
Oid reloftype
Definition: pg_dump.h:310
int numParents
Definition: pg_dump.h:325
bool interesting
Definition: pg_dump.h:319
char * toast_reloptions
Definition: pg_dump.h:295
struct _tableInfo ** parents
Definition: pg_dump.h:326
DumpableAcl dacl
Definition: pg_dump.h:286
bool relispopulated
Definition: pg_dump.h:290
char * attgenerated
Definition: pg_dump.h:340
int * attlen
Definition: pg_dump.h:341
Oid reltype
Definition: pg_dump.h:309
char ** attfdwoptions
Definition: pg_dump.h:347
bool hasoids
Definition: pg_dump.h:302
Oid toast_oid
Definition: pg_dump.h:305
Oid foreign_server
Definition: pg_dump.h:311
bool hasrules
Definition: pg_dump.h:297
struct _triggerInfo * triggers
Definition: pg_dump.h:368
bool * attisdropped
Definition: pg_dump.h:338
bool needs_override
Definition: pg_dump.h:358
struct _constraintInfo * checkexprs
Definition: pg_dump.h:357
int * attstattarget
Definition: pg_dump.h:335
uint32 frozenxid
Definition: pg_dump.h:303
char * typstorage
Definition: pg_dump.h:337
int owning_col
Definition: pg_dump.h:314
char * checkoption
Definition: pg_dump.h:294
int numatts
Definition: pg_dump.h:332
bool hastriggers
Definition: pg_dump.h:298
const char * rolname
Definition: pg_dump.h:287
struct _attrDefInfo ** attrdefs
Definition: pg_dump.h:356
char ** attoptions
Definition: pg_dump.h:344
bool * notnull_throwaway
Definition: pg_dump.h:354
char relreplident
Definition: pg_dump.h:291
int numTriggers
Definition: pg_dump.h:367
uint32 minmxid
Definition: pg_dump.h:304
Oid * attcollation
Definition: pg_dump.h:345
bool * notnull_noinh
Definition: pg_dump.h:353
char * attstorage
Definition: pg_dump.h:336
int toastpages
Definition: pg_dump.h:317
Oid owning_tab
Definition: pg_dump.h:313
struct _tableDataInfo * dataObj
Definition: pg_dump.h:366
char * amname
Definition: pg_dump.h:359
bool dummy_view
Definition: pg_dump.h:320
bool forcerowsec
Definition: pg_dump.h:301
bool hascolumnACLs
Definition: pg_dump.h:299
char ** atttypnames
Definition: pg_dump.h:334
char ** attmissingval
Definition: pg_dump.h:348
char relpersistence
Definition: pg_dump.h:289
char ** attnames
Definition: pg_dump.h:333
char relkind
Definition: pg_dump.h:288
bool hasindex
Definition: pg_dump.h:296
bool unsafe_partitions
Definition: pg_dump.h:323
char * reloptions
Definition: pg_dump.h:293
int numIndexes
Definition: pg_dump.h:364
int relpages
Definition: pg_dump.h:316
uint32 toast_frozenxid
Definition: pg_dump.h:306
uint32 toast_minmxid
Definition: pg_dump.h:307
char * attalign
Definition: pg_dump.h:342
char * attcompression
Definition: pg_dump.h:346
bool postponed_def
Definition: pg_dump.h:321
bool * notnull_inh
Definition: pg_dump.h:355
bool rowsec
Definition: pg_dump.h:300
Oid tmpllexize
Definition: pg_dump.h:546
Oid tmplinit
Definition: pg_dump.h:545
DumpableObject dobj
Definition: pg_dump.h:544
pgoff_t dataLength
struct _tocEntry * next
DumpId * dependencies
DumpableObject dobj
Definition: pg_dump.h:510
Oid trffromsql
Definition: pg_dump.h:513
TableInfo * tgtable
Definition: pg_dump.h:446
DumpableObject dobj
Definition: pg_dump.h:445
char tgenabled
Definition: pg_dump.h:447
char * tgdef
Definition: pg_dump.h:449
bool tgispartition
Definition: pg_dump.h:448
bool isMultirange
Definition: pg_dump.h:206
struct _constraintInfo * domChecks
Definition: pg_dump.h:212
DumpableAcl dacl
Definition: pg_dump.h:192
DumpableObject dobj
Definition: pg_dump.h:191
bool isDefined
Definition: pg_dump.h:207
char * ftypname
Definition: pg_dump.h:199
char typrelkind
Definition: pg_dump.h:203
Oid typelem
Definition: pg_dump.h:201
struct _shellTypeInfo * shellType
Definition: pg_dump.h:209
int nDomChecks
Definition: pg_dump.h:211
char typtype
Definition: pg_dump.h:204
const char * rolname
Definition: pg_dump.h:200
Oid typrelid
Definition: pg_dump.h:202
bool isArray
Definition: pg_dump.h:205
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
#define MaxCommandIdAttributeNumber
Definition: sysattr.h:25
#define MaxTransactionIdAttributeNumber
Definition: sysattr.h:24
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
#define MinCommandIdAttributeNumber
Definition: sysattr.h:23
static StringInfo copybuf
Definition: tablesync.c:130
static void * fn(void *arg)
Definition: thread-alloc.c:119
#define FirstNormalObjectId
Definition: transam.h:197
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3704
const char * description
const char * type
const char * name
ArchiveMode
Definition: xlog.h:62