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-2019, 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 "getopt_long.h"
42 
43 #include "access/attnum.h"
44 #include "access/sysattr.h"
45 #include "access/transam.h"
46 #include "catalog/pg_aggregate_d.h"
47 #include "catalog/pg_am_d.h"
48 #include "catalog/pg_attribute_d.h"
49 #include "catalog/pg_cast_d.h"
50 #include "catalog/pg_class_d.h"
51 #include "catalog/pg_default_acl_d.h"
52 #include "catalog/pg_largeobject_d.h"
53 #include "catalog/pg_largeobject_metadata_d.h"
54 #include "catalog/pg_proc_d.h"
55 #include "catalog/pg_trigger_d.h"
56 #include "catalog/pg_type_d.h"
57 #include "libpq/libpq-fs.h"
58 #include "storage/block.h"
59 
60 #include "dumputils.h"
61 #include "parallel.h"
62 #include "pg_backup_db.h"
63 #include "pg_backup_utils.h"
64 #include "pg_dump.h"
65 #include "fe_utils/connect.h"
66 #include "fe_utils/string_utils.h"
67 
68 
69 typedef struct
70 {
71  const char *descr; /* comment for an object */
72  Oid classoid; /* object class (catalog OID) */
73  Oid objoid; /* object OID */
74  int objsubid; /* subobject (table column #) */
75 } CommentItem;
76 
77 typedef struct
78 {
79  const char *provider; /* label provider of this security label */
80  const char *label; /* security label for an object */
81  Oid classoid; /* object class (catalog OID) */
82  Oid objoid; /* object OID */
83  int objsubid; /* subobject (table column #) */
84 } SecLabelItem;
85 
86 typedef enum OidOptions
87 {
89  zeroAsAny = 2,
92 } OidOptions;
93 
94 /* global decls */
95 static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
96 
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
99 
100 /*
101  * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102  * FirstNormalObjectId - 1.
103  */
104 static Oid g_last_builtin_oid; /* value of the last builtin oid */
105 
106 /* The specified names/patterns should to match at least one entity */
107 static int strict_names = 0;
108 
109 /*
110  * Object inclusion/exclusion lists
111  *
112  * The string lists record the patterns given by command-line switches,
113  * which we then convert to lists of OIDs of matching objects.
114  */
116 static SimpleOidList schema_include_oids = {NULL, NULL};
118 static SimpleOidList schema_exclude_oids = {NULL, NULL};
119 
121 static SimpleOidList table_include_oids = {NULL, NULL};
123 static SimpleOidList table_exclude_oids = {NULL, NULL};
125 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
126 
127 
128 char g_opaque_type[10]; /* name for the opaque type */
129 
130 /* placeholders for the delimiters for comments */
132 char g_comment_end[10];
133 
134 static const CatalogId nilCatalogId = {0, 0};
135 
136 /* override for standard extra_float_digits setting */
137 static bool have_extra_float_digits = false;
139 
140 /*
141  * The default number of rows per INSERT when
142  * --inserts is specified without --rows-per-insert
143  */
144 #define DUMP_DEFAULT_ROWS_PER_INSERT 1
145 
146 /*
147  * Macro for producing quoted, schema-qualified name of a dumpable object.
148  */
149 #define fmtQualifiedDumpable(obj) \
150  fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
151  (obj)->dobj.name)
152 
153 static void help(const char *progname);
154 static void setup_connection(Archive *AH,
155  const char *dumpencoding, const char *dumpsnapshot,
156  char *use_role);
158 static void expand_schema_name_patterns(Archive *fout,
159  SimpleStringList *patterns,
160  SimpleOidList *oids,
161  bool strict_names);
162 static void expand_table_name_patterns(Archive *fout,
163  SimpleStringList *patterns,
164  SimpleOidList *oids,
165  bool strict_names);
166 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
167 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
168 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
169 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
170 static void dumpComment(Archive *fout, const char *type, const char *name,
171  const char *namespace, const char *owner,
172  CatalogId catalogId, int subid, DumpId dumpId);
173 static int findComments(Archive *fout, Oid classoid, Oid objoid,
174  CommentItem **items);
175 static int collectComments(Archive *fout, CommentItem **items);
176 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
177  const char *namespace, const char *owner,
178  CatalogId catalogId, int subid, DumpId dumpId);
179 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
180  SecLabelItem **items);
181 static int collectSecLabels(Archive *fout, SecLabelItem **items);
182 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
183 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
184 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
185 static void dumpType(Archive *fout, TypeInfo *tyinfo);
186 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
187 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
188 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
189 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
190 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
191 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
192 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
193 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
194 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
195 static void dumpFunc(Archive *fout, FuncInfo *finfo);
196 static void dumpCast(Archive *fout, CastInfo *cast);
197 static void dumpTransform(Archive *fout, TransformInfo *transform);
198 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
199 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
200 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
201 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
202 static void dumpCollation(Archive *fout, CollInfo *collinfo);
203 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
204 static void dumpRule(Archive *fout, RuleInfo *rinfo);
205 static void dumpAgg(Archive *fout, AggInfo *agginfo);
206 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
207 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
208 static void dumpTable(Archive *fout, TableInfo *tbinfo);
209 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
210 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
211 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
212 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
213 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
214 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
215 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
216 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
217 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
218 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
219 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
220 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
221 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
222 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
223 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
224 static void dumpUserMappings(Archive *fout,
225  const char *servername, const char *namespace,
226  const char *owner, CatalogId catalogId, DumpId dumpId);
227 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
228 
229 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
230  const char *type, const char *name, const char *subname,
231  const char *nspname, const char *owner,
232  const char *acls, const char *racls,
233  const char *initacls, const char *initracls);
234 
235 static void getDependencies(Archive *fout);
236 static void BuildArchiveDependencies(Archive *fout);
238  DumpId **dependencies, int *nDeps, int *allocDeps);
239 
241 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
242  DumpableObject *boundaryObjs);
243 
244 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
245 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind);
246 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo);
247 static void buildMatViewRefreshDependencies(Archive *fout);
248 static void getTableDataFKConstraints(void);
249 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
250  bool is_agg);
251 static char *format_function_arguments_old(Archive *fout,
252  FuncInfo *finfo, int nallargs,
253  char **allargtypes,
254  char **argmodes,
255  char **argnames);
256 static char *format_function_signature(Archive *fout,
257  FuncInfo *finfo, bool honor_quotes);
258 static char *convertRegProcReference(Archive *fout,
259  const char *proc);
260 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
261 static char *convertTSFunction(Archive *fout, Oid funcOid);
262 static Oid findLastBuiltinOid_V71(Archive *fout);
263 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
264 static void getBlobs(Archive *fout);
265 static void dumpBlob(Archive *fout, BlobInfo *binfo);
266 static int dumpBlobs(Archive *fout, void *arg);
267 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
268 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
269 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
270 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
271 static void dumpDatabase(Archive *AH);
272 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
273  const char *dbname, Oid dboid);
274 static void dumpEncoding(Archive *AH);
275 static void dumpStdStrings(Archive *AH);
276 static void dumpSearchPath(Archive *AH);
278  PQExpBuffer upgrade_buffer,
279  Oid pg_type_oid,
280  bool force_array_type);
282  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
283 static void binary_upgrade_set_pg_class_oids(Archive *fout,
284  PQExpBuffer upgrade_buffer,
285  Oid pg_class_oid, bool is_index);
286 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
287  DumpableObject *dobj,
288  const char *objtype,
289  const char *objname,
290  const char *objnamespace);
291 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
292 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
293 static bool nonemptyReloptions(const char *reloptions);
294 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
295  const char *prefix, Archive *fout);
296 static char *get_synchronized_snapshot(Archive *fout);
297 static void setupDumpWorker(Archive *AHX);
298 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
299 
300 
301 int
302 main(int argc, char **argv)
303 {
304  int c;
305  const char *filename = NULL;
306  const char *format = "p";
307  TableInfo *tblinfo;
308  int numTables;
309  DumpableObject **dobjs;
310  int numObjs;
311  DumpableObject *boundaryObjs;
312  int i;
313  int optindex;
314  char *endptr;
315  RestoreOptions *ropt;
316  Archive *fout; /* the script file */
317  bool g_verbose = false;
318  const char *dumpencoding = NULL;
319  const char *dumpsnapshot = NULL;
320  char *use_role = NULL;
321  long rowsPerInsert;
322  int numWorkers = 1;
323  trivalue prompt_password = TRI_DEFAULT;
324  int compressLevel = -1;
325  int plainText = 0;
326  ArchiveFormat archiveFormat = archUnknown;
327  ArchiveMode archiveMode;
328 
329  static DumpOptions dopt;
330 
331  static struct option long_options[] = {
332  {"data-only", no_argument, NULL, 'a'},
333  {"blobs", no_argument, NULL, 'b'},
334  {"no-blobs", no_argument, NULL, 'B'},
335  {"clean", no_argument, NULL, 'c'},
336  {"create", no_argument, NULL, 'C'},
337  {"dbname", required_argument, NULL, 'd'},
338  {"file", required_argument, NULL, 'f'},
339  {"format", required_argument, NULL, 'F'},
340  {"host", required_argument, NULL, 'h'},
341  {"jobs", 1, NULL, 'j'},
342  {"no-reconnect", no_argument, NULL, 'R'},
343  {"no-owner", no_argument, NULL, 'O'},
344  {"port", required_argument, NULL, 'p'},
345  {"schema", required_argument, NULL, 'n'},
346  {"exclude-schema", required_argument, NULL, 'N'},
347  {"schema-only", no_argument, NULL, 's'},
348  {"superuser", required_argument, NULL, 'S'},
349  {"table", required_argument, NULL, 't'},
350  {"exclude-table", required_argument, NULL, 'T'},
351  {"no-password", no_argument, NULL, 'w'},
352  {"password", no_argument, NULL, 'W'},
353  {"username", required_argument, NULL, 'U'},
354  {"verbose", no_argument, NULL, 'v'},
355  {"no-privileges", no_argument, NULL, 'x'},
356  {"no-acl", no_argument, NULL, 'x'},
357  {"compress", required_argument, NULL, 'Z'},
358  {"encoding", required_argument, NULL, 'E'},
359  {"help", no_argument, NULL, '?'},
360  {"version", no_argument, NULL, 'V'},
361 
362  /*
363  * the following options don't have an equivalent short option letter
364  */
365  {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
366  {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
367  {"column-inserts", no_argument, &dopt.column_inserts, 1},
368  {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
369  {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
370  {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
371  {"exclude-table-data", required_argument, NULL, 4},
372  {"extra-float-digits", required_argument, NULL, 8},
373  {"if-exists", no_argument, &dopt.if_exists, 1},
374  {"inserts", no_argument, NULL, 9},
375  {"lock-wait-timeout", required_argument, NULL, 2},
376  {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
377  {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
378  {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
379  {"role", required_argument, NULL, 3},
380  {"section", required_argument, NULL, 5},
381  {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
382  {"snapshot", required_argument, NULL, 6},
383  {"strict-names", no_argument, &strict_names, 1},
384  {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
385  {"no-comments", no_argument, &dopt.no_comments, 1},
386  {"no-publications", no_argument, &dopt.no_publications, 1},
387  {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
388  {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
389  {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
390  {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
391  {"no-sync", no_argument, NULL, 7},
392  {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
393  {"rows-per-insert", required_argument, NULL, 10},
394 
395  {NULL, 0, NULL, 0}
396  };
397 
398  pg_logging_init(argv[0]);
400  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
401 
402  /*
403  * Initialize what we need for parallel execution, especially for thread
404  * support on Windows.
405  */
407 
408  strcpy(g_comment_start, "-- ");
409  g_comment_end[0] = '\0';
410  strcpy(g_opaque_type, "opaque");
411 
412  progname = get_progname(argv[0]);
413 
414  if (argc > 1)
415  {
416  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
417  {
418  help(progname);
419  exit_nicely(0);
420  }
421  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
422  {
423  puts("pg_dump (PostgreSQL) " PG_VERSION);
424  exit_nicely(0);
425  }
426  }
427 
428  InitDumpOptions(&dopt);
429 
430  while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:Op:RsS:t:T:U:vwWxZ:",
431  long_options, &optindex)) != -1)
432  {
433  switch (c)
434  {
435  case 'a': /* Dump data only */
436  dopt.dataOnly = true;
437  break;
438 
439  case 'b': /* Dump blobs */
440  dopt.outputBlobs = true;
441  break;
442 
443  case 'B': /* Don't dump blobs */
444  dopt.dontOutputBlobs = true;
445  break;
446 
447  case 'c': /* clean (i.e., drop) schema prior to create */
448  dopt.outputClean = 1;
449  break;
450 
451  case 'C': /* Create DB */
452  dopt.outputCreateDB = 1;
453  break;
454 
455  case 'd': /* database name */
456  dopt.dbname = pg_strdup(optarg);
457  break;
458 
459  case 'E': /* Dump encoding */
460  dumpencoding = pg_strdup(optarg);
461  break;
462 
463  case 'f':
464  filename = pg_strdup(optarg);
465  break;
466 
467  case 'F':
468  format = pg_strdup(optarg);
469  break;
470 
471  case 'h': /* server host */
472  dopt.pghost = pg_strdup(optarg);
473  break;
474 
475  case 'j': /* number of dump jobs */
476  numWorkers = atoi(optarg);
477  break;
478 
479  case 'n': /* include schema(s) */
480  simple_string_list_append(&schema_include_patterns, optarg);
481  dopt.include_everything = false;
482  break;
483 
484  case 'N': /* exclude schema(s) */
485  simple_string_list_append(&schema_exclude_patterns, optarg);
486  break;
487 
488  case 'O': /* Don't reconnect to match owner */
489  dopt.outputNoOwner = 1;
490  break;
491 
492  case 'p': /* server port */
493  dopt.pgport = pg_strdup(optarg);
494  break;
495 
496  case 'R':
497  /* no-op, still accepted for backwards compatibility */
498  break;
499 
500  case 's': /* dump schema only */
501  dopt.schemaOnly = true;
502  break;
503 
504  case 'S': /* Username for superuser in plain text output */
506  break;
507 
508  case 't': /* include table(s) */
509  simple_string_list_append(&table_include_patterns, optarg);
510  dopt.include_everything = false;
511  break;
512 
513  case 'T': /* exclude table(s) */
514  simple_string_list_append(&table_exclude_patterns, optarg);
515  break;
516 
517  case 'U':
518  dopt.username = pg_strdup(optarg);
519  break;
520 
521  case 'v': /* verbose */
522  g_verbose = true;
524  break;
525 
526  case 'w':
527  prompt_password = TRI_NO;
528  break;
529 
530  case 'W':
531  prompt_password = TRI_YES;
532  break;
533 
534  case 'x': /* skip ACL dump */
535  dopt.aclsSkip = true;
536  break;
537 
538  case 'Z': /* Compression Level */
539  compressLevel = atoi(optarg);
540  if (compressLevel < 0 || compressLevel > 9)
541  {
542  pg_log_error("compression level must be in range 0..9");
543  exit_nicely(1);
544  }
545  break;
546 
547  case 0:
548  /* This covers the long options. */
549  break;
550 
551  case 2: /* lock-wait-timeout */
553  break;
554 
555  case 3: /* SET ROLE */
556  use_role = pg_strdup(optarg);
557  break;
558 
559  case 4: /* exclude table(s) data */
560  simple_string_list_append(&tabledata_exclude_patterns, optarg);
561  break;
562 
563  case 5: /* section */
565  break;
566 
567  case 6: /* snapshot */
568  dumpsnapshot = pg_strdup(optarg);
569  break;
570 
571  case 7: /* no-sync */
572  dosync = false;
573  break;
574 
575  case 8:
577  extra_float_digits = atoi(optarg);
578  if (extra_float_digits < -15 || extra_float_digits > 3)
579  {
580  pg_log_error("extra_float_digits must be in range -15..3");
581  exit_nicely(1);
582  }
583  break;
584 
585  case 9: /* inserts */
586 
587  /*
588  * dump_inserts also stores --rows-per-insert, careful not to
589  * overwrite that.
590  */
591  if (dopt.dump_inserts == 0)
593  break;
594 
595  case 10: /* rows per insert */
596  errno = 0;
597  rowsPerInsert = strtol(optarg, &endptr, 10);
598 
599  if (endptr == optarg || *endptr != '\0' ||
600  rowsPerInsert <= 0 || rowsPerInsert > INT_MAX ||
601  errno == ERANGE)
602  {
603  pg_log_error("rows-per-insert must be in range %d..%d",
604  1, INT_MAX);
605  exit_nicely(1);
606  }
607  dopt.dump_inserts = (int) rowsPerInsert;
608  break;
609 
610  default:
611  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
612  exit_nicely(1);
613  }
614  }
615 
616  /*
617  * Non-option argument specifies database name as long as it wasn't
618  * already specified with -d / --dbname
619  */
620  if (optind < argc && dopt.dbname == NULL)
621  dopt.dbname = argv[optind++];
622 
623  /* Complain if any arguments remain */
624  if (optind < argc)
625  {
626  pg_log_error("too many command-line arguments (first is \"%s\")",
627  argv[optind]);
628  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
629  progname);
630  exit_nicely(1);
631  }
632 
633  /* --column-inserts implies --inserts */
634  if (dopt.column_inserts && dopt.dump_inserts == 0)
636 
637  /*
638  * Binary upgrade mode implies dumping sequence data even in schema-only
639  * mode. This is not exposed as a separate option, but kept separate
640  * internally for clarity.
641  */
642  if (dopt.binary_upgrade)
643  dopt.sequence_data = 1;
644 
645  if (dopt.dataOnly && dopt.schemaOnly)
646  {
647  pg_log_error("options -s/--schema-only and -a/--data-only cannot be used together");
648  exit_nicely(1);
649  }
650 
651  if (dopt.dataOnly && dopt.outputClean)
652  {
653  pg_log_error("options -c/--clean and -a/--data-only cannot be used together");
654  exit_nicely(1);
655  }
656 
657  if (dopt.if_exists && !dopt.outputClean)
658  fatal("option --if-exists requires option -c/--clean");
659 
660  /*
661  * --inserts are already implied above if --column-inserts or
662  * --rows-per-insert were specified.
663  */
664  if (dopt.do_nothing && dopt.dump_inserts == 0)
665  fatal("option --on-conflict-do-nothing requires option --inserts, --rows-per-insert or --column-inserts");
666 
667  /* Identify archive format to emit */
668  archiveFormat = parseArchiveFormat(format, &archiveMode);
669 
670  /* archiveFormat specific setup */
671  if (archiveFormat == archNull)
672  plainText = 1;
673 
674  /* Custom and directory formats are compressed by default, others not */
675  if (compressLevel == -1)
676  {
677 #ifdef HAVE_LIBZ
678  if (archiveFormat == archCustom || archiveFormat == archDirectory)
679  compressLevel = Z_DEFAULT_COMPRESSION;
680  else
681 #endif
682  compressLevel = 0;
683  }
684 
685 #ifndef HAVE_LIBZ
686  if (compressLevel != 0)
687  pg_log_warning("requested compression not available in this installation -- archive will be uncompressed");
688  compressLevel = 0;
689 #endif
690 
691  /*
692  * If emitting an archive format, we always want to emit a DATABASE item,
693  * in case --create is specified at pg_restore time.
694  */
695  if (!plainText)
696  dopt.outputCreateDB = 1;
697 
698  /*
699  * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
700  * parallel jobs because that's the maximum limit for the
701  * WaitForMultipleObjects() call.
702  */
703  if (numWorkers <= 0
704 #ifdef WIN32
705  || numWorkers > MAXIMUM_WAIT_OBJECTS
706 #endif
707  )
708  fatal("invalid number of parallel jobs");
709 
710  /* Parallel backup only in the directory archive format so far */
711  if (archiveFormat != archDirectory && numWorkers > 1)
712  fatal("parallel backup only supported by the directory format");
713 
714  /* Open the output file */
715  fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
716  archiveMode, setupDumpWorker);
717 
718  /* Make dump options accessible right away */
719  SetArchiveOptions(fout, &dopt, NULL);
720 
721  /* Register the cleanup hook */
722  on_exit_close_archive(fout);
723 
724  /* Let the archiver know how noisy to be */
725  fout->verbose = g_verbose;
726 
727 
728  /*
729  * We allow the server to be back to 8.0, and up to any minor release of
730  * our own major version. (See also version check in pg_dumpall.c.)
731  */
732  fout->minRemoteVersion = 80000;
733  fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
734 
735  fout->numWorkers = numWorkers;
736 
737  /*
738  * Open the database using the Archiver, so it knows about it. Errors mean
739  * death.
740  */
741  ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
742  setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
743 
744  /*
745  * Disable security label support if server version < v9.1.x (prevents
746  * access to nonexistent pg_seclabel catalog)
747  */
748  if (fout->remoteVersion < 90100)
749  dopt.no_security_labels = 1;
750 
751  /*
752  * On hot standbys, never try to dump unlogged table data, since it will
753  * just throw an error.
754  */
755  if (fout->isStandby)
756  dopt.no_unlogged_table_data = true;
757 
758  /* Select the appropriate subquery to convert user IDs to names */
759  if (fout->remoteVersion >= 80100)
760  username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
761  else
762  username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
763 
764  /* check the version for the synchronized snapshots feature */
765  if (numWorkers > 1 && fout->remoteVersion < 90200
766  && !dopt.no_synchronized_snapshots)
767  fatal("Synchronized snapshots are not supported by this server version.\n"
768  "Run with --no-synchronized-snapshots instead if you do not need\n"
769  "synchronized snapshots.");
770 
771  /* check the version when a snapshot is explicitly specified by user */
772  if (dumpsnapshot && fout->remoteVersion < 90200)
773  fatal("Exported snapshots are not supported by this server version.");
774 
775  /*
776  * Find the last built-in OID, if needed (prior to 8.1)
777  *
778  * With 8.1 and above, we can just use FirstNormalObjectId - 1.
779  */
780  if (fout->remoteVersion < 80100)
782  else
784 
785  pg_log_info("last built-in OID is %u", g_last_builtin_oid);
786 
787  /* Expand schema selection patterns into OID lists */
788  if (schema_include_patterns.head != NULL)
789  {
790  expand_schema_name_patterns(fout, &schema_include_patterns,
791  &schema_include_oids,
792  strict_names);
793  if (schema_include_oids.head == NULL)
794  fatal("no matching schemas were found");
795  }
796  expand_schema_name_patterns(fout, &schema_exclude_patterns,
797  &schema_exclude_oids,
798  false);
799  /* non-matching exclusion patterns aren't an error */
800 
801  /* Expand table selection patterns into OID lists */
802  if (table_include_patterns.head != NULL)
803  {
804  expand_table_name_patterns(fout, &table_include_patterns,
805  &table_include_oids,
806  strict_names);
807  if (table_include_oids.head == NULL)
808  fatal("no matching tables were found");
809  }
810  expand_table_name_patterns(fout, &table_exclude_patterns,
811  &table_exclude_oids,
812  false);
813 
814  expand_table_name_patterns(fout, &tabledata_exclude_patterns,
815  &tabledata_exclude_oids,
816  false);
817 
818  /* non-matching exclusion patterns aren't an error */
819 
820  /*
821  * Dumping blobs is the default for dumps where an inclusion switch is not
822  * used (an "include everything" dump). -B can be used to exclude blobs
823  * from those dumps. -b can be used to include blobs even when an
824  * inclusion switch is used.
825  *
826  * -s means "schema only" and blobs are data, not schema, so we never
827  * include blobs when -s is used.
828  */
829  if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
830  dopt.outputBlobs = true;
831 
832  /*
833  * Now scan the database and create DumpableObject structs for all the
834  * objects we intend to dump.
835  */
836  tblinfo = getSchemaData(fout, &numTables);
837 
838  if (fout->remoteVersion < 80400)
839  guessConstraintInheritance(tblinfo, numTables);
840 
841  if (!dopt.schemaOnly)
842  {
843  getTableData(&dopt, tblinfo, numTables, 0);
845  if (dopt.dataOnly)
847  }
848 
849  if (dopt.schemaOnly && dopt.sequence_data)
850  getTableData(&dopt, tblinfo, numTables, RELKIND_SEQUENCE);
851 
852  /*
853  * In binary-upgrade mode, we do not have to worry about the actual blob
854  * data or the associated metadata that resides in the pg_largeobject and
855  * pg_largeobject_metadata tables, respectively.
856  *
857  * However, we do need to collect blob information as there may be
858  * comments or other information on blobs that we do need to dump out.
859  */
860  if (dopt.outputBlobs || dopt.binary_upgrade)
861  getBlobs(fout);
862 
863  /*
864  * Collect dependency data to assist in ordering the objects.
865  */
866  getDependencies(fout);
867 
868  /* Lastly, create dummy objects to represent the section boundaries */
869  boundaryObjs = createBoundaryObjects();
870 
871  /* Get pointers to all the known DumpableObjects */
872  getDumpableObjects(&dobjs, &numObjs);
873 
874  /*
875  * Add dummy dependencies to enforce the dump section ordering.
876  */
877  addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
878 
879  /*
880  * Sort the objects into a safe dump order (no forward references).
881  *
882  * We rely on dependency information to help us determine a safe order, so
883  * the initial sort is mostly for cosmetic purposes: we sort by name to
884  * ensure that logically identical schemas will dump identically.
885  */
886  sortDumpableObjectsByTypeName(dobjs, numObjs);
887 
888  sortDumpableObjects(dobjs, numObjs,
889  boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
890 
891  /*
892  * Create archive TOC entries for all the objects to be dumped, in a safe
893  * order.
894  */
895 
896  /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
897  dumpEncoding(fout);
898  dumpStdStrings(fout);
899  dumpSearchPath(fout);
900 
901  /* The database items are always next, unless we don't want them at all */
902  if (dopt.outputCreateDB)
903  dumpDatabase(fout);
904 
905  /* Now the rearrangeable objects. */
906  for (i = 0; i < numObjs; i++)
907  dumpDumpableObject(fout, dobjs[i]);
908 
909  /*
910  * Set up options info to ensure we dump what we want.
911  */
912  ropt = NewRestoreOptions();
913  ropt->filename = filename;
914 
915  /* if you change this list, see dumpOptionsFromRestoreOptions */
916  ropt->dropSchema = dopt.outputClean;
917  ropt->dataOnly = dopt.dataOnly;
918  ropt->schemaOnly = dopt.schemaOnly;
919  ropt->if_exists = dopt.if_exists;
920  ropt->column_inserts = dopt.column_inserts;
921  ropt->dumpSections = dopt.dumpSections;
922  ropt->aclsSkip = dopt.aclsSkip;
923  ropt->superuser = dopt.outputSuperuser;
924  ropt->createDB = dopt.outputCreateDB;
925  ropt->noOwner = dopt.outputNoOwner;
926  ropt->noTablespace = dopt.outputNoTablespaces;
927  ropt->disable_triggers = dopt.disable_triggers;
928  ropt->use_setsessauth = dopt.use_setsessauth;
930  ropt->dump_inserts = dopt.dump_inserts;
931  ropt->no_comments = dopt.no_comments;
932  ropt->no_publications = dopt.no_publications;
934  ropt->no_subscriptions = dopt.no_subscriptions;
935  ropt->lockWaitTimeout = dopt.lockWaitTimeout;
938  ropt->sequence_data = dopt.sequence_data;
939  ropt->binary_upgrade = dopt.binary_upgrade;
940 
941  if (compressLevel == -1)
942  ropt->compression = 0;
943  else
944  ropt->compression = compressLevel;
945 
946  ropt->suppressDumpWarnings = true; /* We've already shown them */
947 
948  SetArchiveOptions(fout, &dopt, ropt);
949 
950  /* Mark which entries should be output */
952 
953  /*
954  * The archive's TOC entries are now marked as to which ones will actually
955  * be output, so we can set up their dependency lists properly. This isn't
956  * necessary for plain-text output, though.
957  */
958  if (!plainText)
960 
961  /*
962  * And finally we can do the actual output.
963  *
964  * Note: for non-plain-text output formats, the output file is written
965  * inside CloseArchive(). This is, um, bizarre; but not worth changing
966  * right now.
967  */
968  if (plainText)
969  RestoreArchive(fout);
970 
971  CloseArchive(fout);
972 
973  exit_nicely(0);
974 }
975 
976 
977 static void
978 help(const char *progname)
979 {
980  printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
981  printf(_("Usage:\n"));
982  printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
983 
984  printf(_("\nGeneral options:\n"));
985  printf(_(" -f, --file=FILENAME output file or directory name\n"));
986  printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
987  " plain text (default))\n"));
988  printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
989  printf(_(" -v, --verbose verbose mode\n"));
990  printf(_(" -V, --version output version information, then exit\n"));
991  printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
992  printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
993  printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
994  printf(_(" -?, --help show this help, then exit\n"));
995 
996  printf(_("\nOptions controlling the output content:\n"));
997  printf(_(" -a, --data-only dump only the data, not the schema\n"));
998  printf(_(" -b, --blobs include large objects in dump\n"));
999  printf(_(" -B, --no-blobs exclude large objects in dump\n"));
1000  printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
1001  printf(_(" -C, --create include commands to create database in dump\n"));
1002  printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
1003  printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
1004  printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
1005  printf(_(" -O, --no-owner skip restoration of object ownership in\n"
1006  " plain-text format\n"));
1007  printf(_(" -s, --schema-only dump only the schema, no data\n"));
1008  printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
1009  printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
1010  printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
1011  printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
1012  printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
1013  printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
1014  printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
1015  printf(_(" --disable-triggers disable triggers during data-only restore\n"));
1016  printf(_(" --enable-row-security enable row security (dump only content user has\n"
1017  " access to)\n"));
1018  printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
1019  printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
1020  printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
1021  printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
1022  printf(_(" --load-via-partition-root load partitions via the root table\n"));
1023  printf(_(" --no-comments do not dump comments\n"));
1024  printf(_(" --no-publications do not dump publications\n"));
1025  printf(_(" --no-security-labels do not dump security label assignments\n"));
1026  printf(_(" --no-subscriptions do not dump subscriptions\n"));
1027  printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
1028  printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
1029  printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
1030  printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
1031  printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
1032  printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
1033  printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
1034  printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
1035  printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
1036  printf(_(" --strict-names require table and/or schema include patterns to\n"
1037  " match at least one entity each\n"));
1038  printf(_(" --use-set-session-authorization\n"
1039  " use SET SESSION AUTHORIZATION commands instead of\n"
1040  " ALTER OWNER commands to set ownership\n"));
1041 
1042  printf(_("\nConnection options:\n"));
1043  printf(_(" -d, --dbname=DBNAME database to dump\n"));
1044  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1045  printf(_(" -p, --port=PORT database server port number\n"));
1046  printf(_(" -U, --username=NAME connect as specified database user\n"));
1047  printf(_(" -w, --no-password never prompt for password\n"));
1048  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1049  printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1050 
1051  printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1052  "variable value is used.\n\n"));
1053  printf(_("Report bugs to <pgsql-bugs@lists.postgresql.org>.\n"));
1054 }
1055 
1056 static void
1057 setup_connection(Archive *AH, const char *dumpencoding,
1058  const char *dumpsnapshot, char *use_role)
1059 {
1060  DumpOptions *dopt = AH->dopt;
1061  PGconn *conn = GetConnection(AH);
1062  const char *std_strings;
1063 
1065 
1066  /*
1067  * Set the client encoding if requested.
1068  */
1069  if (dumpencoding)
1070  {
1071  if (PQsetClientEncoding(conn, dumpencoding) < 0)
1072  fatal("invalid client encoding \"%s\" specified",
1073  dumpencoding);
1074  }
1075 
1076  /*
1077  * Get the active encoding and the standard_conforming_strings setting, so
1078  * we know how to escape strings.
1079  */
1080  AH->encoding = PQclientEncoding(conn);
1081 
1082  std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1083  AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1084 
1085  /*
1086  * Set the role if requested. In a parallel dump worker, we'll be passed
1087  * use_role == NULL, but AH->use_role is already set (if user specified it
1088  * originally) and we should use that.
1089  */
1090  if (!use_role && AH->use_role)
1091  use_role = AH->use_role;
1092 
1093  /* Set the role if requested */
1094  if (use_role && AH->remoteVersion >= 80100)
1095  {
1096  PQExpBuffer query = createPQExpBuffer();
1097 
1098  appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1099  ExecuteSqlStatement(AH, query->data);
1100  destroyPQExpBuffer(query);
1101 
1102  /* save it for possible later use by parallel workers */
1103  if (!AH->use_role)
1104  AH->use_role = pg_strdup(use_role);
1105  }
1106 
1107  /* Set the datestyle to ISO to ensure the dump's portability */
1108  ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1109 
1110  /* Likewise, avoid using sql_standard intervalstyle */
1111  if (AH->remoteVersion >= 80400)
1112  ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1113 
1114  /*
1115  * Use an explicitly specified extra_float_digits if it has been
1116  * provided. Otherwise, set extra_float_digits so that we can dump float
1117  * data exactly (given correctly implemented float I/O code, anyway).
1118  */
1120  {
1122  appendPQExpBuffer(q, "SET extra_float_digits TO %d",
1124  ExecuteSqlStatement(AH, q->data);
1125  destroyPQExpBuffer(q);
1126  }
1127  else if (AH->remoteVersion >= 90000)
1128  ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1129  else
1130  ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1131 
1132  /*
1133  * If synchronized scanning is supported, disable it, to prevent
1134  * unpredictable changes in row ordering across a dump and reload.
1135  */
1136  if (AH->remoteVersion >= 80300)
1137  ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1138 
1139  /*
1140  * Disable timeouts if supported.
1141  */
1142  ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1143  if (AH->remoteVersion >= 90300)
1144  ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1145  if (AH->remoteVersion >= 90600)
1146  ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1147 
1148  /*
1149  * Quote all identifiers, if requested.
1150  */
1151  if (quote_all_identifiers && AH->remoteVersion >= 90100)
1152  ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1153 
1154  /*
1155  * Adjust row-security mode, if supported.
1156  */
1157  if (AH->remoteVersion >= 90500)
1158  {
1159  if (dopt->enable_row_security)
1160  ExecuteSqlStatement(AH, "SET row_security = on");
1161  else
1162  ExecuteSqlStatement(AH, "SET row_security = off");
1163  }
1164 
1165  /*
1166  * Start transaction-snapshot mode transaction to dump consistent data.
1167  */
1168  ExecuteSqlStatement(AH, "BEGIN");
1169  if (AH->remoteVersion >= 90100)
1170  {
1171  /*
1172  * To support the combination of serializable_deferrable with the jobs
1173  * option we use REPEATABLE READ for the worker connections that are
1174  * passed a snapshot. As long as the snapshot is acquired in a
1175  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1176  * REPEATABLE READ transaction provides the appropriate integrity
1177  * guarantees. This is a kluge, but safe for back-patching.
1178  */
1179  if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1181  "SET TRANSACTION ISOLATION LEVEL "
1182  "SERIALIZABLE, READ ONLY, DEFERRABLE");
1183  else
1185  "SET TRANSACTION ISOLATION LEVEL "
1186  "REPEATABLE READ, READ ONLY");
1187  }
1188  else
1189  {
1191  "SET TRANSACTION ISOLATION LEVEL "
1192  "SERIALIZABLE, READ ONLY");
1193  }
1194 
1195  /*
1196  * If user specified a snapshot to use, select that. In a parallel dump
1197  * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1198  * is already set (if the server can handle it) and we should use that.
1199  */
1200  if (dumpsnapshot)
1201  AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1202 
1203  if (AH->sync_snapshot_id)
1204  {
1205  PQExpBuffer query = createPQExpBuffer();
1206 
1207  appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1208  appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1209  ExecuteSqlStatement(AH, query->data);
1210  destroyPQExpBuffer(query);
1211  }
1212  else if (AH->numWorkers > 1 &&
1213  AH->remoteVersion >= 90200 &&
1215  {
1216  if (AH->isStandby && AH->remoteVersion < 100000)
1217  fatal("Synchronized snapshots on standby servers are not supported by this server version.\n"
1218  "Run with --no-synchronized-snapshots instead if you do not need\n"
1219  "synchronized snapshots.");
1220 
1221 
1223  }
1224 }
1225 
1226 /* Set up connection for a parallel worker process */
1227 static void
1229 {
1230  /*
1231  * We want to re-select all the same values the master connection is
1232  * using. We'll have inherited directly-usable values in
1233  * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1234  * inherited encoding value back to a string to pass to setup_connection.
1235  */
1236  setup_connection(AH,
1238  NULL,
1239  NULL);
1240 }
1241 
1242 static char *
1244 {
1245  char *query = "SELECT pg_catalog.pg_export_snapshot()";
1246  char *result;
1247  PGresult *res;
1248 
1249  res = ExecuteSqlQueryForSingleRow(fout, query);
1250  result = pg_strdup(PQgetvalue(res, 0, 0));
1251  PQclear(res);
1252 
1253  return result;
1254 }
1255 
1256 static ArchiveFormat
1258 {
1259  ArchiveFormat archiveFormat;
1260 
1261  *mode = archModeWrite;
1262 
1263  if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1264  {
1265  /* This is used by pg_dumpall, and is not documented */
1266  archiveFormat = archNull;
1267  *mode = archModeAppend;
1268  }
1269  else if (pg_strcasecmp(format, "c") == 0)
1270  archiveFormat = archCustom;
1271  else if (pg_strcasecmp(format, "custom") == 0)
1272  archiveFormat = archCustom;
1273  else if (pg_strcasecmp(format, "d") == 0)
1274  archiveFormat = archDirectory;
1275  else if (pg_strcasecmp(format, "directory") == 0)
1276  archiveFormat = archDirectory;
1277  else if (pg_strcasecmp(format, "p") == 0)
1278  archiveFormat = archNull;
1279  else if (pg_strcasecmp(format, "plain") == 0)
1280  archiveFormat = archNull;
1281  else if (pg_strcasecmp(format, "t") == 0)
1282  archiveFormat = archTar;
1283  else if (pg_strcasecmp(format, "tar") == 0)
1284  archiveFormat = archTar;
1285  else
1286  fatal("invalid output format \"%s\" specified", format);
1287  return archiveFormat;
1288 }
1289 
1290 /*
1291  * Find the OIDs of all schemas matching the given list of patterns,
1292  * and append them to the given OID list.
1293  */
1294 static void
1296  SimpleStringList *patterns,
1297  SimpleOidList *oids,
1298  bool strict_names)
1299 {
1300  PQExpBuffer query;
1301  PGresult *res;
1302  SimpleStringListCell *cell;
1303  int i;
1304 
1305  if (patterns->head == NULL)
1306  return; /* nothing to do */
1307 
1308  query = createPQExpBuffer();
1309 
1310  /*
1311  * The loop below runs multiple SELECTs might sometimes result in
1312  * duplicate entries in the OID list, but we don't care.
1313  */
1314 
1315  for (cell = patterns->head; cell; cell = cell->next)
1316  {
1317  appendPQExpBuffer(query,
1318  "SELECT oid FROM pg_catalog.pg_namespace n\n");
1319  processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1320  false, NULL, "n.nspname", NULL, NULL);
1321 
1322  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1323  if (strict_names && PQntuples(res) == 0)
1324  fatal("no matching schemas were found for pattern \"%s\"", cell->val);
1325 
1326  for (i = 0; i < PQntuples(res); i++)
1327  {
1328  simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1329  }
1330 
1331  PQclear(res);
1332  resetPQExpBuffer(query);
1333  }
1334 
1335  destroyPQExpBuffer(query);
1336 }
1337 
1338 /*
1339  * Find the OIDs of all tables matching the given list of patterns,
1340  * and append them to the given OID list. See also expand_dbname_patterns()
1341  * in pg_dumpall.c
1342  */
1343 static void
1345  SimpleStringList *patterns, SimpleOidList *oids,
1346  bool strict_names)
1347 {
1348  PQExpBuffer query;
1349  PGresult *res;
1350  SimpleStringListCell *cell;
1351  int i;
1352 
1353  if (patterns->head == NULL)
1354  return; /* nothing to do */
1355 
1356  query = createPQExpBuffer();
1357 
1358  /*
1359  * this might sometimes result in duplicate entries in the OID list, but
1360  * we don't care.
1361  */
1362 
1363  for (cell = patterns->head; cell; cell = cell->next)
1364  {
1365  /*
1366  * Query must remain ABSOLUTELY devoid of unqualified names. This
1367  * would be unnecessary given a pg_table_is_visible() variant taking a
1368  * search_path argument.
1369  */
1370  appendPQExpBuffer(query,
1371  "SELECT c.oid"
1372  "\nFROM pg_catalog.pg_class c"
1373  "\n LEFT JOIN pg_catalog.pg_namespace n"
1374  "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1375  "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1376  "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1377  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1378  RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1379  RELKIND_PARTITIONED_TABLE);
1380  processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1381  false, "n.nspname", "c.relname", NULL,
1382  "pg_catalog.pg_table_is_visible(c.oid)");
1383 
1384  ExecuteSqlStatement(fout, "RESET search_path");
1385  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1388  if (strict_names && PQntuples(res) == 0)
1389  fatal("no matching tables were found for pattern \"%s\"", cell->val);
1390 
1391  for (i = 0; i < PQntuples(res); i++)
1392  {
1393  simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1394  }
1395 
1396  PQclear(res);
1397  resetPQExpBuffer(query);
1398  }
1399 
1400  destroyPQExpBuffer(query);
1401 }
1402 
1403 /*
1404  * checkExtensionMembership
1405  * Determine whether object is an extension member, and if so,
1406  * record an appropriate dependency and set the object's dump flag.
1407  *
1408  * It's important to call this for each object that could be an extension
1409  * member. Generally, we integrate this with determining the object's
1410  * to-be-dumped-ness, since extension membership overrides other rules for that.
1411  *
1412  * Returns true if object is an extension member, else false.
1413  */
1414 static bool
1416 {
1417  ExtensionInfo *ext = findOwningExtension(dobj->catId);
1418 
1419  if (ext == NULL)
1420  return false;
1421 
1422  dobj->ext_member = true;
1423 
1424  /* Record dependency so that getDependencies needn't deal with that */
1425  addObjectDependency(dobj, ext->dobj.dumpId);
1426 
1427  /*
1428  * In 9.6 and above, mark the member object to have any non-initial ACL,
1429  * policies, and security labels dumped.
1430  *
1431  * Note that any initial ACLs (see pg_init_privs) will be removed when we
1432  * extract the information about the object. We don't provide support for
1433  * initial policies and security labels and it seems unlikely for those to
1434  * ever exist, but we may have to revisit this later.
1435  *
1436  * Prior to 9.6, we do not include any extension member components.
1437  *
1438  * In binary upgrades, we still dump all components of the members
1439  * individually, since the idea is to exactly reproduce the database
1440  * contents rather than replace the extension contents with something
1441  * different.
1442  */
1443  if (fout->dopt->binary_upgrade)
1444  dobj->dump = ext->dobj.dump;
1445  else
1446  {
1447  if (fout->remoteVersion < 90600)
1448  dobj->dump = DUMP_COMPONENT_NONE;
1449  else
1450  dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1453  }
1454 
1455  return true;
1456 }
1457 
1458 /*
1459  * selectDumpableNamespace: policy-setting subroutine
1460  * Mark a namespace as to be dumped or not
1461  */
1462 static void
1464 {
1465  /*
1466  * If specific tables are being dumped, do not dump any complete
1467  * namespaces. If specific namespaces are being dumped, dump just those
1468  * namespaces. Otherwise, dump all non-system namespaces.
1469  */
1470  if (table_include_oids.head != NULL)
1471  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1472  else if (schema_include_oids.head != NULL)
1473  nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1474  simple_oid_list_member(&schema_include_oids,
1475  nsinfo->dobj.catId.oid) ?
1477  else if (fout->remoteVersion >= 90600 &&
1478  strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1479  {
1480  /*
1481  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1482  * they are interesting (and not the original ACLs which were set at
1483  * initdb time, see pg_init_privs).
1484  */
1485  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1486  }
1487  else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1488  strcmp(nsinfo->dobj.name, "information_schema") == 0)
1489  {
1490  /* Other system schemas don't get dumped */
1491  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1492  }
1493  else if (strcmp(nsinfo->dobj.name, "public") == 0)
1494  {
1495  /*
1496  * The public schema is a strange beast that sits in a sort of
1497  * no-mans-land between being a system object and a user object. We
1498  * don't want to dump creation or comment commands for it, because
1499  * that complicates matters for non-superuser use of pg_dump. But we
1500  * should dump any ACL changes that have occurred for it, and of
1501  * course we should dump contained objects.
1502  */
1503  nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1505  }
1506  else
1507  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1508 
1509  /*
1510  * In any case, a namespace can be excluded by an exclusion switch
1511  */
1512  if (nsinfo->dobj.dump_contains &&
1513  simple_oid_list_member(&schema_exclude_oids,
1514  nsinfo->dobj.catId.oid))
1515  nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1516 
1517  /*
1518  * If the schema belongs to an extension, allow extension membership to
1519  * override the dump decision for the schema itself. However, this does
1520  * not change dump_contains, so this won't change what we do with objects
1521  * within the schema. (If they belong to the extension, they'll get
1522  * suppressed by it, otherwise not.)
1523  */
1524  (void) checkExtensionMembership(&nsinfo->dobj, fout);
1525 }
1526 
1527 /*
1528  * selectDumpableTable: policy-setting subroutine
1529  * Mark a table as to be dumped or not
1530  */
1531 static void
1533 {
1534  if (checkExtensionMembership(&tbinfo->dobj, fout))
1535  return; /* extension membership overrides all else */
1536 
1537  /*
1538  * If specific tables are being dumped, dump just those tables; else, dump
1539  * according to the parent namespace's dump flag.
1540  */
1541  if (table_include_oids.head != NULL)
1542  tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1543  tbinfo->dobj.catId.oid) ?
1545  else
1546  tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1547 
1548  /*
1549  * In any case, a table can be excluded by an exclusion switch
1550  */
1551  if (tbinfo->dobj.dump &&
1552  simple_oid_list_member(&table_exclude_oids,
1553  tbinfo->dobj.catId.oid))
1554  tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1555 }
1556 
1557 /*
1558  * selectDumpableType: policy-setting subroutine
1559  * Mark a type as to be dumped or not
1560  *
1561  * If it's a table's rowtype or an autogenerated array type, we also apply a
1562  * special type code to facilitate sorting into the desired order. (We don't
1563  * want to consider those to be ordinary types because that would bring tables
1564  * up into the datatype part of the dump order.) We still set the object's
1565  * dump flag; that's not going to cause the dummy type to be dumped, but we
1566  * need it so that casts involving such types will be dumped correctly -- see
1567  * dumpCast. This means the flag should be set the same as for the underlying
1568  * object (the table or base type).
1569  */
1570 static void
1572 {
1573  /* skip complex types, except for standalone composite types */
1574  if (OidIsValid(tyinfo->typrelid) &&
1575  tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1576  {
1577  TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1578 
1579  tyinfo->dobj.objType = DO_DUMMY_TYPE;
1580  if (tytable != NULL)
1581  tyinfo->dobj.dump = tytable->dobj.dump;
1582  else
1583  tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1584  return;
1585  }
1586 
1587  /* skip auto-generated array types */
1588  if (tyinfo->isArray)
1589  {
1590  tyinfo->dobj.objType = DO_DUMMY_TYPE;
1591 
1592  /*
1593  * Fall through to set the dump flag; we assume that the subsequent
1594  * rules will do the same thing as they would for the array's base
1595  * type. (We cannot reliably look up the base type here, since
1596  * getTypes may not have processed it yet.)
1597  */
1598  }
1599 
1600  if (checkExtensionMembership(&tyinfo->dobj, fout))
1601  return; /* extension membership overrides all else */
1602 
1603  /* Dump based on if the contents of the namespace are being dumped */
1604  tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1605 }
1606 
1607 /*
1608  * selectDumpableDefaultACL: policy-setting subroutine
1609  * Mark a default ACL as to be dumped or not
1610  *
1611  * For per-schema default ACLs, dump if the schema is to be dumped.
1612  * Otherwise dump if we are dumping "everything". Note that dataOnly
1613  * and aclsSkip are checked separately.
1614  */
1615 static void
1617 {
1618  /* Default ACLs can't be extension members */
1619 
1620  if (dinfo->dobj.namespace)
1621  /* default ACLs are considered part of the namespace */
1622  dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1623  else
1624  dinfo->dobj.dump = dopt->include_everything ?
1626 }
1627 
1628 /*
1629  * selectDumpableCast: policy-setting subroutine
1630  * Mark a cast as to be dumped or not
1631  *
1632  * Casts do not belong to any particular namespace (since they haven't got
1633  * names), nor do they have identifiable owners. To distinguish user-defined
1634  * casts from built-in ones, we must resort to checking whether the cast's
1635  * OID is in the range reserved for initdb.
1636  */
1637 static void
1639 {
1640  if (checkExtensionMembership(&cast->dobj, fout))
1641  return; /* extension membership overrides all else */
1642 
1643  /*
1644  * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1645  * support ACLs currently.
1646  */
1647  if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1648  cast->dobj.dump = DUMP_COMPONENT_NONE;
1649  else
1650  cast->dobj.dump = fout->dopt->include_everything ?
1652 }
1653 
1654 /*
1655  * selectDumpableProcLang: policy-setting subroutine
1656  * Mark a procedural language as to be dumped or not
1657  *
1658  * Procedural languages do not belong to any particular namespace. To
1659  * identify built-in languages, we must resort to checking whether the
1660  * language's OID is in the range reserved for initdb.
1661  */
1662 static void
1664 {
1665  if (checkExtensionMembership(&plang->dobj, fout))
1666  return; /* extension membership overrides all else */
1667 
1668  /*
1669  * Only include procedural languages when we are dumping everything.
1670  *
1671  * For from-initdb procedural languages, only include ACLs, as we do for
1672  * the pg_catalog namespace. We need this because procedural languages do
1673  * not live in any namespace.
1674  */
1675  if (!fout->dopt->include_everything)
1676  plang->dobj.dump = DUMP_COMPONENT_NONE;
1677  else
1678  {
1679  if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1680  plang->dobj.dump = fout->remoteVersion < 90600 ?
1682  else
1683  plang->dobj.dump = DUMP_COMPONENT_ALL;
1684  }
1685 }
1686 
1687 /*
1688  * selectDumpableAccessMethod: policy-setting subroutine
1689  * Mark an access method as to be dumped or not
1690  *
1691  * Access methods do not belong to any particular namespace. To identify
1692  * built-in access methods, we must resort to checking whether the
1693  * method's OID is in the range reserved for initdb.
1694  */
1695 static void
1697 {
1698  if (checkExtensionMembership(&method->dobj, fout))
1699  return; /* extension membership overrides all else */
1700 
1701  /*
1702  * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1703  * they do not support ACLs currently.
1704  */
1705  if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1706  method->dobj.dump = DUMP_COMPONENT_NONE;
1707  else
1708  method->dobj.dump = fout->dopt->include_everything ?
1710 }
1711 
1712 /*
1713  * selectDumpableExtension: policy-setting subroutine
1714  * Mark an extension as to be dumped or not
1715  *
1716  * Built-in extensions should be skipped except for checking ACLs, since we
1717  * assume those will already be installed in the target database. We identify
1718  * such extensions by their having OIDs in the range reserved for initdb.
1719  * We dump all user-added extensions by default, or none of them if
1720  * include_everything is false (i.e., a --schema or --table switch was given).
1721  */
1722 static void
1724 {
1725  /*
1726  * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1727  * change permissions on their member objects, if they wish to, and have
1728  * those changes preserved.
1729  */
1730  if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1731  extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1732  else
1733  extinfo->dobj.dump = extinfo->dobj.dump_contains =
1736 }
1737 
1738 /*
1739  * selectDumpablePublicationTable: policy-setting subroutine
1740  * Mark a publication table as to be dumped or not
1741  *
1742  * Publication tables have schemas, but those are ignored in decision making,
1743  * because publications are only dumped when we are dumping everything.
1744  */
1745 static void
1747 {
1748  if (checkExtensionMembership(dobj, fout))
1749  return; /* extension membership overrides all else */
1750 
1751  dobj->dump = fout->dopt->include_everything ?
1753 }
1754 
1755 /*
1756  * selectDumpableObject: policy-setting subroutine
1757  * Mark a generic dumpable object as to be dumped or not
1758  *
1759  * Use this only for object types without a special-case routine above.
1760  */
1761 static void
1763 {
1764  if (checkExtensionMembership(dobj, fout))
1765  return; /* extension membership overrides all else */
1766 
1767  /*
1768  * Default policy is to dump if parent namespace is dumpable, or for
1769  * non-namespace-associated items, dump if we're dumping "everything".
1770  */
1771  if (dobj->namespace)
1772  dobj->dump = dobj->namespace->dobj.dump_contains;
1773  else
1774  dobj->dump = fout->dopt->include_everything ?
1776 }
1777 
1778 /*
1779  * Dump a table's contents for loading using the COPY command
1780  * - this routine is called by the Archiver when it wants the table
1781  * to be dumped.
1782  */
1783 
1784 static int
1785 dumpTableData_copy(Archive *fout, void *dcontext)
1786 {
1787  TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1788  TableInfo *tbinfo = tdinfo->tdtable;
1789  const char *classname = tbinfo->dobj.name;
1791 
1792  /*
1793  * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1794  * which uses it already.
1795  */
1796  PQExpBuffer clistBuf = createPQExpBuffer();
1797  PGconn *conn = GetConnection(fout);
1798  PGresult *res;
1799  int ret;
1800  char *copybuf;
1801  const char *column_list;
1802 
1803  pg_log_info("dumping contents of table \"%s.%s\"",
1804  tbinfo->dobj.namespace->dobj.name, classname);
1805 
1806  /*
1807  * Specify the column list explicitly so that we have no possibility of
1808  * retrieving data in the wrong column order. (The default column
1809  * ordering of COPY will not be what we want in certain corner cases
1810  * involving ADD COLUMN and inheritance.)
1811  */
1812  column_list = fmtCopyColumnList(tbinfo, clistBuf);
1813 
1814  if (tdinfo->filtercond)
1815  {
1816  /* Note: this syntax is only supported in 8.2 and up */
1817  appendPQExpBufferStr(q, "COPY (SELECT ");
1818  /* klugery to get rid of parens in column list */
1819  if (strlen(column_list) > 2)
1820  {
1821  appendPQExpBufferStr(q, column_list + 1);
1822  q->data[q->len - 1] = ' ';
1823  }
1824  else
1825  appendPQExpBufferStr(q, "* ");
1826  appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1827  fmtQualifiedDumpable(tbinfo),
1828  tdinfo->filtercond);
1829  }
1830  else
1831  {
1832  appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1833  fmtQualifiedDumpable(tbinfo),
1834  column_list);
1835  }
1836  res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1837  PQclear(res);
1838  destroyPQExpBuffer(clistBuf);
1839 
1840  for (;;)
1841  {
1842  ret = PQgetCopyData(conn, &copybuf, 0);
1843 
1844  if (ret < 0)
1845  break; /* done or error */
1846 
1847  if (copybuf)
1848  {
1849  WriteData(fout, copybuf, ret);
1850  PQfreemem(copybuf);
1851  }
1852 
1853  /* ----------
1854  * THROTTLE:
1855  *
1856  * There was considerable discussion in late July, 2000 regarding
1857  * slowing down pg_dump when backing up large tables. Users with both
1858  * slow & fast (multi-processor) machines experienced performance
1859  * degradation when doing a backup.
1860  *
1861  * Initial attempts based on sleeping for a number of ms for each ms
1862  * of work were deemed too complex, then a simple 'sleep in each loop'
1863  * implementation was suggested. The latter failed because the loop
1864  * was too tight. Finally, the following was implemented:
1865  *
1866  * If throttle is non-zero, then
1867  * See how long since the last sleep.
1868  * Work out how long to sleep (based on ratio).
1869  * If sleep is more than 100ms, then
1870  * sleep
1871  * reset timer
1872  * EndIf
1873  * EndIf
1874  *
1875  * where the throttle value was the number of ms to sleep per ms of
1876  * work. The calculation was done in each loop.
1877  *
1878  * Most of the hard work is done in the backend, and this solution
1879  * still did not work particularly well: on slow machines, the ratio
1880  * was 50:1, and on medium paced machines, 1:1, and on fast
1881  * multi-processor machines, it had little or no effect, for reasons
1882  * that were unclear.
1883  *
1884  * Further discussion ensued, and the proposal was dropped.
1885  *
1886  * For those people who want this feature, it can be implemented using
1887  * gettimeofday in each loop, calculating the time since last sleep,
1888  * multiplying that by the sleep ratio, then if the result is more
1889  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1890  * function to sleep for a subsecond period ie.
1891  *
1892  * select(0, NULL, NULL, NULL, &tvi);
1893  *
1894  * This will return after the interval specified in the structure tvi.
1895  * Finally, call gettimeofday again to save the 'last sleep time'.
1896  * ----------
1897  */
1898  }
1899  archprintf(fout, "\\.\n\n\n");
1900 
1901  if (ret == -2)
1902  {
1903  /* copy data transfer failed */
1904  pg_log_error("Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.", classname);
1905  pg_log_error("Error message from server: %s", PQerrorMessage(conn));
1906  pg_log_error("The command was: %s", q->data);
1907  exit_nicely(1);
1908  }
1909 
1910  /* Check command status and return to normal libpq state */
1911  res = PQgetResult(conn);
1912  if (PQresultStatus(res) != PGRES_COMMAND_OK)
1913  {
1914  pg_log_error("Dumping the contents of table \"%s\" failed: PQgetResult() failed.", classname);
1915  pg_log_error("Error message from server: %s", PQerrorMessage(conn));
1916  pg_log_error("The command was: %s", q->data);
1917  exit_nicely(1);
1918  }
1919  PQclear(res);
1920 
1921  /* Do this to ensure we've pumped libpq back to idle state */
1922  if (PQgetResult(conn) != NULL)
1923  pg_log_warning("unexpected extra results during COPY of table \"%s\"",
1924  classname);
1925 
1926  destroyPQExpBuffer(q);
1927  return 1;
1928 }
1929 
1930 /*
1931  * Dump table data using INSERT commands.
1932  *
1933  * Caution: when we restore from an archive file direct to database, the
1934  * INSERT commands emitted by this function have to be parsed by
1935  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1936  * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1937  */
1938 static int
1939 dumpTableData_insert(Archive *fout, void *dcontext)
1940 {
1941  TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1942  TableInfo *tbinfo = tdinfo->tdtable;
1943  DumpOptions *dopt = fout->dopt;
1945  PQExpBuffer insertStmt = NULL;
1946  PGresult *res;
1947  int nfields;
1948  int rows_per_statement = dopt->dump_inserts;
1949  int rows_this_statement = 0;
1950 
1951  appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1952  "SELECT * FROM ONLY %s",
1953  fmtQualifiedDumpable(tbinfo));
1954  if (tdinfo->filtercond)
1955  appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1956 
1957  ExecuteSqlStatement(fout, q->data);
1958 
1959  while (1)
1960  {
1961  res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1962  PGRES_TUPLES_OK);
1963  nfields = PQnfields(res);
1964 
1965  /*
1966  * First time through, we build as much of the INSERT statement as
1967  * possible in "insertStmt", which we can then just print for each
1968  * statement. If the table happens to have zero columns then this will
1969  * be a complete statement, otherwise it will end in "VALUES" and be
1970  * ready to have the row's column values printed.
1971  */
1972  if (insertStmt == NULL)
1973  {
1974  TableInfo *targettab;
1975 
1976  insertStmt = createPQExpBuffer();
1977 
1978  /*
1979  * When load-via-partition-root is set, get the root table name
1980  * for the partition table, so that we can reload data through the
1981  * root table.
1982  */
1983  if (dopt->load_via_partition_root && tbinfo->ispartition)
1984  targettab = getRootTableInfo(tbinfo);
1985  else
1986  targettab = tbinfo;
1987 
1988  appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1989  fmtQualifiedDumpable(targettab));
1990 
1991  /* corner case for zero-column table */
1992  if (nfields == 0)
1993  {
1994  appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1995  }
1996  else
1997  {
1998  /* append the list of column names if required */
1999  if (dopt->column_inserts)
2000  {
2001  appendPQExpBufferChar(insertStmt, '(');
2002  for (int field = 0; field < nfields; field++)
2003  {
2004  if (field > 0)
2005  appendPQExpBufferStr(insertStmt, ", ");
2006  appendPQExpBufferStr(insertStmt,
2007  fmtId(PQfname(res, field)));
2008  }
2009  appendPQExpBufferStr(insertStmt, ") ");
2010  }
2011 
2012  if (tbinfo->needs_override)
2013  appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
2014 
2015  appendPQExpBufferStr(insertStmt, "VALUES");
2016  }
2017  }
2018 
2019  for (int tuple = 0; tuple < PQntuples(res); tuple++)
2020  {
2021  /* Write the INSERT if not in the middle of a multi-row INSERT. */
2022  if (rows_this_statement == 0)
2023  archputs(insertStmt->data, fout);
2024 
2025  /*
2026  * If it is zero-column table then we've already written the
2027  * complete statement, which will mean we've disobeyed
2028  * --rows-per-insert when it's set greater than 1. We do support
2029  * a way to make this multi-row with: SELECT UNION ALL SELECT
2030  * UNION ALL ... but that's non-standard so we should avoid it
2031  * given that using INSERTs is mostly only ever needed for
2032  * cross-database exports.
2033  */
2034  if (nfields == 0)
2035  continue;
2036 
2037  /* Emit a row heading */
2038  if (rows_per_statement == 1)
2039  archputs(" (", fout);
2040  else if (rows_this_statement > 0)
2041  archputs(",\n\t(", fout);
2042  else
2043  archputs("\n\t(", fout);
2044 
2045  for (int field = 0; field < nfields; field++)
2046  {
2047  if (field > 0)
2048  archputs(", ", fout);
2049  if (tbinfo->attgenerated[field])
2050  {
2051  archputs("DEFAULT", fout);
2052  continue;
2053  }
2054  if (PQgetisnull(res, tuple, field))
2055  {
2056  archputs("NULL", fout);
2057  continue;
2058  }
2059 
2060  /* XXX This code is partially duplicated in ruleutils.c */
2061  switch (PQftype(res, field))
2062  {
2063  case INT2OID:
2064  case INT4OID:
2065  case INT8OID:
2066  case OIDOID:
2067  case FLOAT4OID:
2068  case FLOAT8OID:
2069  case NUMERICOID:
2070  {
2071  /*
2072  * These types are printed without quotes unless
2073  * they contain values that aren't accepted by the
2074  * scanner unquoted (e.g., 'NaN'). Note that
2075  * strtod() and friends might accept NaN, so we
2076  * can't use that to test.
2077  *
2078  * In reality we only need to defend against
2079  * infinity and NaN, so we need not get too crazy
2080  * about pattern matching here.
2081  */
2082  const char *s = PQgetvalue(res, tuple, field);
2083 
2084  if (strspn(s, "0123456789 +-eE.") == strlen(s))
2085  archputs(s, fout);
2086  else
2087  archprintf(fout, "'%s'", s);
2088  }
2089  break;
2090 
2091  case BITOID:
2092  case VARBITOID:
2093  archprintf(fout, "B'%s'",
2094  PQgetvalue(res, tuple, field));
2095  break;
2096 
2097  case BOOLOID:
2098  if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2099  archputs("true", fout);
2100  else
2101  archputs("false", fout);
2102  break;
2103 
2104  default:
2105  /* All other types are printed as string literals. */
2106  resetPQExpBuffer(q);
2108  PQgetvalue(res, tuple, field),
2109  fout);
2110  archputs(q->data, fout);
2111  break;
2112  }
2113  }
2114 
2115  /* Terminate the row ... */
2116  archputs(")", fout);
2117 
2118  /* ... and the statement, if the target no. of rows is reached */
2119  if (++rows_this_statement >= rows_per_statement)
2120  {
2121  if (dopt->do_nothing)
2122  archputs(" ON CONFLICT DO NOTHING;\n", fout);
2123  else
2124  archputs(";\n", fout);
2125  /* Reset the row counter */
2126  rows_this_statement = 0;
2127  }
2128  }
2129 
2130  if (PQntuples(res) <= 0)
2131  {
2132  PQclear(res);
2133  break;
2134  }
2135  PQclear(res);
2136  }
2137 
2138  /* Terminate any statements that didn't make the row count. */
2139  if (rows_this_statement > 0)
2140  {
2141  if (dopt->do_nothing)
2142  archputs(" ON CONFLICT DO NOTHING;\n", fout);
2143  else
2144  archputs(";\n", fout);
2145  }
2146 
2147  archputs("\n\n", fout);
2148 
2149  ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2150 
2151  destroyPQExpBuffer(q);
2152  if (insertStmt != NULL)
2153  destroyPQExpBuffer(insertStmt);
2154 
2155  return 1;
2156 }
2157 
2158 /*
2159  * getRootTableInfo:
2160  * get the root TableInfo for the given partition table.
2161  */
2162 static TableInfo *
2164 {
2165  TableInfo *parentTbinfo;
2166 
2167  Assert(tbinfo->ispartition);
2168  Assert(tbinfo->numParents == 1);
2169 
2170  parentTbinfo = tbinfo->parents[0];
2171  while (parentTbinfo->ispartition)
2172  {
2173  Assert(parentTbinfo->numParents == 1);
2174  parentTbinfo = parentTbinfo->parents[0];
2175  }
2176 
2177  return parentTbinfo;
2178 }
2179 
2180 /*
2181  * dumpTableData -
2182  * dump the contents of a single table
2183  *
2184  * Actually, this just makes an ArchiveEntry for the table contents.
2185  */
2186 static void
2188 {
2189  DumpOptions *dopt = fout->dopt;
2190  TableInfo *tbinfo = tdinfo->tdtable;
2191  PQExpBuffer copyBuf = createPQExpBuffer();
2192  PQExpBuffer clistBuf = createPQExpBuffer();
2193  DataDumperPtr dumpFn;
2194  char *copyStmt;
2195  const char *copyFrom;
2196 
2197  if (!dopt->dump_inserts)
2198  {
2199  /* Dump/restore using COPY */
2200  dumpFn = dumpTableData_copy;
2201 
2202  /*
2203  * When load-via-partition-root is set, get the root table name for
2204  * the partition table, so that we can reload data through the root
2205  * table.
2206  */
2207  if (dopt->load_via_partition_root && tbinfo->ispartition)
2208  {
2209  TableInfo *parentTbinfo;
2210 
2211  parentTbinfo = getRootTableInfo(tbinfo);
2212  copyFrom = fmtQualifiedDumpable(parentTbinfo);
2213  }
2214  else
2215  copyFrom = fmtQualifiedDumpable(tbinfo);
2216 
2217  /* must use 2 steps here 'cause fmtId is nonreentrant */
2218  appendPQExpBuffer(copyBuf, "COPY %s ",
2219  copyFrom);
2220  appendPQExpBuffer(copyBuf, "%s FROM stdin;\n",
2221  fmtCopyColumnList(tbinfo, clistBuf));
2222  copyStmt = copyBuf->data;
2223  }
2224  else
2225  {
2226  /* Restore using INSERT */
2227  dumpFn = dumpTableData_insert;
2228  copyStmt = NULL;
2229  }
2230 
2231  /*
2232  * Note: although the TableDataInfo is a full DumpableObject, we treat its
2233  * dependency on its table as "special" and pass it to ArchiveEntry now.
2234  * See comments for BuildArchiveDependencies.
2235  */
2236  if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2237  {
2238  TocEntry *te;
2239 
2240  te = ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2241  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2242  .namespace = tbinfo->dobj.namespace->dobj.name,
2243  .owner = tbinfo->rolname,
2244  .description = "TABLE DATA",
2245  .section = SECTION_DATA,
2246  .copyStmt = copyStmt,
2247  .deps = &(tbinfo->dobj.dumpId),
2248  .nDeps = 1,
2249  .dumpFn = dumpFn,
2250  .dumpArg = tdinfo));
2251 
2252  /*
2253  * Set the TocEntry's dataLength in case we are doing a parallel dump
2254  * and want to order dump jobs by table size. We choose to measure
2255  * dataLength in table pages during dump, so no scaling is needed.
2256  * However, relpages is declared as "integer" in pg_class, and hence
2257  * also in TableInfo, but it's really BlockNumber a/k/a unsigned int.
2258  * Cast so that we get the right interpretation of table sizes
2259  * exceeding INT_MAX pages.
2260  */
2261  te->dataLength = (BlockNumber) tbinfo->relpages;
2262  }
2263 
2264  destroyPQExpBuffer(copyBuf);
2265  destroyPQExpBuffer(clistBuf);
2266 }
2267 
2268 /*
2269  * refreshMatViewData -
2270  * load or refresh the contents of a single materialized view
2271  *
2272  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2273  * statement.
2274  */
2275 static void
2277 {
2278  TableInfo *tbinfo = tdinfo->tdtable;
2279  PQExpBuffer q;
2280 
2281  /* If the materialized view is not flagged as populated, skip this. */
2282  if (!tbinfo->relispopulated)
2283  return;
2284 
2285  q = createPQExpBuffer();
2286 
2287  appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2288  fmtQualifiedDumpable(tbinfo));
2289 
2290  if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2291  ArchiveEntry(fout,
2292  tdinfo->dobj.catId, /* catalog ID */
2293  tdinfo->dobj.dumpId, /* dump ID */
2294  ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2295  .namespace = tbinfo->dobj.namespace->dobj.name,
2296  .owner = tbinfo->rolname,
2297  .description = "MATERIALIZED VIEW DATA",
2298  .section = SECTION_POST_DATA,
2299  .createStmt = q->data,
2300  .deps = tdinfo->dobj.dependencies,
2301  .nDeps = tdinfo->dobj.nDeps));
2302 
2303  destroyPQExpBuffer(q);
2304 }
2305 
2306 /*
2307  * getTableData -
2308  * set up dumpable objects representing the contents of tables
2309  */
2310 static void
2312 {
2313  int i;
2314 
2315  for (i = 0; i < numTables; i++)
2316  {
2317  if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2318  (!relkind || tblinfo[i].relkind == relkind))
2319  makeTableDataInfo(dopt, &(tblinfo[i]));
2320  }
2321 }
2322 
2323 /*
2324  * Make a dumpable object for the data of this specific table
2325  *
2326  * Note: we make a TableDataInfo if and only if we are going to dump the
2327  * table data; the "dump" flag in such objects isn't used.
2328  */
2329 static void
2331 {
2332  TableDataInfo *tdinfo;
2333 
2334  /*
2335  * Nothing to do if we already decided to dump the table. This will
2336  * happen for "config" tables.
2337  */
2338  if (tbinfo->dataObj != NULL)
2339  return;
2340 
2341  /* Skip VIEWs (no data to dump) */
2342  if (tbinfo->relkind == RELKIND_VIEW)
2343  return;
2344  /* Skip FOREIGN TABLEs (no data to dump) */
2345  if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2346  return;
2347  /* Skip partitioned tables (data in partitions) */
2348  if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2349  return;
2350 
2351  /* Don't dump data in unlogged tables, if so requested */
2352  if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2353  dopt->no_unlogged_table_data)
2354  return;
2355 
2356  /* Check that the data is not explicitly excluded */
2357  if (simple_oid_list_member(&tabledata_exclude_oids,
2358  tbinfo->dobj.catId.oid))
2359  return;
2360 
2361  /* OK, let's dump it */
2362  tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2363 
2364  if (tbinfo->relkind == RELKIND_MATVIEW)
2365  tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2366  else if (tbinfo->relkind == RELKIND_SEQUENCE)
2367  tdinfo->dobj.objType = DO_SEQUENCE_SET;
2368  else
2369  tdinfo->dobj.objType = DO_TABLE_DATA;
2370 
2371  /*
2372  * Note: use tableoid 0 so that this object won't be mistaken for
2373  * something that pg_depend entries apply to.
2374  */
2375  tdinfo->dobj.catId.tableoid = 0;
2376  tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2377  AssignDumpId(&tdinfo->dobj);
2378  tdinfo->dobj.name = tbinfo->dobj.name;
2379  tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2380  tdinfo->tdtable = tbinfo;
2381  tdinfo->filtercond = NULL; /* might get set later */
2382  addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2383 
2384  tbinfo->dataObj = tdinfo;
2385 }
2386 
2387 /*
2388  * The refresh for a materialized view must be dependent on the refresh for
2389  * any materialized view that this one is dependent on.
2390  *
2391  * This must be called after all the objects are created, but before they are
2392  * sorted.
2393  */
2394 static void
2396 {
2397  PQExpBuffer query;
2398  PGresult *res;
2399  int ntups,
2400  i;
2401  int i_classid,
2402  i_objid,
2403  i_refobjid;
2404 
2405  /* No Mat Views before 9.3. */
2406  if (fout->remoteVersion < 90300)
2407  return;
2408 
2409  query = createPQExpBuffer();
2410 
2411  appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2412  "( "
2413  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2414  "FROM pg_depend d1 "
2415  "JOIN pg_class c1 ON c1.oid = d1.objid "
2416  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2417  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2418  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2419  "AND d2.objid = r1.oid "
2420  "AND d2.refobjid <> d1.objid "
2421  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2422  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2423  CppAsString2(RELKIND_VIEW) ") "
2424  "WHERE d1.classid = 'pg_class'::regclass "
2425  "UNION "
2426  "SELECT w.objid, d3.refobjid, c3.relkind "
2427  "FROM w "
2428  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2429  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2430  "AND d3.objid = r3.oid "
2431  "AND d3.refobjid <> w.refobjid "
2432  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2433  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2434  CppAsString2(RELKIND_VIEW) ") "
2435  ") "
2436  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2437  "FROM w "
2438  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2439 
2440  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2441 
2442  ntups = PQntuples(res);
2443 
2444  i_classid = PQfnumber(res, "classid");
2445  i_objid = PQfnumber(res, "objid");
2446  i_refobjid = PQfnumber(res, "refobjid");
2447 
2448  for (i = 0; i < ntups; i++)
2449  {
2450  CatalogId objId;
2451  CatalogId refobjId;
2452  DumpableObject *dobj;
2453  DumpableObject *refdobj;
2454  TableInfo *tbinfo;
2455  TableInfo *reftbinfo;
2456 
2457  objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2458  objId.oid = atooid(PQgetvalue(res, i, i_objid));
2459  refobjId.tableoid = objId.tableoid;
2460  refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2461 
2462  dobj = findObjectByCatalogId(objId);
2463  if (dobj == NULL)
2464  continue;
2465 
2466  Assert(dobj->objType == DO_TABLE);
2467  tbinfo = (TableInfo *) dobj;
2468  Assert(tbinfo->relkind == RELKIND_MATVIEW);
2469  dobj = (DumpableObject *) tbinfo->dataObj;
2470  if (dobj == NULL)
2471  continue;
2472  Assert(dobj->objType == DO_REFRESH_MATVIEW);
2473 
2474  refdobj = findObjectByCatalogId(refobjId);
2475  if (refdobj == NULL)
2476  continue;
2477 
2478  Assert(refdobj->objType == DO_TABLE);
2479  reftbinfo = (TableInfo *) refdobj;
2480  Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2481  refdobj = (DumpableObject *) reftbinfo->dataObj;
2482  if (refdobj == NULL)
2483  continue;
2484  Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2485 
2486  addObjectDependency(dobj, refdobj->dumpId);
2487 
2488  if (!reftbinfo->relispopulated)
2489  tbinfo->relispopulated = false;
2490  }
2491 
2492  PQclear(res);
2493 
2494  destroyPQExpBuffer(query);
2495 }
2496 
2497 /*
2498  * getTableDataFKConstraints -
2499  * add dump-order dependencies reflecting foreign key constraints
2500  *
2501  * This code is executed only in a data-only dump --- in schema+data dumps
2502  * we handle foreign key issues by not creating the FK constraints until
2503  * after the data is loaded. In a data-only dump, however, we want to
2504  * order the table data objects in such a way that a table's referenced
2505  * tables are restored first. (In the presence of circular references or
2506  * self-references this may be impossible; we'll detect and complain about
2507  * that during the dependency sorting step.)
2508  */
2509 static void
2511 {
2512  DumpableObject **dobjs;
2513  int numObjs;
2514  int i;
2515 
2516  /* Search through all the dumpable objects for FK constraints */
2517  getDumpableObjects(&dobjs, &numObjs);
2518  for (i = 0; i < numObjs; i++)
2519  {
2520  if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2521  {
2522  ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2523  TableInfo *ftable;
2524 
2525  /* Not interesting unless both tables are to be dumped */
2526  if (cinfo->contable == NULL ||
2527  cinfo->contable->dataObj == NULL)
2528  continue;
2529  ftable = findTableByOid(cinfo->confrelid);
2530  if (ftable == NULL ||
2531  ftable->dataObj == NULL)
2532  continue;
2533 
2534  /*
2535  * Okay, make referencing table's TABLE_DATA object depend on the
2536  * referenced table's TABLE_DATA object.
2537  */
2539  ftable->dataObj->dobj.dumpId);
2540  }
2541  }
2542  free(dobjs);
2543 }
2544 
2545 
2546 /*
2547  * guessConstraintInheritance:
2548  * In pre-8.4 databases, we can't tell for certain which constraints
2549  * are inherited. We assume a CHECK constraint is inherited if its name
2550  * matches the name of any constraint in the parent. Originally this code
2551  * tried to compare the expression texts, but that can fail for various
2552  * reasons --- for example, if the parent and child tables are in different
2553  * schemas, reverse-listing of function calls may produce different text
2554  * (schema-qualified or not) depending on search path.
2555  *
2556  * In 8.4 and up we can rely on the conislocal field to decide which
2557  * constraints must be dumped; much safer.
2558  *
2559  * This function assumes all conislocal flags were initialized to true.
2560  * It clears the flag on anything that seems to be inherited.
2561  */
2562 static void
2564 {
2565  int i,
2566  j,
2567  k;
2568 
2569  for (i = 0; i < numTables; i++)
2570  {
2571  TableInfo *tbinfo = &(tblinfo[i]);
2572  int numParents;
2573  TableInfo **parents;
2574  TableInfo *parent;
2575 
2576  /* Sequences and views never have parents */
2577  if (tbinfo->relkind == RELKIND_SEQUENCE ||
2578  tbinfo->relkind == RELKIND_VIEW)
2579  continue;
2580 
2581  /* Don't bother computing anything for non-target tables, either */
2582  if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2583  continue;
2584 
2585  numParents = tbinfo->numParents;
2586  parents = tbinfo->parents;
2587 
2588  if (numParents == 0)
2589  continue; /* nothing to see here, move along */
2590 
2591  /* scan for inherited CHECK constraints */
2592  for (j = 0; j < tbinfo->ncheck; j++)
2593  {
2594  ConstraintInfo *constr;
2595 
2596  constr = &(tbinfo->checkexprs[j]);
2597 
2598  for (k = 0; k < numParents; k++)
2599  {
2600  int l;
2601 
2602  parent = parents[k];
2603  for (l = 0; l < parent->ncheck; l++)
2604  {
2605  ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2606 
2607  if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2608  {
2609  constr->conislocal = false;
2610  break;
2611  }
2612  }
2613  if (!constr->conislocal)
2614  break;
2615  }
2616  }
2617  }
2618 }
2619 
2620 
2621 /*
2622  * dumpDatabase:
2623  * dump the database definition
2624  */
2625 static void
2627 {
2628  DumpOptions *dopt = fout->dopt;
2629  PQExpBuffer dbQry = createPQExpBuffer();
2630  PQExpBuffer delQry = createPQExpBuffer();
2631  PQExpBuffer creaQry = createPQExpBuffer();
2632  PQExpBuffer labelq = createPQExpBuffer();
2633  PGconn *conn = GetConnection(fout);
2634  PGresult *res;
2635  int i_tableoid,
2636  i_oid,
2637  i_datname,
2638  i_dba,
2639  i_encoding,
2640  i_collate,
2641  i_ctype,
2642  i_frozenxid,
2643  i_minmxid,
2644  i_datacl,
2645  i_rdatacl,
2646  i_datistemplate,
2647  i_datconnlimit,
2648  i_tablespace;
2649  CatalogId dbCatId;
2650  DumpId dbDumpId;
2651  const char *datname,
2652  *dba,
2653  *encoding,
2654  *collate,
2655  *ctype,
2656  *datacl,
2657  *rdatacl,
2658  *datistemplate,
2659  *datconnlimit,
2660  *tablespace;
2661  uint32 frozenxid,
2662  minmxid;
2663  char *qdatname;
2664 
2665  pg_log_info("saving database definition");
2666 
2667  /* Fetch the database-level properties for this database */
2668  if (fout->remoteVersion >= 90600)
2669  {
2670  appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2671  "(%s datdba) AS dba, "
2672  "pg_encoding_to_char(encoding) AS encoding, "
2673  "datcollate, datctype, datfrozenxid, datminmxid, "
2674  "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2675  " SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2676  " EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2677  " AS datacl, "
2678  "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2679  " SELECT unnest(acldefault('d',datdba)) AS acl "
2680  " EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2681  " AS rdatacl, "
2682  "datistemplate, datconnlimit, "
2683  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2684  "shobj_description(oid, 'pg_database') AS description "
2685 
2686  "FROM pg_database "
2687  "WHERE datname = current_database()",
2689  }
2690  else if (fout->remoteVersion >= 90300)
2691  {
2692  appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2693  "(%s datdba) AS dba, "
2694  "pg_encoding_to_char(encoding) AS encoding, "
2695  "datcollate, datctype, datfrozenxid, datminmxid, "
2696  "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2697  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2698  "shobj_description(oid, 'pg_database') AS description "
2699 
2700  "FROM pg_database "
2701  "WHERE datname = current_database()",
2703  }
2704  else if (fout->remoteVersion >= 80400)
2705  {
2706  appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2707  "(%s datdba) AS dba, "
2708  "pg_encoding_to_char(encoding) AS encoding, "
2709  "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2710  "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2711  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2712  "shobj_description(oid, 'pg_database') AS description "
2713 
2714  "FROM pg_database "
2715  "WHERE datname = current_database()",
2717  }
2718  else if (fout->remoteVersion >= 80200)
2719  {
2720  appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2721  "(%s datdba) AS dba, "
2722  "pg_encoding_to_char(encoding) AS encoding, "
2723  "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2724  "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2725  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2726  "shobj_description(oid, 'pg_database') AS description "
2727 
2728  "FROM pg_database "
2729  "WHERE datname = current_database()",
2731  }
2732  else
2733  {
2734  appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2735  "(%s datdba) AS dba, "
2736  "pg_encoding_to_char(encoding) AS encoding, "
2737  "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2738  "datacl, '' as rdatacl, datistemplate, "
2739  "-1 as datconnlimit, "
2740  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2741  "FROM pg_database "
2742  "WHERE datname = current_database()",
2744  }
2745 
2746  res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2747 
2748  i_tableoid = PQfnumber(res, "tableoid");
2749  i_oid = PQfnumber(res, "oid");
2750  i_datname = PQfnumber(res, "datname");
2751  i_dba = PQfnumber(res, "dba");
2752  i_encoding = PQfnumber(res, "encoding");
2753  i_collate = PQfnumber(res, "datcollate");
2754  i_ctype = PQfnumber(res, "datctype");
2755  i_frozenxid = PQfnumber(res, "datfrozenxid");
2756  i_minmxid = PQfnumber(res, "datminmxid");
2757  i_datacl = PQfnumber(res, "datacl");
2758  i_rdatacl = PQfnumber(res, "rdatacl");
2759  i_datistemplate = PQfnumber(res, "datistemplate");
2760  i_datconnlimit = PQfnumber(res, "datconnlimit");
2761  i_tablespace = PQfnumber(res, "tablespace");
2762 
2763  dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2764  dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2765  datname = PQgetvalue(res, 0, i_datname);
2766  dba = PQgetvalue(res, 0, i_dba);
2767  encoding = PQgetvalue(res, 0, i_encoding);
2768  collate = PQgetvalue(res, 0, i_collate);
2769  ctype = PQgetvalue(res, 0, i_ctype);
2770  frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2771  minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2772  datacl = PQgetvalue(res, 0, i_datacl);
2773  rdatacl = PQgetvalue(res, 0, i_rdatacl);
2774  datistemplate = PQgetvalue(res, 0, i_datistemplate);
2775  datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2776  tablespace = PQgetvalue(res, 0, i_tablespace);
2777 
2778  qdatname = pg_strdup(fmtId(datname));
2779 
2780  /*
2781  * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2782  * and tablespace since those can't be altered later. Other DB properties
2783  * are left to the DATABASE PROPERTIES entry, so that they can be applied
2784  * after reconnecting to the target DB.
2785  */
2786  appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2787  qdatname);
2788  if (strlen(encoding) > 0)
2789  {
2790  appendPQExpBufferStr(creaQry, " ENCODING = ");
2791  appendStringLiteralAH(creaQry, encoding, fout);
2792  }
2793  if (strlen(collate) > 0)
2794  {
2795  appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2796  appendStringLiteralAH(creaQry, collate, fout);
2797  }
2798  if (strlen(ctype) > 0)
2799  {
2800  appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2801  appendStringLiteralAH(creaQry, ctype, fout);
2802  }
2803 
2804  /*
2805  * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2806  * thing; the decision whether to specify a tablespace should be left till
2807  * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2808  * label the DATABASE entry with the tablespace and let the normal
2809  * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2810  * attention to default_tablespace, so that won't work.
2811  */
2812  if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2813  !dopt->outputNoTablespaces)
2814  appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2815  fmtId(tablespace));
2816  appendPQExpBufferStr(creaQry, ";\n");
2817 
2818  appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2819  qdatname);
2820 
2821  dbDumpId = createDumpId();
2822 
2823  ArchiveEntry(fout,
2824  dbCatId, /* catalog ID */
2825  dbDumpId, /* dump ID */
2826  ARCHIVE_OPTS(.tag = datname,
2827  .owner = dba,
2828  .description = "DATABASE",
2829  .section = SECTION_PRE_DATA,
2830  .createStmt = creaQry->data,
2831  .dropStmt = delQry->data));
2832 
2833  /* Compute correct tag for archive entry */
2834  appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2835 
2836  /* Dump DB comment if any */
2837  if (fout->remoteVersion >= 80200)
2838  {
2839  /*
2840  * 8.2 and up keep comments on shared objects in a shared table, so we
2841  * cannot use the dumpComment() code used for other database objects.
2842  * Be careful that the ArchiveEntry parameters match that function.
2843  */
2844  char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2845 
2846  if (comment && *comment && !dopt->no_comments)
2847  {
2848  resetPQExpBuffer(dbQry);
2849 
2850  /*
2851  * Generates warning when loaded into a differently-named
2852  * database.
2853  */
2854  appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2855  appendStringLiteralAH(dbQry, comment, fout);
2856  appendPQExpBufferStr(dbQry, ";\n");
2857 
2858  ArchiveEntry(fout, nilCatalogId, createDumpId(),
2859  ARCHIVE_OPTS(.tag = labelq->data,
2860  .owner = dba,
2861  .description = "COMMENT",
2862  .section = SECTION_NONE,
2863  .createStmt = dbQry->data,
2864  .deps = &dbDumpId,
2865  .nDeps = 1));
2866  }
2867  }
2868  else
2869  {
2870  dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2871  dbCatId, 0, dbDumpId);
2872  }
2873 
2874  /* Dump DB security label, if enabled */
2875  if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2876  {
2877  PGresult *shres;
2878  PQExpBuffer seclabelQry;
2879 
2880  seclabelQry = createPQExpBuffer();
2881 
2882  buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2883  shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2884  resetPQExpBuffer(seclabelQry);
2885  emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2886  if (seclabelQry->len > 0)
2887  ArchiveEntry(fout, nilCatalogId, createDumpId(),
2888  ARCHIVE_OPTS(.tag = labelq->data,
2889  .owner = dba,
2890  .description = "SECURITY LABEL",
2891  .section = SECTION_NONE,
2892  .createStmt = seclabelQry->data,
2893  .deps = &dbDumpId,
2894  .nDeps = 1));
2895  destroyPQExpBuffer(seclabelQry);
2896  PQclear(shres);
2897  }
2898 
2899  /*
2900  * Dump ACL if any. Note that we do not support initial privileges
2901  * (pg_init_privs) on databases.
2902  */
2903  dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2904  qdatname, NULL, NULL,
2905  dba, datacl, rdatacl, "", "");
2906 
2907  /*
2908  * Now construct a DATABASE PROPERTIES archive entry to restore any
2909  * non-default database-level properties. (The reason this must be
2910  * separate is that we cannot put any additional commands into the TOC
2911  * entry that has CREATE DATABASE. pg_restore would execute such a group
2912  * in an implicit transaction block, and the backend won't allow CREATE
2913  * DATABASE in that context.)
2914  */
2915  resetPQExpBuffer(creaQry);
2916  resetPQExpBuffer(delQry);
2917 
2918  if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2919  appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2920  qdatname, datconnlimit);
2921 
2922  if (strcmp(datistemplate, "t") == 0)
2923  {
2924  appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2925  qdatname);
2926 
2927  /*
2928  * The backend won't accept DROP DATABASE on a template database. We
2929  * can deal with that by removing the template marking before the DROP
2930  * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
2931  * since no such command is currently supported, fake it with a direct
2932  * UPDATE on pg_database.
2933  */
2934  appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2935  "SET datistemplate = false WHERE datname = ");
2936  appendStringLiteralAH(delQry, datname, fout);
2937  appendPQExpBufferStr(delQry, ";\n");
2938  }
2939 
2940  /* Add database-specific SET options */
2941  dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2942 
2943  /*
2944  * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2945  * entry, too, for lack of a better place.
2946  */
2947  if (dopt->binary_upgrade)
2948  {
2949  appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2950  appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2951  "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2952  "WHERE datname = ",
2953  frozenxid, minmxid);
2954  appendStringLiteralAH(creaQry, datname, fout);
2955  appendPQExpBufferStr(creaQry, ";\n");
2956  }
2957 
2958  if (creaQry->len > 0)
2959  ArchiveEntry(fout, nilCatalogId, createDumpId(),
2960  ARCHIVE_OPTS(.tag = datname,
2961  .owner = dba,
2962  .description = "DATABASE PROPERTIES",
2963  .section = SECTION_PRE_DATA,
2964  .createStmt = creaQry->data,
2965  .dropStmt = delQry->data,
2966  .deps = &dbDumpId));
2967 
2968  /*
2969  * pg_largeobject comes from the old system intact, so set its
2970  * relfrozenxids and relminmxids.
2971  */
2972  if (dopt->binary_upgrade)
2973  {
2974  PGresult *lo_res;
2975  PQExpBuffer loFrozenQry = createPQExpBuffer();
2976  PQExpBuffer loOutQry = createPQExpBuffer();
2977  int i_relfrozenxid,
2978  i_relminmxid;
2979 
2980  /*
2981  * pg_largeobject
2982  */
2983  if (fout->remoteVersion >= 90300)
2984  appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2985  "FROM pg_catalog.pg_class\n"
2986  "WHERE oid = %u;\n",
2987  LargeObjectRelationId);
2988  else
2989  appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2990  "FROM pg_catalog.pg_class\n"
2991  "WHERE oid = %u;\n",
2992  LargeObjectRelationId);
2993 
2994  lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2995 
2996  i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2997  i_relminmxid = PQfnumber(lo_res, "relminmxid");
2998 
2999  appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
3000  appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
3001  "SET relfrozenxid = '%u', relminmxid = '%u'\n"
3002  "WHERE oid = %u;\n",
3003  atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
3004  atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
3005  LargeObjectRelationId);
3006  ArchiveEntry(fout, nilCatalogId, createDumpId(),
3007  ARCHIVE_OPTS(.tag = "pg_largeobject",
3008  .description = "pg_largeobject",
3009  .section = SECTION_PRE_DATA,
3010  .createStmt = loOutQry->data));
3011 
3012  PQclear(lo_res);
3013 
3014  destroyPQExpBuffer(loFrozenQry);
3015  destroyPQExpBuffer(loOutQry);
3016  }
3017 
3018  PQclear(res);
3019 
3020  free(qdatname);
3021  destroyPQExpBuffer(dbQry);
3022  destroyPQExpBuffer(delQry);
3023  destroyPQExpBuffer(creaQry);
3024  destroyPQExpBuffer(labelq);
3025 }
3026 
3027 /*
3028  * Collect any database-specific or role-and-database-specific SET options
3029  * for this database, and append them to outbuf.
3030  */
3031 static void
3033  const char *dbname, Oid dboid)
3034 {
3035  PGconn *conn = GetConnection(AH);
3037  PGresult *res;
3038  int count = 1;
3039 
3040  /*
3041  * First collect database-specific options. Pre-8.4 server versions lack
3042  * unnest(), so we do this the hard way by querying once per subscript.
3043  */
3044  for (;;)
3045  {
3046  if (AH->remoteVersion >= 90000)
3047  printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3048  "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3049  count, dboid);
3050  else
3051  printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3052 
3053  res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3054 
3055  if (PQntuples(res) == 1 &&
3056  !PQgetisnull(res, 0, 0))
3057  {
3058  makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3059  "DATABASE", dbname, NULL, NULL,
3060  outbuf);
3061  PQclear(res);
3062  count++;
3063  }
3064  else
3065  {
3066  PQclear(res);
3067  break;
3068  }
3069  }
3070 
3071  /* Now look for role-and-database-specific options */
3072  if (AH->remoteVersion >= 90000)
3073  {
3074  /* Here we can assume we have unnest() */
3075  printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3076  "FROM pg_db_role_setting s, pg_roles r "
3077  "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3078  dboid);
3079 
3080  res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3081 
3082  if (PQntuples(res) > 0)
3083  {
3084  int i;
3085 
3086  for (i = 0; i < PQntuples(res); i++)
3087  makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3088  "ROLE", PQgetvalue(res, i, 0),
3089  "DATABASE", dbname,
3090  outbuf);
3091  }
3092 
3093  PQclear(res);
3094  }
3095 
3096  destroyPQExpBuffer(buf);
3097 }
3098 
3099 /*
3100  * dumpEncoding: put the correct encoding into the archive
3101  */
3102 static void
3104 {
3105  const char *encname = pg_encoding_to_char(AH->encoding);
3107 
3108  pg_log_info("saving encoding = %s", encname);
3109 
3110  appendPQExpBufferStr(qry, "SET client_encoding = ");
3111  appendStringLiteralAH(qry, encname, AH);
3112  appendPQExpBufferStr(qry, ";\n");
3113 
3114  ArchiveEntry(AH, nilCatalogId, createDumpId(),
3115  ARCHIVE_OPTS(.tag = "ENCODING",
3116  .description = "ENCODING",
3117  .section = SECTION_PRE_DATA,
3118  .createStmt = qry->data));
3119 
3120  destroyPQExpBuffer(qry);
3121 }
3122 
3123 
3124 /*
3125  * dumpStdStrings: put the correct escape string behavior into the archive
3126  */
3127 static void
3129 {
3130  const char *stdstrings = AH->std_strings ? "on" : "off";
3132 
3133  pg_log_info("saving standard_conforming_strings = %s",
3134  stdstrings);
3135 
3136  appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3137  stdstrings);
3138 
3139  ArchiveEntry(AH, nilCatalogId, createDumpId(),
3140  ARCHIVE_OPTS(.tag = "STDSTRINGS",
3141  .description = "STDSTRINGS",
3142  .section = SECTION_PRE_DATA,
3143  .createStmt = qry->data));
3144 
3145  destroyPQExpBuffer(qry);
3146 }
3147 
3148 /*
3149  * dumpSearchPath: record the active search_path in the archive
3150  */
3151 static void
3153 {
3155  PQExpBuffer path = createPQExpBuffer();
3156  PGresult *res;
3157  char **schemanames = NULL;
3158  int nschemanames = 0;
3159  int i;
3160 
3161  /*
3162  * We use the result of current_schemas(), not the search_path GUC,
3163  * because that might contain wildcards such as "$user", which won't
3164  * necessarily have the same value during restore. Also, this way avoids
3165  * listing schemas that may appear in search_path but not actually exist,
3166  * which seems like a prudent exclusion.
3167  */
3168  res = ExecuteSqlQueryForSingleRow(AH,
3169  "SELECT pg_catalog.current_schemas(false)");
3170 
3171  if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3172  fatal("could not parse result of current_schemas()");
3173 
3174  /*
3175  * We use set_config(), not a simple "SET search_path" command, because
3176  * the latter has less-clean behavior if the search path is empty. While
3177  * that's likely to get fixed at some point, it seems like a good idea to
3178  * be as backwards-compatible as possible in what we put into archives.
3179  */
3180  for (i = 0; i < nschemanames; i++)
3181  {
3182  if (i > 0)
3183  appendPQExpBufferStr(path, ", ");
3184  appendPQExpBufferStr(path, fmtId(schemanames[i]));
3185  }
3186 
3187  appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3188  appendStringLiteralAH(qry, path->data, AH);
3189  appendPQExpBufferStr(qry, ", false);\n");
3190 
3191  pg_log_info("saving search_path = %s", path->data);
3192 
3193  ArchiveEntry(AH, nilCatalogId, createDumpId(),
3194  ARCHIVE_OPTS(.tag = "SEARCHPATH",
3195  .description = "SEARCHPATH",
3196  .section = SECTION_PRE_DATA,
3197  .createStmt = qry->data));
3198 
3199  /* Also save it in AH->searchpath, in case we're doing plain text dump */
3200  AH->searchpath = pg_strdup(qry->data);
3201 
3202  if (schemanames)
3203  free(schemanames);
3204  PQclear(res);
3205  destroyPQExpBuffer(qry);
3206  destroyPQExpBuffer(path);
3207 }
3208 
3209 
3210 /*
3211  * getBlobs:
3212  * Collect schema-level data about large objects
3213  */
3214 static void
3216 {
3217  DumpOptions *dopt = fout->dopt;
3218  PQExpBuffer blobQry = createPQExpBuffer();
3219  BlobInfo *binfo;
3220  DumpableObject *bdata;
3221  PGresult *res;
3222  int ntups;
3223  int i;
3224  int i_oid;
3225  int i_lomowner;
3226  int i_lomacl;
3227  int i_rlomacl;
3228  int i_initlomacl;
3229  int i_initrlomacl;
3230 
3231  pg_log_info("reading large objects");
3232 
3233  /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3234  if (fout->remoteVersion >= 90600)
3235  {
3236  PQExpBuffer acl_subquery = createPQExpBuffer();
3237  PQExpBuffer racl_subquery = createPQExpBuffer();
3238  PQExpBuffer init_acl_subquery = createPQExpBuffer();
3239  PQExpBuffer init_racl_subquery = createPQExpBuffer();
3240 
3241  buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3242  init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3243  dopt->binary_upgrade);
3244 
3245  appendPQExpBuffer(blobQry,
3246  "SELECT l.oid, (%s l.lomowner) AS rolname, "
3247  "%s AS lomacl, "
3248  "%s AS rlomacl, "
3249  "%s AS initlomacl, "
3250  "%s AS initrlomacl "
3251  "FROM pg_largeobject_metadata l "
3252  "LEFT JOIN pg_init_privs pip ON "
3253  "(l.oid = pip.objoid "
3254  "AND pip.classoid = 'pg_largeobject'::regclass "
3255  "AND pip.objsubid = 0) ",
3257  acl_subquery->data,
3258  racl_subquery->data,
3259  init_acl_subquery->data,
3260  init_racl_subquery->data);
3261 
3262  destroyPQExpBuffer(acl_subquery);
3263  destroyPQExpBuffer(racl_subquery);
3264  destroyPQExpBuffer(init_acl_subquery);
3265  destroyPQExpBuffer(init_racl_subquery);
3266  }
3267  else if (fout->remoteVersion >= 90000)
3268  appendPQExpBuffer(blobQry,
3269  "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3270  "NULL AS rlomacl, NULL AS initlomacl, "
3271  "NULL AS initrlomacl "
3272  " FROM pg_largeobject_metadata",
3274  else
3275  appendPQExpBufferStr(blobQry,
3276  "SELECT DISTINCT loid AS oid, "
3277  "NULL::name AS rolname, NULL::oid AS lomacl, "
3278  "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3279  "NULL::oid AS initrlomacl "
3280  " FROM pg_largeobject");
3281 
3282  res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3283 
3284  i_oid = PQfnumber(res, "oid");
3285  i_lomowner = PQfnumber(res, "rolname");
3286  i_lomacl = PQfnumber(res, "lomacl");
3287  i_rlomacl = PQfnumber(res, "rlomacl");
3288  i_initlomacl = PQfnumber(res, "initlomacl");
3289  i_initrlomacl = PQfnumber(res, "initrlomacl");
3290 
3291  ntups = PQntuples(res);
3292 
3293  /*
3294  * Each large object has its own BLOB archive entry.
3295  */
3296  binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3297 
3298  for (i = 0; i < ntups; i++)
3299  {
3300  binfo[i].dobj.objType = DO_BLOB;
3301  binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3302  binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3303  AssignDumpId(&binfo[i].dobj);
3304 
3305  binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3306  binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3307  binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3308  binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3309  binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3310  binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3311 
3312  if (PQgetisnull(res, i, i_lomacl) &&
3313  PQgetisnull(res, i, i_rlomacl) &&
3314  PQgetisnull(res, i, i_initlomacl) &&
3315  PQgetisnull(res, i, i_initrlomacl))
3316  binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3317 
3318  /*
3319  * In binary-upgrade mode for blobs, we do *not* dump out the blob
3320  * data, as it will be copied by pg_upgrade, which simply copies the
3321  * pg_largeobject table. We *do* however dump out anything but the
3322  * data, as pg_upgrade copies just pg_largeobject, but not
3323  * pg_largeobject_metadata, after the dump is restored.
3324  */
3325  if (dopt->binary_upgrade)
3326  binfo[i].dobj.dump &= ~DUMP_COMPONENT_DATA;
3327  }
3328 
3329  /*
3330  * If we have any large objects, a "BLOBS" archive entry is needed. This
3331  * is just a placeholder for sorting; it carries no data now.
3332  */
3333  if (ntups > 0)
3334  {
3335  bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3336  bdata->objType = DO_BLOB_DATA;
3337  bdata->catId = nilCatalogId;
3338  AssignDumpId(bdata);
3339  bdata->name = pg_strdup("BLOBS");
3340  }
3341 
3342  PQclear(res);
3343  destroyPQExpBuffer(blobQry);
3344 }
3345 
3346 /*
3347  * dumpBlob
3348  *
3349  * dump the definition (metadata) of the given large object
3350  */
3351 static void
3352 dumpBlob(Archive *fout, BlobInfo *binfo)
3353 {
3354  PQExpBuffer cquery = createPQExpBuffer();
3355  PQExpBuffer dquery = createPQExpBuffer();
3356 
3357  appendPQExpBuffer(cquery,
3358  "SELECT pg_catalog.lo_create('%s');\n",
3359  binfo->dobj.name);
3360 
3361  appendPQExpBuffer(dquery,
3362  "SELECT pg_catalog.lo_unlink('%s');\n",
3363  binfo->dobj.name);
3364 
3365  if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3366  ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3367  ARCHIVE_OPTS(.tag = binfo->dobj.name,
3368  .owner = binfo->rolname,
3369  .description = "BLOB",
3370  .section = SECTION_PRE_DATA,
3371  .createStmt = cquery->data,
3372  .dropStmt = dquery->data));
3373 
3374  /* Dump comment if any */
3375  if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3376  dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3377  NULL, binfo->rolname,
3378  binfo->dobj.catId, 0, binfo->dobj.dumpId);
3379 
3380  /* Dump security label if any */
3381  if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3382  dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3383  NULL, binfo->rolname,
3384  binfo->dobj.catId, 0, binfo->dobj.dumpId);
3385 
3386  /* Dump ACL if any */
3387  if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3388  dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3389  binfo->dobj.name, NULL,
3390  NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3391  binfo->initblobacl, binfo->initrblobacl);
3392 
3393  destroyPQExpBuffer(cquery);
3394  destroyPQExpBuffer(dquery);
3395 }
3396 
3397 /*
3398  * dumpBlobs:
3399  * dump the data contents of all large objects
3400  */
3401 static int
3402 dumpBlobs(Archive *fout, void *arg)
3403 {
3404  const char *blobQry;
3405  const char *blobFetchQry;
3406  PGconn *conn = GetConnection(fout);
3407  PGresult *res;
3408  char buf[LOBBUFSIZE];
3409  int ntups;
3410  int i;
3411  int cnt;
3412 
3413  pg_log_info("saving large objects");
3414 
3415  /*
3416  * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3417  * the already-in-memory dumpable objects instead...
3418  */
3419  if (fout->remoteVersion >= 90000)
3420  blobQry =
3421  "DECLARE bloboid CURSOR FOR "
3422  "SELECT oid FROM pg_largeobject_metadata ORDER BY 1";
3423  else
3424  blobQry =
3425  "DECLARE bloboid CURSOR FOR "
3426  "SELECT DISTINCT loid FROM pg_largeobject ORDER BY 1";
3427 
3428  ExecuteSqlStatement(fout, blobQry);
3429 
3430  /* Command to fetch from cursor */
3431  blobFetchQry = "FETCH 1000 IN bloboid";
3432 
3433  do
3434  {
3435  /* Do a fetch */
3436  res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3437 
3438  /* Process the tuples, if any */
3439  ntups = PQntuples(res);
3440  for (i = 0; i < ntups; i++)
3441  {
3442  Oid blobOid;
3443  int loFd;
3444 
3445  blobOid = atooid(PQgetvalue(res, i, 0));
3446  /* Open the BLOB */
3447  loFd = lo_open(conn, blobOid, INV_READ);
3448  if (loFd == -1)
3449  fatal("could not open large object %u: %s",
3450  blobOid, PQerrorMessage(conn));
3451 
3452  StartBlob(fout, blobOid);
3453 
3454  /* Now read it in chunks, sending data to archive */
3455  do
3456  {
3457  cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3458  if (cnt < 0)
3459  fatal("error reading large object %u: %s",
3460  blobOid, PQerrorMessage(conn));
3461 
3462  WriteData(fout, buf, cnt);
3463  } while (cnt > 0);
3464 
3465  lo_close(conn, loFd);
3466 
3467  EndBlob(fout, blobOid);
3468  }
3469 
3470  PQclear(res);
3471  } while (ntups > 0);
3472 
3473  return 1;
3474 }
3475 
3476 /*
3477  * getPolicies
3478  * get information about policies on a dumpable table.
3479  */
3480 void
3481 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3482 {
3483  PQExpBuffer query;
3484  PGresult *res;
3485  PolicyInfo *polinfo;
3486  int i_oid;
3487  int i_tableoid;
3488  int i_polname;
3489  int i_polcmd;
3490  int i_polpermissive;
3491  int i_polroles;
3492  int i_polqual;
3493  int i_polwithcheck;
3494  int i,
3495  j,
3496  ntups;
3497 
3498  if (fout->remoteVersion < 90500)
3499  return;
3500 
3501  query = createPQExpBuffer();
3502 
3503  for (i = 0; i < numTables; i++)
3504  {
3505  TableInfo *tbinfo = &tblinfo[i];
3506 
3507  /* Ignore row security on tables not to be dumped */
3508  if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3509  continue;
3510 
3511  pg_log_info("reading row security enabled for table \"%s.%s\"",
3512  tbinfo->dobj.namespace->dobj.name,
3513  tbinfo->dobj.name);
3514 
3515  /*
3516  * Get row security enabled information for the table. We represent
3517  * RLS being enabled on a table by creating a PolicyInfo object with
3518  * null polname.
3519  */
3520  if (tbinfo->rowsec)
3521  {
3522  /*
3523  * Note: use tableoid 0 so that this object won't be mistaken for
3524  * something that pg_depend entries apply to.
3525  */
3526  polinfo = pg_malloc(sizeof(PolicyInfo));
3527  polinfo->dobj.objType = DO_POLICY;
3528  polinfo->dobj.catId.tableoid = 0;
3529  polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3530  AssignDumpId(&polinfo->dobj);
3531  polinfo->dobj.namespace = tbinfo->dobj.namespace;
3532  polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3533  polinfo->poltable = tbinfo;
3534  polinfo->polname = NULL;
3535  polinfo->polcmd = '\0';
3536  polinfo->polpermissive = 0;
3537  polinfo->polroles = NULL;
3538  polinfo->polqual = NULL;
3539  polinfo->polwithcheck = NULL;
3540  }
3541 
3542  pg_log_info("reading policies for table \"%s.%s\"",
3543  tbinfo->dobj.namespace->dobj.name,
3544  tbinfo->dobj.name);
3545 
3546  resetPQExpBuffer(query);
3547 
3548  /* Get the policies for the table. */
3549  if (fout->remoteVersion >= 100000)
3550  appendPQExpBuffer(query,
3551  "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3552  "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3553  " 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, "
3554  "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3555  "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3556  "FROM pg_catalog.pg_policy pol "
3557  "WHERE polrelid = '%u'",
3558  tbinfo->dobj.catId.oid);
3559  else
3560  appendPQExpBuffer(query,
3561  "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3562  "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3563  " 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, "
3564  "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3565  "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3566  "FROM pg_catalog.pg_policy pol "
3567  "WHERE polrelid = '%u'",
3568  tbinfo->dobj.catId.oid);
3569  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3570 
3571  ntups = PQntuples(res);
3572 
3573  if (ntups == 0)
3574  {
3575  /*
3576  * No explicit policies to handle (only the default-deny policy,
3577  * which is handled as part of the table definition). Clean up
3578  * and return.
3579  */
3580  PQclear(res);
3581  continue;
3582  }
3583 
3584  i_oid = PQfnumber(res, "oid");
3585  i_tableoid = PQfnumber(res, "tableoid");
3586  i_polname = PQfnumber(res, "polname");
3587  i_polcmd = PQfnumber(res, "polcmd");
3588  i_polpermissive = PQfnumber(res, "polpermissive");
3589  i_polroles = PQfnumber(res, "polroles");
3590  i_polqual = PQfnumber(res, "polqual");
3591  i_polwithcheck = PQfnumber(res, "polwithcheck");
3592 
3593  polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3594 
3595  for (j = 0; j < ntups; j++)
3596  {
3597  polinfo[j].dobj.objType = DO_POLICY;
3598  polinfo[j].dobj.catId.tableoid =
3599  atooid(PQgetvalue(res, j, i_tableoid));
3600  polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3601  AssignDumpId(&polinfo[j].dobj);
3602  polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3603  polinfo[j].poltable = tbinfo;
3604  polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3605  polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3606 
3607  polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3608  polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3609 
3610  if (PQgetisnull(res, j, i_polroles))
3611  polinfo[j].polroles = NULL;
3612  else
3613  polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3614 
3615  if (PQgetisnull(res, j, i_polqual))
3616  polinfo[j].polqual = NULL;
3617  else
3618  polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3619 
3620  if (PQgetisnull(res, j, i_polwithcheck))
3621  polinfo[j].polwithcheck = NULL;
3622  else
3623  polinfo[j].polwithcheck
3624  = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3625  }
3626  PQclear(res);
3627  }
3628  destroyPQExpBuffer(query);
3629 }
3630 
3631 /*
3632  * dumpPolicy
3633  * dump the definition of the given policy
3634  */
3635 static void
3637 {
3638  DumpOptions *dopt = fout->dopt;
3639  TableInfo *tbinfo = polinfo->poltable;
3640  PQExpBuffer query;
3641  PQExpBuffer delqry;
3642  const char *cmd;
3643  char *tag;
3644 
3645  if (dopt->dataOnly)
3646  return;
3647 
3648  /*
3649  * If polname is NULL, then this record is just indicating that ROW LEVEL
3650  * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3651  * ROW LEVEL SECURITY.
3652  */
3653  if (polinfo->polname == NULL)
3654  {
3655  query = createPQExpBuffer();
3656 
3657  appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3658  fmtQualifiedDumpable(tbinfo));
3659 
3660  /*
3661  * We must emit the ROW SECURITY object's dependency on its table
3662  * explicitly, because it will not match anything in pg_depend (unlike
3663  * the case for other PolicyInfo objects).
3664  */
3665  if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3666  ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3667  ARCHIVE_OPTS(.tag = polinfo->dobj.name,
3668  .namespace = polinfo->dobj.namespace->dobj.name,
3669  .owner = tbinfo->rolname,
3670  .description = "ROW SECURITY",
3671  .section = SECTION_POST_DATA,
3672  .createStmt = query->data,
3673  .deps = &(tbinfo->dobj.dumpId),
3674  .nDeps = 1));
3675 
3676  destroyPQExpBuffer(query);
3677  return;
3678  }
3679 
3680  if (polinfo->polcmd == '*')
3681  cmd = "";
3682  else if (polinfo->polcmd == 'r')
3683  cmd = " FOR SELECT";
3684  else if (polinfo->polcmd == 'a')
3685  cmd = " FOR INSERT";
3686  else if (polinfo->polcmd == 'w')
3687  cmd = " FOR UPDATE";
3688  else if (polinfo->polcmd == 'd')
3689  cmd = " FOR DELETE";
3690  else
3691  {
3692  pg_log_error("unexpected policy command type: %c",
3693  polinfo->polcmd);
3694  exit_nicely(1);
3695  }
3696 
3697  query = createPQExpBuffer();
3698  delqry = createPQExpBuffer();
3699 
3700  appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3701 
3702  appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3703  !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3704 
3705  if (polinfo->polroles != NULL)
3706  appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3707 
3708  if (polinfo->polqual != NULL)
3709  appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3710 
3711  if (polinfo->polwithcheck != NULL)
3712  appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3713 
3714  appendPQExpBuffer(query, ";\n");
3715 
3716  appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3717  appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3718 
3719  tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3720 
3721  if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3722  ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3723  ARCHIVE_OPTS(.tag = tag,
3724  .namespace = polinfo->dobj.namespace->dobj.name,
3725  .owner = tbinfo->rolname,
3726  .description = "POLICY",
3727  .section = SECTION_POST_DATA,
3728  .createStmt = query->data,
3729  .dropStmt = delqry->data));
3730 
3731  free(tag);
3732  destroyPQExpBuffer(query);
3733  destroyPQExpBuffer(delqry);
3734 }
3735 
3736 /*
3737  * getPublications
3738  * get information about publications
3739  */
3740 void
3742 {
3743  DumpOptions *dopt = fout->dopt;
3744  PQExpBuffer query;
3745  PGresult *res;
3746  PublicationInfo *pubinfo;
3747  int i_tableoid;
3748  int i_oid;
3749  int i_pubname;
3750  int i_rolname;
3751  int i_puballtables;
3752  int i_pubinsert;
3753  int i_pubupdate;
3754  int i_pubdelete;
3755  int i_pubtruncate;
3756  int i,
3757  ntups;
3758 
3759  if (dopt->no_publications || fout->remoteVersion < 100000)
3760  return;
3761 
3762  query = createPQExpBuffer();
3763 
3764  resetPQExpBuffer(query);
3765 
3766  /* Get the publications. */
3767  if (fout->remoteVersion >= 110000)
3768  appendPQExpBuffer(query,
3769  "SELECT p.tableoid, p.oid, p.pubname, "
3770  "(%s p.pubowner) AS rolname, "
3771  "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3772  "FROM pg_publication p",
3774  else
3775  appendPQExpBuffer(query,
3776  "SELECT p.tableoid, p.oid, p.pubname, "
3777  "(%s p.pubowner) AS rolname, "
3778  "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3779  "FROM pg_publication p",
3781 
3782  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3783 
3784  ntups = PQntuples(res);
3785 
3786  i_tableoid = PQfnumber(res, "tableoid");
3787  i_oid = PQfnumber(res, "oid");
3788  i_pubname = PQfnumber(res, "pubname");
3789  i_rolname = PQfnumber(res, "rolname");
3790  i_puballtables = PQfnumber(res, "puballtables");
3791  i_pubinsert = PQfnumber(res, "pubinsert");
3792  i_pubupdate = PQfnumber(res, "pubupdate");
3793  i_pubdelete = PQfnumber(res, "pubdelete");
3794  i_pubtruncate = PQfnumber(res, "pubtruncate");
3795 
3796  pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3797 
3798  for (i = 0; i < ntups; i++)
3799  {
3800  pubinfo[i].dobj.objType = DO_PUBLICATION;
3801  pubinfo[i].dobj.catId.tableoid =
3802  atooid(PQgetvalue(res, i, i_tableoid));
3803  pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3804  AssignDumpId(&pubinfo[i].dobj);
3805  pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3806  pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3807  pubinfo[i].puballtables =
3808  (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3809  pubinfo[i].pubinsert =
3810  (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3811  pubinfo[i].pubupdate =
3812  (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3813  pubinfo[i].pubdelete =
3814  (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3815  pubinfo[i].pubtruncate =
3816  (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
3817 
3818  if (strlen(pubinfo[i].rolname) == 0)
3819  pg_log_warning("owner of publication \"%s\" appears to be invalid",
3820  pubinfo[i].dobj.name);
3821 
3822  /* Decide whether we want to dump it */
3823  selectDumpableObject(&(pubinfo[i].dobj), fout);
3824  }
3825  PQclear(res);
3826 
3827  destroyPQExpBuffer(query);
3828 }
3829 
3830 /*
3831  * dumpPublication
3832  * dump the definition of the given publication
3833  */
3834 static void
3836 {
3837  PQExpBuffer delq;
3838  PQExpBuffer query;
3839  char *qpubname;
3840  bool first = true;
3841 
3842  if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3843  return;
3844 
3845  delq = createPQExpBuffer();
3846  query = createPQExpBuffer();
3847 
3848  qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3849 
3850  appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3851  qpubname);
3852 
3853  appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3854  qpubname);
3855 
3856  if (pubinfo->puballtables)
3857  appendPQExpBufferStr(query, " FOR ALL TABLES");
3858 
3859  appendPQExpBufferStr(query, " WITH (publish = '");
3860  if (pubinfo->pubinsert)
3861  {
3862  appendPQExpBufferStr(query, "insert");
3863  first = false;
3864  }
3865 
3866  if (pubinfo->pubupdate)
3867  {
3868  if (!first)
3869  appendPQExpBufferStr(query, ", ");
3870 
3871  appendPQExpBufferStr(query, "update");
3872  first = false;
3873  }
3874 
3875  if (pubinfo->pubdelete)
3876  {
3877  if (!first)
3878  appendPQExpBufferStr(query, ", ");
3879 
3880  appendPQExpBufferStr(query, "delete");
3881  first = false;
3882  }
3883 
3884  if (pubinfo->pubtruncate)
3885  {
3886  if (!first)
3887  appendPQExpBufferStr(query, ", ");
3888 
3889  appendPQExpBufferStr(query, "truncate");
3890  first = false;
3891  }
3892 
3893  appendPQExpBufferStr(query, "');\n");
3894 
3895  ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3896  ARCHIVE_OPTS(.tag = pubinfo->dobj.name,
3897  .owner = pubinfo->rolname,
3898  .description = "PUBLICATION",
3899  .section = SECTION_POST_DATA,
3900  .createStmt = query->data,
3901  .dropStmt = delq->data));
3902 
3903  if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3904  dumpComment(fout, "PUBLICATION", qpubname,
3905  NULL, pubinfo->rolname,
3906  pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3907 
3908  if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3909  dumpSecLabel(fout, "PUBLICATION", qpubname,
3910  NULL, pubinfo->rolname,
3911  pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3912 
3913  destroyPQExpBuffer(delq);
3914  destroyPQExpBuffer(query);
3915  free(qpubname);
3916 }
3917 
3918 /*
3919  * getPublicationTables
3920  * get information about publication membership for dumpable tables.
3921  */
3922 void
3924 {
3925  PQExpBuffer query;
3926  PGresult *res;
3927  PublicationRelInfo *pubrinfo;
3928  DumpOptions *dopt = fout->dopt;
3929  int i_tableoid;
3930  int i_oid;
3931  int i_pubname;
3932  int i,
3933  j,
3934  ntups;
3935 
3936  if (dopt->no_publications || fout->remoteVersion < 100000)
3937  return;
3938 
3939  query = createPQExpBuffer();
3940 
3941  for (i = 0; i < numTables; i++)
3942  {
3943  TableInfo *tbinfo = &tblinfo[i];
3944 
3945  /* Only plain tables can be aded to publications. */
3946  if (tbinfo->relkind != RELKIND_RELATION)
3947  continue;
3948 
3949  /*
3950  * Ignore publication membership of tables whose definitions are not
3951  * to be dumped.
3952  */
3953  if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3954  continue;
3955 
3956  pg_log_info("reading publication membership for table \"%s.%s\"",
3957  tbinfo->dobj.namespace->dobj.name,
3958  tbinfo->dobj.name);
3959 
3960  resetPQExpBuffer(query);
3961 
3962  /* Get the publication membership for the table. */
3963  appendPQExpBuffer(query,
3964  "SELECT pr.tableoid, pr.oid, p.pubname "
3965  "FROM pg_publication_rel pr, pg_publication p "
3966  "WHERE pr.prrelid = '%u'"
3967  " AND p.oid = pr.prpubid",
3968  tbinfo->dobj.catId.oid);
3969  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3970 
3971  ntups = PQntuples(res);
3972 
3973  if (ntups == 0)
3974  {
3975  /*
3976  * Table is not member of any publications. Clean up and return.
3977  */
3978  PQclear(res);
3979  continue;
3980  }
3981 
3982  i_tableoid = PQfnumber(res, "tableoid");
3983  i_oid = PQfnumber(res, "oid");
3984  i_pubname = PQfnumber(res, "pubname");
3985 
3986  pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3987 
3988  for (j = 0; j < ntups; j++)
3989  {
3990  pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3991  pubrinfo[j].dobj.catId.tableoid =
3992  atooid(PQgetvalue(res, j, i_tableoid));
3993  pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3994  AssignDumpId(&pubrinfo[j].dobj);
3995  pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3996  pubrinfo[j].dobj.name = tbinfo->dobj.name;
3997  pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3998  pubrinfo[j].pubtable = tbinfo;
3999 
4000  /* Decide whether we want to dump it */
4001  selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
4002  }
4003  PQclear(res);
4004  }
4005  destroyPQExpBuffer(query);
4006 }
4007 
4008 /*
4009  * dumpPublicationTable
4010  * dump the definition of the given publication table mapping
4011  */
4012 static void
4014 {
4015  TableInfo *tbinfo = pubrinfo->pubtable;
4016  PQExpBuffer query;
4017  char *tag;
4018 
4019  if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4020  return;
4021 
4022  tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
4023 
4024  query = createPQExpBuffer();
4025 
4026  appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
4027  fmtId(pubrinfo->pubname));
4028  appendPQExpBuffer(query, " %s;\n",
4029  fmtQualifiedDumpable(tbinfo));
4030 
4031  /*
4032  * There is no point in creating drop query as drop query as the drop is
4033  * done by table drop.
4034  */
4035  ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4036  ARCHIVE_OPTS(.tag = tag,
4037  .namespace = tbinfo->dobj.namespace->dobj.name,
4038  .description = "PUBLICATION TABLE",
4039  .section = SECTION_POST_DATA,
4040  .createStmt = query->data));
4041 
4042  free(tag);
4043  destroyPQExpBuffer(query);
4044 }
4045 
4046 /*
4047  * Is the currently connected user a superuser?
4048  */
4049 static bool
4051 {
4052  ArchiveHandle *AH = (ArchiveHandle *) fout;
4053  const char *val;
4054 
4055  val = PQparameterStatus(AH->connection, "is_superuser");
4056 
4057  if (val && strcmp(val, "on") == 0)
4058  return true;
4059 
4060  return false;
4061 }
4062 
4063 /*
4064  * getSubscriptions
4065  * get information about subscriptions
4066  */
4067 void
4069 {
4070  DumpOptions *dopt = fout->dopt;
4071  PQExpBuffer query;
4072  PGresult *res;
4073  SubscriptionInfo *subinfo;
4074  int i_tableoid;
4075  int i_oid;
4076  int i_subname;
4077  int i_rolname;
4078  int i_subconninfo;
4079  int i_subslotname;
4080  int i_subsynccommit;
4081  int i_subpublications;
4082  int i,
4083  ntups;
4084 
4085  if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4086  return;
4087 
4088  if (!is_superuser(fout))
4089  {
4090  int n;
4091 
4092  res = ExecuteSqlQuery(fout,
4093  "SELECT count(*) FROM pg_subscription "
4094  "WHERE subdbid = (SELECT oid FROM pg_database"
4095  " WHERE datname = current_database())",
4096  PGRES_TUPLES_OK);
4097  n = atoi(PQgetvalue(res, 0, 0));
4098  if (n > 0)
4099  pg_log_warning("subscriptions not dumped because current user is not a superuser");
4100  PQclear(res);
4101  return;
4102  }
4103 
4104  query = createPQExpBuffer();
4105 
4106  resetPQExpBuffer(query);
4107 
4108  /* Get the subscriptions in current database. */
4109  appendPQExpBuffer(query,
4110  "SELECT s.tableoid, s.oid, s.subname,"
4111  "(%s s.subowner) AS rolname, "
4112  " s.subconninfo, s.subslotname, s.subsynccommit, "
4113  " s.subpublications "
4114  "FROM pg_subscription s "
4115  "WHERE s.subdbid = (SELECT oid FROM pg_database"
4116  " WHERE datname = current_database())",
4118  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4119 
4120  ntups = PQntuples(res);
4121 
4122  i_tableoid = PQfnumber(res, "tableoid");
4123  i_oid = PQfnumber(res, "oid");
4124  i_subname = PQfnumber(res, "subname");
4125  i_rolname = PQfnumber(res, "rolname");
4126  i_subconninfo = PQfnumber(res, "subconninfo");
4127  i_subslotname = PQfnumber(res, "subslotname");
4128  i_subsynccommit = PQfnumber(res, "subsynccommit");
4129  i_subpublications = PQfnumber(res, "subpublications");
4130 
4131  subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4132 
4133  for (i = 0; i < ntups; i++)
4134  {
4135  subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4136  subinfo[i].dobj.catId.tableoid =
4137  atooid(PQgetvalue(res, i, i_tableoid));
4138  subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4139  AssignDumpId(&subinfo[i].dobj);
4140  subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4141  subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4142  subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4143  if (PQgetisnull(res, i, i_subslotname))
4144  subinfo[i].subslotname = NULL;
4145  else
4146  subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4147  subinfo[i].subsynccommit =
4148  pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4149  subinfo[i].subpublications =
4150  pg_strdup(PQgetvalue(res, i, i_subpublications));
4151 
4152  if (strlen(subinfo[i].rolname) == 0)
4153  pg_log_warning("owner of subscription \"%s\" appears to be invalid",
4154  subinfo[i].dobj.name);
4155 
4156  /* Decide whether we want to dump it */
4157  selectDumpableObject(&(subinfo[i].dobj), fout);
4158  }
4159  PQclear(res);
4160 
4161  destroyPQExpBuffer(query);
4162 }
4163 
4164 /*
4165  * dumpSubscription
4166  * dump the definition of the given subscription
4167  */
4168 static void
4170 {
4171  PQExpBuffer delq;
4172  PQExpBuffer query;
4173  PQExpBuffer publications;
4174  char *qsubname;
4175  char **pubnames = NULL;
4176  int npubnames = 0;
4177  int i;
4178 
4179  if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4180  return;
4181 
4182  delq = createPQExpBuffer();
4183  query = createPQExpBuffer();
4184 
4185  qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4186 
4187  appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4188  qsubname);
4189 
4190  appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4191  qsubname);
4192  appendStringLiteralAH(query, subinfo->subconninfo, fout);
4193 
4194  /* Build list of quoted publications and append them to query. */
4195  if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4196  {
4197  pg_log_warning("could not parse subpublications array");
4198  if (pubnames)
4199  free(pubnames);
4200  pubnames = NULL;
4201  npubnames = 0;
4202  }
4203 
4204  publications = createPQExpBuffer();
4205  for (i = 0; i < npubnames; i++)
4206  {
4207  if (i > 0)
4208  appendPQExpBufferStr(publications, ", ");
4209 
4210  appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4211  }
4212 
4213  appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4214  if (subinfo->subslotname)
4215  appendStringLiteralAH(query, subinfo->subslotname, fout);
4216  else
4217  appendPQExpBufferStr(query, "NONE");
4218 
4219  if (strcmp(subinfo->subsynccommit, "off") != 0)
4220  appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4221 
4222  appendPQExpBufferStr(query, ");\n");
4223 
4224  ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4225  ARCHIVE_OPTS(.tag = subinfo->dobj.name,
4226  .owner = subinfo->rolname,
4227  .description = "SUBSCRIPTION",
4228  .section = SECTION_POST_DATA,
4229  .createStmt = query->data,
4230  .dropStmt = delq->data));
4231 
4232  if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4233  dumpComment(fout, "SUBSCRIPTION", qsubname,
4234  NULL, subinfo->rolname,
4235  subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4236 
4237  if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4238  dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4239  NULL, subinfo->rolname,
4240  subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4241 
4242  destroyPQExpBuffer(publications);
4243  if (pubnames)
4244  free(pubnames);
4245 
4246  destroyPQExpBuffer(delq);
4247  destroyPQExpBuffer(query);
4248  free(qsubname);
4249 }
4250 
4251 static void
4253  PQExpBuffer upgrade_buffer,
4254  Oid pg_type_oid,
4255  bool force_array_type)
4256 {
4257  PQExpBuffer upgrade_query = createPQExpBuffer();
4258  PGresult *res;
4259  Oid pg_type_array_oid;
4260 
4261  appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4262  appendPQExpBuffer(upgrade_buffer,
4263  "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4264  pg_type_oid);
4265 
4266  /* we only support old >= 8.3 for binary upgrades */
4267  appendPQExpBuffer(upgrade_query,
4268  "SELECT typarray "
4269  "FROM pg_catalog.pg_type "
4270  "WHERE oid = '%u'::pg_catalog.oid;",
4271  pg_type_oid);
4272 
4273  res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4274 
4275  pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4276 
4277  PQclear(res);
4278 
4279  if (!OidIsValid(pg_type_array_oid) && force_array_type)
4280  {
4281  /*
4282  * If the old version didn't assign an array type, but the new version
4283  * does, we must select an unused type OID to assign. This currently
4284  * only happens for domains, when upgrading pre-v11 to v11 and up.
4285  *
4286  * Note: local state here is kind of ugly, but we must have some,
4287  * since we mustn't choose the same unused OID more than once.
4288  */
4289  static Oid next_possible_free_oid = FirstNormalObjectId;
4290  bool is_dup;
4291 
4292  do
4293  {
4294  ++next_possible_free_oid;
4295  printfPQExpBuffer(upgrade_query,
4296  "SELECT EXISTS(SELECT 1 "
4297  "FROM pg_catalog.pg_type "
4298  "WHERE oid = '%u'::pg_catalog.oid);",
4299  next_possible_free_oid);
4300  res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4301  is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4302  PQclear(res);
4303  } while (is_dup);
4304 
4305  pg_type_array_oid = next_possible_free_oid;
4306  }
4307 
4308  if (OidIsValid(pg_type_array_oid))
4309  {
4310  appendPQExpBufferStr(upgrade_buffer,
4311  "\n-- For binary upgrade, must preserve pg_type array oid\n");
4312  appendPQExpBuffer(upgrade_buffer,
4313  "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4314  pg_type_array_oid);
4315  }
4316 
4317  destroyPQExpBuffer(upgrade_query);
4318 }
4319 
4320 static bool
4322  PQExpBuffer upgrade_buffer,
4323  Oid pg_rel_oid)
4324 {
4325  PQExpBuffer upgrade_query = createPQExpBuffer();
4326  PGresult *upgrade_res;
4327  Oid pg_type_oid;
4328  bool toast_set = false;
4329 
4330  /*
4331  * We only support old >= 8.3 for binary upgrades.
4332  *
4333  * We purposefully ignore toast OIDs for partitioned tables; the reason is
4334  * that versions 10 and 11 have them, but 12 does not, so emitting them
4335  * causes the upgrade to fail.
4336  */
4337  appendPQExpBuffer(upgrade_query,
4338  "SELECT c.reltype AS crel, t.reltype AS trel "
4339  "FROM pg_catalog.pg_class c "
4340  "LEFT JOIN pg_catalog.pg_class t ON "
4341  " (c.reltoastrelid = t.oid AND c.relkind <> '%c') "
4342  "WHERE c.oid = '%u'::pg_catalog.oid;",
4343  RELKIND_PARTITIONED_TABLE, pg_rel_oid);
4344 
4345  upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4346 
4347  pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4348 
4349  binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4350  pg_type_oid, false);
4351 
4352  if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4353  {
4354  /* Toast tables do not have pg_type array rows */
4355  Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4356  PQfnumber(upgrade_res, "trel")));
4357 
4358  appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4359  appendPQExpBuffer(upgrade_buffer,
4360  "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4361  pg_type_toast_oid);
4362 
4363  toast_set = true;
4364  }
4365 
4366  PQclear(upgrade_res);
4367  destroyPQExpBuffer(upgrade_query);
4368 
4369  return toast_set;
4370 }
4371 
4372 static void
4374  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4375  bool is_index)
4376 {
4377  PQExpBuffer upgrade_query = createPQExpBuffer();
4378  PGresult *upgrade_res;
4379  Oid pg_class_reltoastrelid;
4380  Oid pg_index_indexrelid;
4381 
4382  appendPQExpBuffer(upgrade_query,
4383  "SELECT c.reltoastrelid, i.indexrelid "
4384  "FROM pg_catalog.pg_class c LEFT JOIN "
4385  "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4386  "WHERE c.oid = '%u'::pg_catalog.oid;",
4387  pg_class_oid);
4388 
4389  upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4390 
4391  pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4392  pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4393 
4394  appendPQExpBufferStr(upgrade_buffer,
4395  "\n-- For binary upgrade, must preserve pg_class oids\n");
4396 
4397  if (!is_index)
4398  {
4399  appendPQExpBuffer(upgrade_buffer,
4400  "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4401  pg_class_oid);
4402  /* only tables have toast tables, not indexes */
4403  if (OidIsValid(pg_class_reltoastrelid))
4404  {
4405  /*
4406  * One complexity is that the table definition might not require
4407  * the creation of a TOAST table, and the TOAST table might have
4408  * been created long after table creation, when the table was
4409  * loaded with wide data. By setting the TOAST oid we force
4410  * creation of the TOAST heap and TOAST index by the backend so we
4411  * can cleanly copy the files during binary upgrade.
4412  */
4413 
4414  appendPQExpBuffer(upgrade_buffer,
4415  "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4416  pg_class_reltoastrelid);
4417 
4418  /* every toast table has an index */
4419  appendPQExpBuffer(upgrade_buffer,
4420  "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4421  pg_index_indexrelid);
4422  }
4423  }
4424  else
4425  appendPQExpBuffer(upgrade_buffer,
4426  "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4427  pg_class_oid);
4428 
4429  appendPQExpBufferChar(upgrade_buffer, '\n');
4430 
4431  PQclear(upgrade_res);
4432  destroyPQExpBuffer(upgrade_query);
4433 }
4434 
4435 /*
4436  * If the DumpableObject is a member of an extension, add a suitable
4437  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4438  *
4439  * For somewhat historical reasons, objname should already be quoted,
4440  * but not objnamespace (if any).
4441  */
4442 static void
4444  DumpableObject *dobj,
4445  const char *objtype,
4446  const char *objname,
4447  const char *objnamespace)
4448 {
4449  DumpableObject *extobj = NULL;
4450  int i;
4451 
4452  if (!dobj->ext_member)
4453  return;
4454 
4455  /*
4456  * Find the parent extension. We could avoid this search if we wanted to
4457  * add a link field to DumpableObject, but the space costs of that would
4458  * be considerable. We assume that member objects could only have a
4459  * direct dependency on their own extension, not any others.
4460  */
4461  for (i = 0; i < dobj->nDeps; i++)
4462  {
4463  extobj = findObjectByDumpId(dobj->dependencies[i]);
4464  if (extobj && extobj->objType == DO_EXTENSION)
4465  break;
4466  extobj = NULL;
4467  }
4468  if (extobj == NULL)
4469  fatal("could not find parent extension for %s %s",
4470  objtype, objname);
4471 
4472  appendPQExpBufferStr(upgrade_buffer,
4473  "\n-- For binary upgrade, handle extension membership the hard way\n");
4474  appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4475  fmtId(extobj->name),
4476  objtype);
4477  if (objnamespace && *objnamespace)
4478  appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4479  appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4480 }
4481 
4482 /*
4483  * getNamespaces:
4484  * read all namespaces in the system catalogs and return them in the
4485  * NamespaceInfo* structure
4486  *
4487  * numNamespaces is set to the number of namespaces read in
4488  */
4489 NamespaceInfo *
4491 {
4492  DumpOptions *dopt = fout->dopt;
4493  PGresult *res;
4494  int ntups;
4495  int i;
4496  PQExpBuffer query;
4497  NamespaceInfo *nsinfo;
4498  int i_tableoid;
4499  int i_oid;
4500  int i_nspname;
4501  int i_rolname;
4502  int i_nspacl;
4503  int i_rnspacl;
4504  int i_initnspacl;
4505  int i_initrnspacl;
4506 
4507  query = createPQExpBuffer();
4508 
4509  /*
4510  * we fetch all namespaces including system ones, so that every object we
4511  * read in can be linked to a containing namespace.
4512  */
4513  if (fout->remoteVersion >= 90600)
4514  {
4515  PQExpBuffer acl_subquery = createPQExpBuffer();
4516  PQExpBuffer racl_subquery = createPQExpBuffer();
4517  PQExpBuffer init_acl_subquery = createPQExpBuffer();
4518  PQExpBuffer init_racl_subquery = createPQExpBuffer();
4519 
4520  buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4521  init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4522  dopt->binary_upgrade);
4523 
4524  appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4525  "(%s nspowner) AS rolname, "
4526  "%s as nspacl, "
4527  "%s as rnspacl, "
4528  "%s as initnspacl, "
4529  "%s as initrnspacl "
4530  "FROM pg_namespace n "
4531  "LEFT JOIN pg_init_privs pip "
4532  "ON (n.oid = pip.objoid "
4533  "AND pip.classoid = 'pg_namespace'::regclass "
4534  "AND pip.objsubid = 0",
4536  acl_subquery->data,
4537  racl_subquery->data,
4538  init_acl_subquery->data,
4539  init_racl_subquery->data);
4540 
4541  appendPQExpBuffer(query, ") ");
4542 
4543  destroyPQExpBuffer(acl_subquery);
4544  destroyPQExpBuffer(racl_subquery);
4545  destroyPQExpBuffer(init_acl_subquery);
4546  destroyPQExpBuffer(init_racl_subquery);
4547  }
4548  else
4549  appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4550  "(%s nspowner) AS rolname, "
4551  "nspacl, NULL as rnspacl, "
4552  "NULL AS initnspacl, NULL as initrnspacl "
4553  "FROM pg_namespace",
4555 
4556  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4557 
4558  ntups = PQntuples(res);
4559 
4560  nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4561 
4562  i_tableoid = PQfnumber(res, "tableoid");
4563  i_oid = PQfnumber(res, "oid");
4564  i_nspname = PQfnumber(res, "nspname");
4565  i_rolname = PQfnumber(res, "rolname");
4566  i_nspacl = PQfnumber(res, "nspacl");
4567  i_rnspacl = PQfnumber(res, "rnspacl");
4568  i_initnspacl = PQfnumber(res, "initnspacl");
4569  i_initrnspacl = PQfnumber(res, "initrnspacl");
4570 
4571  for (i = 0; i < ntups; i++)
4572  {
4573  nsinfo[i].dobj.objType = DO_NAMESPACE;
4574  nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4575  nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4576  AssignDumpId(&nsinfo[i].dobj);
4577  nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4578  nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4579  nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4580  nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4581  nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4582  nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4583 
4584  /* Decide whether to dump this namespace */
4585  selectDumpableNamespace(&nsinfo[i], fout);
4586 
4587  /*
4588  * Do not try to dump ACL if the ACL is empty or the default.
4589  *
4590  * This is useful because, for some schemas/objects, the only
4591  * component we are going to try and dump is the ACL and if we can
4592  * remove that then 'dump' goes to zero/false and we don't consider
4593  * this object for dumping at all later on.
4594  */
4595  if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4596  PQgetisnull(res, i, i_initnspacl) &&
4597  PQgetisnull(res, i, i_initrnspacl))
4598  nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4599 
4600  if (strlen(nsinfo[i].rolname) == 0)
4601  pg_log_warning("owner of schema \"%s\" appears to be invalid",
4602  nsinfo[i].dobj.name);
4603  }
4604 
4605  PQclear(res);
4606  destroyPQExpBuffer(query);
4607 
4608  *numNamespaces = ntups;
4609 
4610  return nsinfo;
4611 }
4612 
4613 /*
4614  * findNamespace:
4615  * given a namespace OID, look up the info read by getNamespaces
4616  */
4617 static NamespaceInfo *
4619 {
4620  NamespaceInfo *nsinfo;
4621 
4622  nsinfo = findNamespaceByOid(nsoid);
4623  if (nsinfo == NULL)
4624  fatal("schema with OID %u does not exist", nsoid);
4625  return nsinfo;
4626 }
4627 
4628 /*
4629  * getExtensions:
4630  * read all extensions in the system catalogs and return them in the
4631  * ExtensionInfo* structure
4632  *
4633  * numExtensions is set to the number of extensions read in
4634  */
4635 ExtensionInfo *
4637 {
4638  DumpOptions *dopt = fout->dopt;
4639  PGresult *res;
4640  int ntups;
4641  int i;
4642  PQExpBuffer query;
4643  ExtensionInfo *extinfo;
4644  int i_tableoid;
4645  int i_oid;
4646  int i_extname;
4647  int i_nspname;
4648  int i_extrelocatable;
4649  int i_extversion;
4650  int i_extconfig;
4651  int i_extcondition;
4652 
4653  /*
4654  * Before 9.1, there are no extensions.
4655  */
4656  if (fout->remoteVersion < 90100)
4657  {
4658  *numExtensions = 0;
4659  return NULL;
4660  }
4661 
4662  query = createPQExpBuffer();
4663 
4664  appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4665  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4666  "FROM pg_extension x "
4667  "JOIN pg_namespace n ON n.oid = x.extnamespace");
4668 
4669  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4670 
4671  ntups = PQntuples(res);
4672 
4673  extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4674 
4675  i_tableoid = PQfnumber(res, "tableoid");
4676  i_oid = PQfnumber(res, "oid");
4677  i_extname = PQfnumber(res, "extname");
4678  i_nspname = PQfnumber(res, "nspname");
4679  i_extrelocatable = PQfnumber(res, "extrelocatable");
4680  i_extversion = PQfnumber(res, "extversion");
4681  i_extconfig = PQfnumber(res, "extconfig");
4682  i_extcondition = PQfnumber(res, "extcondition");
4683 
4684  for (i = 0; i < ntups; i++)
4685  {
4686  extinfo[i].dobj.objType = DO_EXTENSION;
4687  extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4688  extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4689  AssignDumpId(&extinfo[i].dobj);
4690  extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4691  extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4692  extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4693  extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4694  extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4695  extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4696 
4697  /* Decide whether we want to dump it */
4698  selectDumpableExtension(&(extinfo[i]), dopt);
4699  }
4700 
4701  PQclear(res);
4702  destroyPQExpBuffer(query);
4703 
4704  *numExtensions = ntups;
4705 
4706  return extinfo;
4707 }
4708 
4709 /*
4710  * getTypes:
4711  * read all types in the system catalogs and return them in the
4712  * TypeInfo* structure
4713  *
4714  * numTypes is set to the number of types read in
4715  *
4716  * NB: this must run after getFuncs() because we assume we can do
4717  * findFuncByOid().
4718  */
4719 TypeInfo *
4721 {
4722  DumpOptions *dopt = fout->dopt;
4723  PGresult *res;
4724  int ntups;
4725  int i;
4726  PQExpBuffer query = createPQExpBuffer();
4727  TypeInfo *tyinfo;
4728  ShellTypeInfo *stinfo;
4729  int i_tableoid;
4730  int i_oid;
4731  int i_typname;
4732  int i_typnamespace;
4733  int i_typacl;
4734  int i_rtypacl;
4735  int i_inittypacl;
4736  int i_initrtypacl;
4737  int i_rolname;
4738  int i_typelem;
4739  int i_typrelid;
4740  int i_typrelkind;
4741  int i_typtype;
4742  int i_typisdefined;
4743  int i_isarray;
4744 
4745  /*
4746  * we include even the built-in types because those may be used as array
4747  * elements by user-defined types
4748  *
4749  * we filter out the built-in types when we dump out the types
4750  *
4751  * same approach for undefined (shell) types and array types
4752  *
4753  * Note: as of 8.3 we can reliably detect whether a type is an
4754  * auto-generated array type by checking the element type's typarray.
4755  * (Before that the test is capable of generating false positives.) We
4756  * still check for name beginning with '_', though, so as to avoid the
4757  * cost of the subselect probe for all standard types. This would have to
4758  * be revisited if the backend ever allows renaming of array types.
4759  */
4760 
4761  if (fout->remoteVersion >= 90600)
4762  {
4763  PQExpBuffer acl_subquery = createPQExpBuffer();
4764  PQExpBuffer racl_subquery = createPQExpBuffer();
4765  PQExpBuffer initacl_subquery = createPQExpBuffer();
4766  PQExpBuffer initracl_subquery = createPQExpBuffer();
4767 
4768  buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4769  initracl_subquery, "t.typacl", "t.typowner", "'T'",
4770  dopt->binary_upgrade);
4771 
4772  appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4773  "t.typnamespace, "
4774  "%s AS typacl, "
4775  "%s AS rtypacl, "
4776  "%s AS inittypacl, "
4777  "%s AS initrtypacl, "
4778  "(%s t.typowner) AS rolname, "
4779  "t.typelem, t.typrelid, "
4780  "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4781  "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4782  "t.typtype, t.typisdefined, "
4783  "t.typname[0] = '_' AND t.typelem != 0 AND "
4784  "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4785  "FROM pg_type t "
4786  "LEFT JOIN pg_init_privs pip ON "
4787  "(t.oid = pip.objoid "
4788  "AND pip.classoid = 'pg_type'::regclass "
4789  "AND pip.objsubid = 0) ",
4790  acl_subquery->data,
4791  racl_subquery->data,
4792  initacl_subquery->data,
4793  initracl_subquery->data,
4795 
4796  destroyPQExpBuffer(acl_subquery);
4797  destroyPQExpBuffer(racl_subquery);
4798  destroyPQExpBuffer(initacl_subquery);
4799  destroyPQExpBuffer(initracl_subquery);
4800  }
4801  else if (fout->remoteVersion >= 90200)
4802  {
4803  appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4804  "typnamespace, typacl, NULL as rtypacl, "
4805  "NULL AS inittypacl, NULL AS initrtypacl, "
4806  "(%s typowner) AS rolname, "
4807  "typelem, typrelid, "
4808  "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4809  "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4810  "typtype, typisdefined, "
4811  "typname[0] = '_' AND typelem != 0 AND "
4812  "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4813  "FROM pg_type",
4815  }
4816  else if (fout->remoteVersion >= 80300)
4817  {
4818  appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4819  "typnamespace, NULL AS typacl, NULL as rtypacl, "
4820  "NULL AS inittypacl, NULL AS initrtypacl, "
4821  "(%s typowner) AS rolname, "
4822  "typelem, typrelid, "
4823  "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4824  "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4825  "typtype, typisdefined, "
4826  "typname[0] = '_' AND typelem != 0 AND "
4827  "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4828  "FROM pg_type",
4830  }
4831  else
4832  {
4833  appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4834  "typnamespace, NULL AS typacl, NULL as rtypacl, "
4835  "NULL AS inittypacl, NULL AS initrtypacl, "
4836  "(%s typowner) AS rolname, "
4837  "typelem, typrelid, "
4838  "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4839  "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4840  "typtype, typisdefined, "
4841  "typname[0] = '_' AND typelem != 0 AS isarray "
4842  "FROM pg_type",
4844  }
4845 
4846  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4847 
4848  ntups = PQntuples(res);
4849 
4850  tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4851 
4852  i_tableoid = PQfnumber(res, "tableoid");
4853  i_oid = PQfnumber(res, "oid");
4854  i_typname = PQfnumber(res, "typname");
4855  i_typnamespace = PQfnumber(res, "typnamespace");
4856  i_typacl = PQfnumber(res, "typacl");
4857  i_rtypacl = PQfnumber(res, "rtypacl");
4858  i_inittypacl = PQfnumber(res, "inittypacl");
4859  i_initrtypacl = PQfnumber(res, "initrtypacl");
4860  i_rolname = PQfnumber(res, "rolname");
4861  i_typelem = PQfnumber(res, "typelem");
4862  i_typrelid = PQfnumber(res, "typrelid");
4863  i_typrelkind = PQfnumber(res, "typrelkind");
4864  i_typtype = PQfnumber(res, "typtype");
4865  i_typisdefined = PQfnumber(res, "typisdefined");
4866  i_isarray = PQfnumber(res, "isarray");
4867 
4868  for (i = 0; i < ntups; i++)
4869  {
4870  tyinfo[i].dobj.objType = DO_TYPE;
4871  tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4872  tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4873  AssignDumpId(&tyinfo[i].dobj);
4874  tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4875  tyinfo[i].dobj.namespace =
4876  findNamespace(fout,
4877  atooid(PQgetvalue(res, i, i_typnamespace)));
4878  tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4879  tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4880  tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4881  tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4882  tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4883  tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4884  tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4885  tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4886  tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4887  tyinfo[i].shellType = NULL;
4888 
4889  if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4890  tyinfo[i].isDefined = true;
4891  else
4892  tyinfo[i].isDefined = false;
4893 
4894  if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4895  tyinfo[i].isArray = true;
4896  else
4897  tyinfo[i].isArray = false;
4898 
4899  /* Decide whether we want to dump it */
4900  selectDumpableType(&tyinfo[i], fout);
4901 
4902  /* Do not try to dump ACL if no ACL exists. */
4903  if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4904  PQgetisnull(res, i, i_inittypacl) &&
4905  PQgetisnull(res, i, i_initrtypacl))
4906  tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4907 
4908  /*
4909  * If it's a domain, fetch info about its constraints, if any
4910  */
4911  tyinfo[i].nDomChecks = 0;
4912  tyinfo[i].domChecks = NULL;
4913  if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4914  tyinfo[i].typtype == TYPTYPE_DOMAIN)
4915  getDomainConstraints(fout, &(tyinfo[i]));
4916 
4917  /*
4918  * If it's a base type, make a DumpableObject representing a shell
4919  * definition of the type. We will need to dump that ahead of the I/O
4920  * functions for the type. Similarly, range types need a shell
4921  * definition in case they have a canonicalize function.
4922  *
4923  * Note: the shell type doesn't have a catId. You might think it
4924  * should copy the base type's catId, but then it might capture the
4925  * pg_depend entries for the type, which we don't want.
4926  */
4927  if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4928  (tyinfo[i].typtype == TYPTYPE_BASE ||
4929  tyinfo[i].typtype == TYPTYPE_RANGE))
4930  {
4931  stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4932  stinfo->dobj.objType = DO_SHELL_TYPE;
4933  stinfo->dobj.catId = nilCatalogId;
4934  AssignDumpId(&stinfo->dobj);
4935  stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4936  stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4937  stinfo->baseType = &(tyinfo[i]);
4938  tyinfo[i].shellType = stinfo;
4939 
4940  /*
4941  * Initially mark the shell type as not to be dumped. We'll only
4942  * dump it if the I/O or canonicalize functions need to be dumped;
4943  * this is taken care of while sorting dependencies.
4944  */
4945  stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4946  }
4947 
4948  if (strlen(tyinfo[i].rolname) == 0)
4949  pg_log_warning("owner of data type \"%s\" appears to be invalid",
4950  tyinfo[i].dobj.name);
4951  }
4952 
4953  *numTypes = ntups;
4954 
4955  PQclear(res);
4956 
4957  destroyPQExpBuffer(query);
4958 
4959  return tyinfo;
4960 }
4961 
4962 /*
4963  * getOperators:
4964  * read all operators in the system catalogs and return them in the
4965  * OprInfo* structure
4966  *
4967  * numOprs is set to the number of operators read in
4968  */
4969 OprInfo *
4970 getOperators(Archive *fout, int *numOprs)
4971 {
4972  PGresult *res;
4973  int ntups;
4974  int i;
4975  PQExpBuffer query = createPQExpBuffer();
4976  OprInfo *oprinfo;
4977  int i_tableoid;
4978  int i_oid;
4979  int i_oprname;
4980  int i_oprnamespace;
4981  int i_rolname;
4982  int i_oprkind;
4983  int i_oprcode;
4984 
4985  /*
4986  * find all operators, including builtin operators; we filter out
4987  * system-defined operators at dump-out time.
4988  */
4989 
4990  appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4991  "oprnamespace, "
4992  "(%s oprowner) AS rolname, "
4993  "oprkind, "
4994  "oprcode::oid AS oprcode "
4995  "FROM pg_operator",
4997 
4998  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4999 
5000  ntups = PQntuples(res);
5001  *numOprs = ntups;
5002 
5003  oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
5004 
5005  i_tableoid = PQfnumber(res, "tableoid");
5006  i_oid = PQfnumber(res, "oid");
5007  i_oprname = PQfnumber(res, "oprname");
5008  i_oprnamespace = PQfnumber(res, "oprnamespace");
5009  i_rolname = PQfnumber(res, "rolname");
5010  i_oprkind = PQfnumber(res, "oprkind");
5011  i_oprcode = PQfnumber(res, "oprcode");
5012 
5013  for (i = 0; i < ntups; i++)
5014  {
5015  oprinfo[i].dobj.objType = DO_OPERATOR;
5016  oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5017  oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5018  AssignDumpId(&oprinfo[i].dobj);
5019  oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
5020  oprinfo[i].dobj.namespace =
5021  findNamespace(fout,
5022  atooid(PQgetvalue(res, i, i_oprnamespace)));
5023  oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5024  oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
5025  oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
5026 
5027  /* Decide whether we want to dump it */
5028  selectDumpableObject(&(oprinfo[i].dobj), fout);
5029 
5030  /* Operators do not currently have ACLs. */
5031  oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5032 
5033  if (strlen(oprinfo[i].rolname) == 0)
5034  pg_log_warning("owner of operator \"%s\" appears to be invalid",
5035  oprinfo[i].dobj.name);
5036  }
5037 
5038  PQclear(res);
5039 
5040  destroyPQExpBuffer(query);
5041 
5042  return oprinfo;
5043 }
5044 
5045 /*
5046  * getCollations:
5047  * read all collations in the system catalogs and return them in the
5048  * CollInfo* structure
5049  *
5050  * numCollations is set to the number of collations read in
5051  */
5052 CollInfo *
5054 {
5055  PGresult *res;
5056  int ntups;
5057  int i;
5058  PQExpBuffer query;
5059  CollInfo *collinfo;
5060  int i_tableoid;
5061  int i_oid;
5062  int i_collname;
5063  int i_collnamespace;
5064  int i_rolname;
5065 
5066  /* Collations didn't exist pre-9.1 */
5067  if (fout->remoteVersion < 90100)
5068  {
5069  *numCollations = 0;
5070  return NULL;
5071  }
5072 
5073  query = createPQExpBuffer();
5074 
5075  /*
5076  * find all collations, including builtin collations; we filter out
5077  * system-defined collations at dump-out time.
5078  */
5079 
5080  appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5081  "collnamespace, "
5082  "(%s collowner) AS rolname "
5083  "FROM pg_collation",
5085 
5086  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5087 
5088  ntups = PQntuples(res);
5089  *numCollations = ntups;
5090 
5091  collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5092 
5093  i_tableoid = PQfnumber(res, "tableoid");
5094  i_oid = PQfnumber(res, "oid");
5095  i_collname = PQfnumber(res, "collname");
5096  i_collnamespace = PQfnumber(res, "collnamespace");
5097  i_rolname = PQfnumber(res, "rolname");
5098 
5099  for (i = 0; i < ntups; i++)
5100  {
5101  collinfo[i].dobj.objType = DO_COLLATION;
5102  collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5103  collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5104  AssignDumpId(&collinfo[i].dobj);
5105  collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5106  collinfo[i].dobj.namespace =
5107  findNamespace(fout,
5108  atooid(PQgetvalue(res, i, i_collnamespace)));
5109  collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5110 
5111  /* Decide whether we want to dump it */
5112  selectDumpableObject(&(collinfo[i].dobj), fout);
5113 
5114  /* Collations do not currently have ACLs. */
5115  collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5116  }
5117 
5118  PQclear(res);
5119 
5120  destroyPQExpBuffer(query);
5121 
5122  return collinfo;
5123 }
5124 
5125 /*
5126  * getConversions:
5127  * read all conversions in the system catalogs and return them in the
5128  * ConvInfo* structure
5129  *
5130  * numConversions is set to the number of conversions read in
5131  */
5132 ConvInfo *
5133 getConversions(Archive *fout, int *numConversions)
5134 {
5135  PGresult *res;
5136  int ntups;
5137  int i;
5138  PQExpBuffer query;
5139  ConvInfo *convinfo;
5140  int i_tableoid;
5141  int i_oid;
5142  int i_conname;
5143  int i_connamespace;
5144  int i_rolname;
5145 
5146  query = createPQExpBuffer();
5147 
5148  /*
5149  * find all conversions, including builtin conversions; we filter out
5150  * system-defined conversions at dump-out time.
5151  */
5152 
5153  appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5154  "connamespace, "
5155  "(%s conowner) AS rolname "
5156  "FROM pg_conversion",
5158 
5159  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5160 
5161  ntups = PQntuples(res);
5162  *numConversions = ntups;
5163 
5164  convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5165 
5166  i_tableoid = PQfnumber(res, "tableoid");
5167  i_oid = PQfnumber(res, "oid");
5168  i_conname = PQfnumber(res, "conname");
5169  i_connamespace = PQfnumber(res, "connamespace");
5170  i_rolname = PQfnumber(res, "rolname");
5171 
5172  for (i = 0; i < ntups; i++)
5173  {
5174  convinfo[i].dobj.objType = DO_CONVERSION;
5175  convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5176  convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5177  AssignDumpId(&convinfo[i].dobj);
5178  convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5179  convinfo[i].dobj.namespace =
5180  findNamespace(fout,
5181  atooid(PQgetvalue(res, i, i_connamespace)));
5182  convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5183 
5184  /* Decide whether we want to dump it */
5185  selectDumpableObject(&(convinfo[i].dobj), fout);
5186 
5187  /* Conversions do not currently have ACLs. */
5188  convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5189  }
5190 
5191  PQclear(res);
5192 
5193  destroyPQExpBuffer(query);
5194 
5195  return convinfo;
5196 }
5197 
5198 /*
5199  * getAccessMethods:
5200  * read all user-defined access methods in the system catalogs and return
5201  * them in the AccessMethodInfo* structure
5202  *
5203  * numAccessMethods is set to the number of access methods read in
5204  */
5206 getAccessMethods(Archive *fout, int *numAccessMethods)
5207 {
5208  PGresult *res;
5209  int ntups;
5210  int i;
5211  PQExpBuffer query;
5212  AccessMethodInfo *aminfo;
5213  int i_tableoid;
5214  int i_oid;
5215  int i_amname;
5216  int i_amhandler;
5217  int i_amtype;
5218 
5219  /* Before 9.6, there are no user-defined access methods */
5220  if (fout->remoteVersion < 90600)
5221  {
5222  *numAccessMethods = 0;
5223  return NULL;
5224  }
5225 
5226  query = createPQExpBuffer();
5227 
5228  /* Select all access methods from pg_am table */
5229  appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5230  "amhandler::pg_catalog.regproc AS amhandler "
5231  "FROM pg_am");
5232 
5233  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5234 
5235  ntups = PQntuples(res);
5236  *numAccessMethods = ntups;
5237 
5238  aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5239 
5240  i_tableoid = PQfnumber(res, "tableoid");
5241  i_oid = PQfnumber(res, "oid");
5242  i_amname = PQfnumber(res, "amname");
5243  i_amhandler = PQfnumber(res, "amhandler");
5244  i_amtype = PQfnumber(res, "amtype");
5245 
5246  for (i = 0; i < ntups; i++)
5247  {
5248  aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5249  aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5250  aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5251  AssignDumpId(&aminfo[i].dobj);
5252  aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5253  aminfo[i].dobj.namespace = NULL;
5254  aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5255  aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5256 
5257  /* Decide whether we want to dump it */
5258  selectDumpableAccessMethod(&(aminfo[i]), fout);
5259 
5260  /* Access methods do not currently have ACLs. */
5261  aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5262  }
5263 
5264  PQclear(res);
5265 
5266  destroyPQExpBuffer(query);
5267 
5268  return aminfo;
5269 }
5270 
5271 
5272 /*
5273  * getOpclasses:
5274  * read all opclasses in the system catalogs and return them in the
5275  * OpclassInfo* structure
5276  *
5277  * numOpclasses is set to the number of opclasses read in
5278  */
5279 OpclassInfo *
5280 getOpclasses(Archive *fout, int *numOpclasses)
5281 {
5282  PGresult *res;
5283  int ntups;
5284  int i;
5285  PQExpBuffer query = createPQExpBuffer();
5286  OpclassInfo *opcinfo;
5287  int i_tableoid;
5288  int i_oid;
5289  int i_opcname;
5290  int i_opcnamespace;
5291  int i_rolname;
5292 
5293  /*
5294  * find all opclasses, including builtin opclasses; we filter out
5295  * system-defined opclasses at dump-out time.
5296  */
5297 
5298  appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5299  "opcnamespace, "
5300  "(%s opcowner) AS rolname "
5301  "FROM pg_opclass",
5303 
5304  res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5305 
5306  ntups = PQntuples(res);
5307  *numOpclasses = ntups;
5308 
5309  opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5310 
5311  i_tableoid = PQfnumber(res, "tableoid");
5312  i_oid = PQfnumber(res, "oid");
5313  i_opcname = PQfnumber(res, "opcname");
5314  i_opcnamespace = PQfnumber(res,