]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Fix pg_dump's logic for eliding sequence limits that match the defaults.
[postgresql] / src / bin / pg_dump / pg_dump.c
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-2018, 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 #ifdef HAVE_TERMIOS_H
37 #include <termios.h>
38 #endif
39
40 #include "getopt_long.h"
41
42 #include "access/attnum.h"
43 #include "access/sysattr.h"
44 #include "access/transam.h"
45 #include "catalog/pg_aggregate.h"
46 #include "catalog/pg_am.h"
47 #include "catalog/pg_attribute.h"
48 #include "catalog/pg_cast.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_default_acl.h"
51 #include "catalog/pg_largeobject.h"
52 #include "catalog/pg_largeobject_metadata.h"
53 #include "catalog/pg_proc.h"
54 #include "catalog/pg_trigger.h"
55 #include "catalog/pg_type.h"
56 #include "libpq/libpq-fs.h"
57
58 #include "dumputils.h"
59 #include "parallel.h"
60 #include "pg_backup_db.h"
61 #include "pg_backup_utils.h"
62 #include "pg_dump.h"
63 #include "fe_utils/string_utils.h"
64
65
66 typedef struct
67 {
68         const char *descr;                      /* comment for an object */
69         Oid                     classoid;               /* object class (catalog OID) */
70         Oid                     objoid;                 /* object OID */
71         int                     objsubid;               /* subobject (table column #) */
72 } CommentItem;
73
74 typedef struct
75 {
76         const char *provider;           /* label provider of this security label */
77         const char *label;                      /* security label for an object */
78         Oid                     classoid;               /* object class (catalog OID) */
79         Oid                     objoid;                 /* object OID */
80         int                     objsubid;               /* subobject (table column #) */
81 } SecLabelItem;
82
83 typedef enum OidOptions
84 {
85         zeroAsOpaque = 1,
86         zeroAsAny = 2,
87         zeroAsStar = 4,
88         zeroAsNone = 8
89 } OidOptions;
90
91 /* global decls */
92 bool            g_verbose;                      /* User wants verbose narration of our
93                                                                  * activities. */
94 static bool dosync = true;              /* Issue fsync() to make dump durable on disk. */
95
96 /* subquery used to convert user ID (eg, datdba) to user name */
97 static const char *username_subquery;
98
99 /*
100  * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
101  * FirstNormalObjectId - 1.
102  */
103 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
104
105 /* The specified names/patterns should to match at least one entity */
106 static int      strict_names = 0;
107
108 /*
109  * Object inclusion/exclusion lists
110  *
111  * The string lists record the patterns given by command-line switches,
112  * which we then convert to lists of OIDs of matching objects.
113  */
114 static SimpleStringList schema_include_patterns = {NULL, NULL};
115 static SimpleOidList schema_include_oids = {NULL, NULL};
116 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
117 static SimpleOidList schema_exclude_oids = {NULL, NULL};
118
119 static SimpleStringList table_include_patterns = {NULL, NULL};
120 static SimpleOidList table_include_oids = {NULL, NULL};
121 static SimpleStringList table_exclude_patterns = {NULL, NULL};
122 static SimpleOidList table_exclude_oids = {NULL, NULL};
123 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
124 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
125
126
127 char            g_opaque_type[10];      /* name for the opaque type */
128
129 /* placeholders for the delimiters for comments */
130 char            g_comment_start[10];
131 char            g_comment_end[10];
132
133 static const CatalogId nilCatalogId = {0, 0};
134
135 static void help(const char *progname);
136 static void setup_connection(Archive *AH,
137                                  const char *dumpencoding, const char *dumpsnapshot,
138                                  char *use_role);
139 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
140 static void expand_schema_name_patterns(Archive *fout,
141                                                         SimpleStringList *patterns,
142                                                         SimpleOidList *oids,
143                                                         bool strict_names);
144 static void expand_table_name_patterns(Archive *fout,
145                                                    SimpleStringList *patterns,
146                                                    SimpleOidList *oids,
147                                                    bool strict_names);
148 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
149 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
150 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
151 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
152 static void dumpComment(Archive *fout, const char *target,
153                         const char *namespace, const char *owner,
154                         CatalogId catalogId, int subid, DumpId dumpId);
155 static int findComments(Archive *fout, Oid classoid, Oid objoid,
156                          CommentItem **items);
157 static int      collectComments(Archive *fout, CommentItem **items);
158 static void dumpSecLabel(Archive *fout, const char *target,
159                          const char *namespace, const char *owner,
160                          CatalogId catalogId, int subid, DumpId dumpId);
161 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
162                           SecLabelItem **items);
163 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
164 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
165 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
166 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
167 static void dumpType(Archive *fout, TypeInfo *tyinfo);
168 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
169 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
170 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
173 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
175 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
176 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
177 static void dumpFunc(Archive *fout, FuncInfo *finfo);
178 static void dumpCast(Archive *fout, CastInfo *cast);
179 static void dumpTransform(Archive *fout, TransformInfo *transform);
180 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
181 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *collinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
190 static void dumpTable(Archive *fout, TableInfo *tbinfo);
191 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
192 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
193 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
194 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
195 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
196 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
197 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
198 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
199 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
201 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
202 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
203 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
204 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
205 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
206 static void dumpUserMappings(Archive *fout,
207                                  const char *servername, const char *namespace,
208                                  const char *owner, CatalogId catalogId, DumpId dumpId);
209 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
210
211 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
212                 const char *type, const char *name, const char *subname,
213                 const char *tag, const char *nspname, const char *owner,
214                 const char *acls, const char *racls,
215                 const char *initacls, const char *initracls);
216
217 static void getDependencies(Archive *fout);
218 static void BuildArchiveDependencies(Archive *fout);
219 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
220                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
221
222 static DumpableObject *createBoundaryObjects(void);
223 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
224                                                 DumpableObject *boundaryObjs);
225
226 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
227 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
228 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
229 static void buildMatViewRefreshDependencies(Archive *fout);
230 static void getTableDataFKConstraints(void);
231 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
232                                                   bool is_agg);
233 static char *format_function_arguments_old(Archive *fout,
234                                                           FuncInfo *finfo, int nallargs,
235                                                           char **allargtypes,
236                                                           char **argmodes,
237                                                           char **argnames);
238 static char *format_function_signature(Archive *fout,
239                                                   FuncInfo *finfo, bool honor_quotes);
240 static char *convertRegProcReference(Archive *fout,
241                                                 const char *proc);
242 static char *convertOperatorReference(Archive *fout, const char *opr);
243 static char *convertTSFunction(Archive *fout, Oid funcOid);
244 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
245 static void selectSourceSchema(Archive *fout, const char *schemaName);
246 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
247 static void getBlobs(Archive *fout);
248 static void dumpBlob(Archive *fout, BlobInfo *binfo);
249 static int      dumpBlobs(Archive *fout, void *arg);
250 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
251 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
252 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
253 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
254 static void dumpDatabase(Archive *AH);
255 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
256                                    const char *dbname, Oid dboid);
257 static void dumpEncoding(Archive *AH);
258 static void dumpStdStrings(Archive *AH);
259 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
260                                                                                  PQExpBuffer upgrade_buffer,
261                                                                                  Oid pg_type_oid,
262                                                                                  bool force_array_type);
263 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
264                                                                                 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
265 static void binary_upgrade_set_pg_class_oids(Archive *fout,
266                                                                  PQExpBuffer upgrade_buffer,
267                                                                  Oid pg_class_oid, bool is_index);
268 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
269                                                                 DumpableObject *dobj,
270                                                                 const char *objlabel);
271 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
272 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
273 static bool nonemptyReloptions(const char *reloptions);
274 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
275                                                 const char *prefix, Archive *fout);
276 static char *get_synchronized_snapshot(Archive *fout);
277 static void setupDumpWorker(Archive *AHX);
278 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
279
280
281 int
282 main(int argc, char **argv)
283 {
284         int                     c;
285         const char *filename = NULL;
286         const char *format = "p";
287         TableInfo  *tblinfo;
288         int                     numTables;
289         DumpableObject **dobjs;
290         int                     numObjs;
291         DumpableObject *boundaryObjs;
292         int                     i;
293         int                     optindex;
294         RestoreOptions *ropt;
295         Archive    *fout;                       /* the script file */
296         const char *dumpencoding = NULL;
297         const char *dumpsnapshot = NULL;
298         char       *use_role = NULL;
299         int                     numWorkers = 1;
300         trivalue        prompt_password = TRI_DEFAULT;
301         int                     compressLevel = -1;
302         int                     plainText = 0;
303         ArchiveFormat archiveFormat = archUnknown;
304         ArchiveMode archiveMode;
305
306         static DumpOptions dopt;
307
308         static struct option long_options[] = {
309                 {"data-only", no_argument, NULL, 'a'},
310                 {"blobs", no_argument, NULL, 'b'},
311                 {"no-blobs", no_argument, NULL, 'B'},
312                 {"clean", no_argument, NULL, 'c'},
313                 {"create", no_argument, NULL, 'C'},
314                 {"dbname", required_argument, NULL, 'd'},
315                 {"file", required_argument, NULL, 'f'},
316                 {"format", required_argument, NULL, 'F'},
317                 {"host", required_argument, NULL, 'h'},
318                 {"jobs", 1, NULL, 'j'},
319                 {"no-reconnect", no_argument, NULL, 'R'},
320                 {"oids", no_argument, NULL, 'o'},
321                 {"no-owner", no_argument, NULL, 'O'},
322                 {"port", required_argument, NULL, 'p'},
323                 {"schema", required_argument, NULL, 'n'},
324                 {"exclude-schema", required_argument, NULL, 'N'},
325                 {"schema-only", no_argument, NULL, 's'},
326                 {"superuser", required_argument, NULL, 'S'},
327                 {"table", required_argument, NULL, 't'},
328                 {"exclude-table", required_argument, NULL, 'T'},
329                 {"no-password", no_argument, NULL, 'w'},
330                 {"password", no_argument, NULL, 'W'},
331                 {"username", required_argument, NULL, 'U'},
332                 {"verbose", no_argument, NULL, 'v'},
333                 {"no-privileges", no_argument, NULL, 'x'},
334                 {"no-acl", no_argument, NULL, 'x'},
335                 {"compress", required_argument, NULL, 'Z'},
336                 {"encoding", required_argument, NULL, 'E'},
337                 {"help", no_argument, NULL, '?'},
338                 {"version", no_argument, NULL, 'V'},
339
340                 /*
341                  * the following options don't have an equivalent short option letter
342                  */
343                 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
344                 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
345                 {"column-inserts", no_argument, &dopt.column_inserts, 1},
346                 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
347                 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
348                 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
349                 {"exclude-table-data", required_argument, NULL, 4},
350                 {"if-exists", no_argument, &dopt.if_exists, 1},
351                 {"inserts", no_argument, &dopt.dump_inserts, 1},
352                 {"lock-wait-timeout", required_argument, NULL, 2},
353                 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
354                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
355                 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
356                 {"role", required_argument, NULL, 3},
357                 {"section", required_argument, NULL, 5},
358                 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
359                 {"snapshot", required_argument, NULL, 6},
360                 {"strict-names", no_argument, &strict_names, 1},
361                 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
362                 {"no-comments", no_argument, &dopt.no_comments, 1},
363                 {"no-publications", no_argument, &dopt.no_publications, 1},
364                 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
365                 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
366                 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
367                 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
368                 {"no-sync", no_argument, NULL, 7},
369
370                 {NULL, 0, NULL, 0}
371         };
372
373         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
374
375         /*
376          * Initialize what we need for parallel execution, especially for thread
377          * support on Windows.
378          */
379         init_parallel_dump_utils();
380
381         g_verbose = false;
382
383         strcpy(g_comment_start, "-- ");
384         g_comment_end[0] = '\0';
385         strcpy(g_opaque_type, "opaque");
386
387         progname = get_progname(argv[0]);
388
389         if (argc > 1)
390         {
391                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
392                 {
393                         help(progname);
394                         exit_nicely(0);
395                 }
396                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
397                 {
398                         puts("pg_dump (PostgreSQL) " PG_VERSION);
399                         exit_nicely(0);
400                 }
401         }
402
403         InitDumpOptions(&dopt);
404
405         while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
406                                                         long_options, &optindex)) != -1)
407         {
408                 switch (c)
409                 {
410                         case 'a':                       /* Dump data only */
411                                 dopt.dataOnly = true;
412                                 break;
413
414                         case 'b':                       /* Dump blobs */
415                                 dopt.outputBlobs = true;
416                                 break;
417
418                         case 'B':                       /* Don't dump blobs */
419                                 dopt.dontOutputBlobs = true;
420                                 break;
421
422                         case 'c':                       /* clean (i.e., drop) schema prior to create */
423                                 dopt.outputClean = 1;
424                                 break;
425
426                         case 'C':                       /* Create DB */
427                                 dopt.outputCreateDB = 1;
428                                 break;
429
430                         case 'd':                       /* database name */
431                                 dopt.dbname = pg_strdup(optarg);
432                                 break;
433
434                         case 'E':                       /* Dump encoding */
435                                 dumpencoding = pg_strdup(optarg);
436                                 break;
437
438                         case 'f':
439                                 filename = pg_strdup(optarg);
440                                 break;
441
442                         case 'F':
443                                 format = pg_strdup(optarg);
444                                 break;
445
446                         case 'h':                       /* server host */
447                                 dopt.pghost = pg_strdup(optarg);
448                                 break;
449
450                         case 'j':                       /* number of dump jobs */
451                                 numWorkers = atoi(optarg);
452                                 break;
453
454                         case 'n':                       /* include schema(s) */
455                                 simple_string_list_append(&schema_include_patterns, optarg);
456                                 dopt.include_everything = false;
457                                 break;
458
459                         case 'N':                       /* exclude schema(s) */
460                                 simple_string_list_append(&schema_exclude_patterns, optarg);
461                                 break;
462
463                         case 'o':                       /* Dump oids */
464                                 dopt.oids = true;
465                                 break;
466
467                         case 'O':                       /* Don't reconnect to match owner */
468                                 dopt.outputNoOwner = 1;
469                                 break;
470
471                         case 'p':                       /* server port */
472                                 dopt.pgport = pg_strdup(optarg);
473                                 break;
474
475                         case 'R':
476                                 /* no-op, still accepted for backwards compatibility */
477                                 break;
478
479                         case 's':                       /* dump schema only */
480                                 dopt.schemaOnly = true;
481                                 break;
482
483                         case 'S':                       /* Username for superuser in plain text output */
484                                 dopt.outputSuperuser = pg_strdup(optarg);
485                                 break;
486
487                         case 't':                       /* include table(s) */
488                                 simple_string_list_append(&table_include_patterns, optarg);
489                                 dopt.include_everything = false;
490                                 break;
491
492                         case 'T':                       /* exclude table(s) */
493                                 simple_string_list_append(&table_exclude_patterns, optarg);
494                                 break;
495
496                         case 'U':
497                                 dopt.username = pg_strdup(optarg);
498                                 break;
499
500                         case 'v':                       /* verbose */
501                                 g_verbose = true;
502                                 break;
503
504                         case 'w':
505                                 prompt_password = TRI_NO;
506                                 break;
507
508                         case 'W':
509                                 prompt_password = TRI_YES;
510                                 break;
511
512                         case 'x':                       /* skip ACL dump */
513                                 dopt.aclsSkip = true;
514                                 break;
515
516                         case 'Z':                       /* Compression Level */
517                                 compressLevel = atoi(optarg);
518                                 if (compressLevel < 0 || compressLevel > 9)
519                                 {
520                                         write_msg(NULL, "compression level must be in range 0..9\n");
521                                         exit_nicely(1);
522                                 }
523                                 break;
524
525                         case 0:
526                                 /* This covers the long options. */
527                                 break;
528
529                         case 2:                         /* lock-wait-timeout */
530                                 dopt.lockWaitTimeout = pg_strdup(optarg);
531                                 break;
532
533                         case 3:                         /* SET ROLE */
534                                 use_role = pg_strdup(optarg);
535                                 break;
536
537                         case 4:                         /* exclude table(s) data */
538                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
539                                 break;
540
541                         case 5:                         /* section */
542                                 set_dump_section(optarg, &dopt.dumpSections);
543                                 break;
544
545                         case 6:                         /* snapshot */
546                                 dumpsnapshot = pg_strdup(optarg);
547                                 break;
548
549                         case 7:                         /* no-sync */
550                                 dosync = false;
551                                 break;
552
553                         default:
554                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
555                                 exit_nicely(1);
556                 }
557         }
558
559         /*
560          * Non-option argument specifies database name as long as it wasn't
561          * already specified with -d / --dbname
562          */
563         if (optind < argc && dopt.dbname == NULL)
564                 dopt.dbname = argv[optind++];
565
566         /* Complain if any arguments remain */
567         if (optind < argc)
568         {
569                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
570                                 progname, argv[optind]);
571                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
572                                 progname);
573                 exit_nicely(1);
574         }
575
576         /* --column-inserts implies --inserts */
577         if (dopt.column_inserts)
578                 dopt.dump_inserts = 1;
579
580         /*
581          * Binary upgrade mode implies dumping sequence data even in schema-only
582          * mode.  This is not exposed as a separate option, but kept separate
583          * internally for clarity.
584          */
585         if (dopt.binary_upgrade)
586                 dopt.sequence_data = 1;
587
588         if (dopt.dataOnly && dopt.schemaOnly)
589         {
590                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
591                 exit_nicely(1);
592         }
593
594         if (dopt.dataOnly && dopt.outputClean)
595         {
596                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
597                 exit_nicely(1);
598         }
599
600         if (dopt.dump_inserts && dopt.oids)
601         {
602                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
603                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
604                 exit_nicely(1);
605         }
606
607         if (dopt.if_exists && !dopt.outputClean)
608                 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
609
610         /* Identify archive format to emit */
611         archiveFormat = parseArchiveFormat(format, &archiveMode);
612
613         /* archiveFormat specific setup */
614         if (archiveFormat == archNull)
615                 plainText = 1;
616
617         /* Custom and directory formats are compressed by default, others not */
618         if (compressLevel == -1)
619         {
620 #ifdef HAVE_LIBZ
621                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
622                         compressLevel = Z_DEFAULT_COMPRESSION;
623                 else
624 #endif
625                         compressLevel = 0;
626         }
627
628 #ifndef HAVE_LIBZ
629         if (compressLevel != 0)
630                 write_msg(NULL, "WARNING: requested compression not available in this "
631                                   "installation -- archive will be uncompressed\n");
632         compressLevel = 0;
633 #endif
634
635         /*
636          * If emitting an archive format, we always want to emit a DATABASE item,
637          * in case --create is specified at pg_restore time.
638          */
639         if (!plainText)
640                 dopt.outputCreateDB = 1;
641
642         /*
643          * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
644          * parallel jobs because that's the maximum limit for the
645          * WaitForMultipleObjects() call.
646          */
647         if (numWorkers <= 0
648 #ifdef WIN32
649                 || numWorkers > MAXIMUM_WAIT_OBJECTS
650 #endif
651                 )
652                 exit_horribly(NULL, "invalid number of parallel jobs\n");
653
654         /* Parallel backup only in the directory archive format so far */
655         if (archiveFormat != archDirectory && numWorkers > 1)
656                 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
657
658         /* Open the output file */
659         fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
660                                                  archiveMode, setupDumpWorker);
661
662         /* Make dump options accessible right away */
663         SetArchiveOptions(fout, &dopt, NULL);
664
665         /* Register the cleanup hook */
666         on_exit_close_archive(fout);
667
668         /* Let the archiver know how noisy to be */
669         fout->verbose = g_verbose;
670
671         /*
672          * We allow the server to be back to 8.0, and up to any minor release of
673          * our own major version.  (See also version check in pg_dumpall.c.)
674          */
675         fout->minRemoteVersion = 80000;
676         fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
677
678         fout->numWorkers = numWorkers;
679
680         /*
681          * Open the database using the Archiver, so it knows about it. Errors mean
682          * death.
683          */
684         ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
685         setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
686
687         /*
688          * Disable security label support if server version < v9.1.x (prevents
689          * access to nonexistent pg_seclabel catalog)
690          */
691         if (fout->remoteVersion < 90100)
692                 dopt.no_security_labels = 1;
693
694         /*
695          * On hot standbys, never try to dump unlogged table data, since it will
696          * just throw an error.
697          */
698         if (fout->isStandby)
699                 dopt.no_unlogged_table_data = true;
700
701         /* Select the appropriate subquery to convert user IDs to names */
702         if (fout->remoteVersion >= 80100)
703                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
704         else
705                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
706
707         /* check the version for the synchronized snapshots feature */
708         if (numWorkers > 1 && fout->remoteVersion < 90200
709                 && !dopt.no_synchronized_snapshots)
710                 exit_horribly(NULL,
711                                           "Synchronized snapshots are not supported by this server version.\n"
712                                           "Run with --no-synchronized-snapshots instead if you do not need\n"
713                                           "synchronized snapshots.\n");
714
715         /* check the version when a snapshot is explicitly specified by user */
716         if (dumpsnapshot && fout->remoteVersion < 90200)
717                 exit_horribly(NULL,
718                                           "Exported snapshots are not supported by this server version.\n");
719
720         /*
721          * Find the last built-in OID, if needed (prior to 8.1)
722          *
723          * With 8.1 and above, we can just use FirstNormalObjectId - 1.
724          */
725         if (fout->remoteVersion < 80100)
726                 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
727                                                                                                         PQdb(GetConnection(fout)));
728         else
729                 g_last_builtin_oid = FirstNormalObjectId - 1;
730
731         if (g_verbose)
732                 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
733
734         /* Expand schema selection patterns into OID lists */
735         if (schema_include_patterns.head != NULL)
736         {
737                 expand_schema_name_patterns(fout, &schema_include_patterns,
738                                                                         &schema_include_oids,
739                                                                         strict_names);
740                 if (schema_include_oids.head == NULL)
741                         exit_horribly(NULL, "no matching schemas were found\n");
742         }
743         expand_schema_name_patterns(fout, &schema_exclude_patterns,
744                                                                 &schema_exclude_oids,
745                                                                 false);
746         /* non-matching exclusion patterns aren't an error */
747
748         /* Expand table selection patterns into OID lists */
749         if (table_include_patterns.head != NULL)
750         {
751                 expand_table_name_patterns(fout, &table_include_patterns,
752                                                                    &table_include_oids,
753                                                                    strict_names);
754                 if (table_include_oids.head == NULL)
755                         exit_horribly(NULL, "no matching tables were found\n");
756         }
757         expand_table_name_patterns(fout, &table_exclude_patterns,
758                                                            &table_exclude_oids,
759                                                            false);
760
761         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
762                                                            &tabledata_exclude_oids,
763                                                            false);
764
765         /* non-matching exclusion patterns aren't an error */
766
767         /*
768          * Dumping blobs is the default for dumps where an inclusion switch is not
769          * used (an "include everything" dump).  -B can be used to exclude blobs
770          * from those dumps.  -b can be used to include blobs even when an
771          * inclusion switch is used.
772          *
773          * -s means "schema only" and blobs are data, not schema, so we never
774          * include blobs when -s is used.
775          */
776         if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
777                 dopt.outputBlobs = true;
778
779         /*
780          * Now scan the database and create DumpableObject structs for all the
781          * objects we intend to dump.
782          */
783         tblinfo = getSchemaData(fout, &numTables);
784
785         if (fout->remoteVersion < 80400)
786                 guessConstraintInheritance(tblinfo, numTables);
787
788         if (!dopt.schemaOnly)
789         {
790                 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
791                 buildMatViewRefreshDependencies(fout);
792                 if (dopt.dataOnly)
793                         getTableDataFKConstraints();
794         }
795
796         if (dopt.schemaOnly && dopt.sequence_data)
797                 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
798
799         /*
800          * In binary-upgrade mode, we do not have to worry about the actual blob
801          * data or the associated metadata that resides in the pg_largeobject and
802          * pg_largeobject_metadata tables, respectivly.
803          *
804          * However, we do need to collect blob information as there may be
805          * comments or other information on blobs that we do need to dump out.
806          */
807         if (dopt.outputBlobs || dopt.binary_upgrade)
808                 getBlobs(fout);
809
810         /*
811          * Collect dependency data to assist in ordering the objects.
812          */
813         getDependencies(fout);
814
815         /* Lastly, create dummy objects to represent the section boundaries */
816         boundaryObjs = createBoundaryObjects();
817
818         /* Get pointers to all the known DumpableObjects */
819         getDumpableObjects(&dobjs, &numObjs);
820
821         /*
822          * Add dummy dependencies to enforce the dump section ordering.
823          */
824         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
825
826         /*
827          * Sort the objects into a safe dump order (no forward references).
828          *
829          * We rely on dependency information to help us determine a safe order, so
830          * the initial sort is mostly for cosmetic purposes: we sort by name to
831          * ensure that logically identical schemas will dump identically.
832          */
833         sortDumpableObjectsByTypeName(dobjs, numObjs);
834
835         /* If we do a parallel dump, we want the largest tables to go first */
836         if (archiveFormat == archDirectory && numWorkers > 1)
837                 sortDataAndIndexObjectsBySize(dobjs, numObjs);
838
839         sortDumpableObjects(dobjs, numObjs,
840                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
841
842         /*
843          * Create archive TOC entries for all the objects to be dumped, in a safe
844          * order.
845          */
846
847         /* First the special ENCODING and STDSTRINGS entries. */
848         dumpEncoding(fout);
849         dumpStdStrings(fout);
850
851         /* The database items are always next, unless we don't want them at all */
852         if (dopt.outputCreateDB)
853                 dumpDatabase(fout);
854
855         /* Now the rearrangeable objects. */
856         for (i = 0; i < numObjs; i++)
857                 dumpDumpableObject(fout, dobjs[i]);
858
859         /*
860          * Set up options info to ensure we dump what we want.
861          */
862         ropt = NewRestoreOptions();
863         ropt->filename = filename;
864
865         /* if you change this list, see dumpOptionsFromRestoreOptions */
866         ropt->dropSchema = dopt.outputClean;
867         ropt->dataOnly = dopt.dataOnly;
868         ropt->schemaOnly = dopt.schemaOnly;
869         ropt->if_exists = dopt.if_exists;
870         ropt->column_inserts = dopt.column_inserts;
871         ropt->dumpSections = dopt.dumpSections;
872         ropt->aclsSkip = dopt.aclsSkip;
873         ropt->superuser = dopt.outputSuperuser;
874         ropt->createDB = dopt.outputCreateDB;
875         ropt->noOwner = dopt.outputNoOwner;
876         ropt->noTablespace = dopt.outputNoTablespaces;
877         ropt->disable_triggers = dopt.disable_triggers;
878         ropt->use_setsessauth = dopt.use_setsessauth;
879         ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
880         ropt->dump_inserts = dopt.dump_inserts;
881         ropt->no_comments = dopt.no_comments;
882         ropt->no_publications = dopt.no_publications;
883         ropt->no_security_labels = dopt.no_security_labels;
884         ropt->no_subscriptions = dopt.no_subscriptions;
885         ropt->lockWaitTimeout = dopt.lockWaitTimeout;
886         ropt->include_everything = dopt.include_everything;
887         ropt->enable_row_security = dopt.enable_row_security;
888         ropt->sequence_data = dopt.sequence_data;
889         ropt->binary_upgrade = dopt.binary_upgrade;
890
891         if (compressLevel == -1)
892                 ropt->compression = 0;
893         else
894                 ropt->compression = compressLevel;
895
896         ropt->suppressDumpWarnings = true;      /* We've already shown them */
897
898         SetArchiveOptions(fout, &dopt, ropt);
899
900         /* Mark which entries should be output */
901         ProcessArchiveRestoreOptions(fout);
902
903         /*
904          * The archive's TOC entries are now marked as to which ones will actually
905          * be output, so we can set up their dependency lists properly. This isn't
906          * necessary for plain-text output, though.
907          */
908         if (!plainText)
909                 BuildArchiveDependencies(fout);
910
911         /*
912          * And finally we can do the actual output.
913          *
914          * Note: for non-plain-text output formats, the output file is written
915          * inside CloseArchive().  This is, um, bizarre; but not worth changing
916          * right now.
917          */
918         if (plainText)
919                 RestoreArchive(fout);
920
921         CloseArchive(fout);
922
923         exit_nicely(0);
924 }
925
926
927 static void
928 help(const char *progname)
929 {
930         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
931         printf(_("Usage:\n"));
932         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
933
934         printf(_("\nGeneral options:\n"));
935         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
936         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
937                          "                               plain text (default))\n"));
938         printf(_("  -j, --jobs=NUM               use this many parallel jobs to dump\n"));
939         printf(_("  -v, --verbose                verbose mode\n"));
940         printf(_("  -V, --version                output version information, then exit\n"));
941         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
942         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
943         printf(_("  --no-sync                    do not wait for changes to be written safely to disk\n"));
944         printf(_("  -?, --help                   show this help, then exit\n"));
945
946         printf(_("\nOptions controlling the output content:\n"));
947         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
948         printf(_("  -b, --blobs                  include large objects in dump\n"));
949         printf(_("  -B, --no-blobs               exclude large objects in dump\n"));
950         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
951         printf(_("  -C, --create                 include commands to create database in dump\n"));
952         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
953         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
954         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
955         printf(_("  -o, --oids                   include OIDs in dump\n"));
956         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
957                          "                               plain-text format\n"));
958         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
959         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
960         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
961         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
962         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
963         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
964         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
965         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
966         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
967         printf(_("  --enable-row-security        enable row security (dump only content user has\n"
968                          "                               access to)\n"));
969         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
970         printf(_("  --if-exists                  use IF EXISTS when dropping objects\n"));
971         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
972         printf(_("  --no-comments                do not dump comments\n"));
973         printf(_("  --no-publications            do not dump publications\n"));
974         printf(_("  --no-security-labels         do not dump security label assignments\n"));
975         printf(_("  --no-subscriptions           do not dump subscriptions\n"));
976         printf(_("  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs\n"));
977         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
978         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
979         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
980         printf(_("  --load-via-partition-root    load partitions via the root table\n"));
981         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
982         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
983         printf(_("  --snapshot=SNAPSHOT          use given snapshot for the dump\n"));
984         printf(_("  --strict-names               require table and/or schema include patterns to\n"
985                          "                               match at least one entity each\n"));
986         printf(_("  --use-set-session-authorization\n"
987                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
988                          "                               ALTER OWNER commands to set ownership\n"));
989
990         printf(_("\nConnection options:\n"));
991         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
992         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
993         printf(_("  -p, --port=PORT          database server port number\n"));
994         printf(_("  -U, --username=NAME      connect as specified database user\n"));
995         printf(_("  -w, --no-password        never prompt for password\n"));
996         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
997         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
998
999         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1000                          "variable value is used.\n\n"));
1001         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1002 }
1003
1004 static void
1005 setup_connection(Archive *AH, const char *dumpencoding,
1006                                  const char *dumpsnapshot, char *use_role)
1007 {
1008         DumpOptions *dopt = AH->dopt;
1009         PGconn     *conn = GetConnection(AH);
1010         const char *std_strings;
1011
1012         /*
1013          * Set the client encoding if requested.
1014          */
1015         if (dumpencoding)
1016         {
1017                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1018                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1019                                                   dumpencoding);
1020         }
1021
1022         /*
1023          * Get the active encoding and the standard_conforming_strings setting, so
1024          * we know how to escape strings.
1025          */
1026         AH->encoding = PQclientEncoding(conn);
1027
1028         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1029         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1030
1031         /*
1032          * Set the role if requested.  In a parallel dump worker, we'll be passed
1033          * use_role == NULL, but AH->use_role is already set (if user specified it
1034          * originally) and we should use that.
1035          */
1036         if (!use_role && AH->use_role)
1037                 use_role = AH->use_role;
1038
1039         /* Set the role if requested */
1040         if (use_role && AH->remoteVersion >= 80100)
1041         {
1042                 PQExpBuffer query = createPQExpBuffer();
1043
1044                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1045                 ExecuteSqlStatement(AH, query->data);
1046                 destroyPQExpBuffer(query);
1047
1048                 /* save it for possible later use by parallel workers */
1049                 if (!AH->use_role)
1050                         AH->use_role = pg_strdup(use_role);
1051         }
1052
1053         /* Set the datestyle to ISO to ensure the dump's portability */
1054         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1055
1056         /* Likewise, avoid using sql_standard intervalstyle */
1057         if (AH->remoteVersion >= 80400)
1058                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1059
1060         /*
1061          * Set extra_float_digits so that we can dump float data exactly (given
1062          * correctly implemented float I/O code, anyway)
1063          */
1064         if (AH->remoteVersion >= 90000)
1065                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1066         else
1067                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1068
1069         /*
1070          * If synchronized scanning is supported, disable it, to prevent
1071          * unpredictable changes in row ordering across a dump and reload.
1072          */
1073         if (AH->remoteVersion >= 80300)
1074                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1075
1076         /*
1077          * Disable timeouts if supported.
1078          */
1079         ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1080         if (AH->remoteVersion >= 90300)
1081                 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1082         if (AH->remoteVersion >= 90600)
1083                 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1084
1085         /*
1086          * Quote all identifiers, if requested.
1087          */
1088         if (quote_all_identifiers && AH->remoteVersion >= 90100)
1089                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1090
1091         /*
1092          * Adjust row-security mode, if supported.
1093          */
1094         if (AH->remoteVersion >= 90500)
1095         {
1096                 if (dopt->enable_row_security)
1097                         ExecuteSqlStatement(AH, "SET row_security = on");
1098                 else
1099                         ExecuteSqlStatement(AH, "SET row_security = off");
1100         }
1101
1102         /*
1103          * Start transaction-snapshot mode transaction to dump consistent data.
1104          */
1105         ExecuteSqlStatement(AH, "BEGIN");
1106         if (AH->remoteVersion >= 90100)
1107         {
1108                 /*
1109                  * To support the combination of serializable_deferrable with the jobs
1110                  * option we use REPEATABLE READ for the worker connections that are
1111                  * passed a snapshot.  As long as the snapshot is acquired in a
1112                  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1113                  * REPEATABLE READ transaction provides the appropriate integrity
1114                  * guarantees.  This is a kluge, but safe for back-patching.
1115                  */
1116                 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1117                         ExecuteSqlStatement(AH,
1118                                                                 "SET TRANSACTION ISOLATION LEVEL "
1119                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1120                 else
1121                         ExecuteSqlStatement(AH,
1122                                                                 "SET TRANSACTION ISOLATION LEVEL "
1123                                                                 "REPEATABLE READ, READ ONLY");
1124         }
1125         else
1126         {
1127                 ExecuteSqlStatement(AH,
1128                                                         "SET TRANSACTION ISOLATION LEVEL "
1129                                                         "SERIALIZABLE, READ ONLY");
1130         }
1131
1132         /*
1133          * If user specified a snapshot to use, select that.  In a parallel dump
1134          * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1135          * is already set (if the server can handle it) and we should use that.
1136          */
1137         if (dumpsnapshot)
1138                 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1139
1140         if (AH->sync_snapshot_id)
1141         {
1142                 PQExpBuffer query = createPQExpBuffer();
1143
1144                 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1145                 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1146                 ExecuteSqlStatement(AH, query->data);
1147                 destroyPQExpBuffer(query);
1148         }
1149         else if (AH->numWorkers > 1 &&
1150                          AH->remoteVersion >= 90200 &&
1151                          !dopt->no_synchronized_snapshots)
1152         {
1153                 if (AH->isStandby && AH->remoteVersion < 100000)
1154                         exit_horribly(NULL,
1155                                                   "Synchronized snapshots on standby servers are not supported by this server version.\n"
1156                                                   "Run with --no-synchronized-snapshots instead if you do not need\n"
1157                                                   "synchronized snapshots.\n");
1158
1159
1160                 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1161         }
1162 }
1163
1164 /* Set up connection for a parallel worker process */
1165 static void
1166 setupDumpWorker(Archive *AH)
1167 {
1168         /*
1169          * We want to re-select all the same values the master connection is
1170          * using.  We'll have inherited directly-usable values in
1171          * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1172          * inherited encoding value back to a string to pass to setup_connection.
1173          */
1174         setup_connection(AH,
1175                                          pg_encoding_to_char(AH->encoding),
1176                                          NULL,
1177                                          NULL);
1178 }
1179
1180 static char *
1181 get_synchronized_snapshot(Archive *fout)
1182 {
1183         char       *query = "SELECT pg_catalog.pg_export_snapshot()";
1184         char       *result;
1185         PGresult   *res;
1186
1187         res = ExecuteSqlQueryForSingleRow(fout, query);
1188         result = pg_strdup(PQgetvalue(res, 0, 0));
1189         PQclear(res);
1190
1191         return result;
1192 }
1193
1194 static ArchiveFormat
1195 parseArchiveFormat(const char *format, ArchiveMode *mode)
1196 {
1197         ArchiveFormat archiveFormat;
1198
1199         *mode = archModeWrite;
1200
1201         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1202         {
1203                 /* This is used by pg_dumpall, and is not documented */
1204                 archiveFormat = archNull;
1205                 *mode = archModeAppend;
1206         }
1207         else if (pg_strcasecmp(format, "c") == 0)
1208                 archiveFormat = archCustom;
1209         else if (pg_strcasecmp(format, "custom") == 0)
1210                 archiveFormat = archCustom;
1211         else if (pg_strcasecmp(format, "d") == 0)
1212                 archiveFormat = archDirectory;
1213         else if (pg_strcasecmp(format, "directory") == 0)
1214                 archiveFormat = archDirectory;
1215         else if (pg_strcasecmp(format, "p") == 0)
1216                 archiveFormat = archNull;
1217         else if (pg_strcasecmp(format, "plain") == 0)
1218                 archiveFormat = archNull;
1219         else if (pg_strcasecmp(format, "t") == 0)
1220                 archiveFormat = archTar;
1221         else if (pg_strcasecmp(format, "tar") == 0)
1222                 archiveFormat = archTar;
1223         else
1224                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1225         return archiveFormat;
1226 }
1227
1228 /*
1229  * Find the OIDs of all schemas matching the given list of patterns,
1230  * and append them to the given OID list.
1231  */
1232 static void
1233 expand_schema_name_patterns(Archive *fout,
1234                                                         SimpleStringList *patterns,
1235                                                         SimpleOidList *oids,
1236                                                         bool strict_names)
1237 {
1238         PQExpBuffer query;
1239         PGresult   *res;
1240         SimpleStringListCell *cell;
1241         int                     i;
1242
1243         if (patterns->head == NULL)
1244                 return;                                 /* nothing to do */
1245
1246         query = createPQExpBuffer();
1247
1248         /*
1249          * The loop below runs multiple SELECTs might sometimes result in
1250          * duplicate entries in the OID list, but we don't care.
1251          */
1252
1253         for (cell = patterns->head; cell; cell = cell->next)
1254         {
1255                 appendPQExpBuffer(query,
1256                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1257                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1258                                                           false, NULL, "n.nspname", NULL, NULL);
1259
1260                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1261                 if (strict_names && PQntuples(res) == 0)
1262                         exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1263
1264                 for (i = 0; i < PQntuples(res); i++)
1265                 {
1266                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1267                 }
1268
1269                 PQclear(res);
1270                 resetPQExpBuffer(query);
1271         }
1272
1273         destroyPQExpBuffer(query);
1274 }
1275
1276 /*
1277  * Find the OIDs of all tables matching the given list of patterns,
1278  * and append them to the given OID list.
1279  */
1280 static void
1281 expand_table_name_patterns(Archive *fout,
1282                                                    SimpleStringList *patterns, SimpleOidList *oids,
1283                                                    bool strict_names)
1284 {
1285         PQExpBuffer query;
1286         PGresult   *res;
1287         SimpleStringListCell *cell;
1288         int                     i;
1289
1290         if (patterns->head == NULL)
1291                 return;                                 /* nothing to do */
1292
1293         query = createPQExpBuffer();
1294
1295         /*
1296          * this might sometimes result in duplicate entries in the OID list, but
1297          * we don't care.
1298          */
1299
1300         for (cell = patterns->head; cell; cell = cell->next)
1301         {
1302                 appendPQExpBuffer(query,
1303                                                   "SELECT c.oid"
1304                                                   "\nFROM pg_catalog.pg_class c"
1305                                                   "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1306                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c')\n",
1307                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1308                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1309                                                   RELKIND_PARTITIONED_TABLE);
1310                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1311                                                           false, "n.nspname", "c.relname", NULL,
1312                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1313
1314                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1315                 if (strict_names && PQntuples(res) == 0)
1316                         exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1317
1318                 for (i = 0; i < PQntuples(res); i++)
1319                 {
1320                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1321                 }
1322
1323                 PQclear(res);
1324                 resetPQExpBuffer(query);
1325         }
1326
1327         destroyPQExpBuffer(query);
1328 }
1329
1330 /*
1331  * checkExtensionMembership
1332  *              Determine whether object is an extension member, and if so,
1333  *              record an appropriate dependency and set the object's dump flag.
1334  *
1335  * It's important to call this for each object that could be an extension
1336  * member.  Generally, we integrate this with determining the object's
1337  * to-be-dumped-ness, since extension membership overrides other rules for that.
1338  *
1339  * Returns true if object is an extension member, else false.
1340  */
1341 static bool
1342 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1343 {
1344         ExtensionInfo *ext = findOwningExtension(dobj->catId);
1345
1346         if (ext == NULL)
1347                 return false;
1348
1349         dobj->ext_member = true;
1350
1351         /* Record dependency so that getDependencies needn't deal with that */
1352         addObjectDependency(dobj, ext->dobj.dumpId);
1353
1354         /*
1355          * In 9.6 and above, mark the member object to have any non-initial ACL,
1356          * policies, and security labels dumped.
1357          *
1358          * Note that any initial ACLs (see pg_init_privs) will be removed when we
1359          * extract the information about the object.  We don't provide support for
1360          * initial policies and security labels and it seems unlikely for those to
1361          * ever exist, but we may have to revisit this later.
1362          *
1363          * Prior to 9.6, we do not include any extension member components.
1364          *
1365          * In binary upgrades, we still dump all components of the members
1366          * individually, since the idea is to exactly reproduce the database
1367          * contents rather than replace the extension contents with something
1368          * different.
1369          */
1370         if (fout->dopt->binary_upgrade)
1371                 dobj->dump = ext->dobj.dump;
1372         else
1373         {
1374                 if (fout->remoteVersion < 90600)
1375                         dobj->dump = DUMP_COMPONENT_NONE;
1376                 else
1377                         dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1378                                                                                                         DUMP_COMPONENT_SECLABEL |
1379                                                                                                         DUMP_COMPONENT_POLICY);
1380         }
1381
1382         return true;
1383 }
1384
1385 /*
1386  * selectDumpableNamespace: policy-setting subroutine
1387  *              Mark a namespace as to be dumped or not
1388  */
1389 static void
1390 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1391 {
1392         /*
1393          * If specific tables are being dumped, do not dump any complete
1394          * namespaces. If specific namespaces are being dumped, dump just those
1395          * namespaces. Otherwise, dump all non-system namespaces.
1396          */
1397         if (table_include_oids.head != NULL)
1398                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1399         else if (schema_include_oids.head != NULL)
1400                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1401                         simple_oid_list_member(&schema_include_oids,
1402                                                                    nsinfo->dobj.catId.oid) ?
1403                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1404         else if (fout->remoteVersion >= 90600 &&
1405                          strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1406         {
1407                 /*
1408                  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1409                  * they are interesting (and not the original ACLs which were set at
1410                  * initdb time, see pg_init_privs).
1411                  */
1412                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1413         }
1414         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1415                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1416         {
1417                 /* Other system schemas don't get dumped */
1418                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1419         }
1420         else if (strcmp(nsinfo->dobj.name, "public") == 0)
1421         {
1422                 /*
1423                  * The public schema is a strange beast that sits in a sort of
1424                  * no-mans-land between being a system object and a user object.  We
1425                  * don't want to dump creation or comment commands for it, because
1426                  * that complicates matters for non-superuser use of pg_dump.  But we
1427                  * should dump any ACL changes that have occurred for it, and of
1428                  * course we should dump contained objects.
1429                  */
1430                 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1431                 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1432         }
1433         else
1434                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1435
1436         /*
1437          * In any case, a namespace can be excluded by an exclusion switch
1438          */
1439         if (nsinfo->dobj.dump_contains &&
1440                 simple_oid_list_member(&schema_exclude_oids,
1441                                                            nsinfo->dobj.catId.oid))
1442                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1443
1444         /*
1445          * If the schema belongs to an extension, allow extension membership to
1446          * override the dump decision for the schema itself.  However, this does
1447          * not change dump_contains, so this won't change what we do with objects
1448          * within the schema.  (If they belong to the extension, they'll get
1449          * suppressed by it, otherwise not.)
1450          */
1451         (void) checkExtensionMembership(&nsinfo->dobj, fout);
1452 }
1453
1454 /*
1455  * selectDumpableTable: policy-setting subroutine
1456  *              Mark a table as to be dumped or not
1457  */
1458 static void
1459 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1460 {
1461         if (checkExtensionMembership(&tbinfo->dobj, fout))
1462                 return;                                 /* extension membership overrides all else */
1463
1464         /*
1465          * If specific tables are being dumped, dump just those tables; else, dump
1466          * according to the parent namespace's dump flag.
1467          */
1468         if (table_include_oids.head != NULL)
1469                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1470                                                                                                    tbinfo->dobj.catId.oid) ?
1471                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1472         else
1473                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1474
1475         /*
1476          * In any case, a table can be excluded by an exclusion switch
1477          */
1478         if (tbinfo->dobj.dump &&
1479                 simple_oid_list_member(&table_exclude_oids,
1480                                                            tbinfo->dobj.catId.oid))
1481                 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1482 }
1483
1484 /*
1485  * selectDumpableType: policy-setting subroutine
1486  *              Mark a type as to be dumped or not
1487  *
1488  * If it's a table's rowtype or an autogenerated array type, we also apply a
1489  * special type code to facilitate sorting into the desired order.  (We don't
1490  * want to consider those to be ordinary types because that would bring tables
1491  * up into the datatype part of the dump order.)  We still set the object's
1492  * dump flag; that's not going to cause the dummy type to be dumped, but we
1493  * need it so that casts involving such types will be dumped correctly -- see
1494  * dumpCast.  This means the flag should be set the same as for the underlying
1495  * object (the table or base type).
1496  */
1497 static void
1498 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1499 {
1500         /* skip complex types, except for standalone composite types */
1501         if (OidIsValid(tyinfo->typrelid) &&
1502                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1503         {
1504                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1505
1506                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1507                 if (tytable != NULL)
1508                         tyinfo->dobj.dump = tytable->dobj.dump;
1509                 else
1510                         tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1511                 return;
1512         }
1513
1514         /* skip auto-generated array types */
1515         if (tyinfo->isArray)
1516         {
1517                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1518
1519                 /*
1520                  * Fall through to set the dump flag; we assume that the subsequent
1521                  * rules will do the same thing as they would for the array's base
1522                  * type.  (We cannot reliably look up the base type here, since
1523                  * getTypes may not have processed it yet.)
1524                  */
1525         }
1526
1527         if (checkExtensionMembership(&tyinfo->dobj, fout))
1528                 return;                                 /* extension membership overrides all else */
1529
1530         /* Dump based on if the contents of the namespace are being dumped */
1531         tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1532 }
1533
1534 /*
1535  * selectDumpableDefaultACL: policy-setting subroutine
1536  *              Mark a default ACL as to be dumped or not
1537  *
1538  * For per-schema default ACLs, dump if the schema is to be dumped.
1539  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1540  * and aclsSkip are checked separately.
1541  */
1542 static void
1543 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1544 {
1545         /* Default ACLs can't be extension members */
1546
1547         if (dinfo->dobj.namespace)
1548                 /* default ACLs are considered part of the namespace */
1549                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1550         else
1551                 dinfo->dobj.dump = dopt->include_everything ?
1552                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1553 }
1554
1555 /*
1556  * selectDumpableCast: policy-setting subroutine
1557  *              Mark a cast as to be dumped or not
1558  *
1559  * Casts do not belong to any particular namespace (since they haven't got
1560  * names), nor do they have identifiable owners.  To distinguish user-defined
1561  * casts from built-in ones, we must resort to checking whether the cast's
1562  * OID is in the range reserved for initdb.
1563  */
1564 static void
1565 selectDumpableCast(CastInfo *cast, Archive *fout)
1566 {
1567         if (checkExtensionMembership(&cast->dobj, fout))
1568                 return;                                 /* extension membership overrides all else */
1569
1570         /*
1571          * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1572          * support ACLs currently.
1573          */
1574         if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1575                 cast->dobj.dump = DUMP_COMPONENT_NONE;
1576         else
1577                 cast->dobj.dump = fout->dopt->include_everything ?
1578                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1579 }
1580
1581 /*
1582  * selectDumpableProcLang: policy-setting subroutine
1583  *              Mark a procedural language as to be dumped or not
1584  *
1585  * Procedural languages do not belong to any particular namespace.  To
1586  * identify built-in languages, we must resort to checking whether the
1587  * language's OID is in the range reserved for initdb.
1588  */
1589 static void
1590 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1591 {
1592         if (checkExtensionMembership(&plang->dobj, fout))
1593                 return;                                 /* extension membership overrides all else */
1594
1595         /*
1596          * Only include procedural languages when we are dumping everything.
1597          *
1598          * For from-initdb procedural languages, only include ACLs, as we do for
1599          * the pg_catalog namespace.  We need this because procedural languages do
1600          * not live in any namespace.
1601          */
1602         if (!fout->dopt->include_everything)
1603                 plang->dobj.dump = DUMP_COMPONENT_NONE;
1604         else
1605         {
1606                 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1607                         plang->dobj.dump = fout->remoteVersion < 90600 ?
1608                                 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1609                 else
1610                         plang->dobj.dump = DUMP_COMPONENT_ALL;
1611         }
1612 }
1613
1614 /*
1615  * selectDumpableAccessMethod: policy-setting subroutine
1616  *              Mark an access method as to be dumped or not
1617  *
1618  * Access methods do not belong to any particular namespace.  To identify
1619  * built-in access methods, we must resort to checking whether the
1620  * method's OID is in the range reserved for initdb.
1621  */
1622 static void
1623 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1624 {
1625         if (checkExtensionMembership(&method->dobj, fout))
1626                 return;                                 /* extension membership overrides all else */
1627
1628         /*
1629          * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1630          * they do not support ACLs currently.
1631          */
1632         if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1633                 method->dobj.dump = DUMP_COMPONENT_NONE;
1634         else
1635                 method->dobj.dump = fout->dopt->include_everything ?
1636                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1637 }
1638
1639 /*
1640  * selectDumpableExtension: policy-setting subroutine
1641  *              Mark an extension as to be dumped or not
1642  *
1643  * Built-in extensions should be skipped except for checking ACLs, since we
1644  * assume those will already be installed in the target database.  We identify
1645  * such extensions by their having OIDs in the range reserved for initdb.
1646  * We dump all user-added extensions by default, or none of them if
1647  * include_everything is false (i.e., a --schema or --table switch was given).
1648  */
1649 static void
1650 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1651 {
1652         /*
1653          * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1654          * change permissions on their member objects, if they wish to, and have
1655          * those changes preserved.
1656          */
1657         if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1658                 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1659         else
1660                 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1661                         dopt->include_everything ? DUMP_COMPONENT_ALL :
1662                         DUMP_COMPONENT_NONE;
1663 }
1664
1665 /*
1666  * selectDumpablePublicationTable: policy-setting subroutine
1667  *              Mark a publication table as to be dumped or not
1668  *
1669  * Publication tables have schemas, but those are ignored in decision making,
1670  * because publications are only dumped when we are dumping everything.
1671  */
1672 static void
1673 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1674 {
1675         if (checkExtensionMembership(dobj, fout))
1676                 return;                                 /* extension membership overrides all else */
1677
1678         dobj->dump = fout->dopt->include_everything ?
1679                 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1680 }
1681
1682 /*
1683  * selectDumpableObject: policy-setting subroutine
1684  *              Mark a generic dumpable object as to be dumped or not
1685  *
1686  * Use this only for object types without a special-case routine above.
1687  */
1688 static void
1689 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1690 {
1691         if (checkExtensionMembership(dobj, fout))
1692                 return;                                 /* extension membership overrides all else */
1693
1694         /*
1695          * Default policy is to dump if parent namespace is dumpable, or for
1696          * non-namespace-associated items, dump if we're dumping "everything".
1697          */
1698         if (dobj->namespace)
1699                 dobj->dump = dobj->namespace->dobj.dump_contains;
1700         else
1701                 dobj->dump = fout->dopt->include_everything ?
1702                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1703 }
1704
1705 /*
1706  *      Dump a table's contents for loading using the COPY command
1707  *      - this routine is called by the Archiver when it wants the table
1708  *        to be dumped.
1709  */
1710
1711 static int
1712 dumpTableData_copy(Archive *fout, void *dcontext)
1713 {
1714         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1715         TableInfo  *tbinfo = tdinfo->tdtable;
1716         const char *classname = tbinfo->dobj.name;
1717         const bool      hasoids = tbinfo->hasoids;
1718         const bool      oids = tdinfo->oids;
1719         PQExpBuffer q = createPQExpBuffer();
1720
1721         /*
1722          * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1723          * which uses it already.
1724          */
1725         PQExpBuffer clistBuf = createPQExpBuffer();
1726         PGconn     *conn = GetConnection(fout);
1727         PGresult   *res;
1728         int                     ret;
1729         char       *copybuf;
1730         const char *column_list;
1731
1732         if (g_verbose)
1733                 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1734                                   tbinfo->dobj.namespace->dobj.name, classname);
1735
1736         /*
1737          * Make sure we are in proper schema.  We will qualify the table name
1738          * below anyway (in case its name conflicts with a pg_catalog table); but
1739          * this ensures reproducible results in case the table contains regproc,
1740          * regclass, etc columns.
1741          */
1742         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1743
1744         /*
1745          * Specify the column list explicitly so that we have no possibility of
1746          * retrieving data in the wrong column order.  (The default column
1747          * ordering of COPY will not be what we want in certain corner cases
1748          * involving ADD COLUMN and inheritance.)
1749          */
1750         column_list = fmtCopyColumnList(tbinfo, clistBuf);
1751
1752         if (oids && hasoids)
1753         {
1754                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1755                                                   fmtQualifiedId(fout->remoteVersion,
1756                                                                                  tbinfo->dobj.namespace->dobj.name,
1757                                                                                  classname),
1758                                                   column_list);
1759         }
1760         else if (tdinfo->filtercond)
1761         {
1762                 /* Note: this syntax is only supported in 8.2 and up */
1763                 appendPQExpBufferStr(q, "COPY (SELECT ");
1764                 /* klugery to get rid of parens in column list */
1765                 if (strlen(column_list) > 2)
1766                 {
1767                         appendPQExpBufferStr(q, column_list + 1);
1768                         q->data[q->len - 1] = ' ';
1769                 }
1770                 else
1771                         appendPQExpBufferStr(q, "* ");
1772                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1773                                                   fmtQualifiedId(fout->remoteVersion,
1774                                                                                  tbinfo->dobj.namespace->dobj.name,
1775                                                                                  classname),
1776                                                   tdinfo->filtercond);
1777         }
1778         else
1779         {
1780                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1781                                                   fmtQualifiedId(fout->remoteVersion,
1782                                                                                  tbinfo->dobj.namespace->dobj.name,
1783                                                                                  classname),
1784                                                   column_list);
1785         }
1786         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1787         PQclear(res);
1788         destroyPQExpBuffer(clistBuf);
1789
1790         for (;;)
1791         {
1792                 ret = PQgetCopyData(conn, &copybuf, 0);
1793
1794                 if (ret < 0)
1795                         break;                          /* done or error */
1796
1797                 if (copybuf)
1798                 {
1799                         WriteData(fout, copybuf, ret);
1800                         PQfreemem(copybuf);
1801                 }
1802
1803                 /* ----------
1804                  * THROTTLE:
1805                  *
1806                  * There was considerable discussion in late July, 2000 regarding
1807                  * slowing down pg_dump when backing up large tables. Users with both
1808                  * slow & fast (multi-processor) machines experienced performance
1809                  * degradation when doing a backup.
1810                  *
1811                  * Initial attempts based on sleeping for a number of ms for each ms
1812                  * of work were deemed too complex, then a simple 'sleep in each loop'
1813                  * implementation was suggested. The latter failed because the loop
1814                  * was too tight. Finally, the following was implemented:
1815                  *
1816                  * If throttle is non-zero, then
1817                  *              See how long since the last sleep.
1818                  *              Work out how long to sleep (based on ratio).
1819                  *              If sleep is more than 100ms, then
1820                  *                      sleep
1821                  *                      reset timer
1822                  *              EndIf
1823                  * EndIf
1824                  *
1825                  * where the throttle value was the number of ms to sleep per ms of
1826                  * work. The calculation was done in each loop.
1827                  *
1828                  * Most of the hard work is done in the backend, and this solution
1829                  * still did not work particularly well: on slow machines, the ratio
1830                  * was 50:1, and on medium paced machines, 1:1, and on fast
1831                  * multi-processor machines, it had little or no effect, for reasons
1832                  * that were unclear.
1833                  *
1834                  * Further discussion ensued, and the proposal was dropped.
1835                  *
1836                  * For those people who want this feature, it can be implemented using
1837                  * gettimeofday in each loop, calculating the time since last sleep,
1838                  * multiplying that by the sleep ratio, then if the result is more
1839                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1840                  * function to sleep for a subsecond period ie.
1841                  *
1842                  * select(0, NULL, NULL, NULL, &tvi);
1843                  *
1844                  * This will return after the interval specified in the structure tvi.
1845                  * Finally, call gettimeofday again to save the 'last sleep time'.
1846                  * ----------
1847                  */
1848         }
1849         archprintf(fout, "\\.\n\n\n");
1850
1851         if (ret == -2)
1852         {
1853                 /* copy data transfer failed */
1854                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1855                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1856                 write_msg(NULL, "The command was: %s\n", q->data);
1857                 exit_nicely(1);
1858         }
1859
1860         /* Check command status and return to normal libpq state */
1861         res = PQgetResult(conn);
1862         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1863         {
1864                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1865                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1866                 write_msg(NULL, "The command was: %s\n", q->data);
1867                 exit_nicely(1);
1868         }
1869         PQclear(res);
1870
1871         /* Do this to ensure we've pumped libpq back to idle state */
1872         if (PQgetResult(conn) != NULL)
1873                 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1874                                   classname);
1875
1876         destroyPQExpBuffer(q);
1877         return 1;
1878 }
1879
1880 /*
1881  * Dump table data using INSERT commands.
1882  *
1883  * Caution: when we restore from an archive file direct to database, the
1884  * INSERT commands emitted by this function have to be parsed by
1885  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1886  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1887  */
1888 static int
1889 dumpTableData_insert(Archive *fout, void *dcontext)
1890 {
1891         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1892         TableInfo  *tbinfo = tdinfo->tdtable;
1893         const char *classname = tbinfo->dobj.name;
1894         DumpOptions *dopt = fout->dopt;
1895         PQExpBuffer q = createPQExpBuffer();
1896         PQExpBuffer insertStmt = NULL;
1897         PGresult   *res;
1898         int                     tuple;
1899         int                     nfields;
1900         int                     field;
1901
1902         /*
1903          * Make sure we are in proper schema.  We will qualify the table name
1904          * below anyway (in case its name conflicts with a pg_catalog table); but
1905          * this ensures reproducible results in case the table contains regproc,
1906          * regclass, etc columns.
1907          */
1908         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1909
1910         appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1911                                           "SELECT * FROM ONLY %s",
1912                                           fmtQualifiedId(fout->remoteVersion,
1913                                                                          tbinfo->dobj.namespace->dobj.name,
1914                                                                          classname));
1915         if (tdinfo->filtercond)
1916                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1917
1918         ExecuteSqlStatement(fout, q->data);
1919
1920         while (1)
1921         {
1922                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1923                                                           PGRES_TUPLES_OK);
1924                 nfields = PQnfields(res);
1925                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1926                 {
1927                         /*
1928                          * First time through, we build as much of the INSERT statement as
1929                          * possible in "insertStmt", which we can then just print for each
1930                          * line. If the table happens to have zero columns then this will
1931                          * be a complete statement, otherwise it will end in "VALUES(" and
1932                          * be ready to have the row's column values appended.
1933                          */
1934                         if (insertStmt == NULL)
1935                         {
1936                                 insertStmt = createPQExpBuffer();
1937
1938                                 /*
1939                                  * When load-via-partition-root is set, get the root table
1940                                  * name for the partition table, so that we can reload data
1941                                  * through the root table.
1942                                  */
1943                                 if (dopt->load_via_partition_root && tbinfo->ispartition)
1944                                 {
1945                                         TableInfo  *parentTbinfo;
1946
1947                                         parentTbinfo = getRootTableInfo(tbinfo);
1948
1949                                         /*
1950                                          * When we loading data through the root, we will qualify
1951                                          * the table name. This is needed because earlier
1952                                          * search_path will be set for the partition table.
1953                                          */
1954                                         classname = (char *) fmtQualifiedId(fout->remoteVersion,
1955                                                                                                                 parentTbinfo->dobj.namespace->dobj.name,
1956                                                                                                                 parentTbinfo->dobj.name);
1957                                 }
1958                                 else
1959                                         classname = fmtId(tbinfo->dobj.name);
1960
1961                                 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1962                                                                   classname);
1963
1964                                 /* corner case for zero-column table */
1965                                 if (nfields == 0)
1966                                 {
1967                                         appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1968                                 }
1969                                 else
1970                                 {
1971                                         /* append the list of column names if required */
1972                                         if (dopt->column_inserts)
1973                                         {
1974                                                 appendPQExpBufferChar(insertStmt, '(');
1975                                                 for (field = 0; field < nfields; field++)
1976                                                 {
1977                                                         if (field > 0)
1978                                                                 appendPQExpBufferStr(insertStmt, ", ");
1979                                                         appendPQExpBufferStr(insertStmt,
1980                                                                                                  fmtId(PQfname(res, field)));
1981                                                 }
1982                                                 appendPQExpBufferStr(insertStmt, ") ");
1983                                         }
1984
1985                                         if (tbinfo->needs_override)
1986                                                 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1987
1988                                         appendPQExpBufferStr(insertStmt, "VALUES (");
1989                                 }
1990                         }
1991
1992                         archputs(insertStmt->data, fout);
1993
1994                         /* if it is zero-column table then we're done */
1995                         if (nfields == 0)
1996                                 continue;
1997
1998                         for (field = 0; field < nfields; field++)
1999                         {
2000                                 if (field > 0)
2001                                         archputs(", ", fout);
2002                                 if (PQgetisnull(res, tuple, field))
2003                                 {
2004                                         archputs("NULL", fout);
2005                                         continue;
2006                                 }
2007
2008                                 /* XXX This code is partially duplicated in ruleutils.c */
2009                                 switch (PQftype(res, field))
2010                                 {
2011                                         case INT2OID:
2012                                         case INT4OID:
2013                                         case INT8OID:
2014                                         case OIDOID:
2015                                         case FLOAT4OID:
2016                                         case FLOAT8OID:
2017                                         case NUMERICOID:
2018                                                 {
2019                                                         /*
2020                                                          * These types are printed without quotes unless
2021                                                          * they contain values that aren't accepted by the
2022                                                          * scanner unquoted (e.g., 'NaN').  Note that
2023                                                          * strtod() and friends might accept NaN, so we
2024                                                          * can't use that to test.
2025                                                          *
2026                                                          * In reality we only need to defend against
2027                                                          * infinity and NaN, so we need not get too crazy
2028                                                          * about pattern matching here.
2029                                                          */
2030                                                         const char *s = PQgetvalue(res, tuple, field);
2031
2032                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
2033                                                                 archputs(s, fout);
2034                                                         else
2035                                                                 archprintf(fout, "'%s'", s);
2036                                                 }
2037                                                 break;
2038
2039                                         case BITOID:
2040                                         case VARBITOID:
2041                                                 archprintf(fout, "B'%s'",
2042                                                                    PQgetvalue(res, tuple, field));
2043                                                 break;
2044
2045                                         case BOOLOID:
2046                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2047                                                         archputs("true", fout);
2048                                                 else
2049                                                         archputs("false", fout);
2050                                                 break;
2051
2052                                         default:
2053                                                 /* All other types are printed as string literals. */
2054                                                 resetPQExpBuffer(q);
2055                                                 appendStringLiteralAH(q,
2056                                                                                           PQgetvalue(res, tuple, field),
2057                                                                                           fout);
2058                                                 archputs(q->data, fout);
2059                                                 break;
2060                                 }
2061                         }
2062                         archputs(");\n", fout);
2063                 }
2064
2065                 if (PQntuples(res) <= 0)
2066                 {
2067                         PQclear(res);
2068                         break;
2069                 }
2070                 PQclear(res);
2071         }
2072
2073         archputs("\n\n", fout);
2074
2075         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2076
2077         destroyPQExpBuffer(q);
2078         if (insertStmt != NULL)
2079                 destroyPQExpBuffer(insertStmt);
2080
2081         return 1;
2082 }
2083
2084 /*
2085  * getRootTableInfo:
2086  *     get the root TableInfo for the given partition table.
2087  */
2088 static TableInfo *
2089 getRootTableInfo(TableInfo *tbinfo)
2090 {
2091         TableInfo  *parentTbinfo;
2092
2093         Assert(tbinfo->ispartition);
2094         Assert(tbinfo->numParents == 1);
2095
2096         parentTbinfo = tbinfo->parents[0];
2097         while (parentTbinfo->ispartition)
2098         {
2099                 Assert(parentTbinfo->numParents == 1);
2100                 parentTbinfo = parentTbinfo->parents[0];
2101         }
2102
2103         return parentTbinfo;
2104 }
2105
2106 /*
2107  * dumpTableData -
2108  *        dump the contents of a single table
2109  *
2110  * Actually, this just makes an ArchiveEntry for the table contents.
2111  */
2112 static void
2113 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2114 {
2115         DumpOptions *dopt = fout->dopt;
2116         TableInfo  *tbinfo = tdinfo->tdtable;
2117         PQExpBuffer copyBuf = createPQExpBuffer();
2118         PQExpBuffer clistBuf = createPQExpBuffer();
2119         DataDumperPtr dumpFn;
2120         char       *copyStmt;
2121         const char *copyFrom;
2122
2123         if (!dopt->dump_inserts)
2124         {
2125                 /* Dump/restore using COPY */
2126                 dumpFn = dumpTableData_copy;
2127
2128                 /*
2129                  * When load-via-partition-root is set, get the root table name for
2130                  * the partition table, so that we can reload data through the root
2131                  * table.
2132                  */
2133                 if (dopt->load_via_partition_root && tbinfo->ispartition)
2134                 {
2135                         TableInfo  *parentTbinfo;
2136
2137                         parentTbinfo = getRootTableInfo(tbinfo);
2138
2139                         /*
2140                          * When we load data through the root, we will qualify the table
2141                          * name, because search_path is set for the partition.
2142                          */
2143                         copyFrom = fmtQualifiedId(fout->remoteVersion,
2144                                                                           parentTbinfo->dobj.namespace->dobj.name,
2145                                                                           parentTbinfo->dobj.name);
2146                 }
2147                 else
2148                         copyFrom = fmtId(tbinfo->dobj.name);
2149
2150                 /* must use 2 steps here 'cause fmtId is nonreentrant */
2151                 appendPQExpBuffer(copyBuf, "COPY %s ",
2152                                                   copyFrom);
2153                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2154                                                   fmtCopyColumnList(tbinfo, clistBuf),
2155                                                   (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2156                 copyStmt = copyBuf->data;
2157         }
2158         else
2159         {
2160                 /* Restore using INSERT */
2161                 dumpFn = dumpTableData_insert;
2162                 copyStmt = NULL;
2163         }
2164
2165         /*
2166          * Note: although the TableDataInfo is a full DumpableObject, we treat its
2167          * dependency on its table as "special" and pass it to ArchiveEntry now.
2168          * See comments for BuildArchiveDependencies.
2169          */
2170         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2171                 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2172                                          tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2173                                          NULL, tbinfo->rolname,
2174                                          false, "TABLE DATA", SECTION_DATA,
2175                                          "", "", copyStmt,
2176                                          &(tbinfo->dobj.dumpId), 1,
2177                                          dumpFn, tdinfo);
2178
2179         destroyPQExpBuffer(copyBuf);
2180         destroyPQExpBuffer(clistBuf);
2181 }
2182
2183 /*
2184  * refreshMatViewData -
2185  *        load or refresh the contents of a single materialized view
2186  *
2187  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2188  * statement.
2189  */
2190 static void
2191 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2192 {
2193         TableInfo  *tbinfo = tdinfo->tdtable;
2194         PQExpBuffer q;
2195
2196         /* If the materialized view is not flagged as populated, skip this. */
2197         if (!tbinfo->relispopulated)
2198                 return;
2199
2200         q = createPQExpBuffer();
2201
2202         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2203                                           fmtId(tbinfo->dobj.name));
2204
2205         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2206                 ArchiveEntry(fout,
2207                                          tdinfo->dobj.catId,    /* catalog ID */
2208                                          tdinfo->dobj.dumpId,   /* dump ID */
2209                                          tbinfo->dobj.name, /* Name */
2210                                          tbinfo->dobj.namespace->dobj.name, /* Namespace */
2211                                          NULL,          /* Tablespace */
2212                                          tbinfo->rolname,       /* Owner */
2213                                          false,         /* with oids */
2214                                          "MATERIALIZED VIEW DATA",      /* Desc */
2215                                          SECTION_POST_DATA, /* Section */
2216                                          q->data,       /* Create */
2217                                          "",            /* Del */
2218                                          NULL,          /* Copy */
2219                                          tdinfo->dobj.dependencies, /* Deps */
2220                                          tdinfo->dobj.nDeps,    /* # Deps */
2221                                          NULL,          /* Dumper */
2222                                          NULL);         /* Dumper Arg */
2223
2224         destroyPQExpBuffer(q);
2225 }
2226
2227 /*
2228  * getTableData -
2229  *        set up dumpable objects representing the contents of tables
2230  */
2231 static void
2232 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2233 {
2234         int                     i;
2235
2236         for (i = 0; i < numTables; i++)
2237         {
2238                 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2239                         (!relkind || tblinfo[i].relkind == relkind))
2240                         makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2241         }
2242 }
2243
2244 /*
2245  * Make a dumpable object for the data of this specific table
2246  *
2247  * Note: we make a TableDataInfo if and only if we are going to dump the
2248  * table data; the "dump" flag in such objects isn't used.
2249  */
2250 static void
2251 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2252 {
2253         TableDataInfo *tdinfo;
2254
2255         /*
2256          * Nothing to do if we already decided to dump the table.  This will
2257          * happen for "config" tables.
2258          */
2259         if (tbinfo->dataObj != NULL)
2260                 return;
2261
2262         /* Skip VIEWs (no data to dump) */
2263         if (tbinfo->relkind == RELKIND_VIEW)
2264                 return;
2265         /* Skip FOREIGN TABLEs (no data to dump) */
2266         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2267                 return;
2268         /* Skip partitioned tables (data in partitions) */
2269         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2270                 return;
2271
2272         /* Don't dump data in unlogged tables, if so requested */
2273         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2274                 dopt->no_unlogged_table_data)
2275                 return;
2276
2277         /* Check that the data is not explicitly excluded */
2278         if (simple_oid_list_member(&tabledata_exclude_oids,
2279                                                            tbinfo->dobj.catId.oid))
2280                 return;
2281
2282         /* OK, let's dump it */
2283         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2284
2285         if (tbinfo->relkind == RELKIND_MATVIEW)
2286                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2287         else if (tbinfo->relkind == RELKIND_SEQUENCE)
2288                 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2289         else
2290                 tdinfo->dobj.objType = DO_TABLE_DATA;
2291
2292         /*
2293          * Note: use tableoid 0 so that this object won't be mistaken for
2294          * something that pg_depend entries apply to.
2295          */
2296         tdinfo->dobj.catId.tableoid = 0;
2297         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2298         AssignDumpId(&tdinfo->dobj);
2299         tdinfo->dobj.name = tbinfo->dobj.name;
2300         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2301         tdinfo->tdtable = tbinfo;
2302         tdinfo->oids = oids;
2303         tdinfo->filtercond = NULL;      /* might get set later */
2304         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2305
2306         tbinfo->dataObj = tdinfo;
2307 }
2308
2309 /*
2310  * The refresh for a materialized view must be dependent on the refresh for
2311  * any materialized view that this one is dependent on.
2312  *
2313  * This must be called after all the objects are created, but before they are
2314  * sorted.
2315  */
2316 static void
2317 buildMatViewRefreshDependencies(Archive *fout)
2318 {
2319         PQExpBuffer query;
2320         PGresult   *res;
2321         int                     ntups,
2322                                 i;
2323         int                     i_classid,
2324                                 i_objid,
2325                                 i_refobjid;
2326
2327         /* No Mat Views before 9.3. */
2328         if (fout->remoteVersion < 90300)
2329                 return;
2330
2331         /* Make sure we are in proper schema */
2332         selectSourceSchema(fout, "pg_catalog");
2333
2334         query = createPQExpBuffer();
2335
2336         appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2337                                                  "( "
2338                                                  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2339                                                  "FROM pg_depend d1 "
2340                                                  "JOIN pg_class c1 ON c1.oid = d1.objid "
2341                                                  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2342                                                  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2343                                                  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2344                                                  "AND d2.objid = r1.oid "
2345                                                  "AND d2.refobjid <> d1.objid "
2346                                                  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2347                                                  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2348                                                  CppAsString2(RELKIND_VIEW) ") "
2349                                                  "WHERE d1.classid = 'pg_class'::regclass "
2350                                                  "UNION "
2351                                                  "SELECT w.objid, d3.refobjid, c3.relkind "
2352                                                  "FROM w "
2353                                                  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2354                                                  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2355                                                  "AND d3.objid = r3.oid "
2356                                                  "AND d3.refobjid <> w.refobjid "
2357                                                  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2358                                                  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2359                                                  CppAsString2(RELKIND_VIEW) ") "
2360                                                  ") "
2361                                                  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2362                                                  "FROM w "
2363                                                  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2364
2365         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2366
2367         ntups = PQntuples(res);
2368
2369         i_classid = PQfnumber(res, "classid");
2370         i_objid = PQfnumber(res, "objid");
2371         i_refobjid = PQfnumber(res, "refobjid");
2372
2373         for (i = 0; i < ntups; i++)
2374         {
2375                 CatalogId       objId;
2376                 CatalogId       refobjId;
2377                 DumpableObject *dobj;
2378                 DumpableObject *refdobj;
2379                 TableInfo  *tbinfo;
2380                 TableInfo  *reftbinfo;
2381
2382                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2383                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2384                 refobjId.tableoid = objId.tableoid;
2385                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2386
2387                 dobj = findObjectByCatalogId(objId);
2388                 if (dobj == NULL)
2389                         continue;
2390
2391                 Assert(dobj->objType == DO_TABLE);
2392                 tbinfo = (TableInfo *) dobj;
2393                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2394                 dobj = (DumpableObject *) tbinfo->dataObj;
2395                 if (dobj == NULL)
2396                         continue;
2397                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2398
2399                 refdobj = findObjectByCatalogId(refobjId);
2400                 if (refdobj == NULL)
2401                         continue;
2402
2403                 Assert(refdobj->objType == DO_TABLE);
2404                 reftbinfo = (TableInfo *) refdobj;
2405                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2406                 refdobj = (DumpableObject *) reftbinfo->dataObj;
2407                 if (refdobj == NULL)
2408                         continue;
2409                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2410
2411                 addObjectDependency(dobj, refdobj->dumpId);
2412
2413                 if (!reftbinfo->relispopulated)
2414                         tbinfo->relispopulated = false;
2415         }
2416
2417         PQclear(res);
2418
2419         destroyPQExpBuffer(query);
2420 }
2421
2422 /*
2423  * getTableDataFKConstraints -
2424  *        add dump-order dependencies reflecting foreign key constraints
2425  *
2426  * This code is executed only in a data-only dump --- in schema+data dumps
2427  * we handle foreign key issues by not creating the FK constraints until
2428  * after the data is loaded.  In a data-only dump, however, we want to
2429  * order the table data objects in such a way that a table's referenced
2430  * tables are restored first.  (In the presence of circular references or
2431  * self-references this may be impossible; we'll detect and complain about
2432  * that during the dependency sorting step.)
2433  */
2434 static void
2435 getTableDataFKConstraints(void)
2436 {
2437         DumpableObject **dobjs;
2438         int                     numObjs;
2439         int                     i;
2440
2441         /* Search through all the dumpable objects for FK constraints */
2442         getDumpableObjects(&dobjs, &numObjs);
2443         for (i = 0; i < numObjs; i++)
2444         {
2445                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2446                 {
2447                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2448                         TableInfo  *ftable;
2449
2450                         /* Not interesting unless both tables are to be dumped */
2451                         if (cinfo->contable == NULL ||
2452                                 cinfo->contable->dataObj == NULL)
2453                                 continue;
2454                         ftable = findTableByOid(cinfo->confrelid);
2455                         if (ftable == NULL ||
2456                                 ftable->dataObj == NULL)
2457                                 continue;
2458
2459                         /*
2460                          * Okay, make referencing table's TABLE_DATA object depend on the
2461                          * referenced table's TABLE_DATA object.
2462                          */
2463                         addObjectDependency(&cinfo->contable->dataObj->dobj,
2464                                                                 ftable->dataObj->dobj.dumpId);
2465                 }
2466         }
2467         free(dobjs);
2468 }
2469
2470
2471 /*
2472  * guessConstraintInheritance:
2473  *      In pre-8.4 databases, we can't tell for certain which constraints
2474  *      are inherited.  We assume a CHECK constraint is inherited if its name
2475  *      matches the name of any constraint in the parent.  Originally this code
2476  *      tried to compare the expression texts, but that can fail for various
2477  *      reasons --- for example, if the parent and child tables are in different
2478  *      schemas, reverse-listing of function calls may produce different text
2479  *      (schema-qualified or not) depending on search path.
2480  *
2481  *      In 8.4 and up we can rely on the conislocal field to decide which
2482  *      constraints must be dumped; much safer.
2483  *
2484  *      This function assumes all conislocal flags were initialized to true.
2485  *      It clears the flag on anything that seems to be inherited.
2486  */
2487 static void
2488 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2489 {
2490         int                     i,
2491                                 j,
2492                                 k;
2493
2494         for (i = 0; i < numTables; i++)
2495         {
2496                 TableInfo  *tbinfo = &(tblinfo[i]);
2497                 int                     numParents;
2498                 TableInfo **parents;
2499                 TableInfo  *parent;
2500
2501                 /* Sequences and views never have parents */
2502                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2503                         tbinfo->relkind == RELKIND_VIEW)
2504                         continue;
2505
2506                 /* Don't bother computing anything for non-target tables, either */
2507                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2508                         continue;
2509
2510                 numParents = tbinfo->numParents;
2511                 parents = tbinfo->parents;
2512
2513                 if (numParents == 0)
2514                         continue;                       /* nothing to see here, move along */
2515
2516                 /* scan for inherited CHECK constraints */
2517                 for (j = 0; j < tbinfo->ncheck; j++)
2518                 {
2519                         ConstraintInfo *constr;
2520
2521                         constr = &(tbinfo->checkexprs[j]);
2522
2523                         for (k = 0; k < numParents; k++)
2524                         {
2525                                 int                     l;
2526
2527                                 parent = parents[k];
2528                                 for (l = 0; l < parent->ncheck; l++)
2529                                 {
2530                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2531
2532                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2533                                         {
2534                                                 constr->conislocal = false;
2535                                                 break;
2536                                         }
2537                                 }
2538                                 if (!constr->conislocal)
2539                                         break;
2540                         }
2541                 }
2542         }
2543 }
2544
2545
2546 /*
2547  * dumpDatabase:
2548  *      dump the database definition
2549  */
2550 static void
2551 dumpDatabase(Archive *fout)
2552 {
2553         DumpOptions *dopt = fout->dopt;
2554         PQExpBuffer dbQry = createPQExpBuffer();
2555         PQExpBuffer delQry = createPQExpBuffer();
2556         PQExpBuffer creaQry = createPQExpBuffer();
2557         PQExpBuffer labelq = createPQExpBuffer();
2558         PGconn     *conn = GetConnection(fout);
2559         PGresult   *res;
2560         int                     i_tableoid,
2561                                 i_oid,
2562                                 i_dba,
2563                                 i_encoding,
2564                                 i_collate,
2565                                 i_ctype,
2566                                 i_frozenxid,
2567                                 i_minmxid,
2568                                 i_datacl,
2569                                 i_rdatacl,
2570                                 i_datistemplate,
2571                                 i_datconnlimit,
2572                                 i_tablespace;
2573         CatalogId       dbCatId;
2574         DumpId          dbDumpId;
2575         const char *datname,
2576                            *dba,
2577                            *encoding,
2578                            *collate,
2579                            *ctype,
2580                            *datacl,
2581                            *rdatacl,
2582                            *datistemplate,
2583                            *datconnlimit,
2584                            *tablespace;
2585         uint32          frozenxid,
2586                                 minmxid;
2587         char       *qdatname;
2588
2589         datname = PQdb(conn);
2590         qdatname = pg_strdup(fmtId(datname));
2591
2592         if (g_verbose)
2593                 write_msg(NULL, "saving database definition\n");
2594
2595         /* Make sure we are in proper schema */
2596         selectSourceSchema(fout, "pg_catalog");
2597
2598         /* Fetch the database-level properties for this database */
2599         if (fout->remoteVersion >= 90600)
2600         {
2601                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2602                                                   "(%s datdba) AS dba, "
2603                                                   "pg_encoding_to_char(encoding) AS encoding, "
2604                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2605                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2606                                                   "  SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2607                                                   "  EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2608                                                   " AS datacl, "
2609                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2610                                                   "  SELECT unnest(acldefault('d',datdba)) AS acl "
2611                                                   "  EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2612                                                   " AS rdatacl, "
2613                                                   "datistemplate, datconnlimit, "
2614                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2615                                                   "shobj_description(oid, 'pg_database') AS description "
2616
2617                                                   "FROM pg_database "
2618                                                   "WHERE datname = ",
2619                                                   username_subquery);
2620                 appendStringLiteralAH(dbQry, datname, fout);
2621         }
2622         else if (fout->remoteVersion >= 90300)
2623         {
2624                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2625                                                   "(%s datdba) AS dba, "
2626                                                   "pg_encoding_to_char(encoding) AS encoding, "
2627                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2628                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2629                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2630                                                   "shobj_description(oid, 'pg_database') AS description "
2631
2632                                                   "FROM pg_database "
2633                                                   "WHERE datname = ",
2634                                                   username_subquery);
2635                 appendStringLiteralAH(dbQry, datname, fout);
2636         }
2637         else if (fout->remoteVersion >= 80400)
2638         {
2639                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2640                                                   "(%s datdba) AS dba, "
2641                                                   "pg_encoding_to_char(encoding) AS encoding, "
2642                                                   "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2643                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2644                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2645                                                   "shobj_description(oid, 'pg_database') AS description "
2646
2647                                                   "FROM pg_database "
2648                                                   "WHERE datname = ",
2649                                                   username_subquery);
2650                 appendStringLiteralAH(dbQry, datname, fout);
2651         }
2652         else if (fout->remoteVersion >= 80200)
2653         {
2654                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2655                                                   "(%s datdba) AS dba, "
2656                                                   "pg_encoding_to_char(encoding) AS encoding, "
2657                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2658                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2659                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2660                                                   "shobj_description(oid, 'pg_database') AS description "
2661
2662                                                   "FROM pg_database "
2663                                                   "WHERE datname = ",
2664                                                   username_subquery);
2665                 appendStringLiteralAH(dbQry, datname, fout);
2666         }
2667         else
2668         {
2669                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2670                                                   "(%s datdba) AS dba, "
2671                                                   "pg_encoding_to_char(encoding) AS encoding, "
2672                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2673                                                   "datacl, '' as rdatacl, datistemplate, "
2674                                                   "-1 as datconnlimit, "
2675                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2676                                                   "FROM pg_database "
2677                                                   "WHERE datname = ",
2678                                                   username_subquery);
2679                 appendStringLiteralAH(dbQry, datname, fout);
2680         }
2681
2682         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2683
2684         i_tableoid = PQfnumber(res, "tableoid");
2685         i_oid = PQfnumber(res, "oid");
2686         i_dba = PQfnumber(res, "dba");
2687         i_encoding = PQfnumber(res, "encoding");
2688         i_collate = PQfnumber(res, "datcollate");
2689         i_ctype = PQfnumber(res, "datctype");
2690         i_frozenxid = PQfnumber(res, "datfrozenxid");
2691         i_minmxid = PQfnumber(res, "datminmxid");
2692         i_datacl = PQfnumber(res, "datacl");
2693         i_rdatacl = PQfnumber(res, "rdatacl");
2694         i_datistemplate = PQfnumber(res, "datistemplate");
2695         i_datconnlimit = PQfnumber(res, "datconnlimit");
2696         i_tablespace = PQfnumber(res, "tablespace");
2697
2698         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2699         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2700         dba = PQgetvalue(res, 0, i_dba);
2701         encoding = PQgetvalue(res, 0, i_encoding);
2702         collate = PQgetvalue(res, 0, i_collate);
2703         ctype = PQgetvalue(res, 0, i_ctype);
2704         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2705         minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2706         datacl = PQgetvalue(res, 0, i_datacl);
2707         rdatacl = PQgetvalue(res, 0, i_rdatacl);
2708         datistemplate = PQgetvalue(res, 0, i_datistemplate);
2709         datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2710         tablespace = PQgetvalue(res, 0, i_tablespace);
2711
2712         /*
2713          * Prepare the CREATE DATABASE command.  We must specify encoding, locale,
2714          * and tablespace since those can't be altered later.  Other DB properties
2715          * are left to the DATABASE PROPERTIES entry, so that they can be applied
2716          * after reconnecting to the target DB.
2717          */
2718         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2719                                           qdatname);
2720         if (strlen(encoding) > 0)
2721         {
2722                 appendPQExpBufferStr(creaQry, " ENCODING = ");
2723                 appendStringLiteralAH(creaQry, encoding, fout);
2724         }
2725         if (strlen(collate) > 0)
2726         {
2727                 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2728                 appendStringLiteralAH(creaQry, collate, fout);
2729         }
2730         if (strlen(ctype) > 0)
2731         {
2732                 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2733                 appendStringLiteralAH(creaQry, ctype, fout);
2734         }
2735
2736         /*
2737          * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2738          * thing; the decision whether to specify a tablespace should be left till
2739          * pg_restore, so that pg_restore --no-tablespaces applies.  Ideally we'd
2740          * label the DATABASE entry with the tablespace and let the normal
2741          * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2742          * attention to default_tablespace, so that won't work.
2743          */
2744         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2745                 !dopt->outputNoTablespaces)
2746                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2747                                                   fmtId(tablespace));
2748         appendPQExpBufferStr(creaQry, ";\n");
2749
2750         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2751                                           qdatname);
2752
2753         dbDumpId = createDumpId();
2754
2755         ArchiveEntry(fout,
2756                                  dbCatId,               /* catalog ID */
2757                                  dbDumpId,              /* dump ID */
2758                                  datname,               /* Name */
2759                                  NULL,                  /* Namespace */
2760                                  NULL,                  /* Tablespace */
2761                                  dba,                   /* Owner */
2762                                  false,                 /* with oids */
2763                                  "DATABASE",    /* Desc */
2764                                  SECTION_PRE_DATA,      /* Section */
2765                                  creaQry->data, /* Create */
2766                                  delQry->data,  /* Del */
2767                                  NULL,                  /* Copy */
2768                                  NULL,                  /* Deps */
2769                                  0,                             /* # Deps */
2770                                  NULL,                  /* Dumper */
2771                                  NULL);                 /* Dumper Arg */
2772
2773         /* Compute correct tag for comments etc */
2774         appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2775
2776         /* Dump DB comment if any */
2777         if (fout->remoteVersion >= 80200)
2778         {
2779                 /*
2780                  * 8.2 and up keep comments on shared objects in a shared table, so we
2781                  * cannot use the dumpComment() code used for other database objects.
2782                  * Be careful that the ArchiveEntry parameters match that function.
2783                  */
2784                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2785
2786                 if (comment && *comment && !dopt->no_comments)
2787                 {
2788                         resetPQExpBuffer(dbQry);
2789
2790                         /*
2791                          * Generates warning when loaded into a differently-named
2792                          * database.
2793                          */
2794                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2795                         appendStringLiteralAH(dbQry, comment, fout);
2796                         appendPQExpBufferStr(dbQry, ";\n");
2797
2798                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2799                                                  labelq->data, NULL, NULL, dba,
2800                                                  false, "COMMENT", SECTION_NONE,
2801                                                  dbQry->data, "", NULL,
2802                                                  &(dbDumpId), 1,
2803                                                  NULL, NULL);
2804                 }
2805         }
2806         else
2807         {
2808                 dumpComment(fout, labelq->data, NULL, dba,
2809                                         dbCatId, 0, dbDumpId);
2810         }
2811
2812         /* Dump DB security label, if enabled */
2813         if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2814         {
2815                 PGresult   *shres;
2816                 PQExpBuffer seclabelQry;
2817
2818                 seclabelQry = createPQExpBuffer();
2819
2820                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2821                 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2822                 resetPQExpBuffer(seclabelQry);
2823                 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2824                 if (seclabelQry->len > 0)
2825                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2826                                                  labelq->data, NULL, NULL, dba,
2827                                                  false, "SECURITY LABEL", SECTION_NONE,
2828                                                  seclabelQry->data, "", NULL,
2829                                                  &(dbDumpId), 1,
2830                                                  NULL, NULL);
2831                 destroyPQExpBuffer(seclabelQry);
2832                 PQclear(shres);
2833         }
2834
2835         /*
2836          * Dump ACL if any.  Note that we do not support initial privileges
2837          * (pg_init_privs) on databases.
2838          */
2839         dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2840                         qdatname, NULL, labelq->data, NULL,
2841                         dba, datacl, rdatacl, "", "");
2842
2843         /*
2844          * Now construct a DATABASE PROPERTIES archive entry to restore any
2845          * non-default database-level properties.  (The reason this must be
2846          * separate is that we cannot put any additional commands into the TOC
2847          * entry that has CREATE DATABASE.  pg_restore would execute such a group
2848          * in an implicit transaction block, and the backend won't allow CREATE
2849          * DATABASE in that context.)
2850          */
2851         resetPQExpBuffer(creaQry);
2852         resetPQExpBuffer(delQry);
2853
2854         if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2855                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2856                                                   qdatname, datconnlimit);
2857
2858         if (strcmp(datistemplate, "t") == 0)
2859         {
2860                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2861                                                   qdatname);
2862
2863                 /*
2864                  * The backend won't accept DROP DATABASE on a template database.  We
2865                  * can deal with that by removing the template marking before the DROP
2866                  * gets issued.  We'd prefer to use ALTER DATABASE IF EXISTS here, but
2867                  * since no such command is currently supported, fake it with a direct
2868                  * UPDATE on pg_database.
2869                  */
2870                 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2871                                                          "SET datistemplate = false WHERE datname = ");
2872                 appendStringLiteralAH(delQry, datname, fout);
2873                 appendPQExpBufferStr(delQry, ";\n");
2874         }
2875
2876         /* Add database-specific SET options */
2877         dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2878
2879         /*
2880          * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2881          * entry, too, for lack of a better place.
2882          */
2883         if (dopt->binary_upgrade)
2884         {
2885                 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2886                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2887                                                   "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2888                                                   "WHERE datname = ",
2889                                                   frozenxid, minmxid);
2890                 appendStringLiteralAH(creaQry, datname, fout);
2891                 appendPQExpBufferStr(creaQry, ";\n");
2892         }
2893
2894         if (creaQry->len > 0)
2895                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2896                                          datname, NULL, NULL, dba,
2897                                          false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2898                                          creaQry->data, delQry->data, NULL,
2899                                          &(dbDumpId), 1,
2900                                          NULL, NULL);
2901
2902         /*
2903          * pg_largeobject and pg_largeobject_metadata come from the old system
2904          * intact, so set their relfrozenxids and relminmxids.
2905          */
2906         if (dopt->binary_upgrade)
2907         {
2908                 PGresult   *lo_res;
2909                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2910                 PQExpBuffer loOutQry = createPQExpBuffer();
2911                 int                     i_relfrozenxid,
2912                                         i_relminmxid;
2913
2914                 /*
2915                  * pg_largeobject
2916                  */
2917                 if (fout->remoteVersion >= 90300)
2918                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2919                                                           "FROM pg_catalog.pg_class\n"
2920                                                           "WHERE oid = %u;\n",
2921                                                           LargeObjectRelationId);
2922                 else
2923                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2924                                                           "FROM pg_catalog.pg_class\n"
2925                                                           "WHERE oid = %u;\n",
2926                                                           LargeObjectRelationId);
2927
2928                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2929
2930                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2931                 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2932
2933                 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2934                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2935                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2936                                                   "WHERE oid = %u;\n",
2937                                                   atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2938                                                   atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2939                                                   LargeObjectRelationId);
2940                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2941                                          "pg_largeobject", NULL, NULL, "",
2942                                          false, "pg_largeobject", SECTION_PRE_DATA,
2943                                          loOutQry->data, "", NULL,
2944                                          NULL, 0,
2945                                          NULL, NULL);
2946
2947                 PQclear(lo_res);
2948
2949                 /*
2950                  * pg_largeobject_metadata
2951                  */
2952                 if (fout->remoteVersion >= 90000)
2953                 {
2954                         resetPQExpBuffer(loFrozenQry);
2955                         resetPQExpBuffer(loOutQry);
2956
2957                         if (fout->remoteVersion >= 90300)
2958                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2959                                                                   "FROM pg_catalog.pg_class\n"
2960                                                                   "WHERE oid = %u;\n",
2961                                                                   LargeObjectMetadataRelationId);
2962                         else
2963                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2964                                                                   "FROM pg_catalog.pg_class\n"
2965                                                                   "WHERE oid = %u;\n",
2966                                                                   LargeObjectMetadataRelationId);
2967
2968                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2969
2970                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2971                         i_relminmxid = PQfnumber(lo_res, "relminmxid");
2972
2973                         appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2974                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2975                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2976                                                           "WHERE oid = %u;\n",
2977                                                           atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2978                                                           atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2979                                                           LargeObjectMetadataRelationId);
2980                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2981                                                  "pg_largeobject_metadata", NULL, NULL, "",
2982                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2983                                                  loOutQry->data, "", NULL,
2984                                                  NULL, 0,
2985                                                  NULL, NULL);
2986
2987                         PQclear(lo_res);
2988                 }
2989
2990                 destroyPQExpBuffer(loFrozenQry);
2991                 destroyPQExpBuffer(loOutQry);
2992         }
2993
2994         PQclear(res);
2995
2996         free(qdatname);
2997         destroyPQExpBuffer(dbQry);
2998         destroyPQExpBuffer(delQry);
2999         destroyPQExpBuffer(creaQry);
3000         destroyPQExpBuffer(labelq);
3001 }
3002
3003 /*
3004  * Collect any database-specific or role-and-database-specific SET options
3005  * for this database, and append them to outbuf.
3006  */
3007 static void
3008 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
3009                                    const char *dbname, Oid dboid)
3010 {
3011         PGconn     *conn = GetConnection(AH);
3012         PQExpBuffer buf = createPQExpBuffer();
3013         PGresult   *res;
3014         int                     count = 1;
3015
3016         /*
3017          * First collect database-specific options.  Pre-8.4 server versions lack
3018          * unnest(), so we do this the hard way by querying once per subscript.
3019          */
3020         for (;;)
3021         {
3022                 if (AH->remoteVersion >= 90000)
3023                         printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3024                                                           "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3025                                                           count, dboid);
3026                 else
3027                         printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3028
3029                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3030
3031                 if (PQntuples(res) == 1 &&
3032                         !PQgetisnull(res, 0, 0))
3033                 {
3034                         makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3035                                                                    "DATABASE", dbname, NULL, NULL,
3036                                                                    outbuf);
3037                         PQclear(res);
3038                         count++;
3039                 }
3040                 else
3041                 {
3042                         PQclear(res);
3043                         break;
3044                 }
3045         }
3046
3047         /* Now look for role-and-database-specific options */
3048         if (AH->remoteVersion >= 90000)
3049         {
3050                 /* Here we can assume we have unnest() */
3051                 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3052                                                   "FROM pg_db_role_setting s, pg_roles r "
3053                                                   "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3054                                                   dboid);
3055
3056                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3057
3058                 if (PQntuples(res) > 0)
3059                 {
3060                         int                     i;
3061
3062                         for (i = 0; i < PQntuples(res); i++)
3063                                 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3064                                                                            "ROLE", PQgetvalue(res, i, 0),
3065                                                                            "DATABASE", dbname,
3066                                                                            outbuf);
3067                 }
3068
3069                 PQclear(res);
3070         }
3071
3072         destroyPQExpBuffer(buf);
3073 }
3074
3075 /*
3076  * dumpEncoding: put the correct encoding into the archive
3077  */
3078 static void
3079 dumpEncoding(Archive *AH)
3080 {
3081         const char *encname = pg_encoding_to_char(AH->encoding);
3082         PQExpBuffer qry = createPQExpBuffer();
3083
3084         if (g_verbose)
3085                 write_msg(NULL, "saving encoding = %s\n", encname);
3086
3087         appendPQExpBufferStr(qry, "SET client_encoding = ");
3088         appendStringLiteralAH(qry, encname, AH);
3089         appendPQExpBufferStr(qry, ";\n");
3090
3091         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3092                                  "ENCODING", NULL, NULL, "",
3093                                  false, "ENCODING", SECTION_PRE_DATA,
3094                                  qry->data, "", NULL,
3095                                  NULL, 0,
3096                                  NULL, NULL);
3097
3098         destroyPQExpBuffer(qry);
3099 }
3100
3101
3102 /*
3103  * dumpStdStrings: put the correct escape string behavior into the archive
3104  */
3105 static void
3106 dumpStdStrings(Archive *AH)
3107 {
3108         const char *stdstrings = AH->std_strings ? "on" : "off";
3109         PQExpBuffer qry = createPQExpBuffer();
3110
3111         if (g_verbose)
3112                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3113                                   stdstrings);
3114
3115         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3116                                           stdstrings);
3117
3118         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3119                                  "STDSTRINGS", NULL, NULL, "",
3120                                  false, "STDSTRINGS", SECTION_PRE_DATA,
3121                                  qry->data, "", NULL,
3122                                  NULL, 0,
3123                                  NULL, NULL);
3124
3125         destroyPQExpBuffer(qry);
3126 }
3127
3128
3129 /*
3130  * getBlobs:
3131  *      Collect schema-level data about large objects
3132  */
3133 static void
3134 getBlobs(Archive *fout)
3135 {
3136         DumpOptions *dopt = fout->dopt;
3137         PQExpBuffer blobQry = createPQExpBuffer();
3138         BlobInfo   *binfo;
3139         DumpableObject *bdata;
3140         PGresult   *res;
3141         int                     ntups;
3142         int                     i;
3143         int                     i_oid;
3144         int                     i_lomowner;
3145         int                     i_lomacl;
3146         int                     i_rlomacl;
3147         int                     i_initlomacl;
3148         int                     i_initrlomacl;
3149
3150         /* Verbose message */
3151         if (g_verbose)
3152                 write_msg(NULL, "reading large objects\n");
3153
3154         /* Make sure we are in proper schema */
3155         selectSourceSchema(fout, "pg_catalog");
3156
3157         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3158         if (fout->remoteVersion >= 90600)
3159         {
3160                 PQExpBuffer acl_subquery = createPQExpBuffer();
3161                 PQExpBuffer racl_subquery = createPQExpBuffer();
3162                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3163                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3164
3165                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3166                                                 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3167                                                 dopt->binary_upgrade);
3168
3169                 appendPQExpBuffer(blobQry,
3170                                                   "SELECT l.oid, (%s l.lomowner) AS rolname, "
3171                                                   "%s AS lomacl, "
3172                                                   "%s AS rlomacl, "
3173                                                   "%s AS initlomacl, "
3174                                                   "%s AS initrlomacl "
3175                                                   "FROM pg_largeobject_metadata l "
3176                                                   "LEFT JOIN pg_init_privs pip ON "
3177                                                   "(l.oid = pip.objoid "
3178                                                   "AND pip.classoid = 'pg_largeobject'::regclass "
3179                                                   "AND pip.objsubid = 0) ",
3180                                                   username_subquery,
3181                                                   acl_subquery->data,
3182                                                   racl_subquery->data,
3183                                                   init_acl_subquery->data,
3184                                                   init_racl_subquery->data);
3185
3186                 destroyPQExpBuffer(acl_subquery);
3187                 destroyPQExpBuffer(racl_subquery);
3188                 destroyPQExpBuffer(init_acl_subquery);
3189                 destroyPQExpBuffer(init_racl_subquery);
3190         }
3191         else if (fout->remoteVersion >= 90000)
3192                 appendPQExpBuffer(blobQry,
3193                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3194                                                   "NULL AS rlomacl, NULL AS initlomacl, "
3195                                                   "NULL AS initrlomacl "
3196                                                   " FROM pg_largeobject_metadata",
3197                                                   username_subquery);
3198         else
3199                 appendPQExpBufferStr(blobQry,
3200                                                          "SELECT DISTINCT loid AS oid, "
3201                                                          "NULL::name AS rolname, NULL::oid AS lomacl, "
3202                                                          "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3203                                                          "NULL::oid AS initrlomacl "
3204                                                          " FROM pg_largeobject");
3205
3206         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3207
3208         i_oid = PQfnumber(res, "oid");
3209         i_lomowner = PQfnumber(res, "rolname");
3210         i_lomacl = PQfnumber(res, "lomacl");
3211         i_rlomacl = PQfnumber(res, "rlomacl");
3212         i_initlomacl = PQfnumber(res, "initlomacl");
3213         i_initrlomacl = PQfnumber(res, "initrlomacl");
3214
3215         ntups = PQntuples(res);
3216
3217         /*
3218          * Each large object has its own BLOB archive entry.
3219          */
3220         binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3221
3222         for (i = 0; i < ntups; i++)
3223         {
3224                 binfo[i].dobj.objType = DO_BLOB;
3225                 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3226                 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3227                 AssignDumpId(&binfo[i].dobj);
3228
3229                 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3230                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3231                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3232                 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3233                 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3234                 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3235
3236                 if (PQgetisnull(res, i, i_lomacl) &&
3237                         PQgetisnull(res, i, i_rlomacl) &&
3238                         PQgetisnull(res, i, i_initlomacl) &&
3239                         PQgetisnull(res, i, i_initrlomacl))
3240                         binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3241
3242                 /*
3243                  * In binary-upgrade mode for blobs, we do *not* dump out the data or
3244                  * the ACLs, should any exist.  The data and ACL (if any) will be
3245                  * copied by pg_upgrade, which simply copies the pg_largeobject and
3246                  * pg_largeobject_metadata tables.
3247                  *
3248                  * We *do* dump out the definition of the blob because we need that to
3249                  * make the restoration of the comments, and anything else, work since
3250                  * pg_upgrade copies the files behind pg_largeobject and
3251                  * pg_largeobject_metadata after the dump is restored.
3252                  */
3253                 if (dopt->binary_upgrade)
3254                         binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3255         }
3256
3257         /*
3258          * If we have any large objects, a "BLOBS" archive entry is needed. This
3259          * is just a placeholder for sorting; it carries no data now.
3260          */
3261         if (ntups > 0)
3262         {
3263                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3264                 bdata->objType = DO_BLOB_DATA;
3265                 bdata->catId = nilCatalogId;
3266                 AssignDumpId(bdata);
3267                 bdata->name = pg_strdup("BLOBS");
3268         }
3269
3270         PQclear(res);
3271         destroyPQExpBuffer(blobQry);
3272 }
3273
3274 /*
3275  * dumpBlob
3276  *
3277  * dump the definition (metadata) of the given large object
3278  */
3279 static void
3280 dumpBlob(Archive *fout, BlobInfo *binfo)
3281 {
3282         PQExpBuffer cquery = createPQExpBuffer();
3283         PQExpBuffer dquery = createPQExpBuffer();
3284
3285         appendPQExpBuffer(cquery,
3286                                           "SELECT pg_catalog.lo_create('%s');\n",
3287                                           binfo->dobj.name);
3288
3289         appendPQExpBuffer(dquery,
3290                                           "SELECT pg_catalog.lo_unlink('%s');\n",
3291                                           binfo->dobj.name);
3292
3293         if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3294                 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3295                                          binfo->dobj.name,
3296                                          NULL, NULL,
3297                                          binfo->rolname, false,
3298                                          "BLOB", SECTION_PRE_DATA,
3299                                          cquery->data, dquery->data, NULL,
3300                                          NULL, 0,
3301                                          NULL, NULL);
3302
3303         /* set up tag for comment and/or ACL */
3304         resetPQExpBuffer(cquery);
3305         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
3306
3307         /* Dump comment if any */
3308         if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3309                 dumpComment(fout, cquery->data,
3310                                         NULL, binfo->rolname,
3311                                         binfo->dobj.catId, 0, binfo->dobj.dumpId);
3312
3313         /* Dump security label if any */
3314         if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3315                 dumpSecLabel(fout, cquery->data,
3316                                          NULL, binfo->rolname,
3317                                          binfo->dobj.catId, 0, binfo->dobj.dumpId);
3318
3319         /* Dump ACL if any */
3320         if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3321                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3322                                 binfo->dobj.name, NULL, cquery->data,
3323                                 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3324                                 binfo->initblobacl, binfo->initrblobacl);
3325
3326         destroyPQExpBuffer(cquery);
3327         destroyPQExpBuffer(dquery);
3328 }
3329
3330 /*
3331  * dumpBlobs:
3332  *      dump the data contents of all large objects
3333  */
3334 static int
3335 dumpBlobs(Archive *fout, void *arg)
3336 {
3337         const char *blobQry;
3338         const char *blobFetchQry;
3339         PGconn     *conn = GetConnection(fout);
3340         PGresult   *res;
3341         char            buf[LOBBUFSIZE];
3342         int                     ntups;
3343         int                     i;
3344         int                     cnt;
3345
3346         if (g_verbose)
3347                 write_msg(NULL, "saving large objects\n");
3348
3349         /* Make sure we are in proper schema */
3350         selectSourceSchema(fout, "pg_catalog");
3351
3352         /*
3353          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
3354          * the already-in-memory dumpable objects instead...
3355          */
3356         if (fout->remoteVersion >= 90000)
3357                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3358         else
3359                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3360
3361         ExecuteSqlStatement(fout, blobQry);
3362
3363         /* Command to fetch from cursor */
3364         blobFetchQry = "FETCH 1000 IN bloboid";
3365
3366         do
3367         {
3368                 /* Do a fetch */
3369                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3370
3371                 /* Process the tuples, if any */
3372                 ntups = PQntuples(res);
3373                 for (i = 0; i < ntups; i++)
3374                 {
3375                         Oid                     blobOid;
3376                         int                     loFd;
3377
3378                         blobOid = atooid(PQgetvalue(res, i, 0));
3379                         /* Open the BLOB */
3380                         loFd = lo_open(conn, blobOid, INV_READ);
3381                         if (loFd == -1)
3382                                 exit_horribly(NULL, "could not open large object %u: %s",
3383                                                           blobOid, PQerrorMessage(conn));
3384
3385                         StartBlob(fout, blobOid);
3386
3387                         /* Now read it in chunks, sending data to archive */
3388                         do
3389                         {
3390                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3391                                 if (cnt < 0)
3392                                         exit_horribly(NULL, "error reading large object %u: %s",
3393                                                                   blobOid, PQerrorMessage(conn));
3394
3395                                 WriteData(fout, buf, cnt);
3396                         } while (cnt > 0);
3397
3398                         lo_close(conn, loFd);
3399
3400                         EndBlob(fout, blobOid);
3401                 }
3402
3403                 PQclear(res);
3404         } while (ntups > 0);
3405
3406         return 1;
3407 }
3408
3409 /*
3410  * getPolicies
3411  *        get information about policies on a dumpable table.
3412  */
3413 void
3414 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3415 {
3416         PQExpBuffer query;
3417         PGresult   *res;
3418         PolicyInfo *polinfo;
3419         int                     i_oid;
3420         int                     i_tableoid;
3421         int                     i_polname;
3422         int                     i_polcmd;
3423         int                     i_polpermissive;
3424         int                     i_polroles;
3425         int                     i_polqual;
3426         int                     i_polwithcheck;
3427         int                     i,
3428                                 j,
3429                                 ntups;
3430
3431         if (fout->remoteVersion < 90500)
3432                 return;
3433
3434         query = createPQExpBuffer();
3435
3436         for (i = 0; i < numTables; i++)
3437         {
3438                 TableInfo  *tbinfo = &tblinfo[i];
3439
3440                 /* Ignore row security on tables not to be dumped */
3441                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3442                         continue;
3443
3444                 if (g_verbose)
3445                         write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3446                                           tbinfo->dobj.namespace->dobj.name,
3447                                           tbinfo->dobj.name);
3448
3449                 /*
3450                  * Get row security enabled information for the table. We represent
3451                  * RLS enabled on a table by creating PolicyInfo object with an empty
3452                  * policy.
3453                  */
3454                 if (tbinfo->rowsec)
3455                 {
3456                         /*
3457                          * Note: use tableoid 0 so that this object won't be mistaken for
3458                          * something that pg_depend entries apply to.
3459                          */
3460                         polinfo = pg_malloc(sizeof(PolicyInfo));
3461                         polinfo->dobj.objType = DO_POLICY;
3462                         polinfo->dobj.catId.tableoid = 0;
3463                         polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3464                         AssignDumpId(&polinfo->dobj);
3465                         polinfo->dobj.namespace = tbinfo->dobj.namespace;
3466                         polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3467                         polinfo->poltable = tbinfo;
3468                         polinfo->polname = NULL;
3469                         polinfo->polcmd = '\0';
3470                         polinfo->polpermissive = 0;
3471                         polinfo->polroles = NULL;
3472                         polinfo->polqual = NULL;
3473                         polinfo->polwithcheck = NULL;
3474                 }
3475
3476                 if (g_verbose)
3477                         write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3478                                           tbinfo->dobj.namespace->dobj.name,
3479                                           tbinfo->dobj.name);
3480
3481                 /*
3482                  * select table schema to ensure regproc name is qualified if needed
3483                  */
3484                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
3485
3486                 resetPQExpBuffer(query);
3487
3488                 /* Get the policies for the table. */
3489                 if (fout->remoteVersion >= 100000)
3490                         appendPQExpBuffer(query,
3491                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3492                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3493                                                           "   pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3494                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3495                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3496                                                           "FROM pg_catalog.pg_policy pol "
3497                                                           "WHERE polrelid = '%u'",
3498                                                           tbinfo->dobj.catId.oid);
3499                 else
3500                         appendPQExpBuffer(query,
3501                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3502                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3503                                                           "   pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3504                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3505                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3506                                                           "FROM pg_catalog.pg_policy pol "
3507                                                           "WHERE polrelid = '%u'",
3508                                                           tbinfo->dobj.catId.oid);
3509                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3510
3511                 ntups = PQntuples(res);
3512
3513                 if (ntups == 0)
3514                 {
3515                         /*
3516                          * No explicit policies to handle (only the default-deny policy,
3517                          * which is handled as part of the table definition).  Clean up
3518                          * and return.
3519                          */
3520                         PQclear(res);
3521                         continue;
3522                 }
3523
3524                 i_oid = PQfnumber(res, "oid");
3525                 i_tableoid = PQfnumber(res, "tableoid");
3526                 i_polname = PQfnumber(res, "polname");
3527                 i_polcmd = PQfnumber(res, "polcmd");
3528                 i_polpermissive = PQfnumber(res, "polpermissive");
3529                 i_polroles = PQfnumber(res, "polroles");
3530                 i_polqual = PQfnumber(res, "polqual");
3531                 i_polwithcheck = PQfnumber(res, "polwithcheck");
3532
3533                 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3534
3535                 for (j = 0; j < ntups; j++)
3536                 {
3537                         polinfo[j].dobj.objType = DO_POLICY;
3538                         polinfo[j].dobj.catId.tableoid =
3539                                 atooid(PQgetvalue(res, j, i_tableoid));
3540                         polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3541                         AssignDumpId(&polinfo[j].dobj);
3542                         polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3543                         polinfo[j].poltable = tbinfo;
3544                         polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3545                         polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3546
3547                         polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3548                         polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3549
3550                         if (PQgetisnull(res, j, i_polroles))
3551                                 polinfo[j].polroles = NULL;
3552                         else
3553                                 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3554
3555                         if (PQgetisnull(res, j, i_polqual))
3556                                 polinfo[j].polqual = NULL;
3557                         else
3558                                 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3559
3560                         if (PQgetisnull(res, j, i_polwithcheck))
3561                                 polinfo[j].polwithcheck = NULL;
3562                         else
3563                                 polinfo[j].polwithcheck
3564                                         = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3565                 }
3566                 PQclear(res);
3567         }
3568         destroyPQExpBuffer(query);
3569 }
3570
3571 /*
3572  * dumpPolicy
3573  *        dump the definition of the given policy
3574  */
3575 static void
3576 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3577 {
3578         DumpOptions *dopt = fout->dopt;
3579         TableInfo  *tbinfo = polinfo->poltable;
3580         PQExpBuffer query;
3581         PQExpBuffer delqry;
3582         const char *cmd;
3583         char       *tag;
3584
3585         if (dopt->dataOnly)
3586                 return;
3587
3588         /*
3589          * If polname is NULL, then this record is just indicating that ROW LEVEL
3590          * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3591          * ROW LEVEL SECURITY.
3592          */
3593         if (polinfo->polname == NULL)
3594         {
3595                 query = createPQExpBuffer();
3596
3597                 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3598                                                   fmtId(polinfo->dobj.name));
3599
3600                 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3601                         ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3602                                                  polinfo->dobj.name,
3603                                                  polinfo->dobj.namespace->dobj.name,
3604                                                  NULL,
3605                                                  tbinfo->rolname, false,
3606                                                  "ROW SECURITY", SECTION_POST_DATA,
3607                                                  query->data, "", NULL,
3608                                                  NULL, 0,
3609                                                  NULL, NULL);
3610
3611                 destroyPQExpBuffer(query);
3612                 return;
3613         }
3614
3615         if (polinfo->polcmd == '*')
3616                 cmd = "";
3617         else if (polinfo->polcmd == 'r')
3618                 cmd = " FOR SELECT";
3619         else if (polinfo->polcmd == 'a')
3620                 cmd = " FOR INSERT";
3621         else if (polinfo->polcmd == 'w')
3622                 cmd = " FOR UPDATE";
3623         else if (polinfo->polcmd == 'd')
3624                 cmd = " FOR DELETE";
3625         else
3626         {
3627                 write_msg(NULL, "unexpected policy command type: %c\n",
3628                                   polinfo->polcmd);
3629                 exit_nicely(1);
3630         }
3631
3632         query = createPQExpBuffer();
3633         delqry = createPQExpBuffer();
3634
3635         appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3636
3637         appendPQExpBuffer(query, " ON %s%s%s", fmtId(tbinfo->dobj.name),
3638                                           !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3639
3640         if (polinfo->polroles != NULL)
3641                 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3642
3643         if (polinfo->polqual != NULL)
3644                 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3645
3646         if (polinfo->polwithcheck != NULL)
3647                 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3648
3649         appendPQExpBuffer(query, ";\n");
3650
3651         appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3652         appendPQExpBuffer(delqry, " ON %s;\n", fmtId(tbinfo->dobj.name));
3653
3654         tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3655
3656         if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3657                 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3658                                          tag,
3659                                          polinfo->dobj.namespace->dobj.name,
3660                                          NULL,
3661                                          tbinfo->rolname, false,
3662                                          "POLICY", SECTION_POST_DATA,
3663                                          query->data, delqry->data, NULL,
3664                                          NULL, 0,
3665                                          NULL, NULL);
3666
3667         free(tag);
3668         destroyPQExpBuffer(query);
3669         destroyPQExpBuffer(delqry);
3670 }
3671
3672 /*
3673  * getPublications
3674  *        get information about publications
3675  */
3676 void
3677 getPublications(Archive *fout)
3678 {
3679         DumpOptions *dopt = fout->dopt;
3680         PQExpBuffer query;
3681         PGresult   *res;
3682         PublicationInfo *pubinfo;
3683         int                     i_tableoid;
3684         int                     i_oid;
3685         int                     i_pubname;
3686         int                     i_rolname;
3687         int                     i_puballtables;
3688         int                     i_pubinsert;
3689         int                     i_pubupdate;
3690         int                     i_pubdelete;
3691         int                     i,
3692                                 ntups;
3693
3694         if (dopt->no_publications || fout->remoteVersion < 100000)
3695                 return;
3696
3697         query = createPQExpBuffer();
3698
3699         resetPQExpBuffer(query);
3700
3701         /* Make sure we are in proper schema */
3702         selectSourceSchema(fout, "pg_catalog");
3703
3704         /* Get the publications. */
3705         appendPQExpBuffer(query,
3706                                           "SELECT p.tableoid, p.oid, p.pubname, "
3707                                           "(%s p.pubowner) AS rolname, "
3708                                           "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete "
3709                                           "FROM pg_publication p",
3710                                           username_subquery);
3711
3712         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3713
3714         ntups = PQntuples(res);
3715
3716         i_tableoid = PQfnumber(res, "tableoid");
3717         i_oid = PQfnumber(res, "oid");
3718         i_pubname = PQfnumber(res, "pubname");
3719         i_rolname = PQfnumber(res, "rolname");
3720         i_puballtables = PQfnumber(res, "puballtables");
3721         i_pubinsert = PQfnumber(res, "pubinsert");
3722         i_pubupdate = PQfnumber(res, "pubupdate");
3723         i_pubdelete = PQfnumber(res, "pubdelete");
3724
3725         pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3726
3727         for (i = 0; i < ntups; i++)
3728         {
3729                 pubinfo[i].dobj.objType = DO_PUBLICATION;
3730                 pubinfo[i].dobj.catId.tableoid =
3731                         atooid(PQgetvalue(res, i, i_tableoid));
3732                 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3733                 AssignDumpId(&pubinfo[i].dobj);
3734                 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3735                 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3736                 pubinfo[i].puballtables =
3737                         (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3738                 pubinfo[i].pubinsert =
3739                         (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3740                 pubinfo[i].pubupdate =
3741                         (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3742                 pubinfo[i].pubdelete =
3743                         (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3744
3745                 if (strlen(pubinfo[i].rolname) == 0)
3746                         write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3747                                           pubinfo[i].dobj.name);
3748
3749                 /* Decide whether we want to dump it */
3750                 selectDumpableObject(&(pubinfo[i].dobj), fout);
3751         }
3752         PQclear(res);
3753
3754         destroyPQExpBuffer(query);
3755 }
3756
3757 /*
3758  * dumpPublication
3759  *        dump the definition of the given publication
3760  */
3761 static void
3762 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3763 {
3764         PQExpBuffer delq;
3765         PQExpBuffer query;
3766         PQExpBuffer labelq;
3767         bool            first = true;
3768
3769         if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3770                 return;
3771
3772         delq = createPQExpBuffer();
3773         query = createPQExpBuffer();
3774         labelq = createPQExpBuffer();
3775
3776         appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3777                                           fmtId(pubinfo->dobj.name));
3778
3779         appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3780                                           fmtId(pubinfo->dobj.name));
3781
3782         appendPQExpBuffer(labelq, "PUBLICATION %s", fmtId(pubinfo->dobj.name));
3783
3784         if (pubinfo->puballtables)
3785                 appendPQExpBufferStr(query, " FOR ALL TABLES");
3786
3787         appendPQExpBufferStr(query, " WITH (publish = '");
3788         if (pubinfo->pubinsert)
3789         {
3790                 appendPQExpBufferStr(query, "insert");
3791                 first = false;
3792         }
3793
3794         if (pubinfo->pubupdate)
3795         {
3796                 if (!first)
3797                         appendPQExpBufferStr(query, ", ");
3798
3799                 appendPQExpBufferStr(query, "update");
3800                 first = false;
3801         }
3802
3803         if (pubinfo->pubdelete)
3804         {
3805                 if (!first)
3806                         appendPQExpBufferStr(query, ", ");
3807
3808                 appendPQExpBufferStr(query, "delete");
3809                 first = false;
3810         }
3811
3812         appendPQExpBufferStr(query, "');\n");
3813
3814         ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3815                                  pubinfo->dobj.name,
3816                                  NULL,
3817                                  NULL,
3818                                  pubinfo->rolname, false,
3819                                  "PUBLICATION", SECTION_POST_DATA,
3820                                  query->data, delq->data, NULL,
3821                                  NULL, 0,
3822                                  NULL, NULL);
3823
3824         if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3825                 dumpComment(fout, labelq->data,
3826                                         NULL, pubinfo->rolname,
3827                                         pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3828
3829         if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3830                 dumpSecLabel(fout, labelq->data,
3831                                          NULL, pubinfo->rolname,
3832                                          pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3833
3834         destroyPQExpBuffer(delq);
3835         destroyPQExpBuffer(query);
3836 }
3837
3838 /*
3839  * getPublicationTables
3840  *        get information about publication membership for dumpable tables.
3841  */
3842 void
3843 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3844 {
3845         PQExpBuffer query;
3846         PGresult   *res;
3847         PublicationRelInfo *pubrinfo;
3848         int                     i_tableoid;
3849         int                     i_oid;
3850         int                     i_pubname;
3851         int                     i,
3852                                 j,
3853                                 ntups;
3854
3855         if (fout->remoteVersion < 100000)
3856                 return;
3857
3858         query = createPQExpBuffer();
3859
3860         /* Make sure we are in proper schema */
3861         selectSourceSchema(fout, "pg_catalog");
3862
3863         for (i = 0; i < numTables; i++)
3864         {
3865                 TableInfo  *tbinfo = &tblinfo[i];
3866
3867                 /* Only plain tables can be aded to publications. */
3868                 if (tbinfo->relkind != RELKIND_RELATION)
3869                         continue;
3870
3871                 /*
3872                  * Ignore publication membership of tables whose definitions are not
3873                  * to be dumped.
3874                  */
3875                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3876                         continue;
3877
3878                 if (g_verbose)
3879                         write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3880                                           tbinfo->dobj.namespace->dobj.name,
3881                                           tbinfo->dobj.name);
3882
3883                 resetPQExpBuffer(query);
3884
3885                 /* Get the publication membership for the table. */
3886                 appendPQExpBuffer(query,
3887                                                   "SELECT pr.tableoid, pr.oid, p.pubname "
3888                                                   "FROM pg_publication_rel pr, pg_publication p "
3889                                                   "WHERE pr.prrelid = '%u'"
3890                                                   "  AND p.oid = pr.prpubid",
3891                                                   tbinfo->dobj.catId.oid);
3892                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3893
3894                 ntups = PQntuples(res);
3895
3896                 if (ntups == 0)
3897                 {
3898                         /*
3899                          * Table is not member of any publications. Clean up and return.
3900                          */
3901                         PQclear(res);
3902                         continue;
3903                 }
3904
3905                 i_tableoid = PQfnumber(res, "tableoid");
3906                 i_oid = PQfnumber(res, "oid");
3907                 i_pubname = PQfnumber(res, "pubname");
3908
3909                 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3910
3911                 for (j = 0; j < ntups; j++)
3912                 {
3913                         pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3914                         pubrinfo[j].dobj.catId.tableoid =
3915                                 atooid(PQgetvalue(res, j, i_tableoid));
3916                         pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3917                         AssignDumpId(&pubrinfo[j].dobj);
3918                         pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3919                         pubrinfo[j].dobj.name = tbinfo->dobj.name;
3920                         pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3921                         pubrinfo[j].pubtable = tbinfo;
3922
3923                         /* Decide whether we want to dump it */
3924                         selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3925                 }
3926                 PQclear(res);
3927         }
3928         destroyPQExpBuffer(query);
3929 }
3930
3931 /*
3932  * dumpPublicationTable
3933  *        dump the definition of the given publication table mapping
3934  */
3935 static void
3936 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3937 {
3938         TableInfo  *tbinfo = pubrinfo->pubtable;
3939         PQExpBuffer query;
3940         char       *tag;
3941
3942         if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3943                 return;
3944
3945         tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3946
3947         query = createPQExpBuffer();
3948
3949         appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3950                                           fmtId(pubrinfo->pubname));
3951         appendPQExpBuffer(query, " %s;",
3952                                           fmtId(tbinfo->dobj.name));
3953
3954         /*
3955          * There is no point in creating drop query as drop query as the drop is
3956          * done by table drop.
3957          */
3958         ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3959                                  tag,
3960                                  tbinfo->dobj.namespace->dobj.name,
3961                                  NULL,
3962                                  "", false,
3963                                  "PUBLICATION TABLE", SECTION_POST_DATA,
3964                                  query->data, "", NULL,
3965                                  NULL, 0,
3966                                  NULL, NULL);
3967
3968         free(tag);
3969         destroyPQExpBuffer(query);
3970 }
3971
3972 /*
3973  * Is the currently connected user a superuser?
3974  */
3975 static bool
3976 is_superuser(Archive *fout)
3977 {
3978         ArchiveHandle *AH = (ArchiveHandle *) fout;
3979         const char *val;
3980
3981         val = PQparameterStatus(AH->connection, "is_superuser");
3982
3983         if (val && strcmp(val, "on") == 0)
3984                 return true;
3985
3986         return false;
3987 }
3988
3989 /*
3990  * getSubscriptions
3991  *        get information about subscriptions
3992  */
3993 void
3994 getSubscriptions(Archive *fout)
3995 {
3996         DumpOptions *dopt = fout->dopt;
3997         PQExpBuffer query;
3998         PGresult   *res;
3999         SubscriptionInfo *subinfo;
4000         int                     i_tableoid;
4001         int                     i_oid;
4002         int                     i_subname;
4003         int                     i_rolname;
4004         int                     i_subconninfo;
4005         int                     i_subslotname;
4006         int                     i_subsynccommit;
4007         int                     i_subpublications;
4008         int                     i,
4009                                 ntups;
4010
4011         if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4012                 return;
4013
4014         /* Make sure we are in proper schema */
4015         selectSourceSchema(fout, "pg_catalog");
4016
4017         if (!is_superuser(fout))
4018         {
4019                 int                     n;
4020
4021                 res = ExecuteSqlQuery(fout,
4022                                                           "SELECT count(*) FROM pg_subscription "
4023                                                           "WHERE subdbid = (SELECT oid FROM pg_database"
4024                                                           "                 WHERE datname = current_database())",
4025                                                           PGRES_TUPLES_OK);
4026                 n = atoi(PQgetvalue(res, 0, 0));
4027                 if (n > 0)
4028                         write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4029                 PQclear(res);
4030                 return;
4031         }
4032
4033         query = createPQExpBuffer();
4034
4035         resetPQExpBuffer(query);
4036
4037         /* Get the subscriptions in current database. */
4038         appendPQExpBuffer(query,
4039                                           "SELECT s.tableoid, s.oid, s.subname,"
4040                                           "(%s s.subowner) AS rolname, "
4041                                           " s.subconninfo, s.subslotname, s.subsynccommit, "
4042                                           " s.subpublications "
4043                                           "FROM pg_subscription s "
4044                                           "WHERE s.subdbid = (SELECT oid FROM pg_database"
4045                                           "                   WHERE datname = current_database())",
4046                                           username_subquery);
4047         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4048
4049         ntups = PQntuples(res);
4050
4051         i_tableoid = PQfnumber(res, "tableoid");
4052         i_oid = PQfnumber(res, "oid");
4053         i_subname = PQfnumber(res, "subname");
4054         i_rolname = PQfnumber(res, "rolname");
4055         i_subconninfo = PQfnumber(res, "subconninfo");
4056         i_subslotname = PQfnumber(res, "subslotname");
4057         i_subsynccommit = PQfnumber(res, "subsynccommit");
4058         i_subpublications = PQfnumber(res, "subpublications");
4059
4060         subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4061
4062         for (i = 0; i < ntups; i++)
4063         {
4064                 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4065                 subinfo[i].dobj.catId.tableoid =
4066                         atooid(PQgetvalue(res, i, i_tableoid));
4067                 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4068                 AssignDumpId(&subinfo[i].dobj);
4069                 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4070                 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4071                 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4072                 if (PQgetisnull(res, i, i_subslotname))
4073                         subinfo[i].subslotname = NULL;
4074                 else
4075                         subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4076                 subinfo[i].subsynccommit =
4077                         pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4078                 subinfo[i].subpublications =
4079                         pg_strdup(PQgetvalue(res, i, i_subpublications));
4080
4081                 if (strlen(subinfo[i].rolname) == 0)
4082                         write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4083                                           subinfo[i].dobj.name);
4084
4085                 /* Decide whether we want to dump it */
4086                 selectDumpableObject(&(subinfo[i].dobj), fout);
4087         }
4088         PQclear(res);
4089
4090         destroyPQExpBuffer(query);
4091 }
4092
4093 /*
4094  * dumpSubscription
4095  *        dump the definition of the given subscription
4096  */
4097 static void
4098 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4099 {
4100         PQExpBuffer delq;
4101         PQExpBuffer query;
4102         PQExpBuffer labelq;
4103         PQExpBuffer publications;
4104         char      **pubnames = NULL;
4105         int                     npubnames = 0;
4106         int                     i;
4107
4108         if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4109                 return;
4110
4111         delq = createPQExpBuffer();
4112         query = createPQExpBuffer();
4113         labelq = createPQExpBuffer();
4114
4115         appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4116                                           fmtId(subinfo->dobj.name));
4117
4118         appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4119                                           fmtId(subinfo->dobj.name));
4120         appendStringLiteralAH(query, subinfo->subconninfo, fout);
4121
4122         /* Build list of quoted publications and append them to query. */
4123         if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4124         {
4125                 write_msg(NULL,
4126                                   "WARNING: could not parse subpublications array\n");
4127                 if (pubnames)
4128                         free(pubnames);
4129                 pubnames = NULL;
4130                 npubnames = 0;
4131         }
4132
4133         publications = createPQExpBuffer();
4134         for (i = 0; i < npubnames; i++)
4135         {
4136                 if (i > 0)
4137                         appendPQExpBufferStr(publications, ", ");
4138
4139                 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4140         }
4141
4142         appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4143         if (subinfo->subslotname)
4144                 appendStringLiteralAH(query, subinfo->subslotname, fout);
4145         else
4146                 appendPQExpBufferStr(query, "NONE");
4147
4148         if (strcmp(subinfo->subsynccommit, "off") != 0)
4149                 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4150
4151         appendPQExpBufferStr(query, ");\n");
4152
4153         appendPQExpBuffer(labelq, "SUBSCRIPTION %s", fmtId(subinfo->dobj.name));
4154
4155         ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4156                                  subinfo->dobj.name,
4157                                  NULL,
4158                                  NULL,
4159                                  subinfo->rolname, false,
4160                                  "SUBSCRIPTION", SECTION_POST_DATA,
4161                                  query->data, delq->data, NULL,
4162                                  NULL, 0,
4163                                  NULL, NULL);
4164
4165         if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4166                 dumpComment(fout, labelq->data,
4167                                         NULL, subinfo->rolname,
4168                                         subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4169
4170         if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4171                 dumpSecLabel(fout, labelq->data,
4172                                          NULL, subinfo->rolname,
4173                                          subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4174
4175         destroyPQExpBuffer(publications);
4176         if (pubnames)
4177                 free(pubnames);
4178
4179         destroyPQExpBuffer(delq);
4180         destroyPQExpBuffer(query);
4181 }
4182
4183 static void
4184 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4185                                                                                  PQExpBuffer upgrade_buffer,
4186                                                                                  Oid pg_type_oid,
4187                                                                                  bool force_array_type)
4188 {
4189         PQExpBuffer upgrade_query = createPQExpBuffer();
4190         PGresult   *res;
4191         Oid                     pg_type_array_oid;
4192
4193         appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4194         appendPQExpBuffer(upgrade_buffer,
4195                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4196                                           pg_type_oid);
4197
4198         /* we only support old >= 8.3 for binary upgrades */
4199         appendPQExpBuffer(upgrade_query,
4200                                           "SELECT typarray "
4201                                           "FROM pg_catalog.pg_type "
4202                                           "WHERE oid = '%u'::pg_catalog.oid;",
4203                                           pg_type_oid);
4204
4205         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4206
4207         pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4208
4209         PQclear(res);
4210
4211         if (!OidIsValid(pg_type_array_oid) && force_array_type)
4212         {
4213                 /*
4214                  * If the old version didn't assign an array type, but the new version
4215                  * does, we must select an unused type OID to assign.  This currently
4216                  * only happens for domains, when upgrading pre-v11 to v11 and up.
4217                  *
4218                  * Note: local state here is kind of ugly, but we must have some,
4219                  * since we mustn't choose the same unused OID more than once.
4220                  */
4221                 static Oid      next_possible_free_oid = FirstNormalObjectId;
4222                 bool            is_dup;
4223
4224                 do
4225                 {
4226                         ++next_possible_free_oid;
4227                         printfPQExpBuffer(upgrade_query,
4228                                                           "SELECT EXISTS(SELECT 1 "
4229                                                           "FROM pg_catalog.pg_type "
4230                                                           "WHERE oid = '%u'::pg_catalog.oid);",
4231                                                           next_possible_free_oid);
4232                         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4233                         is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4234                         PQclear(res);
4235                 } while (is_dup);
4236
4237                 pg_type_array_oid = next_possible_free_oid;
4238         }
4239
4240         if (OidIsValid(pg_type_array_oid))
4241         {
4242                 appendPQExpBufferStr(upgrade_buffer,
4243                                                          "\n-- For binary upgrade, must preserve pg_type array oid\n");
4244                 appendPQExpBuffer(upgrade_buffer,
4245                                                   "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4246                                                   pg_type_array_oid);
4247         }
4248
4249         destroyPQExpBuffer(upgrade_query);
4250 }
4251
4252 static bool
4253 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4254                                                                                 PQExpBuffer upgrade_buffer,
4255                                                                                 Oid pg_rel_oid)
4256 {
4257         PQExpBuffer upgrade_query = createPQExpBuffer();
4258         PGresult   *upgrade_res;
4259         Oid                     pg_type_oid;
4260         bool            toast_set = false;
4261
4262         /* we only support old >= 8.3 for binary upgrades */
4263         appendPQExpBuffer(upgrade_query,
4264                                           "SELECT c.reltype AS crel, t.reltype AS trel "
4265                                           "FROM pg_catalog.pg_class c "
4266                                           "LEFT JOIN pg_catalog.pg_class t ON "
4267                                           "  (c.reltoastrelid = t.oid) "
4268                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4269                                           pg_rel_oid);
4270
4271         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4272
4273         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4274
4275         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4276                                                                                          pg_type_oid, false);
4277
4278         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4279         {
4280                 /* Toast tables do not have pg_type array rows */
4281                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4282                                                                                                                   PQfnumber(upgrade_res, "trel")));
4283
4284                 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4285                 appendPQExpBuffer(upgrade_buffer,
4286                                                   "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4287                                                   pg_type_toast_oid);
4288
4289                 toast_set = true;
4290         }
4291
4292         PQclear(upgrade_res);
4293         destroyPQExpBuffer(upgrade_query);
4294
4295         return toast_set;
4296 }
4297
4298 static void
4299 binary_upgrade_set_pg_class_oids(Archive *fout,
4300                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4301                                                                  bool is_index)
4302 {
4303         PQExpBuffer upgrade_query = createPQExpBuffer();
4304         PGresult   *upgrade_res;
4305         Oid                     pg_class_reltoastrelid;
4306         Oid                     pg_index_indexrelid;
4307
4308         appendPQExpBuffer(upgrade_query,
4309                                           "SELECT c.reltoastrelid, i.indexrelid "
4310                                           "FROM pg_catalog.pg_class c LEFT JOIN "
4311                                           "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4312                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4313                                           pg_class_oid);
4314
4315         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4316
4317         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4318         pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4319
4320         appendPQExpBufferStr(upgrade_buffer,
4321                                                  "\n-- For binary upgrade, must preserve pg_class oids\n");
4322
4323         if (!is_index)
4324         {
4325                 appendPQExpBuffer(upgrade_buffer,
4326                                                   "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4327                                                   pg_class_oid);
4328                 /* only tables have toast tables, not indexes */
4329                 if (OidIsValid(pg_class_reltoastrelid))
4330                 {
4331                         /*
4332                          * One complexity is that the table definition might not require
4333                          * the creation of a TOAST table, and the TOAST table might have
4334                          * been created long after table creation, when the table was
4335                          * loaded with wide data.  By setting the TOAST oid we force
4336                          * creation of the TOAST heap and TOAST index by the backend so we
4337                          * can cleanly copy the files during binary upgrade.
4338                          */
4339
4340                         appendPQExpBuffer(upgrade_buffer,
4341                                                           "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4342                                                           pg_class_reltoastrelid);
4343
4344                         /* every toast table has an index */
4345                         appendPQExpBuffer(upgrade_buffer,
4346                                                           "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4347                                                           pg_index_indexrelid);
4348                 }
4349         }
4350         else
4351                 appendPQExpBuffer(upgrade_buffer,
4352                                                   "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4353                                                   pg_class_oid);
4354
4355         appendPQExpBufferChar(upgrade_buffer, '\n');
4356
4357         PQclear(upgrade_res);
4358         destroyPQExpBuffer(upgrade_query);
4359 }
4360
4361 /*
4362  * If the DumpableObject is a member of an extension, add a suitable
4363  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4364  */
4365 static void
4366 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4367                                                                 DumpableObject *dobj,
4368                                                                 const char *objlabel)
4369 {
4370         DumpableObject *extobj = NULL;
4371         int                     i;
4372
4373         if (!dobj->ext_member)
4374                 return;
4375
4376         /*
4377          * Find the parent extension.  We could avoid this search if we wanted to
4378          * add a link field to DumpableObject, but the space costs of that would
4379          * be considerable.  We assume that member objects could only have a
4380          * direct dependency on their own extension, not any others.
4381          */
4382         for (i = 0; i < dobj->nDeps; i++)
4383         {
4384                 extobj = findObjectByDumpId(dobj->dependencies[i]);
4385                 if (extobj && extobj->objType == DO_EXTENSION)
4386                         break;
4387                 extobj = NULL;
4388         }
4389         if (extobj == NULL)
4390                 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
4391
4392         appendPQExpBufferStr(upgrade_buffer,
4393                                                  "\n-- For binary upgrade, handle extension membership the hard way\n");
4394         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
4395                                           fmtId(extobj->name),
4396                                           objlabel);
4397 }
4398
4399 /*
4400  * getNamespaces:
4401  *        read all namespaces in the system catalogs and return them in the
4402  * NamespaceInfo* structure
4403  *
4404  *      numNamespaces is set to the number of namespaces read in
4405  */
4406 NamespaceInfo *
4407 getNamespaces(Archive *fout, int *numNamespaces)
4408 {
4409         DumpOptions *dopt = fout->dopt;
4410         PGresult   *res;
4411         int                     ntups;
4412         int                     i;
4413         PQExpBuffer query;
4414         NamespaceInfo *nsinfo;
4415         int                     i_tableoid;
4416         int                     i_oid;
4417         int                     i_nspname;
4418         int                     i_rolname;
4419         int                     i_nspacl;
4420         int                     i_rnspacl;
4421         int                     i_initnspacl;
4422         int                     i_initrnspacl;
4423
4424         query = createPQExpBuffer();
4425
4426         /* Make sure we are in proper schema */
4427         selectSourceSchema(fout, "pg_catalog");
4428
4429         /*
4430          * we fetch all namespaces including system ones, so that every object we
4431          * read in can be linked to a containing namespace.
4432          */
4433         if (fout->remoteVersion >= 90600)
4434         {
4435                 PQExpBuffer acl_subquery = createPQExpBuffer();
4436                 PQExpBuffer racl_subquery = createPQExpBuffer();
4437                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4438                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4439
4440                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4441                                                 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4442                                                 dopt->binary_upgrade);
4443
4444                 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4445                                                   "(%s nspowner) AS rolname, "
4446                                                   "%s as nspacl, "
4447                                                   "%s as rnspacl, "
4448                                                   "%s as initnspacl, "
4449                                                   "%s as initrnspacl "
4450                                                   "FROM pg_namespace n "
4451                                                   "LEFT JOIN pg_init_privs pip "
4452                                                   "ON (n.oid = pip.objoid "
4453                                                   "AND pip.classoid = 'pg_namespace'::regclass "
4454                                                   "AND pip.objsubid = 0",
4455                                                   username_subquery,
4456                                                   acl_subquery->data,
4457                                                   racl_subquery->data,
4458                                                   init_acl_subquery->data,
4459                                                   init_racl_subquery->data);
4460
4461                 appendPQExpBuffer(query, ") ");
4462
4463                 destroyPQExpBuffer(acl_subquery);
4464                 destroyPQExpBuffer(racl_subquery);
4465                 destroyPQExpBuffer(init_acl_subquery);
4466                 destroyPQExpBuffer(init_racl_subquery);
4467         }
4468         else
4469                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4470                                                   "(%s nspowner) AS rolname, "
4471                                                   "nspacl, NULL as rnspacl, "
4472                                                   "NULL AS initnspacl, NULL as initrnspacl "
4473                                                   "FROM pg_namespace",
4474                                                   username_subquery);
4475
4476         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4477
4478         ntups = PQntuples(res);
4479
4480         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4481
4482         i_tableoid = PQfnumber(res, "tableoid");
4483         i_oid = PQfnumber(res, "oid");
4484         i_nspname = PQfnumber(res, "nspname");
4485         i_rolname = PQfnumber(res, "rolname");
4486         i_nspacl = PQfnumber(res, "nspacl");
4487         i_rnspacl = PQfnumber(res, "rnspacl");
4488         i_initnspacl = PQfnumber(res, "initnspacl");
4489         i_initrnspacl = PQfnumber(res, "initrnspacl");
4490
4491         for (i = 0; i < ntups; i++)
4492         {
4493                 nsinfo[i].dobj.objType = DO_NAMESPACE;
4494                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4495                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4496                 AssignDumpId(&nsinfo[i].dobj);
4497                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4498                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4499                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4500                 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4501                 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4502                 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4503
4504                 /* Decide whether to dump this namespace */
4505                 selectDumpableNamespace(&nsinfo[i], fout);
4506
4507                 /*
4508                  * Do not try to dump ACL if the ACL is empty or the default.
4509                  *
4510                  * This is useful because, for some schemas/objects, the only
4511                  * component we are going to try and dump is the ACL and if we can
4512                  * remove that then 'dump' goes to zero/false and we don't consider
4513                  * this object for dumping at all later on.
4514                  */
4515                 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4516                         PQgetisnull(res, i, i_initnspacl) &&
4517                         PQgetisnull(res, i, i_initrnspacl))
4518                         nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4519
4520                 if (strlen(nsinfo[i].rolname) == 0)
4521                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4522                                           nsinfo[i].dobj.name);
4523         }
4524
4525         PQclear(res);
4526         destroyPQExpBuffer(query);
4527
4528         *numNamespaces = ntups;
4529
4530         return nsinfo;
4531 }
4532
4533 /*
4534  * findNamespace:
4535  *              given a namespace OID, look up the info read by getNamespaces
4536  */
4537 static NamespaceInfo *
4538 findNamespace(Archive *fout, Oid nsoid)
4539 {
4540         NamespaceInfo *nsinfo;
4541
4542         nsinfo = findNamespaceByOid(nsoid);
4543         if (nsinfo == NULL)
4544                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4545         return nsinfo;
4546 }
4547
4548 /*
4549  * getExtensions:
4550  *        read all extensions in the system catalogs and return them in the
4551  * ExtensionInfo* structure
4552  *
4553  *      numExtensions is set to the number of extensions read in
4554  */
4555 ExtensionInfo *
4556 getExtensions(Archive *fout, int *numExtensions)
4557 {
4558         DumpOptions *dopt = fout->dopt;
4559         PGresult   *res;
4560         int                     ntups;
4561         int                     i;
4562         PQExpBuffer query;
4563         ExtensionInfo *extinfo;
4564         int                     i_tableoid;
4565         int                     i_oid;
4566         int                     i_extname;
4567         int                     i_nspname;
4568         int                     i_extrelocatable;
4569         int                     i_extversion;
4570         int                     i_extconfig;
4571         int                     i_extcondition;
4572
4573         /*
4574          * Before 9.1, there are no extensions.
4575          */
4576         if (fout->remoteVersion < 90100)
4577         {
4578                 *numExtensions = 0;
4579                 return NULL;
4580         }
4581
4582         query = createPQExpBuffer();
4583
4584         /* Make sure we are in proper schema */
4585         selectSourceSchema(fout, "pg_catalog");
4586
4587         appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4588                                                  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4589                                                  "FROM pg_extension x "
4590                                                  "JOIN pg_namespace n ON n.oid = x.extnamespace");
4591
4592         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4593
4594         ntups = PQntuples(res);
4595
4596         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4597
4598         i_tableoid = PQfnumber(res, "tableoid");
4599         i_oid = PQfnumber(res, "oid");
4600         i_extname = PQfnumber(res, "extname");
4601         i_nspname = PQfnumber(res, "nspname");
4602         i_extrelocatable = PQfnumber(res, "extrelocatable");
4603         i_extversion = PQfnumber(res, "extversion");
4604         i_extconfig = PQfnumber(res, "extconfig");
4605         i_extcondition = PQfnumber(res, "extcondition");
4606
4607         for (i = 0; i < ntups; i++)
4608         {
4609                 extinfo[i].dobj.objType = DO_EXTENSION;
4610                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4611                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4612                 AssignDumpId(&extinfo[i].dobj);
4613                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4614                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4615                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4616                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4617                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4618                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4619
4620                 /* Decide whether we want to dump it */
4621                 selectDumpableExtension(&(extinfo[i]), dopt);
4622         }
4623
4624         PQclear(res);
4625         destroyPQExpBuffer(query);
4626
4627         *numExtensions = ntups;
4628
4629         return extinfo;
4630 }
4631
4632 /*
4633  * getTypes:
4634  *        read all types in the system catalogs and return them in the
4635  * TypeInfo* structure
4636  *
4637  *      numTypes is set to the number of types read in
4638  *
4639  * NB: this must run after getFuncs() because we assume we can do
4640  * findFuncByOid().
4641  */
4642 TypeInfo *
4643 getTypes(Archive *fout, int *numTypes)
4644 {
4645         DumpOptions *dopt = fout->dopt;
4646         PGresult   *res;
4647         int                     ntups;
4648         int                     i;
4649         PQExpBuffer query = createPQExpBuffer();
4650         TypeInfo   *tyinfo;
4651         ShellTypeInfo *stinfo;
4652         int                     i_tableoid;
4653         int                     i_oid;
4654         int                     i_typname;
4655         int                     i_typnamespace;
4656         int                     i_typacl;
4657         int                     i_rtypacl;
4658         int                     i_inittypacl;
4659         int                     i_initrtypacl;
4660         int                     i_rolname;
4661         int                     i_typelem;
4662         int                     i_typrelid;
4663         int                     i_typrelkind;
4664         int                     i_typtype;
4665         int                     i_typisdefined;
4666         int                     i_isarray;
4667
4668         /*
4669          * we include even the built-in types because those may be used as array
4670          * elements by user-defined types
4671          *
4672          * we filter out the built-in types when we dump out the types
4673          *
4674          * same approach for undefined (shell) types and array types
4675          *
4676          * Note: as of 8.3 we can reliably detect whether a type is an
4677          * auto-generated array type by checking the element type's typarray.
4678          * (Before that the test is capable of generating false positives.) We
4679          * still check for name beginning with '_', though, so as to avoid the
4680          * cost of the subselect probe for all standard types.  This would have to
4681          * be revisited if the backend ever allows renaming of array types.
4682          */
4683
4684         /* Make sure we are in proper schema */
4685         selectSourceSchema(fout, "pg_catalog");
4686
4687         if (fout->remoteVersion >= 90600)
4688         {
4689                 PQExpBuffer acl_subquery = createPQExpBuffer();
4690                 PQExpBuffer racl_subquery = createPQExpBuffer();
4691                 PQExpBuffer initacl_subquery = createPQExpBuffer();
4692                 PQExpBuffer initracl_subquery = createPQExpBuffer();
4693
4694                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4695                                                 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4696                                                 dopt->binary_upgrade);
4697
4698                 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4699                                                   "t.typnamespace, "
4700                                                   "%s AS typacl, "
4701                                                   "%s AS rtypacl, "
4702                                                   "%s AS inittypacl, "
4703                                                   "%s AS initrtypacl, "
4704                                                   "(%s t.typowner) AS rolname, "
4705                                                   "t.typelem, t.typrelid, "
4706                                                   "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4707                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4708                                                   "t.typtype, t.typisdefined, "
4709                                                   "t.typname[0] = '_' AND t.typelem != 0 AND "
4710                                                   "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4711                                                   "FROM pg_type t "
4712                                                   "LEFT JOIN pg_init_privs pip ON "
4713                                                   "(t.oid = pip.objoid "
4714                                                   "AND pip.classoid = 'pg_type'::regclass "
4715                                                   "AND pip.objsubid = 0) ",
4716                                                   acl_subquery->data,
4717                                                   racl_subquery->data,
4718                                                   initacl_subquery->data,
4719                                                   initracl_subquery->data,
4720                                                   username_subquery);
4721
4722                 destroyPQExpBuffer(acl_subquery);
4723                 destroyPQExpBuffer(racl_subquery);
4724                 destroyPQExpBuffer(initacl_subquery);
4725                 destroyPQExpBuffer(initracl_subquery);
4726         }
4727         else if (fout->remoteVersion >= 90200)
4728         {
4729                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4730                                                   "typnamespace, typacl, NULL as rtypacl, "
4731                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4732                                                   "(%s typowner) AS rolname, "
4733                                                   "typelem, typrelid, "
4734                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4735                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4736                                                   "typtype, typisdefined, "
4737                                                   "typname[0] = '_' AND typelem != 0 AND "
4738                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4739                                                   "FROM pg_type",
4740                                                   username_subquery);
4741         }
4742         else if (fout->remoteVersion >= 80300)
4743         {
4744                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4745                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4746                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4747                                                   "(%s typowner) AS rolname, "
4748                                                   "typelem, typrelid, "
4749                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4750                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4751                                                   "typtype, typisdefined, "
4752                                                   "typname[0] = '_' AND typelem != 0 AND "
4753                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4754                                                   "FROM pg_type",
4755                                                   username_subquery);
4756         }
4757         else
4758         {
4759                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4760                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4761                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4762                                                   "(%s typowner) AS rolname, "
4763                                                   "typelem, typrelid, "
4764                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4765                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4766                                                   "typtype, typisdefined, "
4767                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
4768                                                   "FROM pg_type",
4769                                                   username_subquery);
4770         }
4771
4772         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4773
4774         ntups = PQntuples(res);
4775
4776         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4777
4778         i_tableoid = PQfnumber(res, "tableoid");
4779         i_oid = PQfnumber(res, "oid");
4780         i_typname = PQfnumber(res, "typname");
4781         i_typnamespace = PQfnumber(res, "typnamespace");
4782         i_typacl = PQfnumber(res, "typacl");
4783         i_rtypacl = PQfnumber(res, "rtypacl");
4784         i_inittypacl = PQfnumber(res, "inittypacl");
4785         i_initrtypacl = PQfnumber(res, "initrtypacl");
4786         i_rolname = PQfnumber(res, "rolname");
4787         i_typelem = PQfnumber(res, "typelem");
4788         i_typrelid = PQfnumber(res, "typrelid");
4789         i_typrelkind = PQfnumber(res, "typrelkind");
4790         i_typtype = PQfnumber(res, "typtype");
4791         i_typisdefined = PQfnumber(res, "typisdefined");
4792         i_isarray = PQfnumber(res, "isarray");
4793
4794         for (i = 0; i < ntups; i++)
4795         {
4796                 tyinfo[i].dobj.objType = DO_TYPE;
4797                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4798                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4799                 AssignDumpId(&tyinfo[i].dobj);
4800                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4801                 tyinfo[i].dobj.namespace =
4802                         findNamespace(fout,
4803                                                   atooid(PQgetvalue(res, i, i_typnamespace)));
4804                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4805                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4806                 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4807                 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4808                 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4809                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4810                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4811                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4812                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4813                 tyinfo[i].shellType = NULL;
4814
4815                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4816                         tyinfo[i].isDefined = true;
4817                 else
4818                         tyinfo[i].isDefined = false;
4819
4820                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4821                         tyinfo[i].isArray = true;
4822                 else
4823                         tyinfo[i].isArray = false;
4824
4825                 /* Decide whether we want to dump it */
4826                 selectDumpableType(&tyinfo[i], fout);
4827
4828                 /* Do not try to dump ACL if no ACL exists. */
4829                 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4830                         PQgetisnull(res, i, i_inittypacl) &&
4831                         PQgetisnull(res, i, i_initrtypacl))
4832                         tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4833
4834                 /*
4835                  * If it's a domain, fetch info about its constraints, if any
4836                  */
4837                 tyinfo[i].nDomChecks = 0;
4838                 tyinfo[i].domChecks = NULL;
4839                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4840                         tyinfo[i].typtype == TYPTYPE_DOMAIN)
4841                         getDomainConstraints(fout, &(tyinfo[i]));
4842
4843                 /*
4844                  * If it's a base type, make a DumpableObject representing a shell
4845                  * definition of the type.  We will need to dump that ahead of the I/O
4846                  * functions for the type.  Similarly, range types need a shell
4847                  * definition in case they have a canonicalize function.
4848                  *
4849                  * Note: the shell type doesn't have a catId.  You might think it
4850                  * should copy the base type's catId, but then it might capture the
4851                  * pg_depend entries for the type, which we don't want.
4852                  */
4853                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4854                         (tyinfo[i].typtype == TYPTYPE_BASE ||
4855                          tyinfo[i].typtype == TYPTYPE_RANGE))
4856                 {
4857                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4858                         stinfo->dobj.objType = DO_SHELL_TYPE;
4859                         stinfo->dobj.catId = nilCatalogId;
4860                         AssignDumpId(&stinfo->dobj);
4861                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4862                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4863                         stinfo->baseType = &(tyinfo[i]);
4864                         tyinfo[i].shellType = stinfo;
4865
4866                         /*
4867                          * Initially mark the shell type as not to be dumped.  We'll only
4868                          * dump it if the I/O or canonicalize functions need to be dumped;
4869                          * this is taken care of while sorting dependencies.
4870                          */
4871                         stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4872                 }
4873
4874                 if (strlen(tyinfo[i].rolname) == 0)
4875                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4876                                           tyinfo[i].dobj.name);
4877         }
4878
4879         *numTypes = ntups;
4880
4881         PQclear(res);
4882
4883         destroyPQExpBuffer(query);
4884
4885         return tyinfo;
4886 }
4887
4888 /*
4889  * getOperators:
4890  *        read all operators in the system catalogs and return them in the
4891  * OprInfo* structure
4892  *
4893  *      numOprs is set to the number of operators read in
4894  */
4895 OprInfo *
4896 getOperators(Archive *fout, int *numOprs)
4897 {
4898         PGresult   *res;
4899         int                     ntups;
4900         int                     i;
4901         PQExpBuffer query = createPQExpBuffer();
4902         OprInfo    *oprinfo;
4903         int                     i_tableoid;
4904         int                     i_oid;
4905         int                     i_oprname;
4906         int                     i_oprnamespace;
4907         int                     i_rolname;
4908         int                     i_oprkind;
4909         int                     i_oprcode;
4910
4911         /*
4912          * find all operators, including builtin operators; we filter out
4913          * system-defined operators at dump-out time.
4914          */
4915
4916         /* Make sure we are in proper schema */
4917         selectSourceSchema(fout, "pg_catalog");
4918
4919         appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4920                                           "oprnamespace, "
4921                                           "(%s oprowner) AS rolname, "
4922                                           "oprkind, "
4923                                           "oprcode::oid AS oprcode "
4924                                           "FROM pg_operator",
4925                                           username_subquery);
4926
4927         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4928
4929         ntups = PQntuples(res);
4930         *numOprs = ntups;
4931
4932         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4933
4934         i_tableoid = PQfnumber(res, "tableoid");
4935         i_oid = PQfnumber(res, "oid");
4936         i_oprname = PQfnumber(res, "oprname");
4937         i_oprnamespace = PQfnumber(res, "oprnamespace");
4938         i_rolname = PQfnumber(res, "rolname");
4939         i_oprkind = PQfnumber(res, "oprkind");
4940         i_oprcode = PQfnumber(res, "oprcode");
4941
4942         for (i = 0; i < ntups; i++)
4943         {
4944                 oprinfo[i].dobj.objType = DO_OPERATOR;
4945                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4946                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4947                 AssignDumpId(&oprinfo[i].dobj);
4948                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4949                 oprinfo[i].dobj.namespace =
4950                         findNamespace(fout,
4951                                                   atooid(PQgetvalue(res, i, i_oprnamespace)));
4952                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4953                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4954                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4955
4956                 /* Decide whether we want to dump it */
4957                 selectDumpableObject(&(oprinfo[i].dobj), fout);
4958
4959                 /* Operators do not currently have ACLs. */
4960                 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4961
4962                 if (strlen(oprinfo[i].rolname) == 0)
4963                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4964                                           oprinfo[i].dobj.name);
4965         }
4966
4967         PQclear(res);
4968
4969         destroyPQExpBuffer(query);
4970
4971         return oprinfo;
4972 }
4973
4974 /*
4975  * getCollations:
4976  *        read all collations in the system catalogs and return them in the
4977  * CollInfo* structure
4978  *
4979  *      numCollations is set to the number of collations read in
4980  */
4981 CollInfo *
4982 getCollations(Archive *fout, int *numCollations)
4983 {
4984         PGresult   *res;
4985         int                     ntups;
4986         int                     i;
4987         PQExpBuffer query;
4988         CollInfo   *collinfo;
4989         int                     i_tableoid;
4990         int                     i_oid;
4991         int                     i_collname;
4992         int                     i_collnamespace;
4993         int                     i_rolname;
4994
4995         /* Collations didn't exist pre-9.1 */
4996         if (fout->remoteVersion < 90100)
4997         {
4998                 *numCollations = 0;
4999                 return NULL;
5000         }
5001
5002         query = createPQExpBuffer();
5003
5004         /*
5005          * find all collations, including builtin collations; we filter out
5006          * system-defined collations at dump-out time.
5007          */
5008
5009         /* Make sure we are in proper schema */
5010         selectSourceSchema(fout, "pg_catalog");
5011
5012         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5013                                           "collnamespace, "
5014                                           "(%s collowner) AS rolname "
5015                                           "FROM pg_collation",
5016                                           username_subquery);
5017
5018         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5019
5020         ntups = PQntuples(res);
5021         *numCollations = ntups;
5022
5023         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5024
5025         i_tableoid = PQfnumber(res, "tableoid");
5026         i_oid = PQfnumber(res, "oid");
5027         i_collname = PQfnumber(res, "collname");
5028         i_collnamespace = PQfnumber(res, "collnamespace");
5029         i_rolname = PQfnumber(res, "rolname");
5030
5031         for (i = 0; i < ntups; i++)
5032         {
5033                 collinfo[i].dobj.objType = DO_COLLATION;
5034                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5035                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5036                 AssignDumpId(&collinfo[i].dobj);
5037                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5038                 collinfo[i].dobj.namespace =
5039                         findNamespace(fout,
5040                                                   atooid(PQgetvalue(res, i, i_collnamespace)));
5041                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5042
5043                 /* Decide whether we want to dump it */
5044                 selectDumpableObject(&(collinfo[i].dobj), fout);
5045
5046                 /* Collations do not currently have ACLs. */
5047                 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5048         }
5049
5050         PQclear(res);
5051
5052         destroyPQExpBuffer(query);
5053
5054         return collinfo;
5055 }
5056
5057 /*
5058  * getConversions:
5059  *        read all conversions in the system catalogs and return them in the
5060  * ConvInfo* structure
5061  *
5062  *      numConversions is set to the number of conversions read in
5063  */
5064 ConvInfo *
5065 getConversions(Archive *fout, int *numConversions)
5066 {
5067         PGresult   *res;
5068         int                     ntups;
5069         int                     i;
5070         PQExpBuffer query;
5071         ConvInfo   *convinfo;
5072         int                     i_tableoid;
5073         int                     i_oid;
5074         int                     i_conname;
5075         int                     i_connamespace;
5076         int                     i_rolname;
5077
5078         query = createPQExpBuffer();
5079
5080         /*
5081          * find all conversions, including builtin conversions; we filter out
5082          * system-defined conversions at dump-out time.
5083          */
5084
5085         /* Make sure we are in proper schema */
5086         selectSourceSchema(fout, "pg_catalog");
5087
5088         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5089                                           "connamespace, "
5090                                           "(%s conowner) AS rolname "
5091                                           "FROM pg_conversion",
5092                                           username_subquery);
5093
5094         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5095
5096         ntups = PQntuples(res);
5097         *numConversions = ntups;
5098
5099         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5100
5101         i_tableoid = PQfnumber(res, "tableoid");
5102         i_oid = PQfnumber(res, "oid");
5103         i_conname = PQfnumber(res, "conname");
5104         i_connamespace = PQfnumber(res, "connamespace");
5105         i_rolname = PQfnumber(res, "rolname");
5106
5107         for (i = 0; i < ntups; i++)
5108         {
5109                 convinfo[i].dobj.objType = DO_CONVERSION;
5110                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5111                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5112                 AssignDumpId(&convinfo[i].dobj);
5113                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5114                 convinfo[i].dobj.namespace =
5115                         findNamespace(fout,
5116                                                   atooid(PQgetvalue(res, i, i_connamespace)));
5117                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5118
5119                 /* Decide whether we want to dump it */
5120                 selectDumpableObject(&(convinfo[i].dobj), fout);
5121
5122                 /* Conversions do not currently have ACLs. */
5123                 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5124         }
5125
5126         PQclear(res);
5127
5128         destroyPQExpBuffer(query);
5129
5130         return convinfo;
5131 }
5132
5133 /*
5134  * getAccessMethods:
5135  *        read all user-defined access methods in the system catalogs and return
5136  *        them in the AccessMethodInfo* structure
5137  *
5138  *      numAccessMethods is set to the number of access methods read in
5139  */
5140 AccessMethodInfo *
5141 getAccessMethods(Archive *fout, int *numAccessMethods)
5142 {
5143         PGresult   *res;
5144         int                     ntups;
5145         int                     i;
5146         PQExpBuffer query;
5147         AccessMethodInfo *aminfo;
5148         int                     i_tableoid;
5149         int                     i_oid;
5150         int                     i_amname;
5151         int                     i_amhandler;
5152         int                     i_amtype;
5153
5154         /* Before 9.6, there are no user-defined access methods */
5155         if (fout->remoteVersion < 90600)
5156         {
5157                 *numAccessMethods = 0;
5158                 return NULL;
5159         }
5160
5161         query = createPQExpBuffer();
5162
5163         /* Make sure we are in proper schema */
5164         selectSourceSchema(fout, "pg_catalog");
5165
5166         /* Select all access methods from pg_am table */
5167         appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5168                                           "amhandler::pg_catalog.regproc AS amhandler "
5169                                           "FROM pg_am");
5170
5171         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5172
5173         ntups = PQntuples(res);
5174         *numAccessMethods = ntups;
5175
5176         aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5177
5178         i_tableoid = PQfnumber(res, "tableoid");
5179         i_oid = PQfnumber(res, "oid");
5180         i_amname = PQfnumber(res, "amname");
5181         i_amhandler = PQfnumber(res, "amhandler");
5182         i_amtype = PQfnumber(res, "amtype");
5183
5184         for (i = 0; i < ntups; i++)
5185         {
5186                 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5187                 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5188                 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5189                 AssignDumpId(&aminfo[i].dobj);
5190                 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5191                 aminfo[i].dobj.namespace = NULL;
5192                 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5193                 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5194
5195                 /* Decide whether we want to dump it */
5196                 selectDumpableAccessMethod(&(aminfo[i]), fout);
5197
5198                 /* Access methods do not currently have ACLs. */
5199                 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5200         }
5201
5202         PQclear(res);
5203
5204         destroyPQExpBuffer(query);
5205
5206         return aminfo;
5207 }
5208
5209
5210 /*
5211  * getOpclasses:
5212  *        read all opclasses in the system catalogs and return them in the
5213  * OpclassInfo* structure
5214  *
5215  *      numOpclasses is set to the number of opclasses read in
5216  */
5217 OpclassInfo *
5218 getOpclasses(Archive *fout, int *numOpclasses)
5219 {
5220         PGresult   *res;
5221         int                     ntups;
5222         int                     i;
5223         PQExpBuffer query = createPQExpBuffer();
5224         OpclassInfo *opcinfo;
5225         int                     i_tableoid;
5226         int                     i_oid;
5227         int                     i_opcname;
5228         int                     i_opcnamespace;
5229         int                     i_rolname;
5230
5231         /*
5232          * find all opclasses, including builtin opclasses; we filter out
5233          * system-defined opclasses at dump-out time.
5234          */
5235
5236         /* Make sure we are in proper schema */
5237         selectSourceSchema(fout, "pg_catalog");
5238
5239         appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5240                                           "opcnamespace, "
5241                                           "(%s opcowner) AS rolname "
5242                                           "FROM pg_opclass",
5243                                           username_subquery);
5244
5245         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5246
5247         ntups = PQntuples(res);
5248         *numOpclasses = ntups;
5249
5250         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5251
5252         i_tableoid = PQfnumber(res, "tableoid");
5253         i_oid = PQfnumber(res, "oid");
5254         i_opcname = PQfnumber(res, "opcname");
5255         i_opcnamespace = PQfnumber(res, "opcnamespace");
5256         i_rolname = PQfnumber(res, "rolname");
5257
5258         for (i = 0; i < ntups; i++)
5259         {
5260                 opcinfo[i].dobj.objType = DO_OPCLASS;
5261                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5262                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5263                 AssignDumpId(&opcinfo[i].dobj);
5264                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5265                 opcinfo[i].dobj.namespace =
5266                         findNamespace(fout,
5267                                                   atooid(PQgetvalue(res, i, i_opcnamespace)));
5268                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5269
5270                 /* Decide whether we want to dump it */
5271                 selectDumpableObject(&(opcinfo[i].dobj), fout);
5272
5273                 /* Op Classes do not currently have ACLs. */
5274                 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5275
5276                 if (strlen(opcinfo[i].rolname) == 0)
5277                         write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5278                                           opcinfo[i].dobj.name);
5279         }
5280
5281         PQclear(res);
5282
5283         destroyPQExpBuffer(query);
5284
5285         return opcinfo;
5286 }
5287
5288 /*
5289  * getOpfamilies:
5290  *        read all opfamilies in the system catalogs and return them in the
5291  * OpfamilyInfo* structure
5292  *
5293  *      numOpfamilies is set to the number of opfamilies read in
5294  */
5295 OpfamilyInfo *
5296 getOpfamilies(Archive *fout, int *numOpfamilies)
5297 {
5298         PGresult   *res;
5299         int                     ntups;
5300         int                     i;
5301         PQExpBuffer query;
5302         OpfamilyInfo *opfinfo;
5303         int                     i_tableoid;
5304         int                     i_oid;
5305         int                     i_opfname;
5306         int                     i_opfnamespace;
5307         int                     i_rolname;
5308
5309         /* Before 8.3, there is no separate concept of opfamilies */
5310         if (fout->remoteVersion < 80300)
5311         {
5312                 *numOpfamilies = 0;
5313                 return NULL;
5314         }
5315
5316         query = createPQExpBuffer();
5317
5318         /*
5319          * find all opfamilies, including builtin opfamilies; we filter out
5320          * system-defined opfamilies at dump-out time.
5321          */
5322
5323         /* Make sure we are in proper schema */
5324         selectSourceSchema(fout, "pg_catalog");
5325
5326         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5327                                           "opfnamespace, "
5328                                           "(%s opfowner) AS rolname "
5329                                           "FROM pg_opfamily",
5330                                           username_subquery);
5331
5332         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5333
5334         ntups = PQntuples(res);
5335         *numOpfamilies = ntups;
5336
5337         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5338
5339         i_tableoid = PQfnumber(res, "tableoid");
5340         i_oid = PQfnumber(res, "oid");
5341         i_opfname = PQfnumber(res, "opfname");
5342         i_opfnamespace = PQfnumber(res, "opfnamespace");
5343         i_rolname = PQfnumber(res, "rolname");
5344
5345         for (i = 0; i < ntups; i++)
5346         {
5347                 opfinfo[i].dobj.objType = DO_OPFAMILY;
5348                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5349                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5350                 AssignDumpId(&opfinfo[i].dobj);
5351                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5352                 opfinfo[i].dobj.namespace =
5353                         findNamespace(fout,
5354                                                   atooid(PQgetvalue(res, i, i_opfnamespace)));
5355                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5356
5357                 /* Decide whether we want to dump it */
5358                 selectDumpableObject(&(opfinfo[i].dobj), fout);
5359
5360                 /* Extensions do not currently have ACLs. */
5361                 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5362
5363                 if (strlen(opfinfo[i].rolname) == 0)
5364                         write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5365                                           opfinfo[i].dobj.name);
5366         }
5367
5368         PQclear(res);
5369
5370         destroyPQExpBuffer(query);
5371
5372         return opfinfo;
5373 }
5374
5375 /*
5376  * getAggregates:
5377  *        read all the user-defined aggregates in the system catalogs and
5378  * return them in the AggInfo* structure
5379  *
5380  * numAggs is set to the number of aggregates read in
5381  */
5382 AggInfo *
5383 getAggregates(Archive *fout, int *numAggs)
5384 {
5385         DumpOptions *dopt = fout->dopt;
5386         PGresult   *res;
5387         int                     ntups;
5388         int                     i;
5389         PQExpBuffer query = createPQExpBuffer();
5390         AggInfo    *agginfo;
5391         int                     i_tableoid;
5392         int                     i_oid;
5393         int                     i_aggname;
5394         int                     i_aggnamespace;
5395         int                     i_pronargs;
5396         int                     i_proargtypes;
5397         int                     i_rolname;
5398         int                     i_aggacl;
5399         int                     i_raggacl;
5400         int                     i_initaggacl;
5401         int                     i_initraggacl;
5402
5403         /* Make sure we are in proper schema */
5404         selectSourceSchema(fout, "pg_catalog");
5405
5406         /*
5407          * Find all interesting aggregates.  See comment in getFuncs() for the
5408          * rationale behind the filtering logic.
5409          */
5410         if (fout->remoteVersion >= 90600)
5411         {
5412                 PQExpBuffer acl_subquery = createPQExpBuffer();
5413                 PQExpBuffer racl_subquery = createPQExpBuffer();
5414                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5415                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5416
5417                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5418                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5419                                                 dopt->binary_upgrade);
5420
5421                 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5422                                                   "p.proname AS aggname, "
5423                                                   "p.pronamespace AS aggnamespace, "
5424                                                   "p.pronargs, p.proargtypes, "
5425                                                   "(%s p.proowner) AS rolname, "
5426                                                   "%s AS aggacl, "
5427                                                   "%s AS raggacl, "
5428                                                   "%s AS initaggacl, "
5429                                                   "%s AS initraggacl "
5430                                                   "FROM pg_proc p "
5431                                                   "LEFT JOIN pg_init_privs pip ON "
5432                                                   "(p.oid = pip.objoid "
5433                                                   "AND pip.classoid = 'pg_proc'::regclass "
5434                                                   "AND pip.objsubid = 0) "
5435                                                   "WHERE p.proisagg AND ("
5436                                                   "p.pronamespace != "
5437                                                   "(SELECT oid FROM pg_namespace "
5438                                                   "WHERE nspname = 'pg_catalog') OR "
5439                                                   "p.proacl IS DISTINCT FROM pip.initprivs",
5440                                                   username_subquery,
5441                                                   acl_subquery->data,
5442                                                   racl_subquery->data,
5443                                                   initacl_subquery->data,
5444                                                   initracl_subquery->data);
5445                 if (dopt->binary_upgrade)
5446                         appendPQExpBufferStr(query,
5447                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5448                                                                  "classid = 'pg_proc'::regclass AND "
5449                                                                  "objid = p.oid AND "
5450                                                                  "refclassid = 'pg_extension'::regclass AND "
5451                                                                  "deptype = 'e')");
5452                 appendPQExpBufferChar(query, ')');
5453
5454                 destroyPQExpBuffer(acl_subquery);
5455                 destroyPQExpBuffer(racl_subquery);
5456                 destroyPQExpBuffer(initacl_subquery);
5457                 destroyPQExpBuffer(initracl_subquery);
5458         }
5459         else if (fout->remoteVersion >= 80200)
5460         {
5461                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5462                                                   "pronamespace AS aggnamespace, "
5463                                                   "pronargs, proargtypes, "
5464                                                   "(%s proowner) AS rolname, "
5465                                                   "proacl AS aggacl, "
5466                                                   "NULL AS raggacl, "
5467                                                   "NULL AS initaggacl, NULL AS initraggacl "
5468                                                   "FROM pg_proc p "
5469                                                   "WHERE proisagg AND ("
5470                                                   "pronamespace != "
5471                                                   "(SELECT oid FROM pg_namespace "
5472                                                   "WHERE nspname = 'pg_catalog')",
5473                                                   username_subquery);
5474                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5475                         appendPQExpBufferStr(query,
5476                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5477                                                                  "classid = 'pg_proc'::regclass AND "
5478                                                                  "objid = p.oid AND "
5479                                                                  "refclassid = 'pg_extension'::regclass AND "
5480                                                                  "deptype = 'e')");
5481                 appendPQExpBufferChar(query, ')');
5482         }
5483         else
5484         {
5485                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5486                                                   "pronamespace AS aggnamespace, "
5487                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5488                                                   "proargtypes, "
5489                                                   "(%s proowner) AS rolname, "
5490                                                   "proacl AS aggacl, "
5491                                                   "NULL AS raggacl, "
5492                                                   "NULL AS initaggacl, NULL AS initraggacl "
5493                                                   "FROM pg_proc "
5494                                                   "WHERE proisagg "
5495                                                   "AND pronamespace != "
5496                                                   "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5497                                                   username_subquery);
5498         }
5499
5500         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5501
5502         ntups = PQntuples(res);
5503         *numAggs = ntups;
5504
5505         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5506
5507         i_tableoid = PQfnumber(res, "tableoid");
5508         i_oid = PQfnumber(res, "oid");
5509         i_aggname = PQfnumber(res, "aggname");
5510         i_aggnamespace = PQfnumber(res, "aggnamespace");
5511         i_pronargs = PQfnumber(res, "pronargs");
5512         i_proargtypes = PQfnumber(res, "proargtypes");
5513         i_rolname = PQfnumber(res, "rolname");
5514         i_aggacl = PQfnumber(res, "aggacl");
5515         i_raggacl = PQfnumber(res, "raggacl");
5516         i_initaggacl = PQfnumber(res, "initaggacl");
5517         i_initraggacl = PQfnumber(res, "initraggacl");
5518
5519         for (i = 0; i < ntups; i++)
5520         {
5521                 agginfo[i].aggfn.dobj.objType = DO_AGG;
5522                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5523                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5524                 AssignDumpId(&agginfo[i].aggfn.dobj);
5525                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5526                 agginfo[i].aggfn.dobj.namespace =
5527                         findNamespace(fout,
5528                                                   atooid(PQgetvalue(res, i, i_aggnamespace)));
5529                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5530                 if (strlen(agginfo[i].aggfn.rolname) == 0)
5531                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5532                                           agginfo[i].aggfn.dobj.name);
5533                 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5534                 agginfo[i].aggfn.prorettype = InvalidOid;       /* not saved */
5535                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5536                 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5537                 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5538                 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5539                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5540                 if (agginfo[i].aggfn.nargs == 0)
5541                         agginfo[i].aggfn.argtypes = NULL;
5542                 else
5543                 {
5544                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5545                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5546                                                   agginfo[i].aggfn.argtypes,
5547                                                   agginfo[i].aggfn.nargs);
5548                 }
5549
5550                 /* Decide whether we want to dump it */
5551                 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5552
5553                 /* Do not try to dump ACL if no ACL exists. */
5554                 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5555                         PQgetisnull(res, i, i_initaggacl) &&
5556                         PQgetisnull(res, i, i_initraggacl))
5557                         agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5558         }
5559
5560         PQclear(res);
5561
5562         destroyPQExpBuffer(query);
5563
5564         return agginfo;
5565 }
5566
5567 /*
5568  * getFuncs:
5569  *        read all the user-defined functions in the system catalogs and
5570  * return them in the FuncInfo* structure
5571  *
5572  * numFuncs is set to the number of functions read in
5573  */
5574 FuncInfo *
5575 getFuncs(Archive *fout, int *numFuncs)
5576 {
5577         DumpOptions *dopt = fout->dopt;
5578         PGresult   *res;
5579         int                     ntups;
5580         int                     i;
5581         PQExpBuffer query = createPQExpBuffer();
5582         FuncInfo   *finfo;
5583         int                     i_tableoid;
5584         int                     i_oid;
5585         int                     i_proname;
5586         int                     i_pronamespace;
5587         int                     i_rolname;
5588         int                     i_prolang;
5589         int                     i_pronargs;
5590         int                     i_proargtypes;
5591         int                     i_prorettype;
5592         int                     i_proacl;
5593         int                     i_rproacl;
5594         int                     i_initproacl;
5595         int                     i_initrproacl;
5596
5597         /* Make sure we are in proper schema */
5598         selectSourceSchema(fout, "pg_catalog");
5599
5600         /*
5601          * Find all interesting functions.  This is a bit complicated:
5602          *
5603          * 1. Always exclude aggregates; those are handled elsewhere.
5604          *
5605          * 2. Always exclude functions that are internally dependent on something
5606          * else, since presumably those will be created as a result of creating
5607          * the something else.  This currently acts only to suppress constructor
5608          * functions for range types (so we only need it in 9.2 and up).  Note
5609          * this is OK only because the constructors don't have any dependencies
5610          * the range type doesn't have; otherwise we might not get creation
5611          * ordering correct.
5612          *
5613          * 3. Otherwise, we normally exclude functions in pg_catalog.  However, if
5614          * they're members of extensions and we are in binary-upgrade mode then
5615          * include them, since we want to dump extension members individually in
5616          * that mode.  Also, if they are used by casts or transforms then we need
5617          * to gather the information about them, though they won't be dumped if
5618          * they are built-in.  Also, in 9.6 and up, include functions in
5619          * pg_catalog if they have an ACL different from what's shown in
5620          * pg_init_privs.
5621          */
5622         if (fout->remoteVersion >= 90600)
5623         {
5624                 PQExpBuffer acl_subquery = createPQExpBuffer();
5625                 PQExpBuffer racl_subquery = createPQExpBuffer();
5626                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5627                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5628
5629                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5630                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5631                                                 dopt->binary_upgrade);
5632
5633                 appendPQExpBuffer(query,
5634                                                   "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5635                                                   "p.pronargs, p.proargtypes, p.prorettype, "
5636                                                   "%s AS proacl, "
5637                                                   "%s AS rproacl, "
5638                                                   "%s AS initproacl, "
5639                                                   "%s AS initrproacl, "
5640                                                   "p.pronamespace, "
5641                                                   "(%s p.proowner) AS rolname "
5642                                                   "FROM pg_proc p "
5643                                                   "LEFT JOIN pg_init_privs pip ON "
5644                                                   "(p.oid = pip.objoid "
5645                                                   "AND pip.classoid = 'pg_proc'::regclass "
5646                                                   "AND pip.objsubid = 0) "
5647                                                   "WHERE NOT proisagg"
5648                                                   "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5649                                                   "WHERE classid = 'pg_proc'::regclass AND "
5650                                                   "objid = p.oid AND deptype = 'i')"
5651                                                   "\n  AND ("
5652                                                   "\n  pronamespace != "
5653                                                   "(SELECT oid FROM pg_namespace "
5654                                                   "WHERE nspname = 'pg_catalog')"
5655                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5656                                                   "\n  WHERE pg_cast.oid > %u "
5657                                                   "\n  AND p.oid = pg_cast.castfunc)"
5658                                                   "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5659                                                   "\n  WHERE pg_transform.oid > %u AND "
5660                                                   "\n  (p.oid = pg_transform.trffromsql"
5661                                                   "\n  OR p.oid = pg_transform.trftosql))",
5662                                                   acl_subquery->data,
5663                                                   racl_subquery->data,
5664                                                   initacl_subquery->data,
5665                                                   initracl_subquery->data,
5666                                                   username_subquery,
5667                                                   g_last_builtin_oid,
5668                                                   g_last_builtin_oid);
5669                 if (dopt->binary_upgrade)
5670                         appendPQExpBufferStr(query,
5671                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5672                                                                  "classid = 'pg_proc'::regclass AND "
5673                                                                  "objid = p.oid AND "
5674                                                                  "refclassid = 'pg_extension'::regclass AND "
5675                                                                  "deptype = 'e')");
5676                 appendPQExpBufferStr(query,
5677                                                          "\n  OR p.proacl IS DISTINCT FROM pip.initprivs");
5678                 appendPQExpBufferChar(query, ')');
5679
5680                 destroyPQExpBuffer(acl_subquery);
5681                 destroyPQExpBuffer(racl_subquery);
5682                 destroyPQExpBuffer(initacl_subquery);
5683                 destroyPQExpBuffer(initracl_subquery);
5684         }
5685         else
5686         {
5687                 appendPQExpBuffer(query,
5688                                                   "SELECT tableoid, oid, proname, prolang, "
5689                                                   "pronargs, proargtypes, prorettype, proacl, "
5690                                                   "NULL as rproacl, "
5691                                                   "NULL as initproacl, NULL AS initrproacl, "
5692                                                   "pronamespace, "
5693                                                   "(%s proowner) AS rolname "
5694                                                   "FROM pg_proc p "
5695                                                   "WHERE NOT proisagg",
5696                                                   username_subquery);
5697                 if (fout->remoteVersion >= 90200)
5698                         appendPQExpBufferStr(query,
5699                                                                  "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5700                                                                  "WHERE classid = 'pg_proc'::regclass AND "
5701                                                                  "objid = p.oid AND deptype = 'i')");
5702                 appendPQExpBuffer(query,
5703                                                   "\n  AND ("
5704                                                   "\n  pronamespace != "
5705                                                   "(SELECT oid FROM pg_namespace "
5706                                                   "WHERE nspname = 'pg_catalog')"
5707                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5708                                                   "\n  WHERE pg_cast.oid > '%u'::oid"
5709                                                   "\n  AND p.oid = pg_cast.castfunc)",
5710                                                   g_last_builtin_oid);
5711
5712                 if (fout->remoteVersion >= 90500)
5713                         appendPQExpBuffer(query,
5714                                                           "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5715                                                           "\n  WHERE pg_transform.oid > '%u'::oid"
5716                                                           "\n  AND (p.oid = pg_transform.trffromsql"
5717                                                           "\n  OR p.oid = pg_transform.trftosql))",
5718                                                           g_last_builtin_oid);
5719
5720                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5721                         appendPQExpBufferStr(query,
5722                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5723                                                                  "classid = 'pg_proc'::regclass AND "
5724                                                                  "objid = p.oid AND "
5725                                                                  "refclassid = 'pg_extension'::regclass AND "
5726                                                                  "deptype = 'e')");
5727                 appendPQExpBufferChar(query, ')');
5728         }
5729
5730         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5731
5732         ntups = PQntuples(res);
5733
5734         *numFuncs = ntups;
5735
5736         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5737
5738         i_tableoid = PQfnumber(res, "tableoid");
5739         i_oid = PQfnumber(res, "oid");
5740         i_proname = PQfnumber(res, "proname");
5741         i_pronamespace = PQfnumber(res, "pronamespace");
5742         i_rolname = PQfnumber(res, "rolname");
5743         i_prolang = PQfnumber(res, "prolang");
5744         i_pronargs = PQfnumber(res, "pronargs");
5745         i_proargtypes = PQfnumber(res, "proargtypes");
5746         i_prorettype = PQfnumber(res, "prorettype");
5747         i_proacl = PQfnumber(res, "proacl");
5748         i_rproacl = PQfnumber(res, "rproacl");
5749         i_initproacl = PQfnumber(res, "initproacl");
5750         i_initrproacl = PQfnumber(res, "initrproacl");
5751
5752         for (i = 0; i < ntups; i++)
5753         {
5754                 finfo[i].dobj.objType = DO_FUNC;
5755                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5756                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5757                 AssignDumpId(&finfo[i].dobj);
5758                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5759                 finfo[i].dobj.namespace =
5760                         findNamespace(fout,
5761                                                   atooid(PQgetvalue(res, i, i_pronamespace)));
5762                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5763                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5764                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5765                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5766                 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5767                 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5768                 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5769                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5770                 if (finfo[i].nargs == 0)
5771                         finfo[i].argtypes = NULL;
5772                 else
5773                 {
5774                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5775                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5776                                                   finfo[i].argtypes, finfo[i].nargs);
5777                 }
5778
5779                 /* Decide whether we want to dump it */
5780                 selectDumpableObject(&(finfo[i].dobj), fout);
5781
5782                 /* Do not try to dump ACL if no ACL exists. */
5783                 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5784                         PQgetisnull(res, i, i_initproacl) &&
5785                         PQgetisnull(res, i, i_initrproacl))
5786                         finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5787
5788                 if (strlen(finfo[i].rolname) == 0)
5789                         write_msg(NULL,
5790                                           "WARNING: owner of function \"%s\" appears to be invalid\n",
5791                                           finfo[i].dobj.name);
5792         }
5793
5794         PQclear(res);
5795
5796         destroyPQExpBuffer(query);
5797
5798         return finfo;
5799 }
5800
5801 /*
5802  * getTables
5803  *        read all the tables (no indexes)
5804  * in the system catalogs return them in the TableInfo* structure
5805  *
5806  * numTables is set to the number of tables read in
5807  */
5808 TableInfo *
5809 getTables(Archive *fout, int *numTables)
5810 {
5811         DumpOptions *dopt = fout->dopt;
5812         PGresult   *res;
5813         int                     ntups;
5814         int                     i;
5815         PQExpBuffer query = createPQExpBuffer();
5816         TableInfo  *tblinfo;
5817         int                     i_reltableoid;
5818         int                     i_reloid;
5819         int                     i_relname;
5820         int                     i_relnamespace;
5821         int                     i_relkind;
5822         int                     i_relacl;
5823         int                     i_rrelacl;
5824         int                     i_initrelacl;
5825         int                     i_initrrelacl;
5826         int                     i_rolname;
5827         int                     i_relchecks;
5828         int                     i_relhastriggers;
5829         int                     i_relhasindex;
5830         int                     i_relhasrules;
5831         int                     i_relrowsec;
5832         int                     i_relforcerowsec;
5833         int                     i_relhasoids;
5834         int                     i_relfrozenxid;
5835         int                     i_relminmxid;
5836         int                     i_toastoid;
5837         int                     i_toastfrozenxid;
5838         int                     i_toastminmxid;
5839         int                     i_relpersistence;
5840         int                     i_relispopulated;
5841         int                     i_relreplident;
5842         int                     i_owning_tab;
5843         int                     i_owning_col;
5844         int                     i_reltablespace;
5845         int                     i_reloptions;
5846         int                     i_checkoption;
5847         int                     i_toastreloptions;
5848         int                     i_reloftype;
5849         int                     i_relpages;
5850         int                     i_is_identity_sequence;
5851         int                     i_changed_acl;
5852         int                     i_partkeydef;
5853         int                     i_ispartition;
5854         int                     i_partbound;
5855
5856         /* Make sure we are in proper schema */
5857         selectSourceSchema(fout, "pg_catalog");
5858
5859         /*
5860          * Find all the tables and table-like objects.
5861          *
5862          * We include system catalogs, so that we can work if a user table is
5863          * defined to inherit from a system catalog (pretty weird, but...)
5864          *
5865          * We ignore relations that are not ordinary tables, sequences, views,
5866          * materialized views, composite types, or foreign tables.
5867          *
5868          * Composite-type table entries won't be dumped as such, but we have to
5869          * make a DumpableObject for them so that we can track dependencies of the
5870          * composite type (pg_depend entries for columns of the composite type
5871          * link to the pg_class entry not the pg_type entry).
5872          *
5873          * Note: in this phase we should collect only a minimal amount of
5874          * information about each table, basically just enough to decide if it is
5875          * interesting. We must fetch all tables in this phase because otherwise
5876          * we cannot correctly identify inherited columns, owned sequences, etc.
5877          */
5878
5879         if (fout->remoteVersion >= 90600)
5880         {
5881                 char       *partkeydef = "NULL";
5882                 char       *ispartition = "false";
5883                 char       *partbound = "NULL";
5884
5885                 PQExpBuffer acl_subquery = createPQExpBuffer();
5886                 PQExpBuffer racl_subquery = createPQExpBuffer();
5887                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5888                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5889
5890                 PQExpBuffer attacl_subquery = createPQExpBuffer();
5891                 PQExpBuffer attracl_subquery = createPQExpBuffer();
5892                 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5893                 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5894
5895                 /*
5896                  * Collect the information about any partitioned tables, which were
5897                  * added in PG10.
5898                  */
5899
5900                 if (fout->remoteVersion >= 100000)
5901                 {
5902                         partkeydef = "pg_get_partkeydef(c.oid)";
5903                         ispartition = "c.relispartition";
5904                         partbound = "pg_get_expr(c.relpartbound, c.oid)";
5905                 }
5906
5907                 /*
5908                  * Left join to pick up dependency info linking sequences to their
5909                  * owning column, if any (note this dependency is AUTO as of 8.2)
5910                  *
5911                  * Left join to detect if any privileges are still as-set-at-init, in
5912                  * which case we won't dump out ACL commands for those.
5913                  */
5914
5915                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5916                                                 initracl_subquery, "c.relacl", "c.relowner",
5917                                                 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5918                                                 " THEN 's' ELSE 'r' END::\"char\"",
5919                                                 dopt->binary_upgrade);
5920
5921                 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5922                                                 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5923                                                 dopt->binary_upgrade);
5924
5925                 appendPQExpBuffer(query,
5926                                                   "SELECT c.tableoid, c.oid, c.relname, "
5927                                                   "%s AS relacl, %s as rrelacl, "
5928                                                   "%s AS initrelacl, %s as initrrelacl, "
5929                                                   "c.relkind, c.relnamespace, "
5930                                                   "(%s c.relowner) AS rolname, "
5931                                                   "c.relchecks, c.relhastriggers, "
5932                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5933                                                   "c.relrowsecurity, c.relforcerowsecurity, "
5934                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5935                                                   "tc.relfrozenxid AS tfrozenxid, "
5936                                                   "tc.relminmxid AS tminmxid, "
5937                                                   "c.relpersistence, c.relispopulated, "
5938                                                   "c.relreplident, c.relpages, "
5939                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5940                                                   "d.refobjid AS owning_tab, "
5941                                                   "d.refobjsubid AS owning_col, "
5942                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5943                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5944                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5945                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5946                                                   "tc.reloptions AS toast_reloptions, "
5947                                                   "c.relkind = '%c' AND EXISTS (SELECT 1 FROM pg_depend WHERE classid = 'pg_class'::regclass AND objid = c.oid AND objsubid = 0 AND refclassid = 'pg_class'::regclass AND deptype = 'i') AS is_identity_sequence, "
5948                                                   "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5949                                                   "(c.oid = pip.objoid "
5950                                                   "AND pip.classoid = 'pg_class'::regclass "
5951                                                   "AND pip.objsubid = at.attnum)"
5952                                                   "WHERE at.attrelid = c.oid AND ("
5953                                                   "%s IS NOT NULL "
5954                                                   "OR %s IS NOT NULL "
5955                                                   "OR %s IS NOT NULL "
5956                                                   "OR %s IS NOT NULL"
5957                                                   "))"
5958                                                   "AS changed_acl, "
5959                                                   "%s AS partkeydef, "
5960                                                   "%s AS ispartition, "
5961                                                   "%s AS partbound "
5962                                                   "FROM pg_class c "
5963                                                   "LEFT JOIN pg_depend d ON "
5964                                                   "(c.relkind = '%c' AND "
5965                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5966                                                   "d.objsubid = 0 AND "
5967                                                   "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5968                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5969                                                   "LEFT JOIN pg_init_privs pip ON "
5970                                                   "(c.oid = pip.objoid "
5971                                                   "AND pip.classoid = 'pg_class'::regclass "
5972                                                   "AND pip.objsubid = 0) "
5973                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5974                                                   "ORDER BY c.oid",
5975                                                   acl_subquery->data,
5976                                                   racl_subquery->data,
5977                                                   initacl_subquery->data,
5978                                                   initracl_subquery->data,
5979                                                   username_subquery,
5980                                                   RELKIND_SEQUENCE,
5981                                                   attacl_subquery->data,
5982                                                   attracl_subquery->data,
5983                                                   attinitacl_subquery->data,
5984                                                   attinitracl_subquery->data,
5985                                                   partkeydef,
5986                                                   ispartition,
5987                                                   partbound,
5988                                                   RELKIND_SEQUENCE,
5989                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5990                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5991                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5992                                                   RELKIND_PARTITIONED_TABLE);
5993
5994                 destroyPQExpBuffer(acl_subquery);
5995                 destroyPQExpBuffer(racl_subquery);
5996                 destroyPQExpBuffer(initacl_subquery);
5997                 destroyPQExpBuffer(initracl_subquery);
5998
5999                 destroyPQExpBuffer(attacl_subquery);
6000                 destroyPQExpBuffer(attracl_subquery);
6001                 destroyPQExpBuffer(attinitacl_subquery);
6002                 destroyPQExpBuffer(attinitracl_subquery);
6003         }
6004         else if (fout->remoteVersion >= 90500)
6005         {
6006                 /*
6007                  * Left join to pick up dependency info linking sequences to their
6008                  * owning column, if any (note this dependency is AUTO as of 8.2)
6009                  */
6010                 appendPQExpBuffer(query,
6011                                                   "SELECT c.tableoid, c.oid, c.relname, "
6012                                                   "c.relacl, NULL as rrelacl, "
6013                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6014                                                   "c.relkind, "
6015                                                   "c.relnamespace, "
6016                                                   "(%s c.relowner) AS rolname, "
6017                                                   "c.relchecks, c.relhastriggers, "
6018                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6019                                                   "c.relrowsecurity, c.relforcerowsecurity, "
6020                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6021                                                   "tc.relfrozenxid AS tfrozenxid, "
6022                                                   "tc.relminmxid AS tminmxid, "
6023                                                   "c.relpersistence, c.relispopulated, "
6024                                                   "c.relreplident, c.relpages, "
6025                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6026                                                   "d.refobjid AS owning_tab, "
6027                                                   "d.refobjsubid AS owning_col, "
6028                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6029                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6030                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6031                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6032                                                   "tc.reloptions AS toast_reloptions, "
6033                                                   "NULL AS changed_acl, "
6034                                                   "NULL AS partkeydef, "
6035                                                   "false AS ispartition, "
6036                                                   "NULL AS partbound "
6037                                                   "FROM pg_class c "
6038                                                   "LEFT JOIN pg_depend d ON "
6039                                                   "(c.relkind = '%c' AND "
6040                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6041                                                   "d.objsubid = 0 AND "
6042                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6043                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6044                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6045                                                   "ORDER BY c.oid",
6046                                                   username_subquery,
6047                                                   RELKIND_SEQUENCE,
6048                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6049                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6050                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6051         }
6052         else if (fout->remoteVersion >= 90400)
6053         {
6054                 /*
6055                  * Left join to pick up dependency info linking sequences to their
6056                  * owning column, if any (note this dependency is AUTO as of 8.2)
6057                  */
6058                 appendPQExpBuffer(query,
6059                                                   "SELECT c.tableoid, c.oid, c.relname, "
6060                                                   "c.relacl, NULL as rrelacl, "
6061                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6062                                                   "c.relkind, "
6063                                                   "c.relnamespace, "
6064                                                   "(%s c.relowner) AS rolname, "
6065                                                   "c.relchecks, c.relhastriggers, "
6066                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6067                                                   "'f'::bool AS relrowsecurity, "
6068                                                   "'f'::bool AS relforcerowsecurity, "
6069                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6070                                                   "tc.relfrozenxid AS tfrozenxid, "
6071                                                   "tc.relminmxid AS tminmxid, "
6072                                                   "c.relpersistence, c.relispopulated, "
6073                                                   "c.relreplident, c.relpages, "
6074                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6075                                                   "d.refobjid AS owning_tab, "
6076                                                   "d.refobjsubid AS owning_col, "
6077                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6078                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6079                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6080                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6081                                                   "tc.reloptions AS toast_reloptions, "
6082                                                   "NULL AS changed_acl, "
6083                                                   "NULL AS partkeydef, "
6084                                                   "false AS ispartition, "
6085                                                   "NULL AS partbound "
6086                                                   "FROM pg_class c "
6087                                                   "LEFT JOIN pg_depend d ON "
6088                                                   "(c.relkind = '%c' AND "
6089                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6090                                                   "d.objsubid = 0 AND "
6091                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6092                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6093                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6094                                                   "ORDER BY c.oid",
6095                                                   username_subquery,
6096                                                   RELKIND_SEQUENCE,
6097                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6098                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6099                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6100         }
6101         else if (fout->remoteVersion >= 90300)
6102         {
6103                 /*
6104                  * Left join to pick up dependency info linking sequences to their
6105                  * owning column, if any (note this dependency is AUTO as of 8.2)
6106                  */
6107                 appendPQExpBuffer(query,
6108                                                   "SELECT c.tableoid, c.oid, c.relname, "
6109                                                   "c.relacl, NULL as rrelacl, "
6110                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6111                                                   "c.relkind, "
6112                                                   "c.relnamespace, "
6113                                                   "(%s c.relowner) AS rolname, "
6114                                                   "c.relchecks, c.relhastriggers, "
6115                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6116                                                   "'f'::bool AS relrowsecurity, "
6117                                                   "'f'::bool AS relforcerowsecurity, "
6118                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6119                                                   "tc.relfrozenxid AS tfrozenxid, "
6120                                                   "tc.relminmxid AS tminmxid, "
6121                                                   "c.relpersistence, c.relispopulated, "
6122                                                   "'d' AS relreplident, c.relpages, "
6123                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6124                                                   "d.refobjid AS owning_tab, "
6125                                                   "d.refobjsubid AS owning_col, "
6126                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6127                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6128                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6129                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6130                                                   "tc.reloptions AS toast_reloptions, "
6131                                                   "NULL AS changed_acl, "
6132                                                   "NULL AS partkeydef, "
6133                                                   "false AS ispartition, "
6134                                                   "NULL AS partbound "
6135                                                   "FROM pg_class c "
6136                                                   "LEFT JOIN pg_depend d ON "
6137                                                   "(c.relkind = '%c' AND "
6138                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6139                                                   "d.objsubid = 0 AND "
6140                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6141                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6142                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6143                                                   "ORDER BY c.oid",
6144                                                   username_subquery,
6145                                                   RELKIND_SEQUENCE,
6146                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6147                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6148                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6149         }
6150         else if (fout->remoteVersion >= 90100)
6151         {
6152                 /*
6153                  * Left join to pick up dependency info linking sequences to their
6154                  * owning column, if any (note this dependency is AUTO as of 8.2)
6155                  */
6156                 appendPQExpBuffer(query,
6157                                                   "SELECT c.tableoid, c.oid, c.relname, "
6158                                                   "c.relacl, NULL as rrelacl, "
6159                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6160                                                   "c.relkind, "
6161                                                   "c.relnamespace, "
6162                                                   "(%s c.relowner) AS rolname, "
6163                                                   "c.relchecks, c.relhastriggers, "
6164                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6165                                                   "'f'::bool AS relrowsecurity, "
6166                                                   "'f'::bool AS relforcerowsecurity, "
6167                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6168                                                   "tc.relfrozenxid AS tfrozenxid, "
6169                                                   "0 AS tminmxid, "
6170                                                   "c.relpersistence, 't' as relispopulated, "
6171                                                   "'d' AS relreplident, c.relpages, "
6172                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6173                                                   "d.refobjid AS owning_tab, "
6174                                                   "d.refobjsubid AS owning_col, "
6175                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6176                                                   "c.reloptions AS reloptions, "
6177                                                   "tc.reloptions AS toast_reloptions, "
6178                                                   "NULL AS changed_acl, "
6179                                                   "NULL AS partkeydef, "
6180                                                   "false AS ispartition, "
6181                                                   "NULL AS partbound "
6182                                                   "FROM pg_class c "
6183                                                   "LEFT JOIN pg_depend d ON "
6184                                                   "(c.relkind = '%c' AND "
6185                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6186                                                   "d.objsubid = 0 AND "
6187                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6188                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6189                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6190                                                   "ORDER BY c.oid",
6191                                                   username_subquery,
6192                                                   RELKIND_SEQUENCE,
6193                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6194                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6195                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6196         }
6197         else if (fout->remoteVersion >= 90000)
6198         {
6199                 /*
6200                  * Left join to pick up dependency info linking sequences to their
6201                  * owning column, if any (note this dependency is AUTO as of 8.2)
6202                  */
6203                 appendPQExpBuffer(query,
6204                                                   "SELECT c.tableoid, c.oid, c.relname, "
6205                                                   "c.relacl, NULL as rrelacl, "
6206                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6207                                                   "c.relkind, "
6208                                                   "c.relnamespace, "
6209                                                   "(%s c.relowner) AS rolname, "
6210                                                   "c.relchecks, c.relhastriggers, "
6211                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6212                                                   "'f'::bool AS relrowsecurity, "
6213                                                   "'f'::bool AS relforcerowsecurity, "
6214                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6215                                                   "tc.relfrozenxid AS tfrozenxid, "
6216                                                   "0 AS tminmxid, "
6217                                                   "'p' AS relpersistence, 't' as relispopulated, "
6218                                                   "'d' AS relreplident, c.relpages, "
6219                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6220                                                   "d.refobjid AS owning_tab, "
6221                                                   "d.refobjsubid AS owning_col, "
6222                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6223                                                   "c.reloptions AS reloptions, "
6224                                                   "tc.reloptions AS toast_reloptions, "
6225                                                   "NULL AS changed_acl, "
6226                                                   "NULL AS partkeydef, "
6227                                                   "false AS ispartition, "
6228                                                   "NULL AS partbound "
6229                                                   "FROM pg_class c "
6230                                                   "LEFT JOIN pg_depend d ON "
6231                                                   "(c.relkind = '%c' AND "
6232                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6233                                                   "d.objsubid = 0 AND "
6234                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6235                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6236                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6237                                                   "ORDER BY c.oid",
6238                                                   username_subquery,
6239                                                   RELKIND_SEQUENCE,
6240                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6241                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6242         }
6243         else if (fout->remoteVersion >= 80400)
6244         {
6245                 /*
6246                  * Left join to pick up dependency info linking sequences to their
6247                  * owning column, if any (note this dependency is AUTO as of 8.2)
6248                  */
6249                 appendPQExpBuffer(query,
6250                                                   "SELECT c.tableoid, c.oid, c.relname, "
6251                                                   "c.relacl, NULL as rrelacl, "
6252                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6253                                                   "c.relkind, "
6254                                                   "c.relnamespace, "
6255                                                   "(%s c.relowner) AS rolname, "
6256                                                   "c.relchecks, c.relhastriggers, "
6257                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6258                                                   "'f'::bool AS relrowsecurity, "
6259                                                   "'f'::bool AS relforcerowsecurity, "
6260                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6261                                                   "tc.relfrozenxid AS tfrozenxid, "
6262                                                   "0 AS tminmxid, "
6263                                                   "'p' AS relpersistence, 't' as relispopulated, "
6264                                                   "'d' AS relreplident, c.relpages, "
6265                                                   "NULL AS reloftype, "
6266                                                   "d.refobjid AS owning_tab, "
6267                                                   "d.refobjsubid AS owning_col, "
6268                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6269                                                   "c.reloptions AS reloptions, "
6270                                                   "tc.reloptions AS toast_reloptions, "
6271                                                   "NULL AS changed_acl, "
6272                                                   "NULL AS partkeydef, "
6273                                                   "false AS ispartition, "
6274                                                   "NULL AS partbound "
6275                                                   "FROM pg_class c "
6276                                                   "LEFT JOIN pg_depend d ON "
6277                                                   "(c.relkind = '%c' AND "
6278                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6279                                                   "d.objsubid = 0 AND "
6280                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6281                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6282                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6283                                                   "ORDER BY c.oid",
6284                                                   username_subquery,
6285                                                   RELKIND_SEQUENCE,
6286                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6287                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6288         }
6289         else if (fout->remoteVersion >= 80200)
6290         {
6291                 /*
6292                  * Left join to pick up dependency info linking sequences to their
6293                  * owning column, if any (note this dependency is AUTO as of 8.2)
6294                  */
6295                 appendPQExpBuffer(query,
6296                                                   "SELECT c.tableoid, c.oid, c.relname, "
6297                                                   "c.relacl, NULL as rrelacl, "
6298                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6299                                                   "c.relkind, "
6300                                                   "c.relnamespace, "
6301                                                   "(%s c.relowner) AS rolname, "
6302                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6303                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6304                                                   "'f'::bool AS relrowsecurity, "
6305                                                   "'f'::bool AS relforcerowsecurity, "
6306                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6307                                                   "tc.relfrozenxid AS tfrozenxid, "
6308                                                   "0 AS tminmxid, "
6309                                                   "'p' AS relpersistence, 't' as relispopulated, "
6310                                                   "'d' AS relreplident, c.relpages, "
6311                                                   "NULL AS reloftype, "
6312                                                   "d.refobjid AS owning_tab, "
6313                                                   "d.refobjsubid AS owning_col, "
6314                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6315                                                   "c.reloptions AS reloptions, "
6316                                                   "NULL AS toast_reloptions, "
6317                                                   "NULL AS changed_acl, "
6318                                                   "NULL AS partkeydef, "
6319                                                   "false AS ispartition, "
6320                                                   "NULL AS partbound "
6321                                                   "FROM pg_class c "
6322                                                   "LEFT JOIN pg_depend d ON "
6323                                                   "(c.relkind = '%c' AND "
6324                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6325                                                   "d.objsubid = 0 AND "
6326                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6327                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6328                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6329                                                   "ORDER BY c.oid",
6330                                                   username_subquery,
6331                                                   RELKIND_SEQUENCE,
6332                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6333                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6334         }
6335         else
6336         {
6337                 /*
6338                  * Left join to pick up dependency info linking sequences to their
6339                  * owning column, if any
6340                  */
6341                 appendPQExpBuffer(query,
6342                                                   "SELECT c.tableoid, c.oid, relname, "
6343                                                   "relacl, NULL as rrelacl, "
6344                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6345                                                   "relkind, relnamespace, "
6346                                                   "(%s relowner) AS rolname, "
6347                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
6348                                                   "relhasindex, relhasrules, relhasoids, "
6349                                                   "'f'::bool AS relrowsecurity, "
6350                                                   "'f'::bool AS relforcerowsecurity, "
6351                                                   "0 AS relfrozenxid, 0 AS relminmxid,"
6352                                                   "0 AS toid, "
6353                                                   "0 AS tfrozenxid, 0 AS tminmxid,"
6354                                                   "'p' AS relpersistence, 't' as relispopulated, "
6355                                                   "'d' AS relreplident, relpages, "
6356                                                   "NULL AS reloftype, "
6357                                                   "d.refobjid AS owning_tab, "
6358                                                   "d.refobjsubid AS owning_col, "
6359                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6360                                                   "NULL AS reloptions, "
6361                                                   "NULL AS toast_reloptions, "
6362                                                   "NULL AS changed_acl, "
6363                                                   "NULL AS partkeydef, "
6364                                                   "false AS ispartition, "
6365                                                   "NULL AS partbound "
6366                                                   "FROM pg_class c "
6367                                                   "LEFT JOIN pg_depend d ON "
6368                                                   "(c.relkind = '%c' AND "
6369                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6370                                                   "d.objsubid = 0 AND "
6371                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
6372                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
6373                                                   "ORDER BY c.oid",
6374                                                   username_subquery,
6375                                                   RELKIND_SEQUENCE,
6376                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6377                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6378         }
6379
6380         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6381
6382         ntups = PQntuples(res);
6383
6384         *numTables = ntups;
6385
6386         /*
6387          * Extract data from result and lock dumpable tables.  We do the locking
6388          * before anything else, to minimize the window wherein a table could
6389          * disappear under us.
6390          *
6391          * Note that we have to save info about all tables here, even when dumping
6392          * only one, because we don't yet know which tables might be inheritance
6393          * ancestors of the target table.
6394          */
6395         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6396
6397         i_reltableoid = PQfnumber(res, "tableoid");
6398         i_reloid = PQfnumber(res, "oid");
6399         i_relname = PQfnumber(res, "relname");
6400         i_relnamespace = PQfnumber(res, "relnamespace");
6401         i_relacl = PQfnumber(res, "relacl");
6402         i_rrelacl = PQfnumber(res, "rrelacl");
6403         i_initrelacl = PQfnumber(res, "initrelacl");
6404         i_initrrelacl = PQfnumber(res, "initrrelacl");
6405         i_relkind = PQfnumber(res, "relkind");
6406         i_rolname = PQfnumber(res, "rolname");
6407         i_relchecks = PQfnumber(res, "relchecks");
6408         i_relhastriggers = PQfnumber(res, "relhastriggers");
6409         i_relhasindex = PQfnumber(res, "relhasindex");
6410         i_relhasrules = PQfnumber(res, "relhasrules");
6411         i_relrowsec = PQfnumber(res, "relrowsecurity");
6412         i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6413         i_relhasoids = PQfnumber(res, "relhasoids");
6414         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6415         i_relminmxid = PQfnumber(res, "relminmxid");
6416         i_toastoid = PQfnumber(res, "toid");
6417         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6418         i_toastminmxid = PQfnumber(res, "tminmxid");
6419         i_relpersistence = PQfnumber(res, "relpersistence");
6420         i_relispopulated = PQfnumber(res, "relispopulated");
6421         i_relreplident = PQfnumber(res, "relreplident");
6422         i_relpages = PQfnumber(res, "relpages");
6423         i_owning_tab = PQfnumber(res, "owning_tab");
6424         i_owning_col = PQfnumber(res, "owning_col");
6425         i_reltablespace = PQfnumber(res, "reltablespace");
6426         i_reloptions = PQfnumber(res, "reloptions");
6427         i_checkoption = PQfnumber(res, "checkoption");
6428         i_toastreloptions = PQfnumber(res, "toast_reloptions");
6429         i_reloftype = PQfnumber(res, "reloftype");
6430         i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6431         i_changed_acl = PQfnumber(res, "changed_acl");
6432         i_partkeydef = PQfnumber(res, "partkeydef");
6433         i_ispartition = PQfnumber(res, "ispartition");
6434         i_partbound = PQfnumber(res, "partbound");
6435
6436         if (dopt->lockWaitTimeout)
6437         {
6438                 /*
6439                  * Arrange to fail instead of waiting forever for a table lock.
6440                  *
6441                  * NB: this coding assumes that the only queries issued within the
6442                  * following loop are LOCK TABLEs; else the timeout may be undesirably
6443                  * applied to other things too.
6444                  */
6445                 resetPQExpBuffer(query);
6446                 appendPQExpBufferStr(query, "SET statement_timeout = ");
6447                 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6448                 ExecuteSqlStatement(fout, query->data);
6449         }
6450
6451         for (i = 0; i < ntups; i++)
6452         {
6453                 tblinfo[i].dobj.objType = DO_TABLE;
6454                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6455                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6456                 AssignDumpId(&tblinfo[i].dobj);
6457                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6458                 tblinfo[i].dobj.namespace =
6459                         findNamespace(fout,
6460                                                   atooid(PQgetvalue(res, i, i_relnamespace)));
6461                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6462                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6463                 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6464                 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6465                 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6466                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6467                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6468                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6469                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6470                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6471                 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6472                 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6473                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6474                 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6475                 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6476                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6477                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6478                 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6479                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6480                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6481                 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6482                 if (PQgetisnull(res, i, i_reloftype))
6483                         tblinfo[i].reloftype = NULL;
6484                 else
6485                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6486                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6487                 if (PQgetisnull(res, i, i_owning_tab))
6488                 {
6489                         tblinfo[i].owning_tab = InvalidOid;
6490                         tblinfo[i].owning_col = 0;
6491                 }
6492                 else
6493                 {
6494                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6495                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6496                 }
6497                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6498                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6499                 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6500                         tblinfo[i].checkoption = NULL;
6501                 else
6502                         tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6503                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6504
6505                 /* other fields were zeroed above */
6506
6507                 /*
6508                  * Decide whether we want to dump this table.
6509                  */
6510                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6511                         tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6512                 else
6513                         selectDumpableTable(&tblinfo[i], fout);
6514
6515                 /*
6516                  * If the table-level and all column-level ACLs for this table are
6517                  * unchanged, then we don't need to worry about including the ACLs for
6518                  * this table.  If any column-level ACLs have been changed, the
6519                  * 'changed_acl' column from the query will indicate that.
6520                  *
6521                  * This can result in a significant performance improvement in cases
6522                  * where we are only looking to dump out the ACL (eg: pg_catalog).
6523                  */
6524                 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6525                         PQgetisnull(res, i, i_initrelacl) &&
6526                         PQgetisnull(res, i, i_initrrelacl) &&
6527                         strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6528                         tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6529
6530                 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6531                 tblinfo[i].dummy_view = false;  /* might get set during sort */
6532                 tblinfo[i].postponed_def = false;       /* might get set during sort */
6533
6534                 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6535                                                                                    strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6536
6537                 /* Partition key string or NULL */
6538                 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6539                 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6540                 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6541
6542                 /*
6543                  * Read-lock target tables to make sure they aren't DROPPED or altered
6544                  * in schema before we get around to dumping them.
6545                  *
6546                  * Note that we don't explicitly lock parents of the target tables; we
6547                  * assume our lock on the child is enough to prevent schema
6548                  * alterations to parent tables.
6549                  *
6550                  * NOTE: it'd be kinda nice to lock other relations too, not only
6551                  * plain tables, but the backend doesn't presently allow that.
6552                  *
6553                  * We only need to lock the table for certain components; see
6554                  * pg_dump.h
6555                  */
6556                 if (tblinfo[i].dobj.dump &&
6557                         (tblinfo[i].relkind == RELKIND_RELATION ||
6558                          tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6559                         (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6560                 {
6561                         resetPQExpBuffer(query);
6562                         appendPQExpBuffer(query,
6563                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
6564                                                           fmtQualifiedId(fout->remoteVersion,
6565                                                                                          tblinfo[i].dobj.namespace->dobj.name,
6566                                                                                          tblinfo[i].dobj.name));
6567                         ExecuteSqlStatement(fout, query->data);
6568                 }
6569
6570                 /* Emit notice if join for owner failed */
6571                 if (strlen(tblinfo[i].rolname) == 0)
6572                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6573                                           tblinfo[i].dobj.name);
6574         }
6575
6576         if (dopt->lockWaitTimeout)
6577         {
6578                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6579         }
6580
6581         PQclear(res);
6582
6583         destroyPQExpBuffer(query);
6584
6585         return tblinfo;
6586 }
6587
6588 /*
6589  * getOwnedSeqs
6590  *        identify owned sequences and mark them as dumpable if owning table is
6591  *
6592  * We used to do this in getTables(), but it's better to do it after the
6593  * index used by findTableByOid() has been set up.
6594  */
6595 void
6596 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6597 {
6598         int                     i;
6599
6600         /*
6601          * Force sequences that are "owned" by table columns to be dumped whenever
6602          * their owning table is being dumped.
6603          */
6604         for (i = 0; i < numTables; i++)
6605         {
6606                 TableInfo  *seqinfo = &tblinfo[i];
6607                 TableInfo  *owning_tab;
6608
6609                 if (!OidIsValid(seqinfo->owning_tab))
6610                         continue;                       /* not an owned sequence */
6611
6612                 owning_tab = findTableByOid(seqinfo->owning_tab);
6613                 if (owning_tab == NULL)
6614                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6615                                                   seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6616
6617                 /*
6618                  * We need to dump the components that are being dumped for the table
6619                  * and any components which the sequence is explicitly marked with.
6620                  *
6621                  * We can't simply use the set of components which are being dumped
6622                  * for the table as the table might be in an extension (and only the
6623                  * non-extension components, eg: ACLs if changed, security labels, and
6624                  * policies, are being dumped) while the sequence is not (and
6625                  * therefore the definition and other components should also be
6626                  * dumped).
6627                  *
6628                  * If the sequence is part of the extension then it should be properly
6629                  * marked by checkExtensionMembership() and this will be a no-op as
6630                  * the table will be equivalently marked.
6631                  */
6632                 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6633
6634                 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6635                         seqinfo->interesting = true;
6636         }
6637 }
6638
6639 /*
6640  * getInherits
6641  *        read all the inheritance information
6642  * from the system catalogs return them in the InhInfo* structure
6643  *
6644  * numInherits is set to the number of pairs read in
6645  */
6646 InhInfo *
6647 getInherits(Archive *fout, int *numInherits)
6648 {
6649         PGresult   *res;
6650         int                     ntups;
6651         int                     i;
6652         PQExpBuffer query = createPQExpBuffer();
6653         InhInfo    *inhinfo;
6654
6655         int                     i_inhrelid;
6656         int                     i_inhparent;
6657
6658         /* Make sure we are in proper schema */
6659         selectSourceSchema(fout, "pg_catalog");
6660
6661         /*
6662          * Find all the inheritance information, excluding implicit inheritance
6663          * via partitioning.  We handle that case using getPartitions(), because
6664          * we want more information about partitions than just the parent-child
6665          * relationship.
6666          */
6667         appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6668
6669         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6670
6671         ntups = PQntuples(res);
6672
6673         *numInherits = ntups;
6674
6675         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6676
6677         i_inhrelid = PQfnumber(res, "inhrelid");
6678         i_inhparent = PQfnumber(res, "inhparent");
6679
6680         for (i = 0; i < ntups; i++)
6681         {
6682                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6683                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6684         }
6685
6686         PQclear(res);
6687
6688         destroyPQExpBuffer(query);
6689
6690         return inhinfo;
6691 }
6692
6693 /*
6694  * getIndexes
6695  *        get information about every index on a dumpable table
6696  *
6697  * Note: index data is not returned directly to the caller, but it
6698  * does get entered into the DumpableObject tables.
6699  */
6700 void
6701 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6702 {
6703         int                     i,
6704                                 j;
6705         PQExpBuffer query = createPQExpBuffer();
6706         PGresult   *res;
6707         IndxInfo   *indxinfo;
6708         ConstraintInfo *constrinfo;
6709         int                     i_tableoid,
6710                                 i_oid,
6711                                 i_indexname,
6712                                 i_parentidx,
6713                                 i_indexdef,
6714                                 i_indnkeys,
6715                                 i_indkey,
6716                                 i_indisclustered,
6717                                 i_indisreplident,
6718                                 i_contype,
6719                                 i_conname,
6720                                 i_condeferrable,
6721                                 i_condeferred,
6722                                 i_contableoid,
6723                                 i_conoid,
6724                                 i_condef,
6725                                 i_tablespace,
6726                                 i_indreloptions,
6727                                 i_relpages;
6728         int                     ntups;
6729
6730         for (i = 0; i < numTables; i++)
6731         {
6732                 TableInfo  *tbinfo = &tblinfo[i];
6733
6734                 if (!tbinfo->hasindex)
6735                         continue;
6736
6737                 /*
6738                  * Ignore indexes of tables whose definitions are not to be dumped.
6739                  *
6740                  * We also need indexes on partitioned tables which have partitions to
6741                  * be dumped, in order to dump the indexes on the partitions.
6742                  */
6743                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6744                         !tbinfo->interesting)
6745                         continue;
6746
6747                 if (g_verbose)
6748                         write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6749                                           tbinfo->dobj.namespace->dobj.name,
6750                                           tbinfo->dobj.name);
6751
6752                 /* Make sure we are in proper schema so indexdef is right */
6753                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6754
6755                 /*
6756                  * The point of the messy-looking outer join is to find a constraint
6757                  * that is related by an internal dependency link to the index. If we
6758                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
6759                  * assume an index won't have more than one internal dependency.
6760                  *
6761                  * As of 9.0 we don't need to look at pg_depend but can check for a
6762                  * match to pg_constraint.conindid.  The check on conrelid is
6763                  * redundant but useful because that column is indexed while conindid
6764                  * is not.
6765                  */
6766                 resetPQExpBuffer(query);
6767                 if (fout->remoteVersion >= 110000)
6768                 {
6769                         appendPQExpBuffer(query,
6770                                                           "SELECT t.tableoid, t.oid, "
6771                                                           "t.relname AS indexname, "
6772                                                           "inh.inhparent AS parentidx, "
6773                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6774                                                           "t.relnatts AS indnkeys, "
6775                                                           "i.indkey, i.indisclustered, "
6776                                                           "i.indisreplident, t.relpages, "
6777                                                           "c.contype, c.conname, "
6778                                                           "c.condeferrable, c.condeferred, "
6779                                                           "c.tableoid AS contableoid, "
6780                                                           "c.oid AS conoid, "
6781                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6782                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6783                                                           "t.reloptions AS indreloptions "
6784                                                           "FROM pg_catalog.pg_index i "
6785                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6786                                                           "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6787                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6788                                                           "ON (i.indrelid = c.conrelid AND "
6789                                                           "i.indexrelid = c.conindid AND "
6790                                                           "c.contype IN ('p','u','x')) "
6791                                                           "LEFT JOIN pg_catalog.pg_inherits inh "
6792                                                           "ON (inh.inhrelid = indexrelid) "
6793                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6794                                                           "AND (i.indisvalid OR t2.relkind = 'p') "
6795                                                           "AND i.indisready "
6796                                                           "ORDER BY indexname",
6797                                                           tbinfo->dobj.catId.oid);
6798                 }
6799                 else if (fout->remoteVersion >= 90400)
6800                 {
6801                         /*
6802                          * the test on indisready is necessary in 9.2, and harmless in
6803                          * earlier/later versions
6804                          */
6805                         appendPQExpBuffer(query,
6806                                                           "SELECT t.tableoid, t.oid, "
6807                                                           "t.relname AS indexname, "
6808                                                           "0 AS parentidx, "
6809                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6810                                                           "t.relnatts AS indnkeys, "
6811                                                           "i.indkey, i.indisclustered, "
6812                                                           "i.indisreplident, t.relpages, "
6813                                                           "c.contype, c.conname, "
6814                                                           "c.condeferrable, c.condeferred, "
6815                                                           "c.tableoid AS contableoid, "
6816                                                           "c.oid AS conoid, "
6817                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6818                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6819                                                           "t.reloptions AS indreloptions "
6820                                                           "FROM pg_catalog.pg_index i "
6821                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6822                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6823                                                           "ON (i.indrelid = c.conrelid AND "
6824                                                           "i.indexrelid = c.conindid AND "
6825                                                           "c.contype IN ('p','u','x')) "
6826                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6827                                                           "AND i.indisvalid AND i.indisready "
6828                                                           "ORDER BY indexname",
6829                                                           tbinfo->dobj.catId.oid);
6830                 }
6831                 else if (fout->remoteVersion >= 90000)
6832                 {
6833                         /*
6834                          * the test on indisready is necessary in 9.2, and harmless in
6835                          * earlier/later versions
6836                          */
6837                         appendPQExpBuffer(query,
6838                                                           "SELECT t.tableoid, t.oid, "
6839                                                           "t.relname AS indexname, "
6840                                                           "0 AS parentidx, "
6841                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6842                                                           "t.relnatts AS indnkeys, "
6843                                                           "i.indkey, i.indisclustered, "
6844                                                           "false AS indisreplident, t.relpages, "
6845                                                           "c.contype, c.conname, "
6846                                                           "c.condeferrable, c.condeferred, "
6847                                                           "c.tableoid AS contableoid, "
6848                                                           "c.oid AS conoid, "
6849                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6850                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6851                                                           "t.reloptions AS indreloptions "
6852                                                           "FROM pg_catalog.pg_index i "
6853                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6854                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6855                                                           "ON (i.indrelid = c.conrelid AND "
6856                                                           "i.indexrelid = c.conindid AND "
6857                                                           "c.contype IN ('p','u','x')) "
6858                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6859                                                           "AND i.indisvalid AND i.indisready "
6860                                                           "ORDER BY indexname",
6861                                                           tbinfo->dobj.catId.oid);
6862                 }
6863                 else if (fout->remoteVersion >= 80200)
6864                 {
6865                         appendPQExpBuffer(query,
6866                                                           "SELECT t.tableoid, t.oid, "
6867                                                           "t.relname AS indexname, "
6868                                                           "0 AS parentidx, "
6869                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6870                                                           "t.relnatts AS indnkeys, "
6871                                                           "i.indkey, i.indisclustered, "
6872                                                           "false AS indisreplident, t.relpages, "
6873                                                           "c.contype, c.conname, "
6874                                                           "c.condeferrable, c.condeferred, "
6875                                                           "c.tableoid AS contableoid, "
6876                                                           "c.oid AS conoid, "
6877                                                           "null AS condef, "
6878                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6879                                                           "t.reloptions AS indreloptions "
6880                                                           "FROM pg_catalog.pg_index i "
6881                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6882                                                           "LEFT JOIN pg_catalog.pg_depend d "
6883                                                           "ON (d.classid = t.tableoid "
6884                                                           "AND d.objid = t.oid "
6885                                                           "AND d.deptype = 'i') "
6886                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6887                                                           "ON (d.refclassid = c.tableoid "
6888                                                           "AND d.refobjid = c.oid) "
6889                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6890                                                           "AND i.indisvalid "
6891                                                           "ORDER BY indexname",
6892                                                           tbinfo->dobj.catId.oid);
6893                 }
6894                 else
6895                 {
6896                         appendPQExpBuffer(query,
6897                                                           "SELECT t.tableoid, t.oid, "
6898                                                           "t.relname AS indexname, "
6899                                                           "0 AS parentidx, "
6900                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6901                                                           "t.relnatts AS indnkeys, "
6902                                                           "i.indkey, i.indisclustered, "
6903                                                           "false AS indisreplident, t.relpages, "
6904                                                           "c.contype, c.conname, "
6905                                                           "c.condeferrable, c.condeferred, "
6906                                                           "c.tableoid AS contableoid, "
6907                                                           "c.oid AS conoid, "
6908                                                           "null AS condef, "
6909                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6910                                                           "null AS indreloptions "
6911                                                           "FROM pg_catalog.pg_index i "
6912                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6913                                                           "LEFT JOIN pg_catalog.pg_depend d "
6914                                                           "ON (d.classid = t.tableoid "
6915                                                           "AND d.objid = t.oid "
6916                                                           "AND d.deptype = 'i') "
6917                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6918                                                           "ON (d.refclassid = c.tableoid "
6919                                                           "AND d.refobjid = c.oid) "
6920                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6921                                                           "ORDER BY indexname",
6922                                                           tbinfo->dobj.catId.oid);
6923                 }
6924
6925                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6926
6927                 ntups = PQntuples(res);
6928
6929                 i_tableoid = PQfnumber(res, "tableoid");
6930                 i_oid = PQfnumber(res, "oid");
6931                 i_indexname = PQfnumber(res, "indexname");
6932                 i_parentidx = PQfnumber(res, "parentidx");
6933                 i_indexdef = PQfnumber(res, "indexdef");
6934                 i_indnkeys = PQfnumber(res, "indnkeys");
6935                 i_indkey = PQfnumber(res, "indkey");
6936                 i_indisclustered = PQfnumber(res, "indisclustered");
6937                 i_indisreplident = PQfnumber(res, "indisreplident");
6938                 i_relpages = PQfnumber(res, "relpages");
6939                 i_contype = PQfnumber(res, "contype");
6940                 i_conname = PQfnumber(res, "conname");
6941                 i_condeferrable = PQfnumber(res, "condeferrable");
6942                 i_condeferred = PQfnumber(res, "condeferred");
6943                 i_contableoid = PQfnumber(res, "contableoid");
6944                 i_conoid = PQfnumber(res, "conoid");
6945                 i_condef = PQfnumber(res, "condef");
6946                 i_tablespace = PQfnumber(res, "tablespace");
6947                 i_indreloptions = PQfnumber(res, "indreloptions");
6948
6949                 tbinfo->indexes = indxinfo =
6950                         (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6951                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6952                 tbinfo->numIndexes = ntups;
6953
6954                 for (j = 0; j < ntups; j++)
6955                 {
6956                         char            contype;
6957
6958                         indxinfo[j].dobj.objType = DO_INDEX;
6959                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6960                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6961                         AssignDumpId(&indxinfo[j].dobj);
6962                         indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6963                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6964                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6965                         indxinfo[j].indextable = tbinfo;
6966                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6967                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
6968                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6969                         indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6970                         indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnkeys * sizeof(Oid));
6971                         parseOidArray(PQgetvalue(res, j, i_indkey),
6972                                                   indxinfo[j].indkeys, indxinfo[j].indnkeys);
6973                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6974                         indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6975                         indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6976                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
6977                         contype = *(PQgetvalue(res, j, i_contype));
6978
6979                         if (contype == 'p' || contype == 'u' || contype == 'x')
6980                         {
6981                                 /*
6982                                  * If we found a constraint matching the index, create an
6983                                  * entry for it.
6984                                  */
6985                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6986                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6987                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6988                                 AssignDumpId(&constrinfo[j].dobj);
6989                                 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
6990                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6991                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6992                                 constrinfo[j].contable = tbinfo;
6993                                 constrinfo[j].condomain = NULL;
6994                                 constrinfo[j].contype = contype;
6995                                 if (contype == 'x')
6996                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6997                                 else
6998                                         constrinfo[j].condef = NULL;
6999                                 constrinfo[j].confrelid = InvalidOid;
7000                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7001                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7002                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7003                                 constrinfo[j].conislocal = true;
7004                                 constrinfo[j].separate = true;
7005
7006                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7007                         }
7008                         else
7009                         {
7010                                 /* Plain secondary index */
7011                                 indxinfo[j].indexconstraint = 0;
7012                         }
7013                 }
7014
7015                 PQclear(res);
7016         }
7017
7018         destroyPQExpBuffer(query);
7019 }
7020
7021 /*
7022  * getExtendedStatistics
7023  *        get information about extended-statistics objects.
7024  *
7025  * Note: extended statistics data is not returned directly to the caller, but
7026  * it does get entered into the DumpableObject tables.
7027  */
7028 void
7029 getExtendedStatistics(Archive *fout)
7030 {
7031         PQExpBuffer query;
7032         PGresult   *res;
7033         StatsExtInfo *statsextinfo;
7034         int                     ntups;
7035         int                     i_tableoid;
7036         int                     i_oid;
7037         int                     i_stxname;
7038         int                     i_stxnamespace;
7039         int                     i_rolname;
7040         int                     i;
7041
7042         /* Extended statistics were new in v10 */
7043         if (fout->remoteVersion < 100000)
7044                 return;
7045
7046         query = createPQExpBuffer();
7047
7048         /* Make sure we are in proper schema */
7049         selectSourceSchema(fout, "pg_catalog");
7050
7051         appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7052                                           "stxnamespace, (%s stxowner) AS rolname "
7053                                           "FROM pg_catalog.pg_statistic_ext",
7054                                           username_subquery);
7055
7056         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7057
7058         ntups = PQntuples(res);
7059
7060         i_tableoid = PQfnumber(res, "tableoid");
7061         i_oid = PQfnumber(res, "oid");
7062         i_stxname = PQfnumber(res, "stxname");
7063         i_stxnamespace = PQfnumber(res, "stxnamespace");
7064         i_rolname = PQfnumber(res, "rolname");
7065
7066         statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7067
7068         for (i = 0; i < ntups; i++)
7069         {
7070                 statsextinfo[i].dobj.objType = DO_STATSEXT;
7071                 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7072                 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7073                 AssignDumpId(&statsextinfo[i].dobj);
7074                 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7075                 statsextinfo[i].dobj.namespace =
7076                         findNamespace(fout,
7077                                                   atooid(PQgetvalue(res, i, i_stxnamespace)));
7078                 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7079
7080                 /* Decide whether we want to dump it */
7081                 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7082
7083                 /* Stats objects do not currently have ACLs. */
7084                 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7085         }
7086
7087         PQclear(res);
7088         destroyPQExpBuffer(query);
7089 }
7090
7091 /*
7092  * getConstraints
7093  *
7094  * Get info about constraints on dumpable tables.
7095  *
7096  * Currently handles foreign keys only.
7097  * Unique and primary key constraints are handled with indexes,
7098  * while check constraints are processed in getTableAttrs().
7099  */
7100 void
7101 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7102 {
7103         int                     i,
7104                                 j;
7105         ConstraintInfo *constrinfo;
7106         PQExpBuffer query;
7107         PGresult   *res;
7108         int                     i_contableoid,
7109                                 i_conoid,
7110                                 i_conname,
7111                                 i_confrelid,
7112                                 i_condef;
7113         int                     ntups;
7114
7115         query = createPQExpBuffer();
7116
7117         for (i = 0; i < numTables; i++)
7118         {
7119                 TableInfo  *tbinfo = &tblinfo[i];
7120
7121                 if (!tbinfo->hastriggers ||
7122                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7123                         continue;
7124
7125                 if (g_verbose)
7126                         write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7127                                           tbinfo->dobj.namespace->dobj.name,
7128                                           tbinfo->dobj.name);
7129
7130                 /*
7131                  * select table schema to ensure constraint expr is qualified if
7132                  * needed
7133                  */
7134                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7135
7136                 resetPQExpBuffer(query);
7137                 appendPQExpBuffer(query,
7138                                                   "SELECT tableoid, oid, conname, confrelid, "
7139                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
7140                                                   "FROM pg_catalog.pg_constraint "
7141                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
7142                                                   "AND contype = 'f'",
7143                                                   tbinfo->dobj.catId.oid);
7144                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7145
7146                 ntups = PQntuples(res);
7147
7148                 i_contableoid = PQfnumber(res, "tableoid");
7149                 i_conoid = PQfnumber(res, "oid");
7150                 i_conname = PQfnumber(res, "conname");
7151                 i_confrelid = PQfnumber(res, "confrelid");
7152                 i_condef = PQfnumber(res, "condef");
7153
7154                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7155
7156                 for (j = 0; j < ntups; j++)
7157                 {
7158                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7159                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7160                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7161                         AssignDumpId(&constrinfo[j].dobj);
7162                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7163                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7164                         constrinfo[j].contable = tbinfo;
7165                         constrinfo[j].condomain = NULL;
7166                         constrinfo[j].contype = 'f';
7167                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7168                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7169                         constrinfo[j].conindex = 0;
7170                         constrinfo[j].condeferrable = false;
7171                         constrinfo[j].condeferred = false;
7172                         constrinfo[j].conislocal = true;
7173                         constrinfo[j].separate = true;
7174                 }
7175
7176                 PQclear(res);
7177         }
7178
7179         destroyPQExpBuffer(query);
7180 }
7181
7182 /*
7183  * getDomainConstraints
7184  *
7185  * Get info about constraints on a domain.
7186  */
7187 static void
7188 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7189 {
7190         int                     i;
7191         ConstraintInfo *constrinfo;
7192         PQExpBuffer query;
7193         PGresult   *res;
7194         int                     i_tableoid,
7195                                 i_oid,
7196                                 i_conname,
7197                                 i_consrc;
7198         int                     ntups;
7199
7200         /*
7201          * select appropriate schema to ensure names in constraint are properly
7202          * qualified
7203          */
7204         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7205
7206         query = createPQExpBuffer();
7207
7208         if (fout->remoteVersion >= 90100)
7209                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7210                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7211                                                   "convalidated "
7212                                                   "FROM pg_catalog.pg_constraint "
7213                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7214                                                   "ORDER BY conname",
7215                                                   tyinfo->dobj.catId.oid);
7216
7217         else
7218                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7219                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7220                                                   "true as convalidated "
7221                                                   "FROM pg_catalog.pg_constraint "
7222                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7223                                                   "ORDER BY conname",
7224                                                   tyinfo->dobj.catId.oid);
7225
7226         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7227
7228         ntups = PQntuples(res);
7229
7230         i_tableoid = PQfnumber(res, "tableoid");
7231         i_oid = PQfnumber(res, "oid");
7232         i_conname = PQfnumber(res, "conname");
7233         i_consrc = PQfnumber(res, "consrc");
7234
7235         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7236
7237         tyinfo->nDomChecks = ntups;
7238         tyinfo->domChecks = constrinfo;
7239
7240         for (i = 0; i < ntups; i++)
7241         {
7242                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
7243
7244                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7245                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7246                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7247                 AssignDumpId(&constrinfo[i].dobj);
7248                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7249                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7250                 constrinfo[i].contable = NULL;
7251                 constrinfo[i].condomain = tyinfo;
7252                 constrinfo[i].contype = 'c';
7253                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7254                 constrinfo[i].confrelid = InvalidOid;
7255                 constrinfo[i].conindex = 0;
7256                 constrinfo[i].condeferrable = false;
7257                 constrinfo[i].condeferred = false;
7258                 constrinfo[i].conislocal = true;
7259
7260                 constrinfo[i].separate = !validated;
7261
7262                 /*
7263                  * Make the domain depend on the constraint, ensuring it won't be
7264                  * output till any constraint dependencies are OK.  If the constraint
7265                  * has not been validated, it's going to be dumped after the domain
7266                  * anyway, so this doesn't matter.
7267                  */
7268                 if (validated)
7269                         addObjectDependency(&tyinfo->dobj,
7270                                                                 constrinfo[i].dobj.dumpId);
7271         }
7272
7273         PQclear(res);
7274
7275         destroyPQExpBuffer(query);
7276 }
7277
7278 /*
7279  * getRules
7280  *        get basic information about every rule in the system
7281  *
7282  * numRules is set to the number of rules read in
7283  */
7284 RuleInfo *
7285 getRules(Archive *fout, int *numRules)
7286 {
7287         PGresult   *res;
7288         int                     ntups;
7289         int                     i;
7290         PQExpBuffer query = createPQExpBuffer();
7291         RuleInfo   *ruleinfo;
7292         int                     i_tableoid;
7293         int                     i_oid;
7294         int                     i_rulename;
7295         int                     i_ruletable;
7296         int                     i_ev_type;
7297         int                     i_is_instead;
7298         int                     i_ev_enabled;
7299
7300         /* Make sure we are in proper schema */
7301         selectSourceSchema(fout, "pg_catalog");
7302
7303         if (fout->remoteVersion >= 80300)
7304         {
7305                 appendPQExpBufferStr(query, "SELECT "
7306                                                          "tableoid, oid, rulename, "
7307                                                          "ev_class AS ruletable, ev_type, is_instead, "
7308                                                          "ev_enabled "
7309                                                          "FROM pg_rewrite "
7310                                                          "ORDER BY oid");
7311         }
7312         else
7313         {
7314                 appendPQExpBufferStr(query, "SELECT "
7315                                                          "tableoid, oid, rulename, "
7316                                                          "ev_class AS ruletable, ev_type, is_instead, "
7317                                                          "'O'::char AS ev_enabled "
7318                                                          "FROM pg_rewrite "
7319                                                          "ORDER BY oid");
7320         }
7321
7322         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7323
7324         ntups = PQntuples(res);
7325
7326         *numRules = ntups;
7327
7328         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7329
7330         i_tableoid = PQfnumber(res, "tableoid");
7331         i_oid = PQfnumber(res, "oid");
7332         i_rulename = PQfnumber(res, "rulename");
7333         i_ruletable = PQfnumber(res, "ruletable");
7334         i_ev_type = PQfnumber(res, "ev_type");
7335         i_is_instead = PQfnumber(res, "is_instead");
7336         i_ev_enabled = PQfnumber(res, "ev_enabled");
7337
7338         for (i = 0; i < ntups; i++)
7339         {
7340                 Oid                     ruletableoid;
7341
7342                 ruleinfo[i].dobj.objType = DO_RULE;
7343                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7344                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7345                 AssignDumpId(&ruleinfo[i].dobj);
7346                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7347                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7348                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7349                 if (ruleinfo[i].ruletable == NULL)
7350                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7351                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
7352                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7353                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7354                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7355                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7356                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7357                 if (ruleinfo[i].ruletable)
7358                 {
7359                         /*
7360                          * If the table is a view or materialized view, force its ON
7361                          * SELECT rule to be sorted before the view itself --- this
7362                          * ensures that any dependencies for the rule affect the table's
7363                          * positioning. Other rules are forced to appear after their
7364                          * table.
7365                          */
7366                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7367                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7368                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7369                         {
7370                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7371                                                                         ruleinfo[i].dobj.dumpId);
7372                                 /* We'll merge the rule into CREATE VIEW, if possible */
7373                                 ruleinfo[i].separate = false;
7374                         }
7375                         else
7376                         {
7377                                 addObjectDependency(&ruleinfo[i].dobj,
7378                                                                         ruleinfo[i].ruletable->dobj.dumpId);
7379                                 ruleinfo[i].separate = true;
7380                         }
7381                 }
7382                 else
7383                         ruleinfo[i].separate = true;
7384         }
7385
7386         PQclear(res);
7387
7388         destroyPQExpBuffer(query);
7389
7390         return ruleinfo;
7391 }
7392
7393 /*
7394  * getTriggers
7395  *        get information about every trigger on a dumpable table
7396  *
7397  * Note: trigger data is not returned directly to the caller, but it
7398  * does get entered into the DumpableObject tables.
7399  */
7400 void
7401 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7402 {
7403         int                     i,
7404                                 j;
7405         PQExpBuffer query = createPQExpBuffer();
7406         PGresult   *res;
7407         TriggerInfo *tginfo;
7408         int                     i_tableoid,
7409                                 i_oid,
7410                                 i_tgname,
7411                                 i_tgfname,
7412                                 i_tgtype,
7413                                 i_tgnargs,
7414                                 i_tgargs,
7415                                 i_tgisconstraint,
7416                                 i_tgconstrname,
7417                                 i_tgconstrrelid,
7418                                 i_tgconstrrelname,
7419                                 i_tgenabled,
7420                                 i_tgdeferrable,
7421                                 i_tginitdeferred,
7422                                 i_tgdef;
7423         int                     ntups;
7424
7425         for (i = 0; i < numTables; i++)
7426         {
7427                 TableInfo  *tbinfo = &tblinfo[i];
7428
7429                 if (!tbinfo->hastriggers ||
7430                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7431                         continue;
7432
7433                 if (g_verbose)
7434                         write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7435                                           tbinfo->dobj.namespace->dobj.name,
7436                                           tbinfo->dobj.name);
7437
7438                 /*
7439                  * select table schema to ensure regproc name is qualified if needed
7440                  */
7441                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7442
7443                 resetPQExpBuffer(query);
7444                 if (fout->remoteVersion >= 90000)
7445                 {
7446                         /*
7447                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
7448                          * could result in non-forward-compatible dumps of WHEN clauses
7449                          * due to under-parenthesization.
7450                          */
7451                         appendPQExpBuffer(query,
7452                                                           "SELECT tgname, "
7453                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7454                                                           "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7455                                                           "tgenabled, tableoid, oid "
7456                                                           "FROM pg_catalog.pg_trigger t "
7457                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7458                                                           "AND NOT tgisinternal",
7459                                                           tbinfo->dobj.catId.oid);
7460                 }
7461                 else if (fout->remoteVersion >= 80300)
7462                 {
7463                         /*
7464                          * We ignore triggers that are tied to a foreign-key constraint
7465                          */
7466                         appendPQExpBuffer(query,
7467                                                           "SELECT tgname, "
7468                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7469                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7470                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7471                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7472                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7473                                                           "FROM pg_catalog.pg_trigger t "
7474                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7475                                                           "AND tgconstraint = 0",
7476                                                           tbinfo->dobj.catId.oid);
7477                 }
7478                 else
7479                 {
7480                         /*
7481                          * We ignore triggers that are tied to a foreign-key constraint,
7482                          * but in these versions we have to grovel through pg_constraint
7483                          * to find out
7484                          */
7485                         appendPQExpBuffer(query,
7486                                                           "SELECT tgname, "
7487                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7488                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7489                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7490                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7491                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7492                                                           "FROM pg_catalog.pg_trigger t "
7493                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7494                                                           "AND (NOT tgisconstraint "
7495                                                           " OR NOT EXISTS"
7496                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
7497                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7498                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7499                                                           tbinfo->dobj.catId.oid);
7500                 }
7501
7502                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7503
7504                 ntups = PQntuples(res);
7505
7506                 i_tableoid = PQfnumber(res, "tableoid");
7507                 i_oid = PQfnumber(res, "oid");
7508                 i_tgname = PQfnumber(res, "tgname");
7509                 i_tgfname = PQfnumber(res, "tgfname");
7510                 i_tgtype = PQfnumber(res, "tgtype");
7511                 i_tgnargs = PQfnumber(res, "tgnargs");
7512                 i_tgargs = PQfnumber(res, "tgargs");
7513                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7514                 i_tgconstrname = PQfnumber(res, "tgconstrname");
7515                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7516                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7517                 i_tgenabled = PQfnumber(res, "tgenabled");
7518                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7519                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7520                 i_tgdef = PQfnumber(res, "tgdef");
7521
7522                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7523
7524                 tbinfo->numTriggers = ntups;
7525                 tbinfo->triggers = tginfo;
7526
7527                 for (j = 0; j < ntups; j++)
7528                 {
7529                         tginfo[j].dobj.objType = DO_TRIGGER;
7530                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7531                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7532                         AssignDumpId(&tginfo[j].dobj);
7533                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7534                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7535                         tginfo[j].tgtable = tbinfo;
7536                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7537                         if (i_tgdef >= 0)
7538                         {
7539                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7540
7541                                 /* remaining fields are not valid if we have tgdef */
7542                                 tginfo[j].tgfname = NULL;
7543                                 tginfo[j].tgtype = 0;
7544                                 tginfo[j].tgnargs = 0;
7545                                 tginfo[j].tgargs = NULL;
7546                                 tginfo[j].tgisconstraint = false;
7547                                 tginfo[j].tgdeferrable = false;
7548                                 tginfo[j].tginitdeferred = false;
7549                                 tginfo[j].tgconstrname = NULL;
7550                                 tginfo[j].tgconstrrelid = InvalidOid;
7551                                 tginfo[j].tgconstrrelname = NULL;
7552                         }
7553                         else
7554                         {
7555                                 tginfo[j].tgdef = NULL;
7556
7557                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7558                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7559                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7560                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7561                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7562                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7563                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7564
7565                                 if (tginfo[j].tgisconstraint)
7566                                 {
7567                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7568                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7569                                         if (OidIsValid(tginfo[j].tgconstrrelid))
7570                                         {
7571                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
7572                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7573                                                                                   tginfo[j].dobj.name,
7574                                                                                   tbinfo->dobj.name,
7575                                                                                   tginfo[j].tgconstrrelid);
7576                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7577                                         }
7578                                         else
7579                                                 tginfo[j].tgconstrrelname = NULL;
7580                                 }
7581                                 else
7582                                 {
7583                                         tginfo[j].tgconstrname = NULL;
7584                                         tginfo[j].tgconstrrelid = InvalidOid;
7585                                         tginfo[j].tgconstrrelname = NULL;
7586                                 }
7587                         }
7588                 }
7589
7590                 PQclear(res);
7591         }
7592
7593         destroyPQExpBuffer(query);
7594 }
7595
7596 /*
7597  * getEventTriggers
7598  *        get information about event triggers
7599  */
7600 EventTriggerInfo *
7601 getEventTriggers(Archive *fout, int *numEventTriggers)
7602 {
7603         int                     i;
7604         PQExpBuffer query;
7605         PGresult   *res;
7606         EventTriggerInfo *evtinfo;
7607         int                     i_tableoid,
7608                                 i_oid,
7609                                 i_evtname,
7610                                 i_evtevent,
7611                                 i_evtowner,
7612                                 i_evttags,
7613                                 i_evtfname,
7614                                 i_evtenabled;
7615         int                     ntups;
7616
7617         /* Before 9.3, there are no event triggers */
7618         if (fout->remoteVersion < 90300)
7619         {
7620                 *numEventTriggers = 0;
7621                 return NULL;
7622         }
7623
7624         query = createPQExpBuffer();
7625
7626         /* Make sure we are in proper schema */
7627         selectSourceSchema(fout, "pg_catalog");
7628
7629         appendPQExpBuffer(query,
7630                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7631                                           "evtevent, (%s evtowner) AS evtowner, "
7632                                           "array_to_string(array("
7633                                           "select quote_literal(x) "
7634                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
7635                                           "e.evtfoid::regproc as evtfname "
7636                                           "FROM pg_event_trigger e "
7637                                           "ORDER BY e.oid",
7638                                           username_subquery);
7639
7640         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7641
7642         ntups = PQntuples(res);
7643
7644         *numEventTriggers = ntups;
7645
7646         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7647
7648         i_tableoid = PQfnumber(res, "tableoid");
7649         i_oid = PQfnumber(res, "oid");
7650         i_evtname = PQfnumber(res, "evtname");
7651         i_evtevent = PQfnumber(res, "evtevent");
7652         i_evtowner = PQfnumber(res, "evtowner");
7653         i_evttags = PQfnumber(res, "evttags");
7654         i_evtfname = PQfnumber(res, "evtfname");
7655         i_evtenabled = PQfnumber(res, "evtenabled");
7656
7657         for (i = 0; i < ntups; i++)
7658         {
7659                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7660                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7661                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7662                 AssignDumpId(&evtinfo[i].dobj);
7663                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7664                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7665                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7666                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7667                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7668                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7669                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7670
7671                 /* Decide whether we want to dump it */
7672                 selectDumpableObject(&(evtinfo[i].dobj), fout);
7673
7674                 /* Event Triggers do not currently have ACLs. */
7675                 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7676         }
7677
7678         PQclear(res);
7679
7680         destroyPQExpBuffer(query);
7681
7682         return evtinfo;
7683 }
7684
7685 /*
7686  * getProcLangs
7687  *        get basic information about every procedural language in the system
7688  *
7689  * numProcLangs is set to the number of langs read in
7690  *
7691  * NB: this must run after getFuncs() because we assume we can do
7692  * findFuncByOid().
7693  */
7694 ProcLangInfo *
7695 getProcLangs(Archive *fout, int *numProcLangs)
7696 {
7697         DumpOptions *dopt = fout->dopt;
7698         PGresult   *res;
7699         int                     ntups;
7700         int                     i;
7701         PQExpBuffer query = createPQExpBuffer();
7702         ProcLangInfo *planginfo;
7703         int                     i_tableoid;
7704         int                     i_oid;
7705         int                     i_lanname;
7706         int                     i_lanpltrusted;
7707         int                     i_lanplcallfoid;
7708         int                     i_laninline;
7709         int                     i_lanvalidator;
7710         int                     i_lanacl;
7711         int                     i_rlanacl;
7712         int                     i_initlanacl;
7713         int                     i_initrlanacl;
7714         int                     i_lanowner;
7715
7716         /* Make sure we are in proper schema */
7717         selectSourceSchema(fout, "pg_catalog");
7718
7719         if (fout->remoteVersion >= 90600)
7720         {
7721                 PQExpBuffer acl_subquery = createPQExpBuffer();
7722                 PQExpBuffer racl_subquery = createPQExpBuffer();
7723                 PQExpBuffer initacl_subquery = createPQExpBuffer();
7724                 PQExpBuffer initracl_subquery = createPQExpBuffer();
7725
7726                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7727                                                 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7728                                                 dopt->binary_upgrade);
7729
7730                 /* pg_language has a laninline column */
7731                 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7732                                                   "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7733                                                   "l.laninline, l.lanvalidator, "
7734                                                   "%s AS lanacl, "
7735                                                   "%s AS rlanacl, "
7736                                                   "%s AS initlanacl, "
7737                                                   "%s AS initrlanacl, "
7738                                                   "(%s l.lanowner) AS lanowner "
7739                                                   "FROM pg_language l "
7740                                                   "LEFT JOIN pg_init_privs pip ON "
7741                                                   "(l.oid = pip.objoid "
7742                                                   "AND pip.classoid = 'pg_language'::regclass "
7743                                                   "AND pip.objsubid = 0) "
7744                                                   "WHERE l.lanispl "
7745                                                   "ORDER BY l.oid",
7746                                                   acl_subquery->data,
7747                                                   racl_subquery->data,
7748                                                   initacl_subquery->data,
7749                                                   initracl_subquery->data,
7750                                                   username_subquery);
7751
7752                 destroyPQExpBuffer(acl_subquery);
7753                 destroyPQExpBuffer(racl_subquery);
7754                 destroyPQExpBuffer(initacl_subquery);
7755                 destroyPQExpBuffer(initracl_subquery);
7756         }
7757         else if (fout->remoteVersion >= 90000)
7758         {
7759                 /* pg_language has a laninline column */
7760                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7761                                                   "lanname, lanpltrusted, lanplcallfoid, "
7762                                                   "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7763                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7764                                                   "(%s lanowner) AS lanowner "
7765                                                   "FROM pg_language "
7766                                                   "WHERE lanispl "
7767                                                   "ORDER BY oid",
7768                                                   username_subquery);
7769         }
7770         else if (fout->remoteVersion >= 80300)
7771         {
7772                 /* pg_language has a lanowner column */
7773                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7774                                                   "lanname, lanpltrusted, lanplcallfoid, "
7775                                                   "0 AS laninline, lanvalidator, lanacl, "
7776                                                   "NULL AS rlanacl, "
7777                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7778                                                   "(%s lanowner) AS lanowner "
7779                                                   "FROM pg_language "
7780                                                   "WHERE lanispl "
7781                                                   "ORDER BY oid",
7782                                                   username_subquery);
7783         }
7784         else if (fout->remoteVersion >= 80100)
7785         {
7786                 /* Languages are owned by the bootstrap superuser, OID 10 */
7787                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7788                                                   "lanname, lanpltrusted, lanplcallfoid, "
7789                                                   "0 AS laninline, lanvalidator, lanacl, "
7790                                                   "NULL AS rlanacl, "
7791                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7792                                                   "(%s '10') AS lanowner "
7793                                                   "FROM pg_language "
7794                                                   "WHERE lanispl "
7795                                                   "ORDER BY oid",
7796                                                   username_subquery);
7797         }
7798         else
7799         {
7800                 /* Languages are owned by the bootstrap superuser, sysid 1 */
7801                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7802                                                   "lanname, lanpltrusted, lanplcallfoid, "
7803                                                   "0 AS laninline, lanvalidator, lanacl, "
7804                                                   "NULL AS rlanacl, "
7805                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7806                                                   "(%s '1') AS lanowner "
7807                                                   "FROM pg_language "
7808                                                   "WHERE lanispl "
7809                                                   "ORDER BY oid",
7810                                                   username_subquery);
7811         }
7812
7813         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7814
7815         ntups = PQntuples(res);
7816
7817         *numProcLangs = ntups;
7818
7819         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7820
7821         i_tableoid = PQfnumber(res, "tableoid");
7822         i_oid = PQfnumber(res, "oid");
7823         i_lanname = PQfnumber(res, "lanname");
7824         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7825         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7826         i_laninline = PQfnumber(res, "laninline");
7827         i_lanvalidator = PQfnumber(res, "lanvalidator");
7828         i_lanacl = PQfnumber(res, "lanacl");
7829         i_rlanacl = PQfnumber(res, "rlanacl");
7830         i_initlanacl = PQfnumber(res, "initlanacl");
7831         i_initrlanacl = PQfnumber(res, "initrlanacl");
7832         i_lanowner = PQfnumber(res, "lanowner");
7833
7834         for (i = 0; i < ntups; i++)
7835         {
7836                 planginfo[i].dobj.objType = DO_PROCLANG;
7837                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7838                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7839                 AssignDumpId(&planginfo[i].dobj);
7840
7841                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7842                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7843                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7844                 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7845                 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7846                 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7847                 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7848                 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7849                 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7850                 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7851
7852                 /* Decide whether we want to dump it */
7853                 selectDumpableProcLang(&(planginfo[i]), fout);
7854
7855                 /* Do not try to dump ACL if no ACL exists. */
7856                 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7857                         PQgetisnull(res, i, i_initlanacl) &&
7858                         PQgetisnull(res, i, i_initrlanacl))
7859                         planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7860         }
7861
7862         PQclear(res);
7863
7864         destroyPQExpBuffer(query);
7865
7866         return planginfo;
7867 }
7868
7869 /*
7870  * getCasts
7871  *        get basic information about every cast in the system
7872  *
7873  * numCasts is set to the number of casts read in
7874  */
7875 CastInfo *
7876 getCasts(Archive *fout, int *numCasts)
7877 {
7878         PGresult   *res;
7879         int                     ntups;
7880         int                     i;
7881         PQExpBuffer query = createPQExpBuffer();
7882         CastInfo   *castinfo;
7883         int                     i_tableoid;
7884         int                     i_oid;
7885         int                     i_castsource;
7886         int                     i_casttarget;
7887         int                     i_castfunc;
7888         int                     i_castcontext;
7889         int                     i_castmethod;
7890
7891         /* Make sure we are in proper schema */
7892         selectSourceSchema(fout, "pg_catalog");
7893
7894         if (fout->remoteVersion >= 80400)
7895         {
7896                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7897                                                          "castsource, casttarget, castfunc, castcontext, "
7898                                                          "castmethod "
7899                                                          "FROM pg_cast ORDER BY 3,4");
7900         }
7901         else
7902         {
7903                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7904                                                          "castsource, casttarget, castfunc, castcontext, "
7905                                                          "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7906                                                          "FROM pg_cast ORDER BY 3,4");
7907         }
7908
7909         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7910
7911         ntups = PQntuples(res);
7912
7913         *numCasts = ntups;
7914
7915         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7916
7917         i_tableoid = PQfnumber(res, "tableoid");
7918         i_oid = PQfnumber(res, "oid");
7919         i_castsource = PQfnumber(res, "castsource");
7920         i_casttarget = PQfnumber(res, "casttarget");
7921         i_castfunc = PQfnumber(res, "castfunc");
7922         i_castcontext = PQfnumber(res, "castcontext");
7923         i_castmethod = PQfnumber(res, "castmethod");
7924
7925         for (i = 0; i < ntups; i++)
7926         {
7927                 PQExpBufferData namebuf;
7928                 TypeInfo   *sTypeInfo;
7929                 TypeInfo   *tTypeInfo;
7930
7931                 castinfo[i].dobj.objType = DO_CAST;
7932                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7933                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7934                 AssignDumpId(&castinfo[i].dobj);
7935                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7936                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7937                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7938                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7939                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7940
7941                 /*
7942                  * Try to name cast as concatenation of typnames.  This is only used
7943                  * for purposes of sorting.  If we fail to find either type, the name
7944                  * will be an empty string.
7945                  */
7946                 initPQExpBuffer(&namebuf);
7947                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7948                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7949                 if (sTypeInfo && tTypeInfo)
7950                         appendPQExpBuffer(&namebuf, "%s %s",
7951                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7952                 castinfo[i].dobj.name = namebuf.data;
7953
7954                 /* Decide whether we want to dump it */
7955                 selectDumpableCast(&(castinfo[i]), fout);
7956
7957                 /* Casts do not currently have ACLs. */
7958                 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7959         }
7960
7961         PQclear(res);
7962
7963         destroyPQExpBuffer(query);
7964
7965         return castinfo;
7966 }
7967
7968 static char *
7969 get_language_name(Archive *fout, Oid langid)
7970 {
7971         PQExpBuffer query;
7972         PGresult   *res;
7973         char       *lanname;
7974
7975         query = createPQExpBuffer();
7976         appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7977         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7978         lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7979         destroyPQExpBuffer(query);
7980         PQclear(res);
7981
7982         return lanname;
7983 }
7984
7985 /*
7986  * getTransforms
7987  *        get basic information about every transform in the system
7988  *
7989  * numTransforms is set to the number of transforms read in
7990  */
7991 TransformInfo *
7992 getTransforms(Archive *fout, int *numTransforms)
7993 {
7994         PGresult   *res;
7995         int                     ntups;
7996         int                     i;
7997         PQExpBuffer query;
7998         TransformInfo *transforminfo;
7999         int                     i_tableoid;
8000         int                     i_oid;
8001         int                     i_trftype;
8002         int                     i_trflang;
8003         int                     i_trffromsql;
8004         int                     i_trftosql;
8005
8006         /* Transforms didn't exist pre-9.5 */
8007         if (fout->remoteVersion < 90500)
8008         {
8009                 *numTransforms = 0;
8010                 return NULL;
8011         }
8012
8013         query = createPQExpBuffer();
8014
8015         /* Make sure we are in proper schema */
8016         selectSourceSchema(fout, "pg_catalog");
8017
8018         appendPQExpBuffer(query, "SELECT tableoid, oid, "
8019                                           "trftype, trflang, trffromsql::oid, trftosql::oid "
8020                                           "FROM pg_transform "
8021                                           "ORDER BY 3,4");
8022
8023         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8024
8025         ntups = PQntuples(res);
8026
8027         *numTransforms = ntups;
8028
8029         transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8030
8031         i_tableoid = PQfnumber(res, "tableoid");
8032         i_oid = PQfnumber(res, "oid");
8033         i_trftype = PQfnumber(res, "trftype");
8034         i_trflang = PQfnumber(res, "trflang");
8035         i_trffromsql = PQfnumber(res, "trffromsql");
8036         i_trftosql = PQfnumber(res, "trftosql");
8037
8038         for (i = 0; i < ntups; i++)
8039         {
8040                 PQExpBufferData namebuf;
8041                 TypeInfo   *typeInfo;
8042                 char       *lanname;
8043
8044                 transforminfo[i].dobj.objType = DO_TRANSFORM;
8045                 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8046                 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8047                 AssignDumpId(&transforminfo[i].dobj);
8048                 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8049                 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8050                 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8051                 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8052
8053                 /*
8054                  * Try to name transform as concatenation of type and language name.
8055                  * This is only used for purposes of sorting.  If we fail to find
8056                  * either, the name will be an empty string.
8057                  */
8058                 initPQExpBuffer(&namebuf);
8059                 typeInfo = findTypeByOid(transforminfo[i].trftype);
8060                 lanname = get_language_name(fout, transforminfo[i].trflang);
8061                 if (typeInfo && lanname)
8062                         appendPQExpBuffer(&namebuf, "%s %s",
8063                                                           typeInfo->dobj.name, lanname);
8064                 transforminfo[i].dobj.name = namebuf.data;
8065                 free(lanname);
8066
8067                 /* Decide whether we want to dump it */
8068                 selectDumpableObject(&(transforminfo[i].dobj), fout);
8069         }
8070
8071         PQclear(res);
8072
8073         destroyPQExpBuffer(query);
8074
8075         return transforminfo;
8076 }
8077
8078 /*
8079  * getTableAttrs -
8080  *        for each interesting table, read info about its attributes
8081  *        (names, types, default values, CHECK constraints, etc)
8082  *
8083  * This is implemented in a very inefficient way right now, looping
8084  * through the tblinfo and doing a join per table to find the attrs and their
8085  * types.  However, because we want type names and so forth to be named
8086  * relative to the schema of each table, we couldn't do it in just one
8087  * query.  (Maybe one query per schema?)
8088  *
8089  *      modifies tblinfo
8090  */
8091 void
8092 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8093 {
8094         DumpOptions *dopt = fout->dopt;
8095         int                     i,
8096                                 j;
8097         PQExpBuffer q = createPQExpBuffer();
8098         int                     i_attnum;
8099         int                     i_attname;
8100         int                     i_atttypname;
8101         int                     i_atttypmod;
8102         int                     i_attstattarget;
8103         int                     i_attstorage;
8104         int                     i_typstorage;
8105         int                     i_attnotnull;
8106         int                     i_atthasdef;
8107         int                     i_attidentity;
8108         int                     i_attisdropped;
8109         int                     i_attlen;
8110         int                     i_attalign;
8111         int                     i_attislocal;
8112         int                     i_attoptions;
8113         int                     i_attcollation;
8114         int                     i_attfdwoptions;
8115         PGresult   *res;
8116         int                     ntups;
8117         bool            hasdefaults;
8118
8119         for (i = 0; i < numTables; i++)
8120         {
8121                 TableInfo  *tbinfo = &tblinfo[i];
8122
8123                 /* Don't bother to collect info for sequences */
8124                 if (tbinfo->relkind == RELKIND_SEQUENCE)
8125                         continue;
8126
8127                 /* Don't bother with uninteresting tables, either */
8128                 if (!tbinfo->interesting)
8129                         continue;
8130
8131                 /*
8132                  * Make sure we are in proper schema for this table; this allows
8133                  * correct retrieval of formatted type names and default exprs
8134                  */
8135                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
8136
8137                 /* find all the user attributes and their types */
8138
8139                 /*
8140                  * we must read the attribute names in attribute number order! because
8141                  * we will use the attnum to index into the attnames array later.
8142                  */
8143                 if (g_verbose)
8144                         write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8145                                           tbinfo->dobj.namespace->dobj.name,
8146                                           tbinfo->dobj.name);
8147
8148                 resetPQExpBuffer(q);
8149
8150                 if (fout->remoteVersion >= 100000)
8151                 {
8152                         /*
8153                          * attidentity is new in version 10.
8154                          */
8155                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8156                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8157                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8158                                                           "a.attlen, a.attalign, a.attislocal, "
8159                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8160                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8161                                                           "CASE WHEN a.attcollation <> t.typcollation "
8162                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8163                                                           "a.attidentity, "
8164                                                           "pg_catalog.array_to_string(ARRAY("
8165                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8166                                                           "' ' || pg_catalog.quote_literal(option_value) "
8167                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8168                                                           "ORDER BY option_name"
8169                                                           "), E',\n    ') AS attfdwoptions "
8170                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8171                                                           "ON a.atttypid = t.oid "
8172                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8173                                                           "AND a.attnum > 0::pg_catalog.int2 "
8174                                                           "ORDER BY a.attnum",
8175                                                           tbinfo->dobj.catId.oid);
8176                 }
8177                 else if (fout->remoteVersion >= 90200)
8178                 {
8179                         /*
8180                          * attfdwoptions is new in 9.2.
8181                          */
8182                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8183                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8184                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8185                                                           "a.attlen, a.attalign, a.attislocal, "
8186                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8187                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8188                                                           "CASE WHEN a.attcollation <> t.typcollation "
8189                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8190                                                           "pg_catalog.array_to_string(ARRAY("
8191                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8192                                                           "' ' || pg_catalog.quote_literal(option_value) "
8193                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8194                                                           "ORDER BY option_name"
8195                                                           "), E',\n    ') AS attfdwoptions "
8196                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8197                                                           "ON a.atttypid = t.oid "
8198                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8199                                                           "AND a.attnum > 0::pg_catalog.int2 "
8200                                                           "ORDER BY a.attnum",
8201                                                           tbinfo->dobj.catId.oid);
8202                 }
8203                 else if (fout->remoteVersion >= 90100)
8204                 {
8205                         /*
8206                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
8207                          * clauses for attributes whose collation is different from their
8208                          * type's default, we use a CASE here to suppress uninteresting
8209                          * attcollations cheaply.
8210                          */
8211                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8212                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8213                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8214                                                           "a.attlen, a.attalign, a.attislocal, "
8215                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8216                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8217                                                           "CASE WHEN a.attcollation <> t.typcollation "
8218                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8219                                                           "NULL AS attfdwoptions "
8220                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8221                                                           "ON a.atttypid = t.oid "
8222                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8223                                                           "AND a.attnum > 0::pg_catalog.int2 "
8224                                                           "ORDER BY a.attnum",
8225                                                           tbinfo->dobj.catId.oid);
8226                 }
8227                 else if (fout->remoteVersion >= 90000)
8228                 {
8229                         /* attoptions is new in 9.0 */
8230                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8231                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8232                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8233                                                           "a.attlen, a.attalign, a.attislocal, "
8234                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8235                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8236                                                           "0 AS attcollation, "
8237                                                           "NULL AS attfdwoptions "
8238                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8239                                                           "ON a.atttypid = t.oid "
8240                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8241                                                           "AND a.attnum > 0::pg_catalog.int2 "
8242                                                           "ORDER BY a.attnum",
8243                                                           tbinfo->dobj.catId.oid);
8244                 }
8245                 else
8246                 {
8247                         /* need left join here to not fail on dropped columns ... */
8248                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8249                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8250                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8251                                                           "a.attlen, a.attalign, a.attislocal, "
8252                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8253                                                           "'' AS attoptions, 0 AS attcollation, "
8254                                                           "NULL AS attfdwoptions "
8255                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8256                                                           "ON a.atttypid = t.oid "
8257                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8258                                                           "AND a.attnum > 0::pg_catalog.int2 "
8259                                                           "ORDER BY a.attnum",
8260                                                           tbinfo->dobj.catId.oid);
8261                 }
8262
8263                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8264
8265                 ntups = PQntuples(res);
8266
8267                 i_attnum = PQfnumber(res, "attnum");
8268                 i_attname = PQfnumber(res, "attname");
8269                 i_atttypname = PQfnumber(res, "atttypname");
8270                 i_atttypmod = PQfnumber(res, "atttypmod");
8271                 i_attstattarget = PQfnumber(res, "attstattarget");
8272                 i_attstorage = PQfnumber(res, "attstorage");
8273                 i_typstorage = PQfnumber(res, "typstorage");
8274                 i_attnotnull = PQfnumber(res, "attnotnull");
8275                 i_atthasdef = PQfnumber(res, "atthasdef");
8276                 i_attidentity = PQfnumber(res, "attidentity");
8277                 i_attisdropped = PQfnumber(res, "attisdropped");
8278                 i_attlen = PQfnumber(res, "attlen");
8279                 i_attalign = PQfnumber(res, "attalign");
8280                 i_attislocal = PQfnumber(res, "attislocal");
8281                 i_attoptions = PQfnumber(res, "attoptions");
8282                 i_attcollation = PQfnumber(res, "attcollation");
8283                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8284
8285                 tbinfo->numatts = ntups;
8286                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8287                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8288                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8289                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8290                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8291                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8292                 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8293                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8294                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8295                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8296                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8297                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8298                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8299                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8300                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8301                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8302                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8303                 hasdefaults = false;
8304
8305                 for (j = 0; j < ntups; j++)
8306                 {
8307                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8308                                 exit_horribly(NULL,
8309                                                           "invalid column numbering in table \"%s\"\n",
8310                                                           tbinfo->dobj.name);
8311                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8312                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8313                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8314                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8315                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8316                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8317                         tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8318                         tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8319                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8320                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8321                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8322                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8323                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8324                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8325                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8326                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8327                         tbinfo->attrdefs[j] = NULL; /* fix below */
8328                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8329                                 hasdefaults = true;
8330                         /* these flags will be set in flagInhAttrs() */
8331                         tbinfo->inhNotNull[j] = false;
8332                 }
8333
8334                 PQclear(res);
8335
8336                 /*
8337                  * Get info about column defaults
8338                  */
8339                 if (hasdefaults)
8340                 {
8341                         AttrDefInfo *attrdefs;
8342                         int                     numDefaults;
8343
8344                         if (g_verbose)
8345                                 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8346                                                   tbinfo->dobj.namespace->dobj.name,
8347                                                   tbinfo->dobj.name);
8348
8349                         printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8350                                                           "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8351                                                           "FROM pg_catalog.pg_attrdef "
8352                                                           "WHERE adrelid = '%u'::pg_catalog.oid",
8353                                                           tbinfo->dobj.catId.oid);
8354
8355                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8356
8357                         numDefaults = PQntuples(res);
8358                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8359
8360                         for (j = 0; j < numDefaults; j++)
8361                         {
8362                                 int                     adnum;
8363
8364                                 adnum = atoi(PQgetvalue(res, j, 2));
8365
8366                                 if (adnum <= 0 || adnum > ntups)
8367                                         exit_horribly(NULL,
8368                                                                   "invalid adnum value %d for table \"%s\"\n",
8369                                                                   adnum, tbinfo->dobj.name);
8370
8371                                 /*
8372                                  * dropped columns shouldn't have defaults, but just in case,
8373                                  * ignore 'em
8374                                  */
8375                                 if (tbinfo->attisdropped[adnum - 1])
8376                                         continue;
8377
8378                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
8379                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8380                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8381                                 AssignDumpId(&attrdefs[j].dobj);
8382                                 attrdefs[j].adtable = tbinfo;
8383                                 attrdefs[j].adnum = adnum;
8384                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8385
8386                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8387                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8388
8389                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8390
8391                                 /*
8392                                  * Defaults on a VIEW must always be dumped as separate ALTER
8393                                  * TABLE commands.  Defaults on regular tables are dumped as
8394                                  * part of the CREATE TABLE if possible, which it won't be if
8395                                  * the column is not going to be emitted explicitly.
8396                                  */
8397                                 if (tbinfo->relkind == RELKIND_VIEW)
8398                                 {
8399                                         attrdefs[j].separate = true;
8400                                 }
8401                                 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8402                                 {
8403                                         /* column will be suppressed, print default separately */
8404                                         attrdefs[j].separate = true;
8405                                 }
8406                                 else
8407                                 {
8408                                         attrdefs[j].separate = false;
8409
8410                                         /*
8411                                          * Mark the default as needing to appear before the table,
8412                                          * so that any dependencies it has must be emitted before
8413                                          * the CREATE TABLE.  If this is not possible, we'll
8414                                          * change to "separate" mode while sorting dependencies.
8415                                          */
8416                                         addObjectDependency(&tbinfo->dobj,
8417                                                                                 attrdefs[j].dobj.dumpId);
8418                                 }
8419
8420                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8421                         }
8422                         PQclear(res);
8423                 }
8424
8425                 /*
8426                  * Get info about table CHECK constraints
8427                  */
8428                 if (tbinfo->ncheck > 0)
8429                 {
8430                         ConstraintInfo *constrs;
8431                         int                     numConstrs;
8432
8433                         if (g_verbose)
8434                                 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8435                                                   tbinfo->dobj.namespace->dobj.name,
8436                                                   tbinfo->dobj.name);
8437
8438                         resetPQExpBuffer(q);
8439                         if (fout->remoteVersion >= 90200)
8440                         {
8441                                 /*
8442                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
8443                                  * but it wasn't ever false for check constraints until 9.2).
8444                                  */
8445                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8446                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8447                                                                   "conislocal, convalidated "
8448                                                                   "FROM pg_catalog.pg_constraint "
8449                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8450                                                                   "   AND contype = 'c' "
8451                                                                   "ORDER BY conname",
8452                                                                   tbinfo->dobj.catId.oid);
8453                         }
8454                         else if (fout->remoteVersion >= 80400)
8455                         {
8456                                 /* conislocal is new in 8.4 */
8457                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8458                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8459                                                                   "conislocal, true AS convalidated "
8460                                                                   "FROM pg_catalog.pg_constraint "
8461                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8462                                                                   "   AND contype = 'c' "
8463                                                                   "ORDER BY conname",
8464                                                                   tbinfo->dobj.catId.oid);
8465                         }
8466                         else
8467                         {
8468                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8469                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8470                                                                   "true AS conislocal, true AS convalidated "
8471                                                                   "FROM pg_catalog.pg_constraint "
8472                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8473                                                                   "   AND contype = 'c' "
8474                                                                   "ORDER BY conname",
8475                                                                   tbinfo->dobj.catId.oid);
8476                         }
8477
8478                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8479
8480                         numConstrs = PQntuples(res);
8481                         if (numConstrs != tbinfo->ncheck)
8482                         {
8483                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8484                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
8485                                                                                  tbinfo->ncheck),
8486                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8487                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8488                                 exit_nicely(1);
8489                         }
8490
8491                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8492                         tbinfo->checkexprs = constrs;
8493
8494                         for (j = 0; j < numConstrs; j++)
8495                         {
8496                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
8497
8498                                 constrs[j].dobj.objType = DO_CONSTRAINT;
8499                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8500                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8501                                 AssignDumpId(&constrs[j].dobj);
8502                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8503                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8504                                 constrs[j].contable = tbinfo;
8505                                 constrs[j].condomain = NULL;
8506                                 constrs[j].contype = 'c';
8507                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8508                                 constrs[j].confrelid = InvalidOid;
8509                                 constrs[j].conindex = 0;
8510                                 constrs[j].condeferrable = false;
8511                                 constrs[j].condeferred = false;
8512                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8513
8514                                 /*
8515                                  * An unvalidated constraint needs to be dumped separately, so
8516                                  * that potentially-violating existing data is loaded before
8517                                  * the constraint.
8518                                  */
8519                                 constrs[j].separate = !validated;
8520
8521                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
8522
8523                                 /*
8524                                  * Mark the constraint as needing to appear before the table
8525                                  * --- this is so that any other dependencies of the
8526                                  * constraint will be emitted before we try to create the
8527                                  * table.  If the constraint is to be dumped separately, it
8528                                  * will be dumped after data is loaded anyway, so don't do it.
8529                                  * (There's an automatic dependency in the opposite direction
8530                                  * anyway, so don't need to add one manually here.)
8531                                  */
8532                                 if (!constrs[j].separate)
8533                                         addObjectDependency(&tbinfo->dobj,
8534                                                                                 constrs[j].dobj.dumpId);
8535
8536                                 /*
8537                                  * If the constraint is inherited, this will be detected later
8538                                  * (in pre-8.4 databases).  We also detect later if the
8539                                  * constraint must be split out from the table definition.
8540                                  */
8541                         }
8542                         PQclear(res);
8543                 }
8544         }
8545
8546         destroyPQExpBuffer(q);
8547 }
8548
8549 /*
8550  * Test whether a column should be printed as part of table's CREATE TABLE.
8551  * Column number is zero-based.
8552  *
8553  * Normally this is always true, but it's false for dropped columns, as well
8554  * as those that were inherited without any local definition.  (If we print
8555  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8556  * However, in binary_upgrade mode, we must print all such columns anyway and
8557  * fix the attislocal/attisdropped state later, so as to keep control of the
8558  * physical column order.
8559  *
8560  * This function exists because there are scattered nonobvious places that
8561  * must be kept in sync with this decision.
8562  */
8563 bool
8564 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8565 {
8566         if (dopt->binary_upgrade)
8567                 return true;
8568         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8569 }
8570
8571
8572 /*
8573  * getTSParsers:
8574  *        read all text search parsers in the system catalogs and return them
8575  *        in the TSParserInfo* structure
8576  *
8577  *      numTSParsers is set to the number of parsers read in
8578  */
8579 TSParserInfo *
8580 getTSParsers(Archive *fout, int *numTSParsers)
8581 {
8582         PGresult   *res;
8583         int                     ntups;
8584         int                     i;
8585         PQExpBuffer query;
8586         TSParserInfo *prsinfo;
8587         int                     i_tableoid;
8588         int                     i_oid;
8589         int                     i_prsname;
8590         int                     i_prsnamespace;
8591         int                     i_prsstart;
8592         int                     i_prstoken;
8593         int                     i_prsend;
8594         int                     i_prsheadline;
8595         int                     i_prslextype;
8596
8597         /* Before 8.3, there is no built-in text search support */
8598         if (fout->remoteVersion < 80300)
8599         {
8600                 *numTSParsers = 0;
8601                 return NULL;
8602         }
8603
8604         query = createPQExpBuffer();
8605
8606         /*
8607          * find all text search objects, including builtin ones; we filter out
8608          * system-defined objects at dump-out time.
8609          */
8610
8611         /* Make sure we are in proper schema */
8612         selectSourceSchema(fout, "pg_catalog");
8613
8614         appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8615                                                  "prsstart::oid, prstoken::oid, "
8616                                                  "prsend::oid, prsheadline::oid, prslextype::oid "
8617                                                  "FROM pg_ts_parser");
8618
8619         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8620
8621         ntups = PQntuples(res);
8622         *numTSParsers = ntups;
8623
8624         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8625
8626         i_tableoid = PQfnumber(res, "tableoid");
8627         i_oid = PQfnumber(res, "oid");
8628         i_prsname = PQfnumber(res, "prsname");
8629         i_prsnamespace = PQfnumber(res, "prsnamespace");
8630         i_prsstart = PQfnumber(res, "prsstart");
8631         i_prstoken = PQfnumber(res, "prstoken");
8632         i_prsend = PQfnumber(res, "prsend");
8633         i_prsheadline = PQfnumber(res, "prsheadline");
8634         i_prslextype = PQfnumber(res, "prslextype");
8635
8636         for (i = 0; i < ntups; i++)
8637         {
8638                 prsinfo[i].dobj.objType = DO_TSPARSER;
8639                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8640                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8641                 AssignDumpId(&prsinfo[i].dobj);
8642                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8643                 prsinfo[i].dobj.namespace =
8644                         findNamespace(fout,
8645                                                   atooid(PQgetvalue(res, i, i_prsnamespace)));
8646                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8647                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8648                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8649                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8650                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8651
8652                 /* Decide whether we want to dump it */
8653                 selectDumpableObject(&(prsinfo[i].dobj), fout);
8654
8655                 /* Text Search Parsers do not currently have ACLs. */
8656                 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8657         }
8658
8659         PQclear(res);
8660
8661         destroyPQExpBuffer(query);
8662
8663         return prsinfo;
8664 }
8665
8666 /*
8667  * getTSDictionaries:
8668  *        read all text search dictionaries in the system catalogs and return them
8669  *        in the TSDictInfo* structure
8670  *
8671  *      numTSDicts is set to the number of dictionaries read in
8672  */
8673 TSDictInfo *
8674 getTSDictionaries(Archive *fout, int *numTSDicts)
8675 {
8676         PGresult   *res;
8677         int                     ntups;
8678         int                     i;
8679         PQExpBuffer query;
8680         TSDictInfo *dictinfo;
8681         int                     i_tableoid;
8682         int                     i_oid;
8683         int                     i_dictname;
8684         int                     i_dictnamespace;
8685         int                     i_rolname;
8686         int                     i_dicttemplate;
8687         int                     i_dictinitoption;
8688
8689         /* Before 8.3, there is no built-in text search support */
8690         if (fout->remoteVersion < 80300)
8691         {
8692                 *numTSDicts = 0;
8693                 return NULL;
8694         }
8695
8696         query = createPQExpBuffer();
8697
8698         /* Make sure we are in proper schema */
8699         selectSourceSchema(fout, "pg_catalog");
8700
8701         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8702                                           "dictnamespace, (%s dictowner) AS rolname, "
8703                                           "dicttemplate, dictinitoption "
8704                                           "FROM pg_ts_dict",
8705                                           username_subquery);
8706
8707         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8708
8709         ntups = PQntuples(res);
8710         *numTSDicts = ntups;
8711
8712         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8713
8714         i_tableoid = PQfnumber(res, "tableoid");
8715         i_oid = PQfnumber(res, "oid");
8716         i_dictname = PQfnumber(res, "dictname");
8717         i_dictnamespace = PQfnumber(res, "dictnamespace");
8718         i_rolname = PQfnumber(res, "rolname");
8719         i_dictinitoption = PQfnumber(res, "dictinitoption");
8720         i_dicttemplate = PQfnumber(res, "dicttemplate");
8721
8722         for (i = 0; i < ntups; i++)
8723         {
8724                 dictinfo[i].dobj.objType = DO_TSDICT;
8725                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8726                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8727                 AssignDumpId(&dictinfo[i].dobj);
8728                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8729                 dictinfo[i].dobj.namespace =
8730                         findNamespace(fout,
8731                                                   atooid(PQgetvalue(res, i, i_dictnamespace)));
8732                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8733                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8734                 if (PQgetisnull(res, i, i_dictinitoption))
8735                         dictinfo[i].dictinitoption = NULL;
8736                 else
8737                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8738
8739                 /* Decide whether we want to dump it */
8740                 selectDumpableObject(&(dictinfo[i].dobj), fout);
8741
8742                 /* Text Search Dictionaries do not currently have ACLs. */
8743                 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8744         }
8745
8746         PQclear(res);
8747
8748         destroyPQExpBuffer(query);
8749
8750         return dictinfo;
8751 }
8752
8753 /*
8754  * getTSTemplates:
8755  *        read all text search templates in the system catalogs and return them
8756  *        in the TSTemplateInfo* structure
8757  *
8758  *      numTSTemplates is set to the number of templates read in
8759  */
8760 TSTemplateInfo *
8761 getTSTemplates(Archive *fout, int *numTSTemplates)
8762 {
8763         PGresult   *res;
8764         int                     ntups;
8765         int                     i;
8766         PQExpBuffer query;
8767         TSTemplateInfo *tmplinfo;
8768         int                     i_tableoid;
8769         int                     i_oid;
8770         int                     i_tmplname;
8771         int                     i_tmplnamespace;
8772         int                     i_tmplinit;
8773         int                     i_tmpllexize;
8774
8775         /* Before 8.3, there is no built-in text search support */
8776         if (fout->remoteVersion < 80300)
8777         {
8778                 *numTSTemplates = 0;
8779                 return NULL;
8780         }
8781
8782         query = createPQExpBuffer();
8783
8784         /* Make sure we are in proper schema */
8785         selectSourceSchema(fout, "pg_catalog");
8786
8787         appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8788                                                  "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8789                                                  "FROM pg_ts_template");
8790
8791         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8792
8793         ntups = PQntuples(res);
8794         *numTSTemplates = ntups;
8795
8796         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8797
8798         i_tableoid = PQfnumber(res, "tableoid");
8799         i_oid = PQfnumber(res, "oid");
8800         i_tmplname = PQfnumber(res, "tmplname");
8801         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8802         i_tmplinit = PQfnumber(res, "tmplinit");
8803         i_tmpllexize = PQfnumber(res, "tmpllexize");
8804
8805         for (i = 0; i < ntups; i++)
8806         {
8807                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8808                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8809                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8810                 AssignDumpId(&tmplinfo[i].dobj);
8811                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8812                 tmplinfo[i].dobj.namespace =
8813                         findNamespace(fout,
8814                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)));
8815                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8816                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8817
8818                 /* Decide whether we want to dump it */
8819                 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8820
8821                 /* Text Search Templates do not currently have ACLs. */
8822                 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8823         }
8824
8825         PQclear(res);
8826
8827         destroyPQExpBuffer(query);
8828
8829         return tmplinfo;
8830 }
8831
8832 /*
8833  * getTSConfigurations:
8834  *        read all text search configurations in the system catalogs and return
8835  *        them in the TSConfigInfo* structure
8836  *
8837  *      numTSConfigs is set to the number of configurations read in
8838  */
8839 TSConfigInfo *
8840 getTSConfigurations(Archive *fout, int *numTSConfigs)
8841 {
8842         PGresult   *res;
8843         int                     ntups;
8844         int                     i;
8845         PQExpBuffer query;
8846         TSConfigInfo *cfginfo;
8847         int                     i_tableoid;
8848         int                     i_oid;
8849         int                     i_cfgname;
8850         int                     i_cfgnamespace;
8851         int                     i_rolname;
8852         int                     i_cfgparser;
8853
8854         /* Before 8.3, there is no built-in text search support */
8855         if (fout->remoteVersion < 80300)
8856         {
8857                 *numTSConfigs = 0;
8858                 return NULL;
8859         }
8860
8861         query = createPQExpBuffer();
8862
8863         /* Make sure we are in proper schema */
8864         selectSourceSchema(fout, "pg_catalog");
8865
8866         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8867                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8868                                           "FROM pg_ts_config",
8869                                           username_subquery);
8870
8871         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8872
8873         ntups = PQntuples(res);
8874         *numTSConfigs = ntups;
8875
8876         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8877
8878         i_tableoid = PQfnumber(res, "tableoid");
8879         i_oid = PQfnumber(res, "oid");
8880         i_cfgname = PQfnumber(res, "cfgname");
8881         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8882         i_rolname = PQfnumber(res, "rolname");
8883         i_cfgparser = PQfnumber(res, "cfgparser");
8884
8885         for (i = 0; i < ntups; i++)
8886         {
8887                 cfginfo[i].dobj.objType = DO_TSCONFIG;
8888                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8889                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8890                 AssignDumpId(&cfginfo[i].dobj);
8891                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8892                 cfginfo[i].dobj.namespace =
8893                         findNamespace(fout,
8894                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)));
8895                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8896                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8897
8898                 /* Decide whether we want to dump it */
8899                 selectDumpableObject(&(cfginfo[i].dobj), fout);
8900
8901                 /* Text Search Configurations do not currently have ACLs. */
8902                 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8903         }
8904
8905         PQclear(res);
8906
8907         destroyPQExpBuffer(query);
8908
8909         return cfginfo;
8910 }
8911
8912 /*
8913  * getForeignDataWrappers:
8914  *        read all foreign-data wrappers in the system catalogs and return
8915  *        them in the FdwInfo* structure
8916  *
8917  *      numForeignDataWrappers is set to the number of fdws read in
8918  */
8919 FdwInfo *
8920 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8921 {
8922         DumpOptions *dopt = fout->dopt;
8923         PGresult   *res;
8924         int                     ntups;
8925         int                     i;
8926         PQExpBuffer query;
8927         FdwInfo    *fdwinfo;
8928         int                     i_tableoid;
8929         int                     i_oid;
8930         int                     i_fdwname;
8931         int                     i_rolname;
8932         int                     i_fdwhandler;
8933         int                     i_fdwvalidator;
8934         int                     i_fdwacl;
8935         int                     i_rfdwacl;
8936         int                     i_initfdwacl;
8937         int                     i_initrfdwacl;
8938         int                     i_fdwoptions;
8939
8940         /* Before 8.4, there are no foreign-data wrappers */
8941         if (fout->remoteVersion < 80400)
8942         {
8943                 *numForeignDataWrappers = 0;
8944                 return NULL;
8945         }
8946
8947         query = createPQExpBuffer();
8948
8949         /* Make sure we are in proper schema */
8950         selectSourceSchema(fout, "pg_catalog");
8951
8952         if (fout->remoteVersion >= 90600)
8953         {
8954                 PQExpBuffer acl_subquery = createPQExpBuffer();
8955                 PQExpBuffer racl_subquery = createPQExpBuffer();
8956                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8957                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8958
8959                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8960                                                 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8961                                                 dopt->binary_upgrade);
8962
8963                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8964                                                   "(%s f.fdwowner) AS rolname, "
8965                                                   "f.fdwhandler::pg_catalog.regproc, "
8966                                                   "f.fdwvalidator::pg_catalog.regproc, "
8967                                                   "%s AS fdwacl, "
8968                                                   "%s AS rfdwacl, "
8969                                                   "%s AS initfdwacl, "
8970                                                   "%s AS initrfdwacl, "
8971                                                   "array_to_string(ARRAY("
8972                                                   "SELECT quote_ident(option_name) || ' ' || "
8973                                                   "quote_literal(option_value) "
8974                                                   "FROM pg_options_to_table(f.fdwoptions) "
8975                                                   "ORDER BY option_name"
8976                                                   "), E',\n    ') AS fdwoptions "
8977                                                   "FROM pg_foreign_data_wrapper f "
8978                                                   "LEFT JOIN pg_init_privs pip ON "
8979                                                   "(f.oid = pip.objoid "
8980                                                   "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8981                                                   "AND pip.objsubid = 0) ",
8982                                                   username_subquery,
8983                                                   acl_subquery->data,
8984                                                   racl_subquery->data,
8985                                                   initacl_subquery->data,
8986                                                   initracl_subquery->data);
8987
8988                 destroyPQExpBuffer(acl_subquery);
8989                 destroyPQExpBuffer(racl_subquery);
8990                 destroyPQExpBuffer(initacl_subquery);
8991                 destroyPQExpBuffer(initracl_subquery);
8992         }
8993         else if (fout->remoteVersion >= 90100)
8994         {
8995                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8996                                                   "(%s fdwowner) AS rolname, "
8997                                                   "fdwhandler::pg_catalog.regproc, "
8998                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
8999                                                   "NULL as rfdwacl, "
9000                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
9001                                                   "array_to_string(ARRAY("
9002                                                   "SELECT quote_ident(option_name) || ' ' || "
9003                                                   "quote_literal(option_value) "
9004                                                   "FROM pg_options_to_table(fdwoptions) "
9005                                                   "ORDER BY option_name"
9006                                                   "), E',\n    ') AS fdwoptions "
9007                                                   "FROM pg_foreign_data_wrapper",
9008                                                   username_subquery);
9009         }
9010         else
9011         {
9012                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9013                                                   "(%s fdwowner) AS rolname, "
9014                                                   "'-' AS fdwhandler, "
9015                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
9016                                                   "NULL as rfdwacl, "
9017                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
9018                                                   "array_to_string(ARRAY("
9019                                                   "SELECT quote_ident(option_name) || ' ' || "
9020                                                   "quote_literal(option_value) "
9021                                                   "FROM pg_options_to_table(fdwoptions) "
9022                                                   "ORDER BY option_name"
9023                                                   "), E',\n    ') AS fdwoptions "
9024                                                   "FROM pg_foreign_data_wrapper",
9025                                                   username_subquery);
9026         }
9027
9028         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9029
9030         ntups = PQntuples(res);
9031         *numForeignDataWrappers = ntups;
9032
9033         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9034
9035         i_tableoid = PQfnumber(res, "tableoid");
9036         i_oid = PQfnumber(res, "oid");
9037         i_fdwname = PQfnumber(res, "fdwname");
9038         i_rolname = PQfnumber(res, "rolname");
9039         i_fdwhandler = PQfnumber(res, "fdwhandler");
9040         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9041         i_fdwacl = PQfnumber(res, "fdwacl");
9042         i_rfdwacl = PQfnumber(res, "rfdwacl");
9043         i_initfdwacl = PQfnumber(res, "initfdwacl");
9044         i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9045         i_fdwoptions = PQfnumber(res, "fdwoptions");
9046
9047         for (i = 0; i < ntups; i++)
9048         {
9049                 fdwinfo[i].dobj.objType = DO_FDW;
9050                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9051                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9052                 AssignDumpId(&fdwinfo[i].dobj);
9053                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9054                 fdwinfo[i].dobj.namespace = NULL;
9055                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9056                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9057                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9058                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9059                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9060                 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9061                 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9062                 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9063
9064                 /* Decide whether we want to dump it */
9065                 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9066
9067                 /* Do not try to dump ACL if no ACL exists. */
9068                 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9069                         PQgetisnull(res, i, i_initfdwacl) &&
9070                         PQgetisnull(res, i, i_initrfdwacl))
9071                         fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9072         }
9073
9074         PQclear(res);
9075
9076         destroyPQExpBuffer(query);
9077
9078         return fdwinfo;
9079 }
9080
9081 /*
9082  * getForeignServers:
9083  *        read all foreign servers in the system catalogs and return
9084  *        them in the ForeignServerInfo * structure
9085  *
9086  *      numForeignServers is set to the number of servers read in
9087  */
9088 ForeignServerInfo *
9089 getForeignServers(Archive *fout, int *numForeignServers)
9090 {
9091         DumpOptions *dopt = fout->dopt;
9092         PGresult   *res;
9093         int                     ntups;
9094         int                     i;
9095         PQExpBuffer query;
9096         ForeignServerInfo *srvinfo;
9097         int                     i_tableoid;
9098         int                     i_oid;
9099         int                     i_srvname;
9100         int                     i_rolname;
9101         int                     i_srvfdw;
9102         int                     i_srvtype;
9103         int                     i_srvversion;
9104         int                     i_srvacl;
9105         int                     i_rsrvacl;
9106         int                     i_initsrvacl;
9107         int                     i_initrsrvacl;
9108         int                     i_srvoptions;
9109
9110         /* Before 8.4, there are no foreign servers */
9111         if (fout->remoteVersion < 80400)
9112         {
9113                 *numForeignServers = 0;
9114                 return NULL;
9115         }
9116
9117         query = createPQExpBuffer();
9118
9119         /* Make sure we are in proper schema */
9120         selectSourceSchema(fout, "pg_catalog");
9121
9122         if (fout->remoteVersion >= 90600)
9123         {
9124                 PQExpBuffer acl_subquery = createPQExpBuffer();
9125                 PQExpBuffer racl_subquery = createPQExpBuffer();
9126                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9127                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9128
9129                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9130                                                 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9131                                                 dopt->binary_upgrade);
9132
9133                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9134                                                   "(%s f.srvowner) AS rolname, "
9135                                                   "f.srvfdw, f.srvtype, f.srvversion, "
9136                                                   "%s AS srvacl, "
9137                                                   "%s AS rsrvacl, "
9138                                                   "%s AS initsrvacl, "
9139                                                   "%s AS initrsrvacl, "
9140                                                   "array_to_string(ARRAY("
9141                                                   "SELECT quote_ident(option_name) || ' ' || "
9142                                                   "quote_literal(option_value) "
9143                                                   "FROM pg_options_to_table(f.srvoptions) "
9144                                                   "ORDER BY option_name"
9145                                                   "), E',\n    ') AS srvoptions "
9146                                                   "FROM pg_foreign_server f "
9147                                                   "LEFT JOIN pg_init_privs pip "
9148                                                   "ON (f.oid = pip.objoid "
9149                                                   "AND pip.classoid = 'pg_foreign_server'::regclass "
9150                                                   "AND pip.objsubid = 0) ",
9151                                                   username_subquery,
9152                                                   acl_subquery->data,
9153                                                   racl_subquery->data,
9154                                                   initacl_subquery->data,
9155                                                   initracl_subquery->data);
9156
9157                 destroyPQExpBuffer(acl_subquery);
9158                 destroyPQExpBuffer(racl_subquery);
9159                 destroyPQExpBuffer(initacl_subquery);
9160                 destroyPQExpBuffer(initracl_subquery);
9161         }
9162         else
9163         {
9164                 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9165                                                   "(%s srvowner) AS rolname, "
9166                                                   "srvfdw, srvtype, srvversion, srvacl, "
9167                                                   "NULL AS rsrvacl, "
9168                                                   "NULL AS initsrvacl, NULL AS initrsrvacl, "
9169                                                   "array_to_string(ARRAY("
9170                                                   "SELECT quote_ident(option_name) || ' ' || "
9171                                                   "quote_literal(option_value) "
9172                                                   "FROM pg_options_to_table(srvoptions) "
9173                                                   "ORDER BY option_name"
9174                                                   "), E',\n    ') AS srvoptions "
9175                                                   "FROM pg_foreign_server",
9176                                                   username_subquery);
9177         }
9178
9179         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9180
9181         ntups = PQntuples(res);
9182         *numForeignServers = ntups;
9183
9184         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9185
9186         i_tableoid = PQfnumber(res, "tableoid");
9187         i_oid = PQfnumber(res, "oid");
9188         i_srvname = PQfnumber(res, "srvname");
9189         i_rolname = PQfnumber(res, "rolname");
9190         i_srvfdw = PQfnumber(res, "srvfdw");
9191         i_srvtype = PQfnumber(res, "srvtype");
9192         i_srvversion = PQfnumber(res, "srvversion");
9193         i_srvacl = PQfnumber(res, "srvacl");
9194         i_rsrvacl = PQfnumber(res, "rsrvacl");
9195         i_initsrvacl = PQfnumber(res, "initsrvacl");
9196         i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9197         i_srvoptions = PQfnumber(res, "srvoptions");
9198
9199         for (i = 0; i < ntups; i++)
9200         {
9201                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9202                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9203                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9204                 AssignDumpId(&srvinfo[i].dobj);
9205                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9206                 srvinfo[i].dobj.namespace = NULL;
9207                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9208                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9209                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9210                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9211                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9212                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9213                 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9214                 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9215                 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9216
9217                 /* Decide whether we want to dump it */
9218                 selectDumpableObject(&(srvinfo[i].dobj), fout);
9219
9220                 /* Do not try to dump ACL if no ACL exists. */
9221                 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9222                         PQgetisnull(res, i, i_initsrvacl) &&
9223                         PQgetisnull(res, i, i_initrsrvacl))
9224                         srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9225         }
9226
9227         PQclear(res);
9228
9229         destroyPQExpBuffer(query);
9230
9231         return srvinfo;
9232 }
9233
9234 /*
9235  * getDefaultACLs:
9236  *        read all default ACL information in the system catalogs and return
9237  *        them in the DefaultACLInfo structure
9238  *
9239  *      numDefaultACLs is set to the number of ACLs read in
9240  */
9241 DefaultACLInfo *
9242 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9243 {
9244         DumpOptions *dopt = fout->dopt;
9245         DefaultACLInfo *daclinfo;
9246         PQExpBuffer query;
9247         PGresult   *res;
9248         int                     i_oid;
9249         int                     i_tableoid;
9250         int                     i_defaclrole;
9251         int                     i_defaclnamespace;
9252         int                     i_defaclobjtype;
9253         int                     i_defaclacl;
9254         int                     i_rdefaclacl;
9255         int                     i_initdefaclacl;
9256         int                     i_initrdefaclacl;
9257         int                     i,
9258                                 ntups;
9259
9260         if (fout->remoteVersion < 90000)
9261         {
9262                 *numDefaultACLs = 0;
9263                 return NULL;
9264         }
9265
9266         query = createPQExpBuffer();
9267
9268         /* Make sure we are in proper schema */
9269         selectSourceSchema(fout, "pg_catalog");
9270
9271         if (fout->remoteVersion >= 90600)
9272         {
9273                 PQExpBuffer acl_subquery = createPQExpBuffer();
9274                 PQExpBuffer racl_subquery = createPQExpBuffer();
9275                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9276                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9277
9278                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9279                                                 initracl_subquery, "defaclacl", "defaclrole",
9280                                                 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9281                                                 dopt->binary_upgrade);
9282
9283                 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9284                                                   "(%s d.defaclrole) AS defaclrole, "
9285                                                   "d.defaclnamespace, "
9286                                                   "d.defaclobjtype, "
9287                                                   "%s AS defaclacl, "
9288                                                   "%s AS rdefaclacl, "
9289                                                   "%s AS initdefaclacl, "
9290                                                   "%s AS initrdefaclacl "
9291                                                   "FROM pg_default_acl d "
9292                                                   "LEFT JOIN pg_init_privs pip ON "
9293                                                   "(d.oid = pip.objoid "
9294                                                   "AND pip.classoid = 'pg_default_acl'::regclass "
9295                                                   "AND pip.objsubid = 0) ",
9296                                                   username_subquery,
9297                                                   acl_subquery->data,
9298                                                   racl_subquery->data,
9299                                                   initacl_subquery->data,
9300                                                   initracl_subquery->data);
9301         }
9302         else
9303         {
9304                 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9305                                                   "(%s defaclrole) AS defaclrole, "
9306                                                   "defaclnamespace, "
9307                                                   "defaclobjtype, "
9308                                                   "defaclacl, "
9309                                                   "NULL AS rdefaclacl, "
9310                                                   "NULL AS initdefaclacl, "
9311                                                   "NULL AS initrdefaclacl "
9312                                                   "FROM pg_default_acl",
9313                                                   username_subquery);
9314         }
9315
9316         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9317
9318         ntups = PQntuples(res);
9319         *numDefaultACLs = ntups;
9320
9321         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9322
9323         i_oid = PQfnumber(res, "oid");
9324         i_tableoid = PQfnumber(res, "tableoid");
9325         i_defaclrole = PQfnumber(res, "defaclrole");
9326         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9327         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9328         i_defaclacl = PQfnumber(res, "defaclacl");
9329         i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9330         i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9331         i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9332
9333         for (i = 0; i < ntups; i++)
9334         {
9335                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9336
9337                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9338                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9339                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9340                 AssignDumpId(&daclinfo[i].dobj);
9341                 /* cheesy ... is it worth coming up with a better object name? */
9342                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9343
9344                 if (nspid != InvalidOid)
9345                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9346                 else
9347                         daclinfo[i].dobj.namespace = NULL;
9348
9349                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9350                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9351                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9352                 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9353                 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9354                 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9355
9356                 /* Decide whether we want to dump it */
9357                 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9358         }
9359
9360         PQclear(res);
9361
9362         destroyPQExpBuffer(query);
9363
9364         return daclinfo;
9365 }
9366
9367 /*
9368  * dumpComment --
9369  *
9370  * This routine is used to dump any comments associated with the
9371  * object handed to this routine. The routine takes a constant character
9372  * string for the target part of the comment-creation command, plus
9373  * the namespace and owner of the object (for labeling the ArchiveEntry),
9374  * plus catalog ID and subid which are the lookup key for pg_description,
9375  * plus the dump ID for the object (for setting a dependency).
9376  * If a matching pg_description entry is found, it is dumped.
9377  *
9378  * Note: although this routine takes a dumpId for dependency purposes,
9379  * that purpose is just to mark the dependency in the emitted dump file
9380  * for possible future use by pg_restore.  We do NOT use it for determining
9381  * ordering of the comment in the dump file, because this routine is called
9382  * after dependency sorting occurs.  This routine should be called just after
9383  * calling ArchiveEntry() for the specified object.
9384  */
9385 static void
9386 dumpComment(Archive *fout, const char *target,
9387                         const char *namespace, const char *owner,
9388                         CatalogId catalogId, int subid, DumpId dumpId)
9389 {
9390         DumpOptions *dopt = fout->dopt;
9391         CommentItem *comments;
9392         int                     ncomments;
9393
9394         /* do nothing, if --no-comments is supplied */
9395         if (dopt->no_comments)
9396                 return;
9397
9398         /* Comments are schema not data ... except blob comments are data */
9399         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
9400         {
9401                 if (dopt->dataOnly)
9402                         return;
9403         }
9404         else
9405         {
9406                 /* We do dump blob comments in binary-upgrade mode */
9407                 if (dopt->schemaOnly && !dopt->binary_upgrade)
9408                         return;
9409         }
9410
9411         /* Search for comments associated with catalogId, using table */
9412         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9413                                                          &comments);
9414
9415         /* Is there one matching the subid? */
9416         while (ncomments > 0)
9417         {
9418                 if (comments->objsubid == subid)
9419                         break;
9420                 comments++;
9421                 ncomments--;
9422         }
9423
9424         /* If a comment exists, build COMMENT ON statement */
9425         if (ncomments > 0)
9426         {
9427                 PQExpBuffer query = createPQExpBuffer();
9428
9429                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
9430                 appendStringLiteralAH(query, comments->descr, fout);
9431                 appendPQExpBufferStr(query, ";\n");
9432
9433                 /*
9434                  * We mark comments as SECTION_NONE because they really belong in the
9435                  * same section as their parent, whether that is pre-data or
9436                  * post-data.
9437                  */
9438                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9439                                          target, namespace, NULL, owner,
9440                                          false, "COMMENT", SECTION_NONE,
9441                                          query->data, "", NULL,
9442                                          &(dumpId), 1,
9443                                          NULL, NULL);
9444
9445                 destroyPQExpBuffer(query);
9446         }
9447 }
9448
9449 /*
9450  * dumpTableComment --
9451  *
9452  * As above, but dump comments for both the specified table (or view)
9453  * and its columns.
9454  */
9455 static void
9456 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9457                                  const char *reltypename)
9458 {
9459         DumpOptions *dopt = fout->dopt;
9460         CommentItem *comments;
9461         int                     ncomments;
9462         PQExpBuffer query;
9463         PQExpBuffer target;
9464
9465         /* do nothing, if --no-comments is supplied */
9466         if (dopt->no_comments)
9467                 return;
9468
9469         /* Comments are SCHEMA not data */
9470         if (dopt->dataOnly)
9471                 return;
9472
9473         /* Search for comments associated with relation, using table */
9474         ncomments = findComments(fout,
9475                                                          tbinfo->dobj.catId.tableoid,
9476                                                          tbinfo->dobj.catId.oid,
9477                                                          &comments);
9478
9479         /* If comments exist, build COMMENT ON statements */
9480         if (ncomments <= 0)
9481                 return;
9482
9483         query = createPQExpBuffer();
9484         target = createPQExpBuffer();
9485
9486         while (ncomments > 0)
9487         {
9488                 const char *descr = comments->descr;
9489                 int                     objsubid = comments->objsubid;
9490
9491                 if (objsubid == 0)
9492                 {
9493                         resetPQExpBuffer(target);
9494                         appendPQExpBuffer(target, "%s %s", reltypename,
9495                                                           fmtId(tbinfo->dobj.name));
9496
9497                         resetPQExpBuffer(query);
9498                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9499                         appendStringLiteralAH(query, descr, fout);
9500                         appendPQExpBufferStr(query, ";\n");
9501
9502                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9503                                                  target->data,
9504                                                  tbinfo->dobj.namespace->dobj.name,
9505                                                  NULL, tbinfo->rolname,
9506                                                  false, "COMMENT", SECTION_NONE,
9507                                                  query->data, "", NULL,
9508                                                  &(tbinfo->dobj.dumpId), 1,
9509                                                  NULL, NULL);
9510                 }
9511                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9512                 {
9513                         resetPQExpBuffer(target);
9514                         appendPQExpBuffer(target, "COLUMN %s.",
9515                                                           fmtId(tbinfo->dobj.name));
9516                         appendPQExpBufferStr(target, fmtId(tbinfo->attnames[objsubid - 1]));
9517
9518                         resetPQExpBuffer(query);
9519                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9520                         appendStringLiteralAH(query, descr, fout);
9521                         appendPQExpBufferStr(query, ";\n");
9522
9523                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9524                                                  target->data,
9525                                                  tbinfo->dobj.namespace->dobj.name,
9526                                                  NULL, tbinfo->rolname,
9527                                                  false, "COMMENT", SECTION_NONE,
9528                                                  query->data, "", NULL,
9529                                                  &(tbinfo->dobj.dumpId), 1,
9530                                                  NULL, NULL);
9531                 }
9532
9533                 comments++;
9534                 ncomments--;
9535         }
9536
9537         destroyPQExpBuffer(query);
9538         destroyPQExpBuffer(target);
9539 }
9540
9541 /*
9542  * findComments --
9543  *
9544  * Find the comment(s), if any, associated with the given object.  All the
9545  * objsubid values associated with the given classoid/objoid are found with
9546  * one search.
9547  */
9548 static int
9549 findComments(Archive *fout, Oid classoid, Oid objoid,
9550                          CommentItem **items)
9551 {
9552         /* static storage for table of comments */
9553         static CommentItem *comments = NULL;
9554         static int      ncomments = -1;
9555
9556         CommentItem *middle = NULL;
9557         CommentItem *low;
9558         CommentItem *high;
9559         int                     nmatch;
9560
9561         /* Get comments if we didn't already */
9562         if (ncomments < 0)
9563                 ncomments = collectComments(fout, &comments);
9564
9565         /*
9566          * Do binary search to find some item matching the object.
9567          */
9568         low = &comments[0];
9569         high = &comments[ncomments - 1];
9570         while (low <= high)
9571         {
9572                 middle = low + (high - low) / 2;
9573
9574                 if (classoid < middle->classoid)
9575                         high = middle - 1;
9576                 else if (classoid > middle->classoid)
9577                         low = middle + 1;
9578                 else if (objoid < middle->objoid)
9579                         high = middle - 1;
9580                 else if (objoid > middle->objoid)
9581                         low = middle + 1;
9582                 else
9583                         break;                          /* found a match */
9584         }
9585
9586         if (low > high)                         /* no matches */
9587         {
9588                 *items = NULL;
9589                 return 0;
9590         }
9591
9592         /*
9593          * Now determine how many items match the object.  The search loop
9594          * invariant still holds: only items between low and high inclusive could
9595          * match.
9596          */
9597         nmatch = 1;
9598         while (middle > low)
9599         {
9600                 if (classoid != middle[-1].classoid ||
9601                         objoid != middle[-1].objoid)
9602                         break;
9603                 middle--;
9604                 nmatch++;
9605         }
9606
9607         *items = middle;
9608
9609         middle += nmatch;
9610         while (middle <= high)
9611         {
9612                 if (classoid != middle->classoid ||
9613                         objoid != middle->objoid)
9614                         break;
9615                 middle++;
9616                 nmatch++;
9617         }
9618
9619         return nmatch;
9620 }
9621
9622 /*
9623  * collectComments --
9624  *
9625  * Construct a table of all comments available for database objects.
9626  * We used to do per-object queries for the comments, but it's much faster
9627  * to pull them all over at once, and on most databases the memory cost
9628  * isn't high.
9629  *
9630  * The table is sorted by classoid/objid/objsubid for speed in lookup.
9631  */
9632 static int
9633 collectComments(Archive *fout, CommentItem **items)
9634 {
9635         PGresult   *res;
9636         PQExpBuffer query;
9637         int                     i_description;
9638         int                     i_classoid;
9639         int                     i_objoid;
9640         int                     i_objsubid;
9641         int                     ntups;
9642         int                     i;
9643         CommentItem *comments;
9644
9645         /*
9646          * Note we do NOT change source schema here; preserve the caller's
9647          * setting, instead.
9648          */
9649
9650         query = createPQExpBuffer();
9651
9652         appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9653                                                  "FROM pg_catalog.pg_description "
9654                                                  "ORDER BY classoid, objoid, objsubid");
9655
9656         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9657
9658         /* Construct lookup table containing OIDs in numeric form */
9659
9660         i_description = PQfnumber(res, "description");
9661         i_classoid = PQfnumber(res, "classoid");
9662         i_objoid = PQfnumber(res, "objoid");
9663         i_objsubid = PQfnumber(res, "objsubid");
9664
9665         ntups = PQntuples(res);
9666
9667         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9668
9669         for (i = 0; i < ntups; i++)
9670         {
9671                 comments[i].descr = PQgetvalue(res, i, i_description);
9672                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9673                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9674                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9675         }
9676
9677         /* Do NOT free the PGresult since we are keeping pointers into it */
9678         destroyPQExpBuffer(query);
9679
9680         *items = comments;
9681         return ntups;
9682 }
9683
9684 /*
9685  * dumpDumpableObject
9686  *
9687  * This routine and its subsidiaries are responsible for creating
9688  * ArchiveEntries (TOC objects) for each object to be dumped.
9689  */
9690 static void
9691 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9692 {
9693         switch (dobj->objType)
9694         {
9695                 case DO_NAMESPACE:
9696                         dumpNamespace(fout, (NamespaceInfo *) dobj);
9697                         break;
9698                 case DO_EXTENSION:
9699                         dumpExtension(fout, (ExtensionInfo *) dobj);
9700                         break;
9701                 case DO_TYPE:
9702                         dumpType(fout, (TypeInfo *) dobj);
9703                         break;
9704                 case DO_SHELL_TYPE:
9705                         dumpShellType(fout, (ShellTypeInfo *) dobj);
9706                         break;
9707                 case DO_FUNC:
9708                         dumpFunc(fout, (FuncInfo *) dobj);
9709                         break;
9710                 case DO_AGG:
9711                         dumpAgg(fout, (AggInfo *) dobj);
9712                         break;
9713                 case DO_OPERATOR:
9714                         dumpOpr(fout, (OprInfo *) dobj);
9715                         break;
9716                 case DO_ACCESS_METHOD:
9717                         dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9718                         break;
9719                 case DO_OPCLASS:
9720                         dumpOpclass(fout, (OpclassInfo *) dobj);
9721                         break;
9722                 case DO_OPFAMILY:
9723                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9724                         break;
9725                 case DO_COLLATION:
9726                         dumpCollation(fout, (CollInfo *) dobj);
9727                         break;
9728                 case DO_CONVERSION:
9729                         dumpConversion(fout, (ConvInfo *) dobj);
9730                         break;
9731                 case DO_TABLE:
9732                         dumpTable(fout, (TableInfo *) dobj);
9733                         break;
9734                 case DO_ATTRDEF:
9735                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
9736                         break;
9737                 case DO_INDEX:
9738                         dumpIndex(fout, (IndxInfo *) dobj);
9739                         break;
9740                 case DO_INDEX_ATTACH:
9741                         dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9742                         break;
9743                 case DO_STATSEXT:
9744                         dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9745                         break;
9746                 case DO_REFRESH_MATVIEW:
9747                         refreshMatViewData(fout, (TableDataInfo *) dobj);
9748                         break;
9749                 case DO_RULE:
9750                         dumpRule(fout, (RuleInfo *) dobj);
9751                         break;
9752                 case DO_TRIGGER:
9753                         dumpTrigger(fout, (TriggerInfo *) dobj);
9754                         break;
9755                 case DO_EVENT_TRIGGER:
9756                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9757                         break;
9758                 case DO_CONSTRAINT:
9759                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9760                         break;
9761                 case DO_FK_CONSTRAINT:
9762                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9763                         break;
9764                 case DO_PROCLANG:
9765                         dumpProcLang(fout, (ProcLangInfo *) dobj);
9766                         break;
9767                 case DO_CAST:
9768                         dumpCast(fout, (CastInfo *) dobj);
9769                         break;
9770                 case DO_TRANSFORM:
9771                         dumpTransform(fout, (TransformInfo *) dobj);
9772                         break;
9773                 case DO_SEQUENCE_SET:
9774                         dumpSequenceData(fout, (TableDataInfo *) dobj);
9775                         break;
9776                 case DO_TABLE_DATA:
9777                         dumpTableData(fout, (TableDataInfo *) dobj);
9778                         break;
9779                 case DO_DUMMY_TYPE:
9780                         /* table rowtypes and array types are never dumped separately */
9781                         break;
9782                 case DO_TSPARSER:
9783                         dumpTSParser(fout, (TSParserInfo *) dobj);
9784                         break;
9785                 case DO_TSDICT:
9786                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
9787                         break;
9788                 case DO_TSTEMPLATE:
9789                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9790                         break;
9791                 case DO_TSCONFIG:
9792                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
9793                         break;
9794                 case DO_FDW:
9795                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9796                         break;
9797                 case DO_FOREIGN_SERVER:
9798                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9799                         break;
9800                 case DO_DEFAULT_ACL:
9801                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9802                         break;
9803                 case DO_BLOB:
9804                         dumpBlob(fout, (BlobInfo *) dobj);
9805                         break;
9806                 case DO_BLOB_DATA:
9807                         if (dobj->dump & DUMP_COMPONENT_DATA)
9808                                 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9809                                                          dobj->name, NULL, NULL, "",
9810                                                          false, "BLOBS", SECTION_DATA,
9811                                                          "", "", NULL,
9812                                                          NULL, 0,
9813                                                          dumpBlobs, NULL);
9814                         break;
9815                 case DO_POLICY:
9816                         dumpPolicy(fout, (PolicyInfo *) dobj);
9817                         break;
9818                 case DO_PUBLICATION:
9819                         dumpPublication(fout, (PublicationInfo *) dobj);
9820                         break;
9821                 case DO_PUBLICATION_REL:
9822                         dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9823                         break;
9824                 case DO_SUBSCRIPTION:
9825                         dumpSubscription(fout, (SubscriptionInfo *) dobj);
9826                         break;
9827                 case DO_PRE_DATA_BOUNDARY:
9828                 case DO_POST_DATA_BOUNDARY:
9829                         /* never dumped, nothing to do */
9830                         break;
9831         }
9832 }
9833
9834 /*
9835  * dumpNamespace
9836  *        writes out to fout the queries to recreate a user-defined namespace
9837  */
9838 static void
9839 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9840 {
9841         DumpOptions *dopt = fout->dopt;
9842         PQExpBuffer q;
9843         PQExpBuffer delq;
9844         PQExpBuffer labelq;
9845         char       *qnspname;
9846
9847         /* Skip if not to be dumped */
9848         if (!nspinfo->dobj.dump || dopt->dataOnly)
9849                 return;
9850
9851         q = createPQExpBuffer();
9852         delq = createPQExpBuffer();
9853         labelq = createPQExpBuffer();
9854
9855         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9856
9857         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9858
9859         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9860
9861         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
9862
9863         if (dopt->binary_upgrade)
9864                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
9865
9866         if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9867                 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9868                                          nspinfo->dobj.name,
9869                                          NULL, NULL,
9870                                          nspinfo->rolname,
9871                                          false, "SCHEMA", SECTION_PRE_DATA,
9872                                          q->data, delq->data, NULL,
9873                                          NULL, 0,
9874                                          NULL, NULL);
9875
9876         /* Dump Schema Comments and Security Labels */
9877         if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9878                 dumpComment(fout, labelq->data,
9879                                         NULL, nspinfo->rolname,
9880                                         nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9881
9882         if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9883                 dumpSecLabel(fout, labelq->data,
9884                                          NULL, nspinfo->rolname,
9885                                          nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9886
9887         if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9888                 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9889                                 qnspname, NULL, labelq->data, NULL,
9890                                 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9891                                 nspinfo->initnspacl, nspinfo->initrnspacl);
9892
9893         free(qnspname);
9894
9895         destroyPQExpBuffer(q);
9896         destroyPQExpBuffer(delq);
9897         destroyPQExpBuffer(labelq);
9898 }
9899
9900 /*
9901  * dumpExtension
9902  *        writes out to fout the queries to recreate an extension
9903  */
9904 static void
9905 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9906 {
9907         DumpOptions *dopt = fout->dopt;
9908         PQExpBuffer q;
9909         PQExpBuffer delq;
9910         PQExpBuffer labelq;
9911         char       *qextname;
9912
9913         /* Skip if not to be dumped */
9914         if (!extinfo->dobj.dump || dopt->dataOnly)
9915                 return;
9916
9917         q = createPQExpBuffer();
9918         delq = createPQExpBuffer();
9919         labelq = createPQExpBuffer();
9920
9921         qextname = pg_strdup(fmtId(extinfo->dobj.name));
9922
9923         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9924
9925         if (!dopt->binary_upgrade)
9926         {
9927                 /*
9928                  * In a regular dump, we simply create the extension, intentionally
9929                  * not specifying a version, so that the destination installation's
9930                  * default version is used.
9931                  *
9932                  * Use of IF NOT EXISTS here is unlike our behavior for other object
9933                  * types; but there are various scenarios in which it's convenient to
9934                  * manually create the desired extension before restoring, so we
9935                  * prefer to allow it to exist already.
9936                  */
9937                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9938                                                   qextname, fmtId(extinfo->namespace));
9939         }
9940         else
9941         {
9942                 /*
9943                  * In binary-upgrade mode, it's critical to reproduce the state of the
9944                  * database exactly, so our procedure is to create an empty extension,
9945                  * restore all the contained objects normally, and add them to the
9946                  * extension one by one.  This function performs just the first of
9947                  * those steps.  binary_upgrade_extension_member() takes care of
9948                  * adding member objects as they're created.
9949                  */
9950                 int                     i;
9951                 int                     n;
9952
9953                 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9954
9955                 /*
9956                  * We unconditionally create the extension, so we must drop it if it
9957                  * exists.  This could happen if the user deleted 'plpgsql' and then
9958                  * readded it, causing its oid to be greater than g_last_builtin_oid.
9959                  */
9960                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9961
9962                 appendPQExpBufferStr(q,
9963                                                          "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9964                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9965                 appendPQExpBufferStr(q, ", ");
9966                 appendStringLiteralAH(q, extinfo->namespace, fout);
9967                 appendPQExpBufferStr(q, ", ");
9968                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9969                 appendStringLiteralAH(q, extinfo->extversion, fout);
9970                 appendPQExpBufferStr(q, ", ");
9971
9972                 /*
9973                  * Note that we're pushing extconfig (an OID array) back into
9974                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
9975                  * preserved in binary upgrade.
9976                  */
9977                 if (strlen(extinfo->extconfig) > 2)
9978                         appendStringLiteralAH(q, extinfo->extconfig, fout);
9979                 else
9980                         appendPQExpBufferStr(q, "NULL");
9981                 appendPQExpBufferStr(q, ", ");
9982                 if (strlen(extinfo->extcondition) > 2)
9983                         appendStringLiteralAH(q, extinfo->extcondition, fout);
9984                 else
9985                         appendPQExpBufferStr(q, "NULL");
9986                 appendPQExpBufferStr(q, ", ");
9987                 appendPQExpBufferStr(q, "ARRAY[");
9988                 n = 0;
9989                 for (i = 0; i < extinfo->dobj.nDeps; i++)
9990                 {
9991                         DumpableObject *extobj;
9992
9993                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9994                         if (extobj && extobj->objType == DO_EXTENSION)
9995                         {
9996                                 if (n++ > 0)
9997                                         appendPQExpBufferChar(q, ',');
9998                                 appendStringLiteralAH(q, extobj->name, fout);
9999                         }
10000                 }
10001                 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10002                 appendPQExpBufferStr(q, ");\n");
10003         }
10004
10005         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
10006
10007         if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10008                 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10009                                          extinfo->dobj.name,
10010                                          NULL, NULL,
10011                                          "",
10012                                          false, "EXTENSION", SECTION_PRE_DATA,
10013                                          q->data, delq->data, NULL,
10014                                          NULL, 0,
10015                                          NULL, NULL);
10016
10017         /* Dump Extension Comments and Security Labels */
10018         if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10019                 dumpComment(fout, labelq->data,
10020                                         NULL, "",
10021                                         extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10022
10023         if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10024                 dumpSecLabel(fout, labelq->data,
10025                                          NULL, "",
10026                                          extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10027
10028         free(qextname);
10029
10030         destroyPQExpBuffer(q);
10031         destroyPQExpBuffer(delq);
10032         destroyPQExpBuffer(labelq);
10033 }
10034
10035 /*
10036  * dumpType
10037  *        writes out to fout the queries to recreate a user-defined type
10038  */
10039 static void
10040 dumpType(Archive *fout, TypeInfo *tyinfo)
10041 {
10042         DumpOptions *dopt = fout->dopt;
10043
10044         /* Skip if not to be dumped */
10045         if (!tyinfo->dobj.dump || dopt->dataOnly)
10046                 return;
10047
10048         /* Dump out in proper style */
10049         if (tyinfo->typtype == TYPTYPE_BASE)
10050                 dumpBaseType(fout, tyinfo);
10051         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10052                 dumpDomain(fout, tyinfo);
10053         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10054                 dumpCompositeType(fout, tyinfo);
10055         else if (tyinfo->typtype == TYPTYPE_ENUM)
10056                 dumpEnumType(fout, tyinfo);
10057         else if (tyinfo->typtype == TYPTYPE_RANGE)
10058                 dumpRangeType(fout, tyinfo);
10059         else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10060                 dumpUndefinedType(fout, tyinfo);
10061         else
10062                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10063                                   tyinfo->dobj.name);
10064 }
10065
10066 /*
10067  * dumpEnumType
10068  *        writes out to fout the queries to recreate a user-defined enum type
10069  */
10070 static void
10071 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10072 {
10073         DumpOptions *dopt = fout->dopt;
10074         PQExpBuffer q = createPQExpBuffer();
10075         PQExpBuffer delq = createPQExpBuffer();
10076         PQExpBuffer labelq = createPQExpBuffer();
10077         PQExpBuffer query = createPQExpBuffer();
10078         PGresult   *res;
10079         int                     num,
10080                                 i;
10081         Oid                     enum_oid;
10082         char       *qtypname;
10083         char       *label;
10084
10085         /* Set proper schema search path */
10086         selectSourceSchema(fout, "pg_catalog");
10087
10088         if (fout->remoteVersion >= 90100)
10089                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10090                                                   "FROM pg_catalog.pg_enum "
10091                                                   "WHERE enumtypid = '%u'"
10092                                                   "ORDER BY enumsortorder",
10093                                                   tyinfo->dobj.catId.oid);
10094         else
10095                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10096                                                   "FROM pg_catalog.pg_enum "
10097                                                   "WHERE enumtypid = '%u'"
10098                                                   "ORDER BY oid",
10099                                                   tyinfo->dobj.catId.oid);
10100
10101         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10102
10103         num = PQntuples(res);
10104
10105         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10106
10107         /*
10108          * DROP must be fully qualified in case same name appears in pg_catalog.
10109          * CASCADE shouldn't be required here as for normal types since the I/O
10110          * functions are generic and do not get dropped.
10111          */
10112         appendPQExpBuffer(delq, "DROP TYPE %s.",
10113                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10114         appendPQExpBuffer(delq, "%s;\n",
10115                                           qtypname);
10116
10117         if (dopt->binary_upgrade)
10118                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10119                                                                                                  tyinfo->dobj.catId.oid,
10120                                                                                                  false);
10121
10122         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10123                                           qtypname);
10124
10125         if (!dopt->binary_upgrade)
10126         {
10127                 /* Labels with server-assigned oids */
10128                 for (i = 0; i < num; i++)
10129                 {
10130                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10131                         if (i > 0)
10132                                 appendPQExpBufferChar(q, ',');
10133                         appendPQExpBufferStr(q, "\n    ");
10134                         appendStringLiteralAH(q, label, fout);
10135                 }
10136         }
10137
10138         appendPQExpBufferStr(q, "\n);\n");
10139
10140         if (dopt->binary_upgrade)
10141         {
10142                 /* Labels with dump-assigned (preserved) oids */
10143                 for (i = 0; i < num; i++)
10144                 {
10145                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10146                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10147
10148                         if (i == 0)
10149                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10150                         appendPQExpBuffer(q,
10151                                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10152                                                           enum_oid);
10153                         appendPQExpBuffer(q, "ALTER TYPE %s.",
10154                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10155                         appendPQExpBuffer(q, "%s ADD VALUE ",
10156                                                           qtypname);
10157                         appendStringLiteralAH(q, label, fout);
10158                         appendPQExpBufferStr(q, ";\n\n");
10159                 }
10160         }
10161
10162         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10163
10164         if (dopt->binary_upgrade)
10165                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10166
10167         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10168                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10169                                          tyinfo->dobj.name,
10170                                          tyinfo->dobj.namespace->dobj.name,
10171                                          NULL,
10172                                          tyinfo->rolname, false,
10173                                          "TYPE", SECTION_PRE_DATA,
10174                                          q->data, delq->data, NULL,
10175                                          NULL, 0,
10176                                          NULL, NULL);
10177
10178         /* Dump Type Comments and Security Labels */
10179         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10180                 dumpComment(fout, labelq->data,
10181                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10182                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10183
10184         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10185                 dumpSecLabel(fout, labelq->data,
10186                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10187                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10188
10189         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10190                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10191                                 qtypname, NULL, labelq->data,
10192                                 tyinfo->dobj.namespace->dobj.name,
10193                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10194                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10195
10196         PQclear(res);
10197         destroyPQExpBuffer(q);
10198         destroyPQExpBuffer(delq);
10199         destroyPQExpBuffer(labelq);
10200         destroyPQExpBuffer(query);
10201 }
10202
10203 /*
10204  * dumpRangeType
10205  *        writes out to fout the queries to recreate a user-defined range type
10206  */
10207 static void
10208 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10209 {
10210         DumpOptions *dopt = fout->dopt;
10211         PQExpBuffer q = createPQExpBuffer();
10212         PQExpBuffer delq = createPQExpBuffer();
10213         PQExpBuffer labelq = createPQExpBuffer();
10214         PQExpBuffer query = createPQExpBuffer();
10215         PGresult   *res;
10216         Oid                     collationOid;
10217         char       *qtypname;
10218         char       *procname;
10219
10220         /*
10221          * select appropriate schema to ensure names in CREATE are properly
10222          * qualified
10223          */
10224         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10225
10226         appendPQExpBuffer(query,
10227                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10228                                           "opc.opcname AS opcname, "
10229                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10230                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10231                                           "opc.opcdefault, "
10232                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
10233                                           "     ELSE rngcollation END AS collation, "
10234                                           "rngcanonical, rngsubdiff "
10235                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10236                                           "     pg_catalog.pg_opclass opc "
10237                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10238                                           "rngtypid = '%u'",
10239                                           tyinfo->dobj.catId.oid);
10240
10241         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10242
10243         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10244
10245         /*
10246          * DROP must be fully qualified in case same name appears in pg_catalog.
10247          * CASCADE shouldn't be required here as for normal types since the I/O
10248          * functions are generic and do not get dropped.
10249          */
10250         appendPQExpBuffer(delq, "DROP TYPE %s.",
10251                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10252         appendPQExpBuffer(delq, "%s;\n",
10253                                           qtypname);
10254
10255         if (dopt->binary_upgrade)
10256                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10257                                                                                                  tyinfo->dobj.catId.oid,
10258                                                                                                  false);
10259
10260         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10261                                           qtypname);
10262
10263         appendPQExpBuffer(q, "\n    subtype = %s",
10264                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10265
10266         /* print subtype_opclass only if not default for subtype */
10267         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10268         {
10269                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10270                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10271
10272                 /* always schema-qualify, don't try to be smart */
10273                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
10274                                                   fmtId(nspname));
10275                 appendPQExpBufferStr(q, fmtId(opcname));
10276         }
10277
10278         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10279         if (OidIsValid(collationOid))
10280         {
10281                 CollInfo   *coll = findCollationByOid(collationOid);
10282
10283                 if (coll)
10284                 {
10285                         /* always schema-qualify, don't try to be smart */
10286                         appendPQExpBuffer(q, ",\n    collation = %s.",
10287                                                           fmtId(coll->dobj.namespace->dobj.name));
10288                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10289                 }
10290         }
10291
10292         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10293         if (strcmp(procname, "-") != 0)
10294                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
10295
10296         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10297         if (strcmp(procname, "-") != 0)
10298                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
10299
10300         appendPQExpBufferStr(q, "\n);\n");
10301
10302         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10303
10304         if (dopt->binary_upgrade)
10305                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10306
10307         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10308                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10309                                          tyinfo->dobj.name,
10310                                          tyinfo->dobj.namespace->dobj.name,
10311                                          NULL,
10312                                          tyinfo->rolname, false,
10313                                          "TYPE", SECTION_PRE_DATA,
10314                                          q->data, delq->data, NULL,
10315                                          NULL, 0,
10316                                          NULL, NULL);
10317
10318         /* Dump Type Comments and Security Labels */
10319         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10320                 dumpComment(fout, labelq->data,
10321                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10322                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10323
10324         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10325                 dumpSecLabel(fout, labelq->data,
10326                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10327                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10328
10329         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10330                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10331                                 qtypname, NULL, labelq->data,
10332                                 tyinfo->dobj.namespace->dobj.name,
10333                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10334                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10335
10336         PQclear(res);
10337         destroyPQExpBuffer(q);
10338         destroyPQExpBuffer(delq);
10339         destroyPQExpBuffer(labelq);
10340         destroyPQExpBuffer(query);
10341 }
10342
10343 /*
10344  * dumpUndefinedType
10345  *        writes out to fout the queries to recreate a !typisdefined type
10346  *
10347  * This is a shell type, but we use different terminology to distinguish
10348  * this case from where we have to emit a shell type definition to break
10349  * circular dependencies.  An undefined type shouldn't ever have anything
10350  * depending on it.
10351  */
10352 static void
10353 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10354 {
10355         DumpOptions *dopt = fout->dopt;
10356         PQExpBuffer q = createPQExpBuffer();
10357         PQExpBuffer delq = createPQExpBuffer();
10358         PQExpBuffer labelq = createPQExpBuffer();
10359         char       *qtypname;
10360
10361         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10362
10363         /*
10364          * DROP must be fully qualified in case same name appears in pg_catalog.
10365          */
10366         appendPQExpBuffer(delq, "DROP TYPE %s.",
10367                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10368         appendPQExpBuffer(delq, "%s;\n",
10369                                           qtypname);
10370
10371         if (dopt->binary_upgrade)
10372                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10373                                                                                                  tyinfo->dobj.catId.oid,
10374                                                                                                  false);
10375
10376         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10377                                           qtypname);
10378
10379         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10380
10381         if (dopt->binary_upgrade)
10382                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10383
10384         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10385                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10386                                          tyinfo->dobj.name,
10387                                          tyinfo->dobj.namespace->dobj.name,
10388                                          NULL,
10389                                          tyinfo->rolname, false,
10390                                          "TYPE", SECTION_PRE_DATA,
10391                                          q->data, delq->data, NULL,
10392                                          NULL, 0,
10393                                          NULL, NULL);
10394
10395         /* Dump Type Comments and Security Labels */
10396         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10397                 dumpComment(fout, labelq->data,
10398                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10399                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10400
10401         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10402                 dumpSecLabel(fout, labelq->data,
10403                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10404                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10405
10406         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10407                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10408                                 qtypname, NULL, labelq->data,
10409                                 tyinfo->dobj.namespace->dobj.name,
10410                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10411                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10412
10413         destroyPQExpBuffer(q);
10414         destroyPQExpBuffer(delq);
10415         destroyPQExpBuffer(labelq);
10416 }
10417
10418 /*
10419  * dumpBaseType
10420  *        writes out to fout the queries to recreate a user-defined base type
10421  */
10422 static void
10423 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10424 {
10425         DumpOptions *dopt = fout->dopt;
10426         PQExpBuffer q = createPQExpBuffer();
10427         PQExpBuffer delq = createPQExpBuffer();
10428         PQExpBuffer labelq = createPQExpBuffer();
10429         PQExpBuffer query = createPQExpBuffer();
10430         PGresult   *res;
10431         char       *qtypname;
10432         char       *typlen;
10433         char       *typinput;
10434         char       *typoutput;
10435         char       *typreceive;
10436         char       *typsend;
10437         char       *typmodin;
10438         char       *typmodout;
10439         char       *typanalyze;
10440         Oid                     typreceiveoid;
10441         Oid                     typsendoid;
10442         Oid                     typmodinoid;
10443         Oid                     typmodoutoid;
10444         Oid                     typanalyzeoid;
10445         char       *typcategory;
10446         char       *typispreferred;
10447         char       *typdelim;
10448         char       *typbyval;
10449         char       *typalign;
10450         char       *typstorage;
10451         char       *typcollatable;
10452         char       *typdefault;
10453         bool            typdefault_is_literal = false;
10454
10455         /* Set proper schema search path so regproc references list correctly */
10456         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10457
10458         /* Fetch type-specific details */
10459         if (fout->remoteVersion >= 90100)
10460         {
10461                 appendPQExpBuffer(query, "SELECT typlen, "
10462                                                   "typinput, typoutput, typreceive, typsend, "
10463                                                   "typmodin, typmodout, typanalyze, "
10464                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10465                                                   "typsend::pg_catalog.oid AS typsendoid, "
10466                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10467                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10468                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10469                                                   "typcategory, typispreferred, "
10470                                                   "typdelim, typbyval, typalign, typstorage, "
10471                                                   "(typcollation <> 0) AS typcollatable, "
10472                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10473                                                   "FROM pg_catalog.pg_type "
10474                                                   "WHERE oid = '%u'::pg_catalog.oid",
10475                                                   tyinfo->dobj.catId.oid);
10476         }
10477         else if (fout->remoteVersion >= 80400)
10478         {
10479                 appendPQExpBuffer(query, "SELECT typlen, "
10480                                                   "typinput, typoutput, typreceive, typsend, "
10481                                                   "typmodin, typmodout, typanalyze, "
10482                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10483                                                   "typsend::pg_catalog.oid AS typsendoid, "
10484                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10485                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10486                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10487                                                   "typcategory, typispreferred, "
10488                                                   "typdelim, typbyval, typalign, typstorage, "
10489                                                   "false AS typcollatable, "
10490                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10491                                                   "FROM pg_catalog.pg_type "
10492                                                   "WHERE oid = '%u'::pg_catalog.oid",
10493                                                   tyinfo->dobj.catId.oid);
10494         }
10495         else if (fout->remoteVersion >= 80300)
10496         {
10497                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10498                 appendPQExpBuffer(query, "SELECT typlen, "
10499                                                   "typinput, typoutput, typreceive, typsend, "
10500                                                   "typmodin, typmodout, typanalyze, "
10501                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10502                                                   "typsend::pg_catalog.oid AS typsendoid, "
10503                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10504                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10505                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10506                                                   "'U' AS typcategory, false AS typispreferred, "
10507                                                   "typdelim, typbyval, typalign, typstorage, "
10508                                                   "false AS typcollatable, "
10509                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10510                                                   "FROM pg_catalog.pg_type "
10511                                                   "WHERE oid = '%u'::pg_catalog.oid",
10512                                                   tyinfo->dobj.catId.oid);
10513         }
10514         else
10515         {
10516                 appendPQExpBuffer(query, "SELECT typlen, "
10517                                                   "typinput, typoutput, typreceive, typsend, "
10518                                                   "'-' AS typmodin, '-' AS typmodout, "
10519                                                   "typanalyze, "
10520                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10521                                                   "typsend::pg_catalog.oid AS typsendoid, "
10522                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
10523                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10524                                                   "'U' AS typcategory, false AS typispreferred, "
10525                                                   "typdelim, typbyval, typalign, typstorage, "
10526                                                   "false AS typcollatable, "
10527                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10528                                                   "FROM pg_catalog.pg_type "
10529                                                   "WHERE oid = '%u'::pg_catalog.oid",
10530                                                   tyinfo->dobj.catId.oid);
10531         }
10532
10533         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10534
10535         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10536         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10537         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10538         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10539         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10540         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10541         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10542         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10543         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10544         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10545         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10546         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10547         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10548         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10549         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10550         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10551         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10552         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10553         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10554         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10555         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10556                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10557         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10558         {
10559                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10560                 typdefault_is_literal = true;   /* it needs quotes */
10561         }
10562         else
10563                 typdefault = NULL;
10564
10565         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10566
10567         /*
10568          * DROP must be fully qualified in case same name appears in pg_catalog.
10569          * The reason we include CASCADE is that the circular dependency between
10570          * the type and its I/O functions makes it impossible to drop the type any
10571          * other way.
10572          */
10573         appendPQExpBuffer(delq, "DROP TYPE %s.",
10574                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10575         appendPQExpBuffer(delq, "%s CASCADE;\n",
10576                                           qtypname);
10577
10578         /*
10579          * We might already have a shell type, but setting pg_type_oid is
10580          * harmless, and in any case we'd better set the array type OID.
10581          */
10582         if (dopt->binary_upgrade)
10583                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10584                                                                                                  tyinfo->dobj.catId.oid,
10585                                                                                                  false);
10586
10587         appendPQExpBuffer(q,
10588                                           "CREATE TYPE %s (\n"
10589                                           "    INTERNALLENGTH = %s",
10590                                           qtypname,
10591                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10592
10593         /* regproc result is sufficiently quoted already */
10594         appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
10595         appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
10596         if (OidIsValid(typreceiveoid))
10597                 appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
10598         if (OidIsValid(typsendoid))
10599                 appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
10600         if (OidIsValid(typmodinoid))
10601                 appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
10602         if (OidIsValid(typmodoutoid))
10603                 appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
10604         if (OidIsValid(typanalyzeoid))
10605                 appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
10606
10607         if (strcmp(typcollatable, "t") == 0)
10608                 appendPQExpBufferStr(q, ",\n    COLLATABLE = true");
10609
10610         if (typdefault != NULL)
10611         {
10612                 appendPQExpBufferStr(q, ",\n    DEFAULT = ");
10613                 if (typdefault_is_literal)
10614                         appendStringLiteralAH(q, typdefault, fout);
10615                 else
10616                         appendPQExpBufferStr(q, typdefault);
10617         }
10618
10619         if (OidIsValid(tyinfo->typelem))
10620         {
10621                 char       *elemType;
10622
10623                 /* reselect schema in case changed by function dump */
10624                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10625                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10626                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
10627                 free(elemType);
10628         }
10629
10630         if (strcmp(typcategory, "U") != 0)
10631         {
10632                 appendPQExpBufferStr(q, ",\n    CATEGORY = ");
10633                 appendStringLiteralAH(q, typcategory, fout);
10634         }
10635
10636         if (strcmp(typispreferred, "t") == 0)
10637                 appendPQExpBufferStr(q, ",\n    PREFERRED = true");
10638
10639         if (typdelim && strcmp(typdelim, ",") != 0)
10640         {
10641                 appendPQExpBufferStr(q, ",\n    DELIMITER = ");
10642                 appendStringLiteralAH(q, typdelim, fout);
10643         }
10644
10645         if (strcmp(typalign, "c") == 0)
10646                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = char");
10647         else if (strcmp(typalign, "s") == 0)
10648                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int2");
10649         else if (strcmp(typalign, "i") == 0)
10650                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int4");
10651         else if (strcmp(typalign, "d") == 0)
10652                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = double");
10653
10654         if (strcmp(typstorage, "p") == 0)
10655                 appendPQExpBufferStr(q, ",\n    STORAGE = plain");
10656         else if (strcmp(typstorage, "e") == 0)
10657                 appendPQExpBufferStr(q, ",\n    STORAGE = external");
10658         else if (strcmp(typstorage, "x") == 0)
10659                 appendPQExpBufferStr(q, ",\n    STORAGE = extended");
10660         else if (strcmp(typstorage, "m") == 0)
10661                 appendPQExpBufferStr(q, ",\n    STORAGE = main");
10662
10663         if (strcmp(typbyval, "t") == 0)
10664                 appendPQExpBufferStr(q, ",\n    PASSEDBYVALUE");
10665
10666         appendPQExpBufferStr(q, "\n);\n");
10667
10668         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10669
10670         if (dopt->binary_upgrade)
10671                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10672
10673         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10674                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10675                                          tyinfo->dobj.name,
10676                                          tyinfo->dobj.namespace->dobj.name,
10677                                          NULL,
10678                                          tyinfo->rolname, false,
10679                                          "TYPE", SECTION_PRE_DATA,
10680                                          q->data, delq->data, NULL,
10681                                          NULL, 0,
10682                                          NULL, NULL);
10683
10684         /* Dump Type Comments and Security Labels */
10685         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10686                 dumpComment(fout, labelq->data,
10687                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10688                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10689
10690         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10691                 dumpSecLabel(fout, labelq->data,
10692                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10693                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10694
10695         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10696                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10697                                 qtypname, NULL, labelq->data,
10698                                 tyinfo->dobj.namespace->dobj.name,
10699                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10700                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10701
10702         PQclear(res);
10703         destroyPQExpBuffer(q);
10704         destroyPQExpBuffer(delq);
10705         destroyPQExpBuffer(labelq);
10706         destroyPQExpBuffer(query);
10707 }
10708
10709 /*
10710  * dumpDomain
10711  *        writes out to fout the queries to recreate a user-defined domain
10712  */
10713 static void
10714 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10715 {
10716         DumpOptions *dopt = fout->dopt;
10717         PQExpBuffer q = createPQExpBuffer();
10718         PQExpBuffer delq = createPQExpBuffer();
10719         PQExpBuffer labelq = createPQExpBuffer();
10720         PQExpBuffer query = createPQExpBuffer();
10721         PGresult   *res;
10722         int                     i;
10723         char       *qtypname;
10724         char       *typnotnull;
10725         char       *typdefn;
10726         char       *typdefault;
10727         Oid                     typcollation;
10728         bool            typdefault_is_literal = false;
10729
10730         /* Set proper schema search path so type references list correctly */
10731         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10732
10733         /* Fetch domain specific details */
10734         if (fout->remoteVersion >= 90100)
10735         {
10736                 /* typcollation is new in 9.1 */
10737                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10738                                                   "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10739                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10740                                                   "t.typdefault, "
10741                                                   "CASE WHEN t.typcollation <> u.typcollation "
10742                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
10743                                                   "FROM pg_catalog.pg_type t "
10744                                                   "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10745                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
10746                                                   tyinfo->dobj.catId.oid);
10747         }
10748         else
10749         {
10750                 appendPQExpBuffer(query, "SELECT typnotnull, "
10751                                                   "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10752                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10753                                                   "typdefault, 0 AS typcollation "
10754                                                   "FROM pg_catalog.pg_type "
10755                                                   "WHERE oid = '%u'::pg_catalog.oid",
10756                                                   tyinfo->dobj.catId.oid);
10757         }
10758
10759         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10760
10761         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10762         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10763         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10764                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10765         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10766         {
10767                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10768                 typdefault_is_literal = true;   /* it needs quotes */
10769         }
10770         else
10771                 typdefault = NULL;
10772         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10773
10774         if (dopt->binary_upgrade)
10775                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10776                                                                                                  tyinfo->dobj.catId.oid,
10777                                                                                                  true); /* force array type */
10778
10779         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10780
10781         appendPQExpBuffer(q,
10782                                           "CREATE DOMAIN %s AS %s",
10783                                           qtypname,
10784                                           typdefn);
10785
10786         /* Print collation only if different from base type's collation */
10787         if (OidIsValid(typcollation))
10788         {
10789                 CollInfo   *coll;
10790
10791                 coll = findCollationByOid(typcollation);
10792                 if (coll)
10793                 {
10794                         /* always schema-qualify, don't try to be smart */
10795                         appendPQExpBuffer(q, " COLLATE %s.",
10796                                                           fmtId(coll->dobj.namespace->dobj.name));
10797                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10798                 }
10799         }
10800
10801         if (typnotnull[0] == 't')
10802                 appendPQExpBufferStr(q, " NOT NULL");
10803
10804         if (typdefault != NULL)
10805         {
10806                 appendPQExpBufferStr(q, " DEFAULT ");
10807                 if (typdefault_is_literal)
10808                         appendStringLiteralAH(q, typdefault, fout);
10809                 else
10810                         appendPQExpBufferStr(q, typdefault);
10811         }
10812
10813         PQclear(res);
10814
10815         /*
10816          * Add any CHECK constraints for the domain
10817          */
10818         for (i = 0; i < tyinfo->nDomChecks; i++)
10819         {
10820                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10821
10822                 if (!domcheck->separate)
10823                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10824                                                           fmtId(domcheck->dobj.name), domcheck->condef);
10825         }
10826
10827         appendPQExpBufferStr(q, ";\n");
10828
10829         /*
10830          * DROP must be fully qualified in case same name appears in pg_catalog
10831          */
10832         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
10833                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10834         appendPQExpBuffer(delq, "%s;\n",
10835                                           qtypname);
10836
10837         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
10838
10839         if (dopt->binary_upgrade)
10840                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10841
10842         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10843                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10844                                          tyinfo->dobj.name,
10845                                          tyinfo->dobj.namespace->dobj.name,
10846                                          NULL,
10847                                          tyinfo->rolname, false,
10848                                          "DOMAIN", SECTION_PRE_DATA,
10849                                          q->data, delq->data, NULL,
10850                                          NULL, 0,
10851                                          NULL, NULL);
10852
10853         /* Dump Domain Comments and Security Labels */
10854         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10855                 dumpComment(fout, labelq->data,
10856                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10857                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10858
10859         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10860                 dumpSecLabel(fout, labelq->data,
10861                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10862                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10863
10864         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10865                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10866                                 qtypname, NULL, labelq->data,
10867                                 tyinfo->dobj.namespace->dobj.name,
10868                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10869                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10870
10871         /* Dump any per-constraint comments */
10872         for (i = 0; i < tyinfo->nDomChecks; i++)
10873         {
10874                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10875                 PQExpBuffer labelq = createPQExpBuffer();
10876
10877                 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
10878                                                   fmtId(domcheck->dobj.name));
10879                 appendPQExpBuffer(labelq, "ON DOMAIN %s",
10880                                                   qtypname);
10881
10882                 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10883                         dumpComment(fout, labelq->data,
10884                                                 tyinfo->dobj.namespace->dobj.name,
10885                                                 tyinfo->rolname,
10886                                                 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10887
10888                 destroyPQExpBuffer(labelq);
10889         }
10890
10891         destroyPQExpBuffer(q);
10892         destroyPQExpBuffer(delq);
10893         destroyPQExpBuffer(labelq);
10894         destroyPQExpBuffer(query);
10895 }
10896
10897 /*
10898  * dumpCompositeType
10899  *        writes out to fout the queries to recreate a user-defined stand-alone
10900  *        composite type
10901  */
10902 static void
10903 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10904 {
10905         DumpOptions *dopt = fout->dopt;
10906         PQExpBuffer q = createPQExpBuffer();
10907         PQExpBuffer dropped = createPQExpBuffer();
10908         PQExpBuffer delq = createPQExpBuffer();
10909         PQExpBuffer labelq = createPQExpBuffer();
10910         PQExpBuffer query = createPQExpBuffer();
10911         PGresult   *res;
10912         char       *qtypname;
10913         int                     ntups;
10914         int                     i_attname;
10915         int                     i_atttypdefn;
10916         int                     i_attlen;
10917         int                     i_attalign;
10918         int                     i_attisdropped;
10919         int                     i_attcollation;
10920         int                     i;
10921         int                     actual_atts;
10922
10923         /* Set proper schema search path so type references list correctly */
10924         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10925
10926         /* Fetch type specific details */
10927         if (fout->remoteVersion >= 90100)
10928         {
10929                 /*
10930                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
10931                  * clauses for attributes whose collation is different from their
10932                  * type's default, we use a CASE here to suppress uninteresting
10933                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
10934                  * collation does not matter for those.
10935                  */
10936                 appendPQExpBuffer(query, "SELECT a.attname, "
10937                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10938                                                   "a.attlen, a.attalign, a.attisdropped, "
10939                                                   "CASE WHEN a.attcollation <> at.typcollation "
10940                                                   "THEN a.attcollation ELSE 0 END AS attcollation "
10941                                                   "FROM pg_catalog.pg_type ct "
10942                                                   "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10943                                                   "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10944                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10945                                                   "ORDER BY a.attnum ",
10946                                                   tyinfo->dobj.catId.oid);
10947         }
10948         else
10949         {
10950                 /*
10951                  * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10952                  * should always be false.
10953                  */
10954                 appendPQExpBuffer(query, "SELECT a.attname, "
10955                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10956                                                   "a.attlen, a.attalign, a.attisdropped, "
10957                                                   "0 AS attcollation "
10958                                                   "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10959                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10960                                                   "AND a.attrelid = ct.typrelid "
10961                                                   "ORDER BY a.attnum ",
10962                                                   tyinfo->dobj.catId.oid);
10963         }
10964
10965         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10966
10967         ntups = PQntuples(res);
10968
10969         i_attname = PQfnumber(res, "attname");
10970         i_atttypdefn = PQfnumber(res, "atttypdefn");
10971         i_attlen = PQfnumber(res, "attlen");
10972         i_attalign = PQfnumber(res, "attalign");
10973         i_attisdropped = PQfnumber(res, "attisdropped");
10974         i_attcollation = PQfnumber(res, "attcollation");
10975
10976         if (dopt->binary_upgrade)
10977         {
10978                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10979                                                                                                  tyinfo->dobj.catId.oid,
10980                                                                                                  false);
10981                 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10982         }
10983
10984         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10985
10986         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10987                                           qtypname);
10988
10989         actual_atts = 0;
10990         for (i = 0; i < ntups; i++)
10991         {
10992                 char       *attname;
10993                 char       *atttypdefn;
10994                 char       *attlen;
10995                 char       *attalign;
10996                 bool            attisdropped;
10997                 Oid                     attcollation;
10998
10999                 attname = PQgetvalue(res, i, i_attname);
11000                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
11001                 attlen = PQgetvalue(res, i, i_attlen);
11002                 attalign = PQgetvalue(res, i, i_attalign);
11003                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
11004                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
11005
11006                 if (attisdropped && !dopt->binary_upgrade)
11007                         continue;
11008
11009                 /* Format properly if not first attr */
11010                 if (actual_atts++ > 0)
11011                         appendPQExpBufferChar(q, ',');
11012                 appendPQExpBufferStr(q, "\n\t");
11013
11014                 if (!attisdropped)
11015                 {
11016                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
11017
11018                         /* Add collation if not default for the column type */
11019                         if (OidIsValid(attcollation))
11020                         {
11021                                 CollInfo   *coll;
11022
11023                                 coll = findCollationByOid(attcollation);
11024                                 if (coll)
11025                                 {
11026                                         /* always schema-qualify, don't try to be smart */
11027                                         appendPQExpBuffer(q, " COLLATE %s.",
11028                                                                           fmtId(coll->dobj.namespace->dobj.name));
11029                                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
11030                                 }
11031                         }
11032                 }
11033                 else
11034                 {
11035                         /*
11036                          * This is a dropped attribute and we're in binary_upgrade mode.
11037                          * Insert a placeholder for it in the CREATE TYPE command, and set
11038                          * length and alignment with direct UPDATE to the catalogs
11039                          * afterwards. See similar code in dumpTableSchema().
11040                          */
11041                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11042
11043                         /* stash separately for insertion after the CREATE TYPE */
11044                         appendPQExpBufferStr(dropped,
11045                                                                  "\n-- For binary upgrade, recreate dropped column.\n");
11046                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11047                                                           "SET attlen = %s, "
11048                                                           "attalign = '%s', attbyval = false\n"
11049                                                           "WHERE attname = ", attlen, attalign);
11050                         appendStringLiteralAH(dropped, attname, fout);
11051                         appendPQExpBufferStr(dropped, "\n  AND attrelid = ");
11052                         appendStringLiteralAH(dropped, qtypname, fout);
11053                         appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11054
11055                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11056                                                           qtypname);
11057                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11058                                                           fmtId(attname));
11059                 }
11060         }
11061         appendPQExpBufferStr(q, "\n);\n");
11062         appendPQExpBufferStr(q, dropped->data);
11063
11064         /*
11065          * DROP must be fully qualified in case same name appears in pg_catalog
11066          */
11067         appendPQExpBuffer(delq, "DROP TYPE %s.",
11068                                           fmtId(tyinfo->dobj.namespace->dobj.name));
11069         appendPQExpBuffer(delq, "%s;\n",
11070                                           qtypname);
11071
11072         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
11073
11074         if (dopt->binary_upgrade)
11075                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
11076
11077         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11078                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11079                                          tyinfo->dobj.name,
11080                                          tyinfo->dobj.namespace->dobj.name,
11081                                          NULL,
11082                                          tyinfo->rolname, false,
11083                                          "TYPE", SECTION_PRE_DATA,
11084                                          q->data, delq->data, NULL,
11085                                          NULL, 0,
11086                                          NULL, NULL);
11087
11088
11089         /* Dump Type Comments and Security Labels */
11090         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11091                 dumpComment(fout, labelq->data,
11092                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11093                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11094
11095         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11096                 dumpSecLabel(fout, labelq->data,
11097                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11098                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11099
11100         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11101                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
11102                                 qtypname, NULL, labelq->data,
11103                                 tyinfo->dobj.namespace->dobj.name,
11104                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11105                                 tyinfo->inittypacl, tyinfo->initrtypacl);
11106
11107         PQclear(res);
11108         destroyPQExpBuffer(q);
11109         destroyPQExpBuffer(dropped);
11110         destroyPQExpBuffer(delq);
11111         destroyPQExpBuffer(labelq);
11112         destroyPQExpBuffer(query);
11113
11114         /* Dump any per-column comments */
11115         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11116                 dumpCompositeTypeColComments(fout, tyinfo);
11117 }
11118
11119 /*
11120  * dumpCompositeTypeColComments
11121  *        writes out to fout the queries to recreate comments on the columns of
11122  *        a user-defined stand-alone composite type
11123  */
11124 static void
11125 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11126 {
11127         CommentItem *comments;
11128         int                     ncomments;
11129         PGresult   *res;
11130         PQExpBuffer query;
11131         PQExpBuffer target;
11132         Oid                     pgClassOid;
11133         int                     i;
11134         int                     ntups;
11135         int                     i_attname;
11136         int                     i_attnum;
11137
11138         /* do nothing, if --no-comments is supplied */
11139         if (fout->dopt->no_comments)
11140                 return;
11141
11142         query = createPQExpBuffer();
11143
11144         appendPQExpBuffer(query,
11145                                           "SELECT c.tableoid, a.attname, a.attnum "
11146                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11147                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11148                                           "  AND NOT a.attisdropped "
11149                                           "ORDER BY a.attnum ",
11150                                           tyinfo->typrelid);
11151
11152         /* Fetch column attnames */
11153         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11154
11155         ntups = PQntuples(res);
11156         if (ntups < 1)
11157         {
11158                 PQclear(res);
11159                 destroyPQExpBuffer(query);
11160                 return;
11161         }
11162
11163         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11164
11165         /* Search for comments associated with type's pg_class OID */
11166         ncomments = findComments(fout,
11167                                                          pgClassOid,
11168                                                          tyinfo->typrelid,
11169                                                          &comments);
11170
11171         /* If no comments exist, we're done */
11172         if (ncomments <= 0)
11173         {
11174                 PQclear(res);
11175                 destroyPQExpBuffer(query);
11176                 return;
11177         }
11178
11179         /* Build COMMENT ON statements */
11180         target = createPQExpBuffer();
11181
11182         i_attnum = PQfnumber(res, "attnum");
11183         i_attname = PQfnumber(res, "attname");
11184         while (ncomments > 0)
11185         {
11186                 const char *attname;
11187
11188                 attname = NULL;
11189                 for (i = 0; i < ntups; i++)
11190                 {
11191                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11192                         {
11193                                 attname = PQgetvalue(res, i, i_attname);
11194                                 break;
11195                         }
11196                 }
11197                 if (attname)                    /* just in case we don't find it */
11198                 {
11199                         const char *descr = comments->descr;
11200
11201                         resetPQExpBuffer(target);
11202                         appendPQExpBuffer(target, "COLUMN %s.",
11203                                                           fmtId(tyinfo->dobj.name));
11204                         appendPQExpBufferStr(target, fmtId(attname));
11205
11206                         resetPQExpBuffer(query);
11207                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
11208                         appendStringLiteralAH(query, descr, fout);
11209                         appendPQExpBufferStr(query, ";\n");
11210
11211                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
11212                                                  target->data,
11213                                                  tyinfo->dobj.namespace->dobj.name,
11214                                                  NULL, tyinfo->rolname,
11215                                                  false, "COMMENT", SECTION_NONE,
11216                                                  query->data, "", NULL,
11217                                                  &(tyinfo->dobj.dumpId), 1,
11218                                                  NULL, NULL);
11219                 }
11220
11221                 comments++;
11222                 ncomments--;
11223         }
11224
11225         PQclear(res);
11226         destroyPQExpBuffer(query);
11227         destroyPQExpBuffer(target);
11228 }
11229
11230 /*
11231  * dumpShellType
11232  *        writes out to fout the queries to create a shell type
11233  *
11234  * We dump a shell definition in advance of the I/O functions for the type.
11235  */
11236 static void
11237 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11238 {
11239         DumpOptions *dopt = fout->dopt;
11240         PQExpBuffer q;
11241
11242         /* Skip if not to be dumped */
11243         if (!stinfo->dobj.dump || dopt->dataOnly)
11244                 return;
11245
11246         q = createPQExpBuffer();
11247
11248         /*
11249          * Note the lack of a DROP command for the shell type; any required DROP
11250          * is driven off the base type entry, instead.  This interacts with
11251          * _printTocEntry()'s use of the presence of a DROP command to decide
11252          * whether an entry needs an ALTER OWNER command.  We don't want to alter
11253          * the shell type's owner immediately on creation; that should happen only
11254          * after it's filled in, otherwise the backend complains.
11255          */
11256
11257         if (dopt->binary_upgrade)
11258                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11259                                                                                                  stinfo->baseType->dobj.catId.oid,
11260                                                                                                  false);
11261
11262         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11263                                           fmtId(stinfo->dobj.name));
11264
11265         if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11266                 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11267                                          stinfo->dobj.name,
11268                                          stinfo->dobj.namespace->dobj.name,
11269                                          NULL,
11270                                          stinfo->baseType->rolname, false,
11271                                          "SHELL TYPE", SECTION_PRE_DATA,
11272                                          q->data, "", NULL,
11273                                          NULL, 0,
11274                                          NULL, NULL);
11275
11276         destroyPQExpBuffer(q);
11277 }
11278
11279 /*
11280  * dumpProcLang
11281  *                writes out to fout the queries to recreate a user-defined
11282  *                procedural language
11283  */
11284 static void
11285 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11286 {
11287         DumpOptions *dopt = fout->dopt;
11288         PQExpBuffer defqry;
11289         PQExpBuffer delqry;
11290         PQExpBuffer labelq;
11291         bool            useParams;
11292         char       *qlanname;
11293         char       *lanschema;
11294         FuncInfo   *funcInfo;
11295         FuncInfo   *inlineInfo = NULL;
11296         FuncInfo   *validatorInfo = NULL;
11297
11298         /* Skip if not to be dumped */
11299         if (!plang->dobj.dump || dopt->dataOnly)
11300                 return;
11301
11302         /*
11303          * Try to find the support function(s).  It is not an error if we don't
11304          * find them --- if the functions are in the pg_catalog schema, as is
11305          * standard in 8.1 and up, then we won't have loaded them. (In this case
11306          * we will emit a parameterless CREATE LANGUAGE command, which will
11307          * require PL template knowledge in the backend to reload.)
11308          */
11309
11310         funcInfo = findFuncByOid(plang->lanplcallfoid);
11311         if (funcInfo != NULL && !funcInfo->dobj.dump)
11312                 funcInfo = NULL;                /* treat not-dumped same as not-found */
11313
11314         if (OidIsValid(plang->laninline))
11315         {
11316                 inlineInfo = findFuncByOid(plang->laninline);
11317                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11318                         inlineInfo = NULL;
11319         }
11320
11321         if (OidIsValid(plang->lanvalidator))
11322         {
11323                 validatorInfo = findFuncByOid(plang->lanvalidator);
11324                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11325                         validatorInfo = NULL;
11326         }
11327
11328         /*
11329          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11330          * with parameters.  Otherwise, we'll write a parameterless command, which
11331          * will rely on data from pg_pltemplate.
11332          */
11333         useParams = (funcInfo != NULL &&
11334                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11335                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11336
11337         defqry = createPQExpBuffer();
11338         delqry = createPQExpBuffer();
11339         labelq = createPQExpBuffer();
11340
11341         qlanname = pg_strdup(fmtId(plang->dobj.name));
11342
11343         /*
11344          * If dumping a HANDLER clause, treat the language as being in the handler
11345          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
11346          * it doesn't really have a schema.
11347          */
11348         if (useParams)
11349                 lanschema = funcInfo->dobj.namespace->dobj.name;
11350         else
11351                 lanschema = NULL;
11352
11353         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11354                                           qlanname);
11355
11356         if (useParams)
11357         {
11358                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11359                                                   plang->lanpltrusted ? "TRUSTED " : "",
11360                                                   qlanname);
11361                 appendPQExpBuffer(defqry, " HANDLER %s",
11362                                                   fmtId(funcInfo->dobj.name));
11363                 if (OidIsValid(plang->laninline))
11364                 {
11365                         appendPQExpBufferStr(defqry, " INLINE ");
11366                         /* Cope with possibility that inline is in different schema */
11367                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
11368                                 appendPQExpBuffer(defqry, "%s.",
11369                                                                   fmtId(inlineInfo->dobj.namespace->dobj.name));
11370                         appendPQExpBufferStr(defqry, fmtId(inlineInfo->dobj.name));
11371                 }
11372                 if (OidIsValid(plang->lanvalidator))
11373                 {
11374                         appendPQExpBufferStr(defqry, " VALIDATOR ");
11375                         /* Cope with possibility that validator is in different schema */
11376                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
11377                                 appendPQExpBuffer(defqry, "%s.",
11378                                                                   fmtId(validatorInfo->dobj.namespace->dobj.name));
11379                         appendPQExpBufferStr(defqry, fmtId(validatorInfo->dobj.name));
11380                 }
11381         }
11382         else
11383         {
11384                 /*
11385                  * If not dumping parameters, then use CREATE OR REPLACE so that the
11386                  * command will not fail if the language is preinstalled in the target
11387                  * database.  We restrict the use of REPLACE to this case so as to
11388                  * eliminate the risk of replacing a language with incompatible
11389                  * parameter settings: this command will only succeed at all if there
11390                  * is a pg_pltemplate entry, and if there is one, the existing entry
11391                  * must match it too.
11392                  */
11393                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11394                                                   qlanname);
11395         }
11396         appendPQExpBufferStr(defqry, ";\n");
11397
11398         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
11399
11400         if (dopt->binary_upgrade)
11401                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
11402
11403         if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11404                 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11405                                          plang->dobj.name,
11406                                          lanschema, NULL, plang->lanowner,
11407                                          false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11408                                          defqry->data, delqry->data, NULL,
11409                                          NULL, 0,
11410                                          NULL, NULL);
11411
11412         /* Dump Proc Lang Comments and Security Labels */
11413         if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11414                 dumpComment(fout, labelq->data,
11415                                         lanschema, plang->lanowner,
11416                                         plang->dobj.catId, 0, plang->dobj.dumpId);
11417
11418         if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11419                 dumpSecLabel(fout, labelq->data,
11420                                          lanschema, plang->lanowner,
11421                                          plang->dobj.catId, 0, plang->dobj.dumpId);
11422
11423         if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11424                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11425                                 qlanname, NULL, labelq->data,
11426                                 lanschema,
11427                                 plang->lanowner, plang->lanacl, plang->rlanacl,
11428                                 plang->initlanacl, plang->initrlanacl);
11429
11430         free(qlanname);
11431
11432         destroyPQExpBuffer(defqry);
11433         destroyPQExpBuffer(delqry);
11434         destroyPQExpBuffer(labelq);
11435 }
11436
11437 /*
11438  * format_function_arguments: generate function name and argument list
11439  *
11440  * This is used when we can rely on pg_get_function_arguments to format
11441  * the argument list.  Note, however, that pg_get_function_arguments
11442  * does not special-case zero-argument aggregates.
11443  */
11444 static char *
11445 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11446 {
11447         PQExpBufferData fn;
11448
11449         initPQExpBuffer(&fn);
11450         appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11451         if (is_agg && finfo->nargs == 0)
11452                 appendPQExpBufferStr(&fn, "(*)");
11453         else
11454                 appendPQExpBuffer(&fn, "(%s)", funcargs);
11455         return fn.data;
11456 }
11457
11458 /*
11459  * format_function_arguments_old: generate function name and argument list
11460  *
11461  * The argument type names are qualified if needed.  The function name
11462  * is never qualified.
11463  *
11464  * This is used only with pre-8.4 servers, so we aren't expecting to see
11465  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11466  *
11467  * Any or all of allargtypes, argmodes, argnames may be NULL.
11468  */
11469 static char *
11470 format_function_arguments_old(Archive *fout,
11471                                                           FuncInfo *finfo, int nallargs,
11472                                                           char **allargtypes,
11473                                                           char **argmodes,
11474                                                           char **argnames)
11475 {
11476         PQExpBufferData fn;
11477         int                     j;
11478
11479         initPQExpBuffer(&fn);
11480         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11481         for (j = 0; j < nallargs; j++)
11482         {
11483                 Oid                     typid;
11484                 char       *typname;
11485                 const char *argmode;
11486                 const char *argname;
11487
11488                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11489                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11490
11491                 if (argmodes)
11492                 {
11493                         switch (argmodes[j][0])
11494                         {
11495                                 case PROARGMODE_IN:
11496                                         argmode = "";
11497                                         break;
11498                                 case PROARGMODE_OUT:
11499                                         argmode = "OUT ";
11500                                         break;
11501                                 case PROARGMODE_INOUT:
11502                                         argmode = "INOUT ";
11503                                         break;
11504                                 default:
11505                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11506                                         argmode = "";
11507                                         break;
11508                         }
11509                 }
11510                 else
11511                         argmode = "";
11512
11513                 argname = argnames ? argnames[j] : (char *) NULL;
11514                 if (argname && argname[0] == '\0')
11515                         argname = NULL;
11516
11517                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11518                                                   (j > 0) ? ", " : "",
11519                                                   argmode,
11520                                                   argname ? fmtId(argname) : "",
11521                                                   argname ? " " : "",
11522                                                   typname);
11523                 free(typname);
11524         }
11525         appendPQExpBufferChar(&fn, ')');
11526         return fn.data;
11527 }
11528
11529 /*
11530  * format_function_signature: generate function name and argument list
11531  *
11532  * This is like format_function_arguments_old except that only a minimal
11533  * list of input argument types is generated; this is sufficient to
11534  * reference the function, but not to define it.
11535  *
11536  * If honor_quotes is false then the function name is never quoted.
11537  * This is appropriate for use in TOC tags, but not in SQL commands.
11538  */
11539 static char *
11540 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11541 {
11542         PQExpBufferData fn;
11543         int                     j;
11544
11545         initPQExpBuffer(&fn);
11546         if (honor_quotes)
11547                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11548         else
11549                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11550         for (j = 0; j < finfo->nargs; j++)
11551         {
11552                 char       *typname;
11553
11554                 if (j > 0)
11555                         appendPQExpBufferStr(&fn, ", ");
11556
11557                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11558                                                                            zeroAsOpaque);
11559                 appendPQExpBufferStr(&fn, typname);
11560                 free(typname);
11561         }
11562         appendPQExpBufferChar(&fn, ')');
11563         return fn.data;
11564 }
11565
11566
11567 /*
11568  * dumpFunc:
11569  *        dump out one function
11570  */
11571 static void
11572 dumpFunc(Archive *fout, FuncInfo *finfo)
11573 {
11574         DumpOptions *dopt = fout->dopt;
11575         PQExpBuffer query;
11576         PQExpBuffer q;
11577         PQExpBuffer delqry;
11578         PQExpBuffer labelq;
11579         PQExpBuffer asPart;
11580         PGresult   *res;
11581         char       *funcsig;            /* identity signature */
11582         char       *funcfullsig = NULL; /* full signature */
11583         char       *funcsig_tag;
11584         char       *proretset;
11585         char       *prosrc;
11586         char       *probin;
11587         char       *funcargs;
11588         char       *funciargs;
11589         char       *funcresult;
11590         bool            is_procedure;
11591         char       *proallargtypes;
11592         char       *proargmodes;
11593         char       *proargnames;
11594         char       *protrftypes;
11595         char       *proiswindow;
11596         char       *provolatile;
11597         char       *proisstrict;
11598         char       *prosecdef;
11599         char       *proleakproof;
11600         char       *proconfig;
11601         char       *procost;
11602         char       *prorows;
11603         char       *proparallel;
11604         char       *lanname;
11605         char       *rettypename;
11606         int                     nallargs;
11607         char      **allargtypes = NULL;
11608         char      **argmodes = NULL;
11609         char      **argnames = NULL;
11610         char      **configitems = NULL;
11611         int                     nconfigitems = 0;
11612         const char *keyword;
11613         int                     i;
11614
11615         /* Skip if not to be dumped */
11616         if (!finfo->dobj.dump || dopt->dataOnly)
11617                 return;
11618
11619         query = createPQExpBuffer();
11620         q = createPQExpBuffer();
11621         delqry = createPQExpBuffer();
11622         labelq = createPQExpBuffer();
11623         asPart = createPQExpBuffer();
11624
11625         /* Set proper schema search path so type references list correctly */
11626         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
11627
11628         /* Fetch function-specific details */
11629         if (fout->remoteVersion >= 90600)
11630         {
11631                 /*
11632                  * proparallel was added in 9.6
11633                  */
11634                 appendPQExpBuffer(query,
11635                                                   "SELECT proretset, prosrc, probin, "
11636                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11637                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11638                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11639                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11640                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11641                                                   "proleakproof, proconfig, procost, prorows, "
11642                                                   "proparallel, "
11643                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11644                                                   "FROM pg_catalog.pg_proc "
11645                                                   "WHERE oid = '%u'::pg_catalog.oid",
11646                                                   finfo->dobj.catId.oid);
11647         }
11648         else if (fout->remoteVersion >= 90500)
11649         {
11650                 /*
11651                  * protrftypes was added in 9.5
11652                  */
11653                 appendPQExpBuffer(query,
11654                                                   "SELECT proretset, prosrc, probin, "
11655                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11656                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11657                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11658                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11659                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11660                                                   "proleakproof, proconfig, procost, prorows, "
11661                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11662                                                   "FROM pg_catalog.pg_proc "
11663                                                   "WHERE oid = '%u'::pg_catalog.oid",
11664                                                   finfo->dobj.catId.oid);
11665         }
11666         else if (fout->remoteVersion >= 90200)
11667         {
11668                 /*
11669                  * proleakproof was added in 9.2
11670                  */
11671                 appendPQExpBuffer(query,
11672                                                   "SELECT proretset, prosrc, probin, "
11673                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11674                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11675                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11676                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11677                                                   "proleakproof, proconfig, procost, prorows, "
11678                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11679                                                   "FROM pg_catalog.pg_proc "
11680                                                   "WHERE oid = '%u'::pg_catalog.oid",
11681                                                   finfo->dobj.catId.oid);
11682         }
11683         else if (fout->remoteVersion >= 80400)
11684         {
11685                 /*
11686                  * In 8.4 and up we rely on pg_get_function_arguments and
11687                  * pg_get_function_result instead of examining proallargtypes etc.
11688                  */
11689                 appendPQExpBuffer(query,
11690                                                   "SELECT proretset, prosrc, probin, "
11691                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11692                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11693                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11694                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11695                                                   "false AS proleakproof, "
11696                                                   " proconfig, procost, prorows, "
11697                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11698                                                   "FROM pg_catalog.pg_proc "
11699                                                   "WHERE oid = '%u'::pg_catalog.oid",
11700                                                   finfo->dobj.catId.oid);
11701         }
11702         else if (fout->remoteVersion >= 80300)
11703         {
11704                 appendPQExpBuffer(query,
11705                                                   "SELECT proretset, prosrc, probin, "
11706                                                   "proallargtypes, proargmodes, proargnames, "
11707                                                   "false AS proiswindow, "
11708                                                   "provolatile, proisstrict, prosecdef, "
11709                                                   "false AS proleakproof, "
11710                                                   "proconfig, procost, prorows, "
11711                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11712                                                   "FROM pg_catalog.pg_proc "
11713                                                   "WHERE oid = '%u'::pg_catalog.oid",
11714                                                   finfo->dobj.catId.oid);
11715         }
11716         else if (fout->remoteVersion >= 80100)
11717         {
11718                 appendPQExpBuffer(query,
11719                                                   "SELECT proretset, prosrc, probin, "
11720                                                   "proallargtypes, proargmodes, proargnames, "
11721                                                   "false AS proiswindow, "
11722                                                   "provolatile, proisstrict, prosecdef, "
11723                                                   "false AS proleakproof, "
11724                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11725                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11726                                                   "FROM pg_catalog.pg_proc "
11727                                                   "WHERE oid = '%u'::pg_catalog.oid",
11728                                                   finfo->dobj.catId.oid);
11729         }
11730         else
11731         {
11732                 appendPQExpBuffer(query,
11733                                                   "SELECT proretset, prosrc, probin, "
11734                                                   "null AS proallargtypes, "
11735                                                   "null AS proargmodes, "
11736                                                   "proargnames, "
11737                                                   "false AS proiswindow, "
11738                                                   "provolatile, proisstrict, prosecdef, "
11739                                                   "false AS proleakproof, "
11740                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11741                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11742                                                   "FROM pg_catalog.pg_proc "
11743                                                   "WHERE oid = '%u'::pg_catalog.oid",
11744                                                   finfo->dobj.catId.oid);
11745         }
11746
11747         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11748
11749         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11750         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11751         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11752         if (fout->remoteVersion >= 80400)
11753         {
11754                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11755                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11756                 is_procedure = PQgetisnull(res, 0, PQfnumber(res, "funcresult"));
11757                 if (is_procedure)
11758                         funcresult = NULL;
11759                 else
11760                         funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11761                 proallargtypes = proargmodes = proargnames = NULL;
11762         }
11763         else
11764         {
11765                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11766                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11767                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11768                 funcargs = funciargs = funcresult = NULL;
11769                 is_procedure = false;
11770         }
11771         if (PQfnumber(res, "protrftypes") != -1)
11772                 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11773         else
11774                 protrftypes = NULL;
11775         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
11776         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11777         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11778         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11779         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11780         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11781         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11782         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11783
11784         if (PQfnumber(res, "proparallel") != -1)
11785                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11786         else
11787                 proparallel = NULL;
11788
11789         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11790
11791         /*
11792          * See backend/commands/functioncmds.c for details of how the 'AS' clause
11793          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
11794          * versions would set it to "-".  There are no known cases in which prosrc
11795          * is unused, so the tests below for "-" are probably useless.
11796          */
11797         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11798         {
11799                 appendPQExpBufferStr(asPart, "AS ");
11800                 appendStringLiteralAH(asPart, probin, fout);
11801                 if (strcmp(prosrc, "-") != 0)
11802                 {
11803                         appendPQExpBufferStr(asPart, ", ");
11804
11805                         /*
11806                          * where we have bin, use dollar quoting if allowed and src
11807                          * contains quote or backslash; else use regular quoting.
11808                          */
11809                         if (dopt->disable_dollar_quoting ||
11810                                 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11811                                 appendStringLiteralAH(asPart, prosrc, fout);
11812                         else
11813                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11814                 }
11815         }
11816         else
11817         {
11818                 if (strcmp(prosrc, "-") != 0)
11819                 {
11820                         appendPQExpBufferStr(asPart, "AS ");
11821                         /* with no bin, dollar quote src unconditionally if allowed */
11822                         if (dopt->disable_dollar_quoting)
11823                                 appendStringLiteralAH(asPart, prosrc, fout);
11824                         else
11825                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11826                 }
11827         }
11828
11829         nallargs = finfo->nargs;        /* unless we learn different from allargs */
11830
11831         if (proallargtypes && *proallargtypes)
11832         {
11833                 int                     nitems = 0;
11834
11835                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11836                         nitems < finfo->nargs)
11837                 {
11838                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11839                         if (allargtypes)
11840                                 free(allargtypes);
11841                         allargtypes = NULL;
11842                 }
11843                 else
11844                         nallargs = nitems;
11845         }
11846
11847         if (proargmodes && *proargmodes)
11848         {
11849                 int                     nitems = 0;
11850
11851                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11852                         nitems != nallargs)
11853                 {
11854                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11855                         if (argmodes)
11856                                 free(argmodes);
11857                         argmodes = NULL;
11858                 }
11859         }
11860
11861         if (proargnames && *proargnames)
11862         {
11863                 int                     nitems = 0;
11864
11865                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11866                         nitems != nallargs)
11867                 {
11868                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
11869                         if (argnames)
11870                                 free(argnames);
11871                         argnames = NULL;
11872                 }
11873         }
11874
11875         if (proconfig && *proconfig)
11876         {
11877                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11878                 {
11879                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
11880                         if (configitems)
11881                                 free(configitems);
11882                         configitems = NULL;
11883                         nconfigitems = 0;
11884                 }
11885         }
11886
11887         if (funcargs)
11888         {
11889                 /* 8.4 or later; we rely on server-side code for most of the work */
11890                 funcfullsig = format_function_arguments(finfo, funcargs, false);
11891                 funcsig = format_function_arguments(finfo, funciargs, false);
11892         }
11893         else
11894                 /* pre-8.4, do it ourselves */
11895                 funcsig = format_function_arguments_old(fout,
11896                                                                                                 finfo, nallargs, allargtypes,
11897                                                                                                 argmodes, argnames);
11898
11899         funcsig_tag = format_function_signature(fout, finfo, false);
11900
11901         keyword = is_procedure ? "PROCEDURE" : "FUNCTION";
11902
11903         /*
11904          * DROP must be fully qualified in case same name appears in pg_catalog
11905          */
11906         appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11907                                           keyword,
11908                                           fmtId(finfo->dobj.namespace->dobj.name),
11909                                           funcsig);
11910
11911         appendPQExpBuffer(q, "CREATE %s %s",
11912                                           keyword,
11913                                           funcfullsig ? funcfullsig :
11914                                           funcsig);
11915         if (is_procedure)
11916                 ;
11917         else if (funcresult)
11918                 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11919         else
11920         {
11921                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11922                                                                                    zeroAsOpaque);
11923                 appendPQExpBuffer(q, " RETURNS %s%s",
11924                                                   (proretset[0] == 't') ? "SETOF " : "",
11925                                                   rettypename);
11926                 free(rettypename);
11927         }
11928
11929         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
11930
11931         if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11932         {
11933                 Oid                *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11934                 int                     i;
11935
11936                 appendPQExpBufferStr(q, " TRANSFORM ");
11937                 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11938                 for (i = 0; typeids[i]; i++)
11939                 {
11940                         if (i != 0)
11941                                 appendPQExpBufferStr(q, ", ");
11942                         appendPQExpBuffer(q, "FOR TYPE %s",
11943                                                           getFormattedTypeName(fout, typeids[i], zeroAsNone));
11944                 }
11945         }
11946
11947         if (proiswindow[0] == 't')
11948                 appendPQExpBufferStr(q, " WINDOW");
11949
11950         if (provolatile[0] != PROVOLATILE_VOLATILE)
11951         {
11952                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11953                         appendPQExpBufferStr(q, " IMMUTABLE");
11954                 else if (provolatile[0] == PROVOLATILE_STABLE)
11955                         appendPQExpBufferStr(q, " STABLE");
11956                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11957                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11958                                                   finfo->dobj.name);
11959         }
11960
11961         if (proisstrict[0] == 't')
11962                 appendPQExpBufferStr(q, " STRICT");
11963
11964         if (prosecdef[0] == 't')
11965                 appendPQExpBufferStr(q, " SECURITY DEFINER");
11966
11967         if (proleakproof[0] == 't')
11968                 appendPQExpBufferStr(q, " LEAKPROOF");
11969
11970         /*
11971          * COST and ROWS are emitted only if present and not default, so as not to
11972          * break backwards-compatibility of the dump without need.  Keep this code
11973          * in sync with the defaults in functioncmds.c.
11974          */
11975         if (strcmp(procost, "0") != 0)
11976         {
11977                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11978                 {
11979                         /* default cost is 1 */
11980                         if (strcmp(procost, "1") != 0)
11981                                 appendPQExpBuffer(q, " COST %s", procost);
11982                 }
11983                 else
11984                 {
11985                         /* default cost is 100 */
11986                         if (strcmp(procost, "100") != 0)
11987                                 appendPQExpBuffer(q, " COST %s", procost);
11988                 }
11989         }
11990         if (proretset[0] == 't' &&
11991                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11992                 appendPQExpBuffer(q, " ROWS %s", prorows);
11993
11994         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11995         {
11996                 if (proparallel[0] == PROPARALLEL_SAFE)
11997                         appendPQExpBufferStr(q, " PARALLEL SAFE");
11998                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11999                         appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
12000                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
12001                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
12002                                                   finfo->dobj.name);
12003         }
12004
12005         for (i = 0; i < nconfigitems; i++)
12006         {
12007                 /* we feel free to scribble on configitems[] here */
12008                 char       *configitem = configitems[i];
12009                 char       *pos;
12010
12011                 pos = strchr(configitem, '=');
12012                 if (pos == NULL)
12013                         continue;
12014                 *pos++ = '\0';
12015                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
12016
12017                 /*
12018                  * Some GUC variable names are 'LIST' type and hence must not be
12019                  * quoted.
12020                  */
12021                 if (pg_strcasecmp(configitem, "DateStyle") == 0
12022                         || pg_strcasecmp(configitem, "search_path") == 0)
12023                         appendPQExpBufferStr(q, pos);
12024                 else
12025                         appendStringLiteralAH(q, pos, fout);
12026         }
12027
12028         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
12029
12030         appendPQExpBuffer(labelq, "%s %s", keyword, funcsig);
12031
12032         if (dopt->binary_upgrade)
12033                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
12034
12035         if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12036                 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12037                                          funcsig_tag,
12038                                          finfo->dobj.namespace->dobj.name,
12039                                          NULL,
12040                                          finfo->rolname, false,
12041                                          keyword, SECTION_PRE_DATA,
12042                                          q->data, delqry->data, NULL,
12043                                          NULL, 0,
12044                                          NULL, NULL);
12045
12046         /* Dump Function Comments and Security Labels */
12047         if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12048                 dumpComment(fout, labelq->data,
12049                                         finfo->dobj.namespace->dobj.name, finfo->rolname,
12050                                         finfo->dobj.catId, 0, finfo->dobj.dumpId);
12051
12052         if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12053                 dumpSecLabel(fout, labelq->data,
12054                                          finfo->dobj.namespace->dobj.name, finfo->rolname,
12055                                          finfo->dobj.catId, 0, finfo->dobj.dumpId);
12056
12057         if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12058                 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
12059                                 funcsig, NULL, labelq->data,
12060                                 finfo->dobj.namespace->dobj.name,
12061                                 finfo->rolname, finfo->proacl, finfo->rproacl,
12062                                 finfo->initproacl, finfo->initrproacl);
12063
12064         PQclear(res);
12065
12066         destroyPQExpBuffer(query);
12067         destroyPQExpBuffer(q);
12068         destroyPQExpBuffer(delqry);
12069         destroyPQExpBuffer(labelq);
12070         destroyPQExpBuffer(asPart);
12071         free(funcsig);
12072         if (funcfullsig)
12073                 free(funcfullsig);
12074         free(funcsig_tag);
12075         if (allargtypes)
12076                 free(allargtypes);
12077         if (argmodes)
12078                 free(argmodes);
12079         if (argnames)
12080                 free(argnames);
12081         if (configitems)
12082                 free(configitems);
12083 }
12084
12085
12086 /*
12087  * Dump a user-defined cast
12088  */
12089 static void
12090 dumpCast(Archive *fout, CastInfo *cast)
12091 {
12092         DumpOptions *dopt = fout->dopt;
12093         PQExpBuffer defqry;
12094         PQExpBuffer delqry;
12095         PQExpBuffer labelq;
12096         FuncInfo   *funcInfo = NULL;
12097         char       *sourceType;
12098         char       *targetType;
12099
12100         /* Skip if not to be dumped */
12101         if (!cast->dobj.dump || dopt->dataOnly)
12102                 return;
12103
12104         /* Cannot dump if we don't have the cast function's info */
12105         if (OidIsValid(cast->castfunc))
12106         {
12107                 funcInfo = findFuncByOid(cast->castfunc);
12108                 if (funcInfo == NULL)
12109                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12110                                                   cast->castfunc);
12111         }
12112
12113         /*
12114          * Make sure we are in proper schema (needed for getFormattedTypeName).
12115          * Casts don't have a schema of their own, so use pg_catalog.
12116          */
12117         selectSourceSchema(fout, "pg_catalog");
12118
12119         defqry = createPQExpBuffer();
12120         delqry = createPQExpBuffer();
12121         labelq = createPQExpBuffer();
12122
12123         sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12124         targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12125         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12126                                           sourceType, targetType);
12127
12128         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12129                                           sourceType, targetType);
12130
12131         switch (cast->castmethod)
12132         {
12133                 case COERCION_METHOD_BINARY:
12134                         appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12135                         break;
12136                 case COERCION_METHOD_INOUT:
12137                         appendPQExpBufferStr(defqry, "WITH INOUT");
12138                         break;
12139                 case COERCION_METHOD_FUNCTION:
12140                         if (funcInfo)
12141                         {
12142                                 char       *fsig = format_function_signature(fout, funcInfo, true);
12143
12144                                 /*
12145                                  * Always qualify the function name, in case it is not in
12146                                  * pg_catalog schema (format_function_signature won't qualify
12147                                  * it).
12148                                  */
12149                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12150                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12151                                 free(fsig);
12152                         }
12153                         else
12154                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12155                         break;
12156                 default:
12157                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12158         }
12159
12160         if (cast->castcontext == 'a')
12161                 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12162         else if (cast->castcontext == 'i')
12163                 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12164         appendPQExpBufferStr(defqry, ";\n");
12165
12166         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12167                                           sourceType, targetType);
12168
12169         if (dopt->binary_upgrade)
12170                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
12171
12172         if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12173                 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12174                                          labelq->data,
12175                                          "pg_catalog", NULL, "",
12176                                          false, "CAST", SECTION_PRE_DATA,
12177                                          defqry->data, delqry->data, NULL,
12178                                          NULL, 0,
12179                                          NULL, NULL);
12180
12181         /* Dump Cast Comments */
12182         if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12183                 dumpComment(fout, labelq->data,
12184                                         "pg_catalog", "",
12185                                         cast->dobj.catId, 0, cast->dobj.dumpId);
12186
12187         free(sourceType);
12188         free(targetType);
12189
12190         destroyPQExpBuffer(defqry);
12191         destroyPQExpBuffer(delqry);
12192         destroyPQExpBuffer(labelq);
12193 }
12194
12195 /*
12196  * Dump a transform
12197  */
12198 static void
12199 dumpTransform(Archive *fout, TransformInfo *transform)
12200 {
12201         DumpOptions *dopt = fout->dopt;
12202         PQExpBuffer defqry;
12203         PQExpBuffer delqry;
12204         PQExpBuffer labelq;
12205         FuncInfo   *fromsqlFuncInfo = NULL;
12206         FuncInfo   *tosqlFuncInfo = NULL;
12207         char       *lanname;
12208         char       *transformType;
12209
12210         /* Skip if not to be dumped */
12211         if (!transform->dobj.dump || dopt->dataOnly)
12212                 return;
12213
12214         /* Cannot dump if we don't have the transform functions' info */
12215         if (OidIsValid(transform->trffromsql))
12216         {
12217                 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12218                 if (fromsqlFuncInfo == NULL)
12219                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12220                                                   transform->trffromsql);
12221         }
12222         if (OidIsValid(transform->trftosql))
12223         {
12224                 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12225                 if (tosqlFuncInfo == NULL)
12226                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12227                                                   transform->trftosql);
12228         }
12229
12230         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
12231         selectSourceSchema(fout, "pg_catalog");
12232
12233         defqry = createPQExpBuffer();
12234         delqry = createPQExpBuffer();
12235         labelq = createPQExpBuffer();
12236
12237         lanname = get_language_name(fout, transform->trflang);
12238         transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12239
12240         appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12241                                           transformType, lanname);
12242
12243         appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12244                                           transformType, lanname);
12245
12246         if (!transform->trffromsql && !transform->trftosql)
12247                 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12248
12249         if (transform->trffromsql)
12250         {
12251                 if (fromsqlFuncInfo)
12252                 {
12253                         char       *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12254
12255                         /*
12256                          * Always qualify the function name, in case it is not in
12257                          * pg_catalog schema (format_function_signature won't qualify it).
12258                          */
12259                         appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12260                                                           fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12261                         free(fsig);
12262                 }
12263                 else
12264                         write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12265         }
12266
12267         if (transform->trftosql)
12268         {
12269                 if (transform->trffromsql)
12270                         appendPQExpBuffer(defqry, ", ");
12271
12272                 if (tosqlFuncInfo)
12273                 {
12274                         char       *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12275
12276                         /*
12277                          * Always qualify the function name, in case it is not in
12278                          * pg_catalog schema (format_function_signature won't qualify it).
12279                          */
12280                         appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12281                                                           fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12282                         free(fsig);
12283                 }
12284                 else
12285                         write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12286         }
12287
12288         appendPQExpBuffer(defqry, ");\n");
12289
12290         appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12291                                           transformType, lanname);
12292
12293         if (dopt->binary_upgrade)
12294                 binary_upgrade_extension_member(defqry, &transform->dobj, labelq->data);
12295
12296         if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12297                 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12298                                          labelq->data,
12299                                          "pg_catalog", NULL, "",
12300                                          false, "TRANSFORM", SECTION_PRE_DATA,
12301                                          defqry->data, delqry->data, NULL,
12302                                          transform->dobj.dependencies, transform->dobj.nDeps,
12303                                          NULL, NULL);
12304
12305         /* Dump Transform Comments */
12306         if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12307                 dumpComment(fout, labelq->data,
12308                                         "pg_catalog", "",
12309                                         transform->dobj.catId, 0, transform->dobj.dumpId);
12310
12311         free(lanname);
12312         free(transformType);
12313         destroyPQExpBuffer(defqry);
12314         destroyPQExpBuffer(delqry);
12315         destroyPQExpBuffer(labelq);
12316 }
12317
12318
12319 /*
12320  * dumpOpr
12321  *        write out a single operator definition
12322  */
12323 static void
12324 dumpOpr(Archive *fout, OprInfo *oprinfo)
12325 {
12326         DumpOptions *dopt = fout->dopt;
12327         PQExpBuffer query;
12328         PQExpBuffer q;
12329         PQExpBuffer delq;
12330         PQExpBuffer labelq;
12331         PQExpBuffer oprid;
12332         PQExpBuffer details;
12333         PGresult   *res;
12334         int                     i_oprkind;
12335         int                     i_oprcode;
12336         int                     i_oprleft;
12337         int                     i_oprright;
12338         int                     i_oprcom;
12339         int                     i_oprnegate;
12340         int                     i_oprrest;
12341         int                     i_oprjoin;
12342         int                     i_oprcanmerge;
12343         int                     i_oprcanhash;
12344         char       *oprkind;
12345         char       *oprcode;
12346         char       *oprleft;
12347         char       *oprright;
12348         char       *oprcom;
12349         char       *oprnegate;
12350         char       *oprrest;
12351         char       *oprjoin;
12352         char       *oprcanmerge;
12353         char       *oprcanhash;
12354         char       *oprregproc;
12355         char       *oprref;
12356
12357         /* Skip if not to be dumped */
12358         if (!oprinfo->dobj.dump || dopt->dataOnly)
12359                 return;
12360
12361         /*
12362          * some operators are invalid because they were the result of user
12363          * defining operators before commutators exist
12364          */
12365         if (!OidIsValid(oprinfo->oprcode))
12366                 return;
12367
12368         query = createPQExpBuffer();
12369         q = createPQExpBuffer();
12370         delq = createPQExpBuffer();
12371         labelq = createPQExpBuffer();
12372         oprid = createPQExpBuffer();
12373         details = createPQExpBuffer();
12374
12375         /* Make sure we are in proper schema so regoperator works correctly */
12376         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
12377
12378         if (fout->remoteVersion >= 80300)
12379         {
12380                 appendPQExpBuffer(query, "SELECT oprkind, "
12381                                                   "oprcode::pg_catalog.regprocedure, "
12382                                                   "oprleft::pg_catalog.regtype, "
12383                                                   "oprright::pg_catalog.regtype, "
12384                                                   "oprcom::pg_catalog.regoperator, "
12385                                                   "oprnegate::pg_catalog.regoperator, "
12386                                                   "oprrest::pg_catalog.regprocedure, "
12387                                                   "oprjoin::pg_catalog.regprocedure, "
12388                                                   "oprcanmerge, oprcanhash "
12389                                                   "FROM pg_catalog.pg_operator "
12390                                                   "WHERE oid = '%u'::pg_catalog.oid",
12391                                                   oprinfo->dobj.catId.oid);
12392         }
12393         else
12394         {
12395                 appendPQExpBuffer(query, "SELECT oprkind, "
12396                                                   "oprcode::pg_catalog.regprocedure, "
12397                                                   "oprleft::pg_catalog.regtype, "
12398                                                   "oprright::pg_catalog.regtype, "
12399                                                   "oprcom::pg_catalog.regoperator, "
12400                                                   "oprnegate::pg_catalog.regoperator, "
12401                                                   "oprrest::pg_catalog.regprocedure, "
12402                                                   "oprjoin::pg_catalog.regprocedure, "
12403                                                   "(oprlsortop != 0) AS oprcanmerge, "
12404                                                   "oprcanhash "
12405                                                   "FROM pg_catalog.pg_operator "
12406                                                   "WHERE oid = '%u'::pg_catalog.oid",
12407                                                   oprinfo->dobj.catId.oid);
12408         }
12409
12410         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12411
12412         i_oprkind = PQfnumber(res, "oprkind");
12413         i_oprcode = PQfnumber(res, "oprcode");
12414         i_oprleft = PQfnumber(res, "oprleft");
12415         i_oprright = PQfnumber(res, "oprright");
12416         i_oprcom = PQfnumber(res, "oprcom");
12417         i_oprnegate = PQfnumber(res, "oprnegate");
12418         i_oprrest = PQfnumber(res, "oprrest");
12419         i_oprjoin = PQfnumber(res, "oprjoin");
12420         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12421         i_oprcanhash = PQfnumber(res, "oprcanhash");
12422
12423         oprkind = PQgetvalue(res, 0, i_oprkind);
12424         oprcode = PQgetvalue(res, 0, i_oprcode);
12425         oprleft = PQgetvalue(res, 0, i_oprleft);
12426         oprright = PQgetvalue(res, 0, i_oprright);
12427         oprcom = PQgetvalue(res, 0, i_oprcom);
12428         oprnegate = PQgetvalue(res, 0, i_oprnegate);
12429         oprrest = PQgetvalue(res, 0, i_oprrest);
12430         oprjoin = PQgetvalue(res, 0, i_oprjoin);
12431         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12432         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12433
12434         oprregproc = convertRegProcReference(fout, oprcode);
12435         if (oprregproc)
12436         {
12437                 appendPQExpBuffer(details, "    PROCEDURE = %s", oprregproc);
12438                 free(oprregproc);
12439         }
12440
12441         appendPQExpBuffer(oprid, "%s (",
12442                                           oprinfo->dobj.name);
12443
12444         /*
12445          * right unary means there's a left arg and left unary means there's a
12446          * right arg
12447          */
12448         if (strcmp(oprkind, "r") == 0 ||
12449                 strcmp(oprkind, "b") == 0)
12450         {
12451                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", oprleft);
12452                 appendPQExpBufferStr(oprid, oprleft);
12453         }
12454         else
12455                 appendPQExpBufferStr(oprid, "NONE");
12456
12457         if (strcmp(oprkind, "l") == 0 ||
12458                 strcmp(oprkind, "b") == 0)
12459         {
12460                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", oprright);
12461                 appendPQExpBuffer(oprid, ", %s)", oprright);
12462         }
12463         else
12464                 appendPQExpBufferStr(oprid, ", NONE)");
12465
12466         oprref = convertOperatorReference(fout, oprcom);
12467         if (oprref)
12468         {
12469                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", oprref);
12470                 free(oprref);
12471         }
12472
12473         oprref = convertOperatorReference(fout, oprnegate);
12474         if (oprref)
12475         {
12476                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", oprref);
12477                 free(oprref);
12478         }
12479
12480         if (strcmp(oprcanmerge, "t") == 0)
12481                 appendPQExpBufferStr(details, ",\n    MERGES");
12482
12483         if (strcmp(oprcanhash, "t") == 0)
12484                 appendPQExpBufferStr(details, ",\n    HASHES");
12485
12486         oprregproc = convertRegProcReference(fout, oprrest);
12487         if (oprregproc)
12488         {
12489                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", oprregproc);
12490                 free(oprregproc);
12491         }
12492
12493         oprregproc = convertRegProcReference(fout, oprjoin);
12494         if (oprregproc)
12495         {
12496                 appendPQExpBuffer(details, ",\n    JOIN = %s", oprregproc);
12497                 free(oprregproc);
12498         }
12499
12500         /*
12501          * DROP must be fully qualified in case same name appears in pg_catalog
12502          */
12503         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12504                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12505                                           oprid->data);
12506
12507         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
12508                                           oprinfo->dobj.name, details->data);
12509
12510         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
12511
12512         if (dopt->binary_upgrade)
12513                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
12514
12515         if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12516                 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12517                                          oprinfo->dobj.name,
12518                                          oprinfo->dobj.namespace->dobj.name,
12519                                          NULL,
12520                                          oprinfo->rolname,
12521                                          false, "OPERATOR", SECTION_PRE_DATA,
12522                                          q->data, delq->data, NULL,
12523                                          NULL, 0,
12524                                          NULL, NULL);
12525
12526         /* Dump Operator Comments */
12527         if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12528                 dumpComment(fout, labelq->data,
12529                                         oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12530                                         oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12531
12532         PQclear(res);
12533
12534         destroyPQExpBuffer(query);
12535         destroyPQExpBuffer(q);
12536         destroyPQExpBuffer(delq);
12537         destroyPQExpBuffer(labelq);
12538         destroyPQExpBuffer(oprid);
12539         destroyPQExpBuffer(details);
12540 }
12541
12542 /*
12543  * Convert a function reference obtained from pg_operator
12544  *
12545  * Returns allocated string of what to print, or NULL if function references
12546  * is InvalidOid. Returned string is expected to be free'd by the caller.
12547  *
12548  * The input is a REGPROCEDURE display; we have to strip the argument-types
12549  * part.
12550  */
12551 static char *
12552 convertRegProcReference(Archive *fout, const char *proc)
12553 {
12554         char       *name;
12555         char       *paren;
12556         bool            inquote;
12557
12558         /* In all cases "-" means a null reference */
12559         if (strcmp(proc, "-") == 0)
12560                 return NULL;
12561
12562         name = pg_strdup(proc);
12563         /* find non-double-quoted left paren */
12564         inquote = false;
12565         for (paren = name; *paren; paren++)
12566         {
12567                 if (*paren == '(' && !inquote)
12568                 {
12569                         *paren = '\0';
12570                         break;
12571                 }
12572                 if (*paren == '"')
12573                         inquote = !inquote;
12574         }
12575         return name;
12576 }
12577
12578 /*
12579  * Convert an operator cross-reference obtained from pg_operator
12580  *
12581  * Returns an allocated string of what to print, or NULL to print nothing.
12582  * Caller is responsible for free'ing result string.
12583  *
12584  * The input is a REGOPERATOR display; we have to strip the argument-types
12585  * part, and add OPERATOR() decoration if the name is schema-qualified.
12586  */
12587 static char *
12588 convertOperatorReference(Archive *fout, const char *opr)
12589 {
12590         char       *name;
12591         char       *oname;
12592         char       *ptr;
12593         bool            inquote;
12594         bool            sawdot;
12595
12596         /* In all cases "0" means a null reference */
12597         if (strcmp(opr, "0") == 0)
12598                 return NULL;
12599
12600         name = pg_strdup(opr);
12601         /* find non-double-quoted left paren, and check for non-quoted dot */
12602         inquote = false;
12603         sawdot = false;
12604         for (ptr = name; *ptr; ptr++)
12605         {
12606                 if (*ptr == '"')
12607                         inquote = !inquote;
12608                 else if (*ptr == '.' && !inquote)
12609                         sawdot = true;
12610                 else if (*ptr == '(' && !inquote)
12611                 {
12612                         *ptr = '\0';
12613                         break;
12614                 }
12615         }
12616         /* If not schema-qualified, don't need to add OPERATOR() */
12617         if (!sawdot)
12618                 return name;
12619         oname = psprintf("OPERATOR(%s)", name);
12620         free(name);
12621         return oname;
12622 }
12623
12624 /*
12625  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12626  *
12627  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12628  * argument lists of these functions are predetermined.  Note that the
12629  * caller should ensure we are in the proper schema, because the results
12630  * are search path dependent!
12631  */
12632 static char *
12633 convertTSFunction(Archive *fout, Oid funcOid)
12634 {
12635         char       *result;
12636         char            query[128];
12637         PGresult   *res;
12638
12639         snprintf(query, sizeof(query),
12640                          "SELECT '%u'::pg_catalog.regproc", funcOid);
12641         res = ExecuteSqlQueryForSingleRow(fout, query);
12642
12643         result = pg_strdup(PQgetvalue(res, 0, 0));
12644
12645         PQclear(res);
12646
12647         return result;
12648 }
12649
12650 /*
12651  * dumpAccessMethod
12652  *        write out a single access method definition
12653  */
12654 static void
12655 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12656 {
12657         DumpOptions *dopt = fout->dopt;
12658         PQExpBuffer q;
12659         PQExpBuffer delq;
12660         PQExpBuffer labelq;
12661         char       *qamname;
12662
12663         /* Skip if not to be dumped */
12664         if (!aminfo->dobj.dump || dopt->dataOnly)
12665                 return;
12666
12667         q = createPQExpBuffer();
12668         delq = createPQExpBuffer();
12669         labelq = createPQExpBuffer();
12670
12671         qamname = pg_strdup(fmtId(aminfo->dobj.name));
12672
12673         appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12674
12675         switch (aminfo->amtype)
12676         {
12677                 case AMTYPE_INDEX:
12678                         appendPQExpBuffer(q, "TYPE INDEX ");
12679                         break;
12680                 default:
12681                         write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12682                                           aminfo->amtype, qamname);
12683                         pg_free(qamname);
12684                         destroyPQExpBuffer(q);
12685                         destroyPQExpBuffer(delq);
12686                         destroyPQExpBuffer(labelq);
12687                         return;
12688         }
12689
12690         appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12691
12692         appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12693                                           qamname);
12694
12695         appendPQExpBuffer(labelq, "ACCESS METHOD %s",
12696                                           qamname);
12697
12698         if (dopt->binary_upgrade)
12699                 binary_upgrade_extension_member(q, &aminfo->dobj, labelq->data);
12700
12701         if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12702                 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12703                                          aminfo->dobj.name,
12704                                          NULL,
12705                                          NULL,
12706                                          "",
12707                                          false, "ACCESS METHOD", SECTION_PRE_DATA,
12708                                          q->data, delq->data, NULL,
12709                                          NULL, 0,
12710                                          NULL, NULL);
12711
12712         /* Dump Access Method Comments */
12713         if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12714                 dumpComment(fout, labelq->data,
12715                                         NULL, "",
12716                                         aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12717
12718         pg_free(qamname);
12719
12720         destroyPQExpBuffer(q);
12721         destroyPQExpBuffer(delq);
12722         destroyPQExpBuffer(labelq);
12723 }
12724
12725 /*
12726  * dumpOpclass
12727  *        write out a single operator class definition
12728  */
12729 static void
12730 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12731 {
12732         DumpOptions *dopt = fout->dopt;
12733         PQExpBuffer query;
12734         PQExpBuffer q;
12735         PQExpBuffer delq;
12736         PQExpBuffer labelq;
12737         PGresult   *res;
12738         int                     ntups;
12739         int                     i_opcintype;
12740         int                     i_opckeytype;
12741         int                     i_opcdefault;
12742         int                     i_opcfamily;
12743         int                     i_opcfamilyname;
12744         int                     i_opcfamilynsp;
12745         int                     i_amname;
12746         int                     i_amopstrategy;
12747         int                     i_amopreqcheck;
12748         int                     i_amopopr;
12749         int                     i_sortfamily;
12750         int                     i_sortfamilynsp;
12751         int                     i_amprocnum;
12752         int                     i_amproc;
12753         int                     i_amproclefttype;
12754         int                     i_amprocrighttype;
12755         char       *opcintype;
12756         char       *opckeytype;
12757         char       *opcdefault;
12758         char       *opcfamily;
12759         char       *opcfamilyname;
12760         char       *opcfamilynsp;
12761         char       *amname;
12762         char       *amopstrategy;
12763         char       *amopreqcheck;
12764         char       *amopopr;
12765         char       *sortfamily;
12766         char       *sortfamilynsp;
12767         char       *amprocnum;
12768         char       *amproc;
12769         char       *amproclefttype;
12770         char       *amprocrighttype;
12771         bool            needComma;
12772         int                     i;
12773
12774         /* Skip if not to be dumped */
12775         if (!opcinfo->dobj.dump || dopt->dataOnly)
12776                 return;
12777
12778         query = createPQExpBuffer();
12779         q = createPQExpBuffer();
12780         delq = createPQExpBuffer();
12781         labelq = createPQExpBuffer();
12782
12783         /* Make sure we are in proper schema so regoperator works correctly */
12784         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
12785
12786         /* Get additional fields from the pg_opclass row */
12787         if (fout->remoteVersion >= 80300)
12788         {
12789                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12790                                                   "opckeytype::pg_catalog.regtype, "
12791                                                   "opcdefault, opcfamily, "
12792                                                   "opfname AS opcfamilyname, "
12793                                                   "nspname AS opcfamilynsp, "
12794                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12795                                                   "FROM pg_catalog.pg_opclass c "
12796                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12797                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12798                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
12799                                                   opcinfo->dobj.catId.oid);
12800         }
12801         else
12802         {
12803                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12804                                                   "opckeytype::pg_catalog.regtype, "
12805                                                   "opcdefault, NULL AS opcfamily, "
12806                                                   "NULL AS opcfamilyname, "
12807                                                   "NULL AS opcfamilynsp, "
12808                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12809                                                   "FROM pg_catalog.pg_opclass "
12810                                                   "WHERE oid = '%u'::pg_catalog.oid",
12811                                                   opcinfo->dobj.catId.oid);
12812         }
12813
12814         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12815
12816         i_opcintype = PQfnumber(res, "opcintype");
12817         i_opckeytype = PQfnumber(res, "opckeytype");
12818         i_opcdefault = PQfnumber(res, "opcdefault");
12819         i_opcfamily = PQfnumber(res, "opcfamily");
12820         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12821         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12822         i_amname = PQfnumber(res, "amname");
12823
12824         /* opcintype may still be needed after we PQclear res */
12825         opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12826         opckeytype = PQgetvalue(res, 0, i_opckeytype);
12827         opcdefault = PQgetvalue(res, 0, i_opcdefault);
12828         /* opcfamily will still be needed after we PQclear res */
12829         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12830         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12831         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12832         /* amname will still be needed after we PQclear res */
12833         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12834
12835         /*
12836          * DROP must be fully qualified in case same name appears in pg_catalog
12837          */
12838         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12839                                           fmtId(opcinfo->dobj.namespace->dobj.name));
12840         appendPQExpBuffer(delq, ".%s",
12841                                           fmtId(opcinfo->dobj.name));
12842         appendPQExpBuffer(delq, " USING %s;\n",
12843                                           fmtId(amname));
12844
12845         /* Build the fixed portion of the CREATE command */
12846         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
12847                                           fmtId(opcinfo->dobj.name));
12848         if (strcmp(opcdefault, "t") == 0)
12849                 appendPQExpBufferStr(q, "DEFAULT ");
12850         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12851                                           opcintype,
12852                                           fmtId(amname));
12853         if (strlen(opcfamilyname) > 0)
12854         {
12855                 appendPQExpBufferStr(q, " FAMILY ");
12856                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12857                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12858                 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12859         }
12860         appendPQExpBufferStr(q, " AS\n    ");
12861
12862         needComma = false;
12863
12864         if (strcmp(opckeytype, "-") != 0)
12865         {
12866                 appendPQExpBuffer(q, "STORAGE %s",
12867                                                   opckeytype);
12868                 needComma = true;
12869         }
12870
12871         PQclear(res);
12872
12873         /*
12874          * Now fetch and print the OPERATOR entries (pg_amop rows).
12875          *
12876          * Print only those opfamily members that are tied to the opclass by
12877          * pg_depend entries.
12878          *
12879          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12880          * older server's opclass in which it is used.  This is to avoid
12881          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12882          * older server and then reload into that old version.  This can go away
12883          * once 8.3 is so old as to not be of interest to anyone.
12884          */
12885         resetPQExpBuffer(query);
12886
12887         if (fout->remoteVersion >= 90100)
12888         {
12889                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12890                                                   "amopopr::pg_catalog.regoperator, "
12891                                                   "opfname AS sortfamily, "
12892                                                   "nspname AS sortfamilynsp "
12893                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12894                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12895                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12896                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12897                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12898                                                   "AND refobjid = '%u'::pg_catalog.oid "
12899                                                   "AND amopfamily = '%s'::pg_catalog.oid "
12900                                                   "ORDER BY amopstrategy",
12901                                                   opcinfo->dobj.catId.oid,
12902                                                   opcfamily);
12903         }
12904         else if (fout->remoteVersion >= 80400)
12905         {
12906                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12907                                                   "amopopr::pg_catalog.regoperator, "
12908                                                   "NULL AS sortfamily, "
12909                                                   "NULL AS sortfamilynsp "
12910                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12911                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12912                                                   "AND refobjid = '%u'::pg_catalog.oid "
12913                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12914                                                   "AND objid = ao.oid "
12915                                                   "ORDER BY amopstrategy",
12916                                                   opcinfo->dobj.catId.oid);
12917         }
12918         else if (fout->remoteVersion >= 80300)
12919         {
12920                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12921                                                   "amopopr::pg_catalog.regoperator, "
12922                                                   "NULL AS sortfamily, "
12923                                                   "NULL AS sortfamilynsp "
12924                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12925                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12926                                                   "AND refobjid = '%u'::pg_catalog.oid "
12927                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12928                                                   "AND objid = ao.oid "
12929                                                   "ORDER BY amopstrategy",
12930                                                   opcinfo->dobj.catId.oid);
12931         }
12932         else
12933         {
12934                 /*
12935                  * Here, we print all entries since there are no opfamilies and hence
12936                  * no loose operators to worry about.
12937                  */
12938                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12939                                                   "amopopr::pg_catalog.regoperator, "
12940                                                   "NULL AS sortfamily, "
12941                                                   "NULL AS sortfamilynsp "
12942                                                   "FROM pg_catalog.pg_amop "
12943                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12944                                                   "ORDER BY amopstrategy",
12945                                                   opcinfo->dobj.catId.oid);
12946         }
12947
12948         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12949
12950         ntups = PQntuples(res);
12951
12952         i_amopstrategy = PQfnumber(res, "amopstrategy");
12953         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12954         i_amopopr = PQfnumber(res, "amopopr");
12955         i_sortfamily = PQfnumber(res, "sortfamily");
12956         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12957
12958         for (i = 0; i < ntups; i++)
12959         {
12960                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12961                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12962                 amopopr = PQgetvalue(res, i, i_amopopr);
12963                 sortfamily = PQgetvalue(res, i, i_sortfamily);
12964                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12965
12966                 if (needComma)
12967                         appendPQExpBufferStr(q, " ,\n    ");
12968
12969                 appendPQExpBuffer(q, "OPERATOR %s %s",
12970                                                   amopstrategy, amopopr);
12971
12972                 if (strlen(sortfamily) > 0)
12973                 {
12974                         appendPQExpBufferStr(q, " FOR ORDER BY ");
12975                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12976                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12977                         appendPQExpBufferStr(q, fmtId(sortfamily));
12978                 }
12979
12980                 if (strcmp(amopreqcheck, "t") == 0)
12981                         appendPQExpBufferStr(q, " RECHECK");
12982
12983                 needComma = true;
12984         }
12985
12986         PQclear(res);
12987
12988         /*
12989          * Now fetch and print the FUNCTION entries (pg_amproc rows).
12990          *
12991          * Print only those opfamily members that are tied to the opclass by
12992          * pg_depend entries.
12993          *
12994          * We print the amproclefttype/amprocrighttype even though in most cases
12995          * the backend could deduce the right values, because of the corner case
12996          * of a btree sort support function for a cross-type comparison.  That's
12997          * only allowed in 9.2 and later, but for simplicity print them in all
12998          * versions that have the columns.
12999          */
13000         resetPQExpBuffer(query);
13001
13002         if (fout->remoteVersion >= 80300)
13003         {
13004                 appendPQExpBuffer(query, "SELECT amprocnum, "
13005                                                   "amproc::pg_catalog.regprocedure, "
13006                                                   "amproclefttype::pg_catalog.regtype, "
13007                                                   "amprocrighttype::pg_catalog.regtype "
13008                                                   "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13009                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13010                                                   "AND refobjid = '%u'::pg_catalog.oid "
13011                                                   "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13012                                                   "AND objid = ap.oid "
13013                                                   "ORDER BY amprocnum",
13014                                                   opcinfo->dobj.catId.oid);
13015         }
13016         else
13017         {
13018                 appendPQExpBuffer(query, "SELECT amprocnum, "
13019                                                   "amproc::pg_catalog.regprocedure, "
13020                                                   "'' AS amproclefttype, "
13021                                                   "'' AS amprocrighttype "
13022                                                   "FROM pg_catalog.pg_amproc "
13023                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
13024                                                   "ORDER BY amprocnum",
13025                                                   opcinfo->dobj.catId.oid);
13026         }
13027
13028         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13029
13030         ntups = PQntuples(res);
13031
13032         i_amprocnum = PQfnumber(res, "amprocnum");
13033         i_amproc = PQfnumber(res, "amproc");
13034         i_amproclefttype = PQfnumber(res, "amproclefttype");
13035         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
13036
13037         for (i = 0; i < ntups; i++)
13038         {
13039                 amprocnum = PQgetvalue(res, i, i_amprocnum);
13040                 amproc = PQgetvalue(res, i, i_amproc);
13041                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
13042                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
13043
13044                 if (needComma)
13045                         appendPQExpBufferStr(q, " ,\n    ");
13046
13047                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
13048
13049                 if (*amproclefttype && *amprocrighttype)
13050                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13051
13052                 appendPQExpBuffer(q, " %s", amproc);
13053
13054                 needComma = true;
13055         }
13056
13057         PQclear(res);
13058
13059         /*
13060          * If needComma is still false it means we haven't added anything after
13061          * the AS keyword.  To avoid printing broken SQL, append a dummy STORAGE
13062          * clause with the same datatype.  This isn't sanctioned by the
13063          * documentation, but actually DefineOpClass will treat it as a no-op.
13064          */
13065         if (!needComma)
13066                 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13067
13068         appendPQExpBufferStr(q, ";\n");
13069
13070         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
13071                                           fmtId(opcinfo->dobj.name));
13072         appendPQExpBuffer(labelq, " USING %s",
13073                                           fmtId(amname));
13074
13075         if (dopt->binary_upgrade)
13076                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
13077
13078         if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13079                 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13080                                          opcinfo->dobj.name,
13081                                          opcinfo->dobj.namespace->dobj.name,
13082                                          NULL,
13083                                          opcinfo->rolname,
13084                                          false, "OPERATOR CLASS", SECTION_PRE_DATA,
13085                                          q->data, delq->data, NULL,
13086                                          NULL, 0,
13087                                          NULL, NULL);
13088
13089         /* Dump Operator Class Comments */
13090         if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13091                 dumpComment(fout, labelq->data,
13092                                         opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13093                                         opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13094
13095         free(opcintype);
13096         free(opcfamily);
13097         free(amname);
13098         destroyPQExpBuffer(query);
13099         destroyPQExpBuffer(q);
13100         destroyPQExpBuffer(delq);
13101         destroyPQExpBuffer(labelq);
13102 }
13103
13104 /*
13105  * dumpOpfamily
13106  *        write out a single operator family definition
13107  *
13108  * Note: this also dumps any "loose" operator members that aren't bound to a
13109  * specific opclass within the opfamily.
13110  */
13111 static void
13112 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13113 {
13114         DumpOptions *dopt = fout->dopt;
13115         PQExpBuffer query;
13116         PQExpBuffer q;
13117         PQExpBuffer delq;
13118         PQExpBuffer labelq;
13119         PGresult   *res;
13120         PGresult   *res_ops;
13121         PGresult   *res_procs;
13122         int                     ntups;
13123         int                     i_amname;
13124         int                     i_amopstrategy;
13125         int                     i_amopreqcheck;
13126         int                     i_amopopr;
13127         int                     i_sortfamily;
13128         int                     i_sortfamilynsp;
13129         int                     i_amprocnum;
13130         int                     i_amproc;
13131         int                     i_amproclefttype;
13132         int                     i_amprocrighttype;
13133         char       *amname;
13134         char       *amopstrategy;
13135         char       *amopreqcheck;
13136         char       *amopopr;
13137         char       *sortfamily;
13138         char       *sortfamilynsp;
13139         char       *amprocnum;
13140         char       *amproc;
13141         char       *amproclefttype;
13142         char       *amprocrighttype;
13143         bool            needComma;
13144         int                     i;
13145
13146         /* Skip if not to be dumped */
13147         if (!opfinfo->dobj.dump || dopt->dataOnly)
13148                 return;
13149
13150         query = createPQExpBuffer();
13151         q = createPQExpBuffer();
13152         delq = createPQExpBuffer();
13153         labelq = createPQExpBuffer();
13154
13155         /* Make sure we are in proper schema so regoperator works correctly */
13156         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
13157
13158         /*
13159          * Fetch only those opfamily members that are tied directly to the
13160          * opfamily by pg_depend entries.
13161          *
13162          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13163          * older server's opclass in which it is used.  This is to avoid
13164          * hard-to-detect breakage if a newer pg_dump is used to dump from an
13165          * older server and then reload into that old version.  This can go away
13166          * once 8.3 is so old as to not be of interest to anyone.
13167          */
13168         if (fout->remoteVersion >= 90100)
13169         {
13170                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13171                                                   "amopopr::pg_catalog.regoperator, "
13172                                                   "opfname AS sortfamily, "
13173                                                   "nspname AS sortfamilynsp "
13174                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13175                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13176                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13177                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13178                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13179                                                   "AND refobjid = '%u'::pg_catalog.oid "
13180                                                   "AND amopfamily = '%u'::pg_catalog.oid "
13181                                                   "ORDER BY amopstrategy",
13182                                                   opfinfo->dobj.catId.oid,
13183                                                   opfinfo->dobj.catId.oid);
13184         }
13185         else if (fout->remoteVersion >= 80400)
13186         {
13187                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13188                                                   "amopopr::pg_catalog.regoperator, "
13189                                                   "NULL AS sortfamily, "
13190                                                   "NULL AS sortfamilynsp "
13191                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13192                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13193                                                   "AND refobjid = '%u'::pg_catalog.oid "
13194                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13195                                                   "AND objid = ao.oid "
13196                                                   "ORDER BY amopstrategy",
13197                                                   opfinfo->dobj.catId.oid);
13198         }
13199         else
13200         {
13201                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13202                                                   "amopopr::pg_catalog.regoperator, "
13203                                                   "NULL AS sortfamily, "
13204                                                   "NULL AS sortfamilynsp "
13205                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13206                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13207                                                   "AND refobjid = '%u'::pg_catalog.oid "
13208                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13209                                                   "AND objid = ao.oid "
13210                                                   "ORDER BY amopstrategy",
13211                                                   opfinfo->dobj.catId.oid);
13212         }
13213
13214         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13215
13216         resetPQExpBuffer(query);
13217
13218         appendPQExpBuffer(query, "SELECT amprocnum, "
13219                                           "amproc::pg_catalog.regprocedure, "
13220                                           "amproclefttype::pg_catalog.regtype, "
13221                                           "amprocrighttype::pg_catalog.regtype "
13222                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13223                                           "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13224                                           "AND refobjid = '%u'::pg_catalog.oid "
13225                                           "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13226                                           "AND objid = ap.oid "
13227                                           "ORDER BY amprocnum",
13228                                           opfinfo->dobj.catId.oid);
13229
13230         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13231
13232         /* Get additional fields from the pg_opfamily row */
13233         resetPQExpBuffer(query);
13234
13235         appendPQExpBuffer(query, "SELECT "
13236                                           "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13237                                           "FROM pg_catalog.pg_opfamily "
13238                                           "WHERE oid = '%u'::pg_catalog.oid",
13239                                           opfinfo->dobj.catId.oid);
13240
13241         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13242
13243         i_amname = PQfnumber(res, "amname");
13244
13245         /* amname will still be needed after we PQclear res */
13246         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13247
13248         /*
13249          * DROP must be fully qualified in case same name appears in pg_catalog
13250          */
13251         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13252                                           fmtId(opfinfo->dobj.namespace->dobj.name));
13253         appendPQExpBuffer(delq, ".%s",
13254                                           fmtId(opfinfo->dobj.name));
13255         appendPQExpBuffer(delq, " USING %s;\n",
13256                                           fmtId(amname));
13257
13258         /* Build the fixed portion of the CREATE command */
13259         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13260                                           fmtId(opfinfo->dobj.name));
13261         appendPQExpBuffer(q, " USING %s;\n",
13262                                           fmtId(amname));
13263
13264         PQclear(res);
13265
13266         /* Do we need an ALTER to add loose members? */
13267         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13268         {
13269                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13270                                                   fmtId(opfinfo->dobj.name));
13271                 appendPQExpBuffer(q, " USING %s ADD\n    ",
13272                                                   fmtId(amname));
13273
13274                 needComma = false;
13275
13276                 /*
13277                  * Now fetch and print the OPERATOR entries (pg_amop rows).
13278                  */
13279                 ntups = PQntuples(res_ops);
13280
13281                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13282                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13283                 i_amopopr = PQfnumber(res_ops, "amopopr");
13284                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13285                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13286
13287                 for (i = 0; i < ntups; i++)
13288                 {
13289                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13290                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13291                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
13292                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13293                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13294
13295                         if (needComma)
13296                                 appendPQExpBufferStr(q, " ,\n    ");
13297
13298                         appendPQExpBuffer(q, "OPERATOR %s %s",
13299                                                           amopstrategy, amopopr);
13300
13301                         if (strlen(sortfamily) > 0)
13302                         {
13303                                 appendPQExpBufferStr(q, " FOR ORDER BY ");
13304                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
13305                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13306                                 appendPQExpBufferStr(q, fmtId(sortfamily));
13307                         }
13308
13309                         if (strcmp(amopreqcheck, "t") == 0)
13310                                 appendPQExpBufferStr(q, " RECHECK");
13311
13312                         needComma = true;
13313                 }
13314
13315                 /*
13316                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
13317                  */
13318                 ntups = PQntuples(res_procs);
13319
13320                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13321                 i_amproc = PQfnumber(res_procs, "amproc");
13322                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13323                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13324
13325                 for (i = 0; i < ntups; i++)
13326                 {
13327                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13328                         amproc = PQgetvalue(res_procs, i, i_amproc);
13329                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13330                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13331
13332                         if (needComma)
13333                                 appendPQExpBufferStr(q, " ,\n    ");
13334
13335                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13336                                                           amprocnum, amproclefttype, amprocrighttype,
13337                                                           amproc);
13338
13339                         needComma = true;
13340                 }
13341
13342                 appendPQExpBufferStr(q, ";\n");
13343         }
13344
13345         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
13346                                           fmtId(opfinfo->dobj.name));
13347         appendPQExpBuffer(labelq, " USING %s",
13348                                           fmtId(amname));
13349
13350         if (dopt->binary_upgrade)
13351                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
13352
13353         if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13354                 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13355                                          opfinfo->dobj.name,
13356                                          opfinfo->dobj.namespace->dobj.name,
13357                                          NULL,
13358                                          opfinfo->rolname,
13359                                          false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13360                                          q->data, delq->data, NULL,
13361                                          NULL, 0,
13362                                          NULL, NULL);
13363
13364         /* Dump Operator Family Comments */
13365         if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13366                 dumpComment(fout, labelq->data,
13367                                         opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13368                                         opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13369
13370         free(amname);
13371         PQclear(res_ops);
13372         PQclear(res_procs);
13373         destroyPQExpBuffer(query);
13374         destroyPQExpBuffer(q);
13375         destroyPQExpBuffer(delq);
13376         destroyPQExpBuffer(labelq);
13377 }
13378
13379 /*
13380  * dumpCollation
13381  *        write out a single collation definition
13382  */
13383 static void
13384 dumpCollation(Archive *fout, CollInfo *collinfo)
13385 {
13386         DumpOptions *dopt = fout->dopt;
13387         PQExpBuffer query;
13388         PQExpBuffer q;
13389         PQExpBuffer delq;
13390         PQExpBuffer labelq;
13391         PGresult   *res;
13392         int                     i_collprovider;
13393         int                     i_collcollate;
13394         int                     i_collctype;
13395         const char *collprovider;
13396         const char *collcollate;
13397         const char *collctype;
13398
13399         /* Skip if not to be dumped */
13400         if (!collinfo->dobj.dump || dopt->dataOnly)
13401                 return;
13402
13403         query = createPQExpBuffer();
13404         q = createPQExpBuffer();
13405         delq = createPQExpBuffer();
13406         labelq = createPQExpBuffer();
13407
13408         /* Make sure we are in proper schema */
13409         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
13410
13411         /* Get collation-specific details */
13412         if (fout->remoteVersion >= 100000)
13413                 appendPQExpBuffer(query, "SELECT "
13414                                                   "collprovider, "
13415                                                   "collcollate, "
13416                                                   "collctype, "
13417                                                   "collversion "
13418                                                   "FROM pg_catalog.pg_collation c "
13419                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13420                                                   collinfo->dobj.catId.oid);
13421         else
13422                 appendPQExpBuffer(query, "SELECT "
13423                                                   "'c' AS collprovider, "
13424                                                   "collcollate, "
13425                                                   "collctype, "
13426                                                   "NULL AS collversion "
13427                                                   "FROM pg_catalog.pg_collation c "
13428                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13429                                                   collinfo->dobj.catId.oid);
13430
13431         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13432
13433         i_collprovider = PQfnumber(res, "collprovider");
13434         i_collcollate = PQfnumber(res, "collcollate");
13435         i_collctype = PQfnumber(res, "collctype");
13436
13437         collprovider = PQgetvalue(res, 0, i_collprovider);
13438         collcollate = PQgetvalue(res, 0, i_collcollate);
13439         collctype = PQgetvalue(res, 0, i_collctype);
13440
13441         /*
13442          * DROP must be fully qualified in case same name appears in pg_catalog
13443          */
13444         appendPQExpBuffer(delq, "DROP COLLATION %s",
13445                                           fmtId(collinfo->dobj.namespace->dobj.name));
13446         appendPQExpBuffer(delq, ".%s;\n",
13447                                           fmtId(collinfo->dobj.name));
13448
13449         appendPQExpBuffer(q, "CREATE COLLATION %s (",
13450                                           fmtId(collinfo->dobj.name));
13451
13452         appendPQExpBufferStr(q, "provider = ");
13453         if (collprovider[0] == 'c')
13454                 appendPQExpBufferStr(q, "libc");
13455         else if (collprovider[0] == 'i')
13456                 appendPQExpBufferStr(q, "icu");
13457         else if (collprovider[0] == 'd')
13458                 /* to allow dumping pg_catalog; not accepted on input */
13459                 appendPQExpBufferStr(q, "default");
13460         else
13461                 exit_horribly(NULL,
13462                                           "unrecognized collation provider: %s\n",
13463                                           collprovider);
13464
13465         if (strcmp(collcollate, collctype) == 0)
13466         {
13467                 appendPQExpBufferStr(q, ", locale = ");
13468                 appendStringLiteralAH(q, collcollate, fout);
13469         }
13470         else
13471         {
13472                 appendPQExpBufferStr(q, ", lc_collate = ");
13473                 appendStringLiteralAH(q, collcollate, fout);
13474                 appendPQExpBufferStr(q, ", lc_ctype = ");
13475                 appendStringLiteralAH(q, collctype, fout);
13476         }
13477
13478         /*
13479          * For binary upgrade, carry over the collation version.  For normal
13480          * dump/restore, omit the version, so that it is computed upon restore.
13481          */
13482         if (dopt->binary_upgrade)
13483         {
13484                 int                     i_collversion;
13485
13486                 i_collversion = PQfnumber(res, "collversion");
13487                 if (!PQgetisnull(res, 0, i_collversion))
13488                 {
13489                         appendPQExpBufferStr(q, ", version = ");
13490                         appendStringLiteralAH(q,
13491                                                                   PQgetvalue(res, 0, i_collversion),
13492                                                                   fout);
13493                 }
13494         }
13495
13496         appendPQExpBufferStr(q, ");\n");
13497
13498         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
13499
13500         if (dopt->binary_upgrade)
13501                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
13502
13503         if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13504                 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13505                                          collinfo->dobj.name,
13506                                          collinfo->dobj.namespace->dobj.name,
13507                                          NULL,
13508                                          collinfo->rolname,
13509                                          false, "COLLATION", SECTION_PRE_DATA,
13510                                          q->data, delq->data, NULL,
13511                                          NULL, 0,
13512                                          NULL, NULL);
13513
13514         /* Dump Collation Comments */
13515         if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13516                 dumpComment(fout, labelq->data,
13517                                         collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13518                                         collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13519
13520         PQclear(res);
13521
13522         destroyPQExpBuffer(query);
13523         destroyPQExpBuffer(q);
13524         destroyPQExpBuffer(delq);
13525         destroyPQExpBuffer(labelq);
13526 }
13527
13528 /*
13529  * dumpConversion
13530  *        write out a single conversion definition
13531  */
13532 static void
13533 dumpConversion(Archive *fout, ConvInfo *convinfo)
13534 {
13535         DumpOptions *dopt = fout->dopt;
13536         PQExpBuffer query;
13537         PQExpBuffer q;
13538         PQExpBuffer delq;
13539         PQExpBuffer labelq;
13540         PGresult   *res;
13541         int                     i_conforencoding;
13542         int                     i_contoencoding;
13543         int                     i_conproc;
13544         int                     i_condefault;
13545         const char *conforencoding;
13546         const char *contoencoding;
13547         const char *conproc;
13548         bool            condefault;
13549
13550         /* Skip if not to be dumped */
13551         if (!convinfo->dobj.dump || dopt->dataOnly)
13552                 return;
13553
13554         query = createPQExpBuffer();
13555         q = createPQExpBuffer();
13556         delq = createPQExpBuffer();
13557         labelq = createPQExpBuffer();
13558
13559         /* Make sure we are in proper schema */
13560         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
13561
13562         /* Get conversion-specific details */
13563         appendPQExpBuffer(query, "SELECT "
13564                                           "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13565                                           "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13566                                           "conproc, condefault "
13567                                           "FROM pg_catalog.pg_conversion c "
13568                                           "WHERE c.oid = '%u'::pg_catalog.oid",
13569                                           convinfo->dobj.catId.oid);
13570
13571         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13572
13573         i_conforencoding = PQfnumber(res, "conforencoding");
13574         i_contoencoding = PQfnumber(res, "contoencoding");
13575         i_conproc = PQfnumber(res, "conproc");
13576         i_condefault = PQfnumber(res, "condefault");
13577
13578         conforencoding = PQgetvalue(res, 0, i_conforencoding);
13579         contoencoding = PQgetvalue(res, 0, i_contoencoding);
13580         conproc = PQgetvalue(res, 0, i_conproc);
13581         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13582
13583         /*
13584          * DROP must be fully qualified in case same name appears in pg_catalog
13585          */
13586         appendPQExpBuffer(delq, "DROP CONVERSION %s",
13587                                           fmtId(convinfo->dobj.namespace->dobj.name));
13588         appendPQExpBuffer(delq, ".%s;\n",
13589                                           fmtId(convinfo->dobj.name));
13590
13591         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13592                                           (condefault) ? "DEFAULT " : "",
13593                                           fmtId(convinfo->dobj.name));
13594         appendStringLiteralAH(q, conforencoding, fout);
13595         appendPQExpBufferStr(q, " TO ");
13596         appendStringLiteralAH(q, contoencoding, fout);
13597         /* regproc output is already sufficiently quoted */
13598         appendPQExpBuffer(q, " FROM %s;\n", conproc);
13599
13600         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
13601
13602         if (dopt->binary_upgrade)
13603                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
13604
13605         if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13606                 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13607                                          convinfo->dobj.name,
13608                                          convinfo->dobj.namespace->dobj.name,
13609                                          NULL,
13610                                          convinfo->rolname,
13611                                          false, "CONVERSION", SECTION_PRE_DATA,
13612                                          q->data, delq->data, NULL,
13613                                          NULL, 0,
13614                                          NULL, NULL);
13615
13616         /* Dump Conversion Comments */
13617         if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13618                 dumpComment(fout, labelq->data,
13619                                         convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13620                                         convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13621
13622         PQclear(res);
13623
13624         destroyPQExpBuffer(query);
13625         destroyPQExpBuffer(q);
13626         destroyPQExpBuffer(delq);
13627         destroyPQExpBuffer(labelq);
13628 }
13629
13630 /*
13631  * format_aggregate_signature: generate aggregate name and argument list
13632  *
13633  * The argument type names are qualified if needed.  The aggregate name
13634  * is never qualified.
13635  */
13636 static char *
13637 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13638 {
13639         PQExpBufferData buf;
13640         int                     j;
13641
13642         initPQExpBuffer(&buf);
13643         if (honor_quotes)
13644                 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13645         else
13646                 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13647
13648         if (agginfo->aggfn.nargs == 0)
13649                 appendPQExpBuffer(&buf, "(*)");
13650         else
13651         {
13652                 appendPQExpBufferChar(&buf, '(');
13653                 for (j = 0; j < agginfo->aggfn.nargs; j++)
13654                 {
13655                         char       *typname;
13656
13657                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13658                                                                                    zeroAsOpaque);
13659
13660                         appendPQExpBuffer(&buf, "%s%s",
13661                                                           (j > 0) ? ", " : "",
13662                                                           typname);
13663                         free(typname);
13664                 }
13665                 appendPQExpBufferChar(&buf, ')');
13666         }
13667         return buf.data;
13668 }
13669
13670 /*
13671  * dumpAgg
13672  *        write out a single aggregate definition
13673  */
13674 static void
13675 dumpAgg(Archive *fout, AggInfo *agginfo)
13676 {
13677         DumpOptions *dopt = fout->dopt;
13678         PQExpBuffer query;
13679         PQExpBuffer q;
13680         PQExpBuffer delq;
13681         PQExpBuffer labelq;
13682         PQExpBuffer details;
13683         char       *aggsig;                     /* identity signature */
13684         char       *aggfullsig = NULL;  /* full signature */
13685         char       *aggsig_tag;
13686         PGresult   *res;
13687         int                     i_aggtransfn;
13688         int                     i_aggfinalfn;
13689         int                     i_aggcombinefn;
13690         int                     i_aggserialfn;
13691         int                     i_aggdeserialfn;
13692         int                     i_aggmtransfn;
13693         int                     i_aggminvtransfn;
13694         int                     i_aggmfinalfn;
13695         int                     i_aggfinalextra;
13696         int                     i_aggmfinalextra;
13697         int                     i_aggfinalmodify;
13698         int                     i_aggmfinalmodify;
13699         int                     i_aggsortop;
13700         int                     i_aggkind;
13701         int                     i_aggtranstype;
13702         int                     i_aggtransspace;
13703         int                     i_aggmtranstype;
13704         int                     i_aggmtransspace;
13705         int                     i_agginitval;
13706         int                     i_aggminitval;
13707         int                     i_convertok;
13708         int                     i_proparallel;
13709         const char *aggtransfn;
13710         const char *aggfinalfn;
13711         const char *aggcombinefn;
13712         const char *aggserialfn;
13713         const char *aggdeserialfn;
13714         const char *aggmtransfn;
13715         const char *aggminvtransfn;
13716         const char *aggmfinalfn;
13717         bool            aggfinalextra;
13718         bool            aggmfinalextra;
13719         char            aggfinalmodify;
13720         char            aggmfinalmodify;
13721         const char *aggsortop;
13722         char       *aggsortconvop;
13723         char            aggkind;
13724         const char *aggtranstype;
13725         const char *aggtransspace;
13726         const char *aggmtranstype;
13727         const char *aggmtransspace;
13728         const char *agginitval;
13729         const char *aggminitval;
13730         bool            convertok;
13731         const char *proparallel;
13732         char            defaultfinalmodify;
13733
13734         /* Skip if not to be dumped */
13735         if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13736                 return;
13737
13738         query = createPQExpBuffer();
13739         q = createPQExpBuffer();
13740         delq = createPQExpBuffer();
13741         labelq = createPQExpBuffer();
13742         details = createPQExpBuffer();
13743
13744         /* Make sure we are in proper schema */
13745         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
13746
13747         /* Get aggregate-specific details */
13748         if (fout->remoteVersion >= 110000)
13749         {
13750                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13751                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13752                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13753                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13754                                                   "aggfinalextra, aggmfinalextra, "
13755                                                   "aggfinalmodify, aggmfinalmodify, "
13756                                                   "aggsortop::pg_catalog.regoperator, "
13757                                                   "aggkind, "
13758                                                   "aggtransspace, agginitval, "
13759                                                   "aggmtransspace, aggminitval, "
13760                                                   "true AS convertok, "
13761                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13762                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13763                                                   "p.proparallel "
13764                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13765                                                   "WHERE a.aggfnoid = p.oid "
13766                                                   "AND p.oid = '%u'::pg_catalog.oid",
13767                                                   agginfo->aggfn.dobj.catId.oid);
13768         }
13769         else if (fout->remoteVersion >= 90600)
13770         {
13771                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13772                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13773                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13774                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13775                                                   "aggfinalextra, aggmfinalextra, "
13776                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13777                                                   "aggsortop::pg_catalog.regoperator, "
13778                                                   "aggkind, "
13779                                                   "aggtransspace, agginitval, "
13780                                                   "aggmtransspace, aggminitval, "
13781                                                   "true AS convertok, "
13782                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13783                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13784                                                   "p.proparallel "
13785                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13786                                                   "WHERE a.aggfnoid = p.oid "
13787                                                   "AND p.oid = '%u'::pg_catalog.oid",
13788                                                   agginfo->aggfn.dobj.catId.oid);
13789         }
13790         else if (fout->remoteVersion >= 90400)
13791         {
13792                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13793                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13794                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13795                                                   "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13796                                                   "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13797                                                   "aggfinalextra, aggmfinalextra, "
13798                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13799                                                   "aggsortop::pg_catalog.regoperator, "
13800                                                   "aggkind, "
13801                                                   "aggtransspace, agginitval, "
13802                                                   "aggmtransspace, aggminitval, "
13803                                                   "true AS convertok, "
13804                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13805                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13806                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13807                                                   "WHERE a.aggfnoid = p.oid "
13808                                                   "AND p.oid = '%u'::pg_catalog.oid",
13809                                                   agginfo->aggfn.dobj.catId.oid);
13810         }
13811         else if (fout->remoteVersion >= 80400)
13812         {
13813                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13814                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13815                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13816                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13817                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13818                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13819                                                   "false AS aggmfinalextra, "
13820                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13821                                                   "aggsortop::pg_catalog.regoperator, "
13822                                                   "'n' AS aggkind, "
13823                                                   "0 AS aggtransspace, agginitval, "
13824                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13825                                                   "true AS convertok, "
13826                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13827                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13828                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13829                                                   "WHERE a.aggfnoid = p.oid "
13830                                                   "AND p.oid = '%u'::pg_catalog.oid",
13831                                                   agginfo->aggfn.dobj.catId.oid);
13832         }
13833         else if (fout->remoteVersion >= 80100)
13834         {
13835                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13836                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13837                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13838                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13839                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13840                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13841                                                   "false AS aggmfinalextra, "
13842                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13843                                                   "aggsortop::pg_catalog.regoperator, "
13844                                                   "'n' AS aggkind, "
13845                                                   "0 AS aggtransspace, agginitval, "
13846                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13847                                                   "true AS convertok "
13848                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13849                                                   "WHERE a.aggfnoid = p.oid "
13850                                                   "AND p.oid = '%u'::pg_catalog.oid",
13851                                                   agginfo->aggfn.dobj.catId.oid);
13852         }
13853         else
13854         {
13855                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13856                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13857                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13858                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13859                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13860                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13861                                                   "false AS aggmfinalextra, "
13862                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13863                                                   "0 AS aggsortop, "
13864                                                   "'n' AS aggkind, "
13865                                                   "0 AS aggtransspace, agginitval, "
13866                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13867                                                   "true AS convertok "
13868                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13869                                                   "WHERE a.aggfnoid = p.oid "
13870                                                   "AND p.oid = '%u'::pg_catalog.oid",
13871                                                   agginfo->aggfn.dobj.catId.oid);
13872         }
13873
13874         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13875
13876         i_aggtransfn = PQfnumber(res, "aggtransfn");
13877         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13878         i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13879         i_aggserialfn = PQfnumber(res, "aggserialfn");
13880         i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13881         i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13882         i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13883         i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13884         i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13885         i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13886         i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13887         i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13888         i_aggsortop = PQfnumber(res, "aggsortop");
13889         i_aggkind = PQfnumber(res, "aggkind");
13890         i_aggtranstype = PQfnumber(res, "aggtranstype");
13891         i_aggtransspace = PQfnumber(res, "aggtransspace");
13892         i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13893         i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13894         i_agginitval = PQfnumber(res, "agginitval");
13895         i_aggminitval = PQfnumber(res, "aggminitval");
13896         i_convertok = PQfnumber(res, "convertok");
13897         i_proparallel = PQfnumber(res, "proparallel");
13898
13899         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13900         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13901         aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13902         aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13903         aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13904         aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13905         aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13906         aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13907         aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13908         aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13909         aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13910         aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13911         aggsortop = PQgetvalue(res, 0, i_aggsortop);
13912         aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13913         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13914         aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13915         aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13916         aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13917         agginitval = PQgetvalue(res, 0, i_agginitval);
13918         aggminitval = PQgetvalue(res, 0, i_aggminitval);
13919         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13920
13921         if (fout->remoteVersion >= 80400)
13922         {
13923                 /* 8.4 or later; we rely on server-side code for most of the work */
13924                 char       *funcargs;
13925                 char       *funciargs;
13926
13927                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13928                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13929                 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13930                 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13931         }
13932         else
13933                 /* pre-8.4, do it ourselves */
13934                 aggsig = format_aggregate_signature(agginfo, fout, true);
13935
13936         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13937
13938         if (i_proparallel != -1)
13939                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13940         else
13941                 proparallel = NULL;
13942
13943         if (!convertok)
13944         {
13945                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13946                                   aggsig);
13947
13948                 if (aggfullsig)
13949                         free(aggfullsig);
13950
13951                 free(aggsig);
13952
13953                 return;
13954         }
13955
13956         /* identify default modify flag for aggkind (must match DefineAggregate) */
13957         defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13958         /* replace omitted flags for old versions */
13959         if (aggfinalmodify == '0')
13960                 aggfinalmodify = defaultfinalmodify;
13961         if (aggmfinalmodify == '0')
13962                 aggmfinalmodify = defaultfinalmodify;
13963
13964         /* regproc and regtype output is already sufficiently quoted */
13965         appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
13966                                           aggtransfn, aggtranstype);
13967
13968         if (strcmp(aggtransspace, "0") != 0)
13969         {
13970                 appendPQExpBuffer(details, ",\n    SSPACE = %s",
13971                                                   aggtransspace);
13972         }
13973
13974         if (!PQgetisnull(res, 0, i_agginitval))
13975         {
13976                 appendPQExpBufferStr(details, ",\n    INITCOND = ");
13977                 appendStringLiteralAH(details, agginitval, fout);
13978         }
13979
13980         if (strcmp(aggfinalfn, "-") != 0)
13981         {
13982                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
13983                                                   aggfinalfn);
13984                 if (aggfinalextra)
13985                         appendPQExpBufferStr(details, ",\n    FINALFUNC_EXTRA");
13986                 if (aggfinalmodify != defaultfinalmodify)
13987                 {
13988                         switch (aggfinalmodify)
13989                         {
13990                                 case AGGMODIFY_READ_ONLY:
13991                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_ONLY");
13992                                         break;
13993                                 case AGGMODIFY_SHARABLE:
13994                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = SHARABLE");
13995                                         break;
13996                                 case AGGMODIFY_READ_WRITE:
13997                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_WRITE");
13998                                         break;
13999                                 default:
14000                                         exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
14001                                                                   agginfo->aggfn.dobj.name);
14002                                         break;
14003                         }
14004                 }
14005         }
14006
14007         if (strcmp(aggcombinefn, "-") != 0)
14008                 appendPQExpBuffer(details, ",\n    COMBINEFUNC = %s", aggcombinefn);
14009
14010         if (strcmp(aggserialfn, "-") != 0)
14011                 appendPQExpBuffer(details, ",\n    SERIALFUNC = %s", aggserialfn);
14012
14013         if (strcmp(aggdeserialfn, "-") != 0)
14014                 appendPQExpBuffer(details, ",\n    DESERIALFUNC = %s", aggdeserialfn);
14015
14016         if (strcmp(aggmtransfn, "-") != 0)
14017         {
14018                 appendPQExpBuffer(details, ",\n    MSFUNC = %s,\n    MINVFUNC = %s,\n    MSTYPE = %s",
14019                                                   aggmtransfn,
14020                                                   aggminvtransfn,
14021                                                   aggmtranstype);
14022         }
14023
14024         if (strcmp(aggmtransspace, "0") != 0)
14025         {
14026                 appendPQExpBuffer(details, ",\n    MSSPACE = %s",
14027                                                   aggmtransspace);
14028         }
14029
14030         if (!PQgetisnull(res, 0, i_aggminitval))
14031         {
14032                 appendPQExpBufferStr(details, ",\n    MINITCOND = ");
14033                 appendStringLiteralAH(details, aggminitval, fout);
14034         }
14035
14036         if (strcmp(aggmfinalfn, "-") != 0)
14037         {
14038                 appendPQExpBuffer(details, ",\n    MFINALFUNC = %s",
14039                                                   aggmfinalfn);
14040                 if (aggmfinalextra)
14041                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_EXTRA");
14042                 if (aggmfinalmodify != defaultfinalmodify)
14043                 {
14044                         switch (aggmfinalmodify)
14045                         {
14046                                 case AGGMODIFY_READ_ONLY:
14047                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_ONLY");
14048                                         break;
14049                                 case AGGMODIFY_SHARABLE:
14050                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = SHARABLE");
14051                                         break;
14052                                 case AGGMODIFY_READ_WRITE:
14053                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_WRITE");
14054                                         break;
14055                                 default:
14056                                         exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
14057                                                                   agginfo->aggfn.dobj.name);
14058                                         break;
14059                         }
14060                 }
14061         }
14062
14063         aggsortconvop = convertOperatorReference(fout, aggsortop);
14064         if (aggsortconvop)
14065         {
14066                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
14067                                                   aggsortconvop);
14068                 free(aggsortconvop);
14069         }
14070
14071         if (aggkind == AGGKIND_HYPOTHETICAL)
14072                 appendPQExpBufferStr(details, ",\n    HYPOTHETICAL");
14073
14074         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
14075         {
14076                 if (proparallel[0] == PROPARALLEL_SAFE)
14077                         appendPQExpBufferStr(details, ",\n    PARALLEL = safe");
14078                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14079                         appendPQExpBufferStr(details, ",\n    PARALLEL = restricted");
14080                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
14081                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
14082                                                   agginfo->aggfn.dobj.name);
14083         }
14084
14085         /*
14086          * DROP must be fully qualified in case same name appears in pg_catalog
14087          */
14088         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14089                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14090                                           aggsig);
14091
14092         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
14093                                           aggfullsig ? aggfullsig : aggsig, details->data);
14094
14095         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
14096
14097         if (dopt->binary_upgrade)
14098                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
14099
14100         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14101                 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14102                                          agginfo->aggfn.dobj.dumpId,
14103                                          aggsig_tag,
14104                                          agginfo->aggfn.dobj.namespace->dobj.name,
14105                                          NULL,
14106                                          agginfo->aggfn.rolname,
14107                                          false, "AGGREGATE", SECTION_PRE_DATA,
14108                                          q->data, delq->data, NULL,
14109                                          NULL, 0,
14110                                          NULL, NULL);
14111
14112         /* Dump Aggregate Comments */
14113         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14114                 dumpComment(fout, labelq->data,
14115                                         agginfo->aggfn.dobj.namespace->dobj.name,
14116                                         agginfo->aggfn.rolname,
14117                                         agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14118
14119         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14120                 dumpSecLabel(fout, labelq->data,
14121                                          agginfo->aggfn.dobj.namespace->dobj.name,
14122                                          agginfo->aggfn.rolname,
14123                                          agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14124
14125         /*
14126          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14127          * command look like a function's GRANT; in particular this affects the
14128          * syntax for zero-argument aggregates and ordered-set aggregates.
14129          */
14130         free(aggsig);
14131
14132         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14133
14134         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14135                 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
14136                                 "FUNCTION",
14137                                 aggsig, NULL, labelq->data,
14138                                 agginfo->aggfn.dobj.namespace->dobj.name,
14139                                 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14140                                 agginfo->aggfn.rproacl,
14141                                 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14142
14143         free(aggsig);
14144         if (aggfullsig)
14145                 free(aggfullsig);
14146         free(aggsig_tag);
14147
14148         PQclear(res);
14149
14150         destroyPQExpBuffer(query);
14151         destroyPQExpBuffer(q);
14152         destroyPQExpBuffer(delq);
14153         destroyPQExpBuffer(labelq);
14154         destroyPQExpBuffer(details);
14155 }
14156
14157 /*
14158  * dumpTSParser
14159  *        write out a single text search parser
14160  */
14161 static void
14162 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14163 {
14164         DumpOptions *dopt = fout->dopt;
14165         PQExpBuffer q;
14166         PQExpBuffer delq;
14167         PQExpBuffer labelq;
14168
14169         /* Skip if not to be dumped */
14170         if (!prsinfo->dobj.dump || dopt->dataOnly)
14171                 return;
14172
14173         q = createPQExpBuffer();
14174         delq = createPQExpBuffer();
14175         labelq = createPQExpBuffer();
14176
14177         /* Make sure we are in proper schema */
14178         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
14179
14180         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14181                                           fmtId(prsinfo->dobj.name));
14182
14183         appendPQExpBuffer(q, "    START = %s,\n",
14184                                           convertTSFunction(fout, prsinfo->prsstart));
14185         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
14186                                           convertTSFunction(fout, prsinfo->prstoken));
14187         appendPQExpBuffer(q, "    END = %s,\n",
14188                                           convertTSFunction(fout, prsinfo->prsend));
14189         if (prsinfo->prsheadline != InvalidOid)
14190                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
14191                                                   convertTSFunction(fout, prsinfo->prsheadline));
14192         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
14193                                           convertTSFunction(fout, prsinfo->prslextype));
14194
14195         /*
14196          * DROP must be fully qualified in case same name appears in pg_catalog
14197          */
14198         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
14199                                           fmtId(prsinfo->dobj.namespace->dobj.name));
14200         appendPQExpBuffer(delq, ".%s;\n",
14201                                           fmtId(prsinfo->dobj.name));
14202
14203         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
14204                                           fmtId(prsinfo->dobj.name));
14205
14206         if (dopt->binary_upgrade)
14207                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
14208
14209         if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14210                 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14211                                          prsinfo->dobj.name,
14212                                          prsinfo->dobj.namespace->dobj.name,
14213                                          NULL,
14214                                          "",
14215                                          false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14216                                          q->data, delq->data, NULL,
14217                                          NULL, 0,
14218                                          NULL, NULL);
14219
14220         /* Dump Parser Comments */
14221         if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14222                 dumpComment(fout, labelq->data,
14223                                         prsinfo->dobj.namespace->dobj.name, "",
14224                                         prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14225
14226         destroyPQExpBuffer(q);
14227         destroyPQExpBuffer(delq);
14228         destroyPQExpBuffer(labelq);
14229 }
14230
14231 /*
14232  * dumpTSDictionary
14233  *        write out a single text search dictionary
14234  */
14235 static void
14236 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14237 {
14238         DumpOptions *dopt = fout->dopt;
14239         PQExpBuffer q;
14240         PQExpBuffer delq;
14241         PQExpBuffer labelq;
14242         PQExpBuffer query;
14243         PGresult   *res;
14244         char       *nspname;
14245         char       *tmplname;
14246
14247         /* Skip if not to be dumped */
14248         if (!dictinfo->dobj.dump || dopt->dataOnly)
14249                 return;
14250
14251         q = createPQExpBuffer();
14252         delq = createPQExpBuffer();
14253         labelq = createPQExpBuffer();
14254         query = createPQExpBuffer();
14255
14256         /* Fetch name and namespace of the dictionary's template */
14257         selectSourceSchema(fout, "pg_catalog");
14258         appendPQExpBuffer(query, "SELECT nspname, tmplname "
14259                                           "FROM pg_ts_template p, pg_namespace n "
14260                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14261                                           dictinfo->dicttemplate);
14262         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14263         nspname = PQgetvalue(res, 0, 0);
14264         tmplname = PQgetvalue(res, 0, 1);
14265
14266         /* Make sure we are in proper schema */
14267         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
14268
14269         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14270                                           fmtId(dictinfo->dobj.name));
14271
14272         appendPQExpBufferStr(q, "    TEMPLATE = ");
14273         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
14274                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14275         appendPQExpBufferStr(q, fmtId(tmplname));
14276
14277         PQclear(res);
14278
14279         /* the dictinitoption can be dumped straight into the command */
14280         if (dictinfo->dictinitoption)
14281                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
14282
14283         appendPQExpBufferStr(q, " );\n");
14284
14285         /*
14286          * DROP must be fully qualified in case same name appears in pg_catalog
14287          */
14288         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
14289                                           fmtId(dictinfo->dobj.namespace->dobj.name));
14290         appendPQExpBuffer(delq, ".%s;\n",
14291                                           fmtId(dictinfo->dobj.name));
14292
14293         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
14294                                           fmtId(dictinfo->dobj.name));
14295
14296         if (dopt->binary_upgrade)
14297                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
14298
14299         if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14300                 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14301                                          dictinfo->dobj.name,
14302                                          dictinfo->dobj.namespace->dobj.name,
14303                                          NULL,
14304                                          dictinfo->rolname,
14305                                          false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14306                                          q->data, delq->data, NULL,
14307                                          NULL, 0,
14308                                          NULL, NULL);
14309
14310         /* Dump Dictionary Comments */
14311         if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14312                 dumpComment(fout, labelq->data,
14313                                         dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14314                                         dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14315
14316         destroyPQExpBuffer(q);
14317         destroyPQExpBuffer(delq);
14318         destroyPQExpBuffer(labelq);
14319         destroyPQExpBuffer(query);
14320 }
14321
14322 /*
14323  * dumpTSTemplate
14324  *        write out a single text search template
14325  */
14326 static void
14327 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14328 {
14329         DumpOptions *dopt = fout->dopt;
14330         PQExpBuffer q;
14331         PQExpBuffer delq;
14332         PQExpBuffer labelq;
14333
14334         /* Skip if not to be dumped */
14335         if (!tmplinfo->dobj.dump || dopt->dataOnly)
14336                 return;
14337
14338         q = createPQExpBuffer();
14339         delq = createPQExpBuffer();
14340         labelq = createPQExpBuffer();
14341
14342         /* Make sure we are in proper schema */
14343         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
14344
14345         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14346                                           fmtId(tmplinfo->dobj.name));
14347
14348         if (tmplinfo->tmplinit != InvalidOid)
14349                 appendPQExpBuffer(q, "    INIT = %s,\n",
14350                                                   convertTSFunction(fout, tmplinfo->tmplinit));
14351         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
14352                                           convertTSFunction(fout, tmplinfo->tmpllexize));
14353
14354         /*
14355          * DROP must be fully qualified in case same name appears in pg_catalog
14356          */
14357         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
14358                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
14359         appendPQExpBuffer(delq, ".%s;\n",
14360                                           fmtId(tmplinfo->dobj.name));
14361
14362         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
14363                                           fmtId(tmplinfo->dobj.name));
14364
14365         if (dopt->binary_upgrade)
14366                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
14367
14368         if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14369                 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14370                                          tmplinfo->dobj.name,
14371                                          tmplinfo->dobj.namespace->dobj.name,
14372                                          NULL,
14373                                          "",
14374                                          false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14375                                          q->data, delq->data, NULL,
14376                                          NULL, 0,
14377                                          NULL, NULL);
14378
14379         /* Dump Template Comments */
14380         if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14381                 dumpComment(fout, labelq->data,
14382                                         tmplinfo->dobj.namespace->dobj.name, "",
14383                                         tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14384
14385         destroyPQExpBuffer(q);
14386         destroyPQExpBuffer(delq);
14387         destroyPQExpBuffer(labelq);
14388 }
14389
14390 /*
14391  * dumpTSConfig
14392  *        write out a single text search configuration
14393  */
14394 static void
14395 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14396 {
14397         DumpOptions *dopt = fout->dopt;
14398         PQExpBuffer q;
14399         PQExpBuffer delq;
14400         PQExpBuffer labelq;
14401         PQExpBuffer query;
14402         PGresult   *res;
14403         char       *nspname;
14404         char       *prsname;
14405         int                     ntups,
14406                                 i;
14407         int                     i_tokenname;
14408         int                     i_dictname;
14409
14410         /* Skip if not to be dumped */
14411         if (!cfginfo->dobj.dump || dopt->dataOnly)
14412                 return;
14413
14414         q = createPQExpBuffer();
14415         delq = createPQExpBuffer();
14416         labelq = createPQExpBuffer();
14417         query = createPQExpBuffer();
14418
14419         /* Fetch name and namespace of the config's parser */
14420         selectSourceSchema(fout, "pg_catalog");
14421         appendPQExpBuffer(query, "SELECT nspname, prsname "
14422                                           "FROM pg_ts_parser p, pg_namespace n "
14423                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14424                                           cfginfo->cfgparser);
14425         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14426         nspname = PQgetvalue(res, 0, 0);
14427         prsname = PQgetvalue(res, 0, 1);
14428
14429         /* Make sure we are in proper schema */
14430         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
14431
14432         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14433                                           fmtId(cfginfo->dobj.name));
14434
14435         appendPQExpBufferStr(q, "    PARSER = ");
14436         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
14437                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
14438         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14439
14440         PQclear(res);
14441
14442         resetPQExpBuffer(query);
14443         appendPQExpBuffer(query,
14444                                           "SELECT\n"
14445                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14446                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14447                                           "  m.mapdict::pg_catalog.regdictionary AS dictname\n"
14448                                           "FROM pg_catalog.pg_ts_config_map AS m\n"
14449                                           "WHERE m.mapcfg = '%u'\n"
14450                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14451                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14452
14453         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14454         ntups = PQntuples(res);
14455
14456         i_tokenname = PQfnumber(res, "tokenname");
14457         i_dictname = PQfnumber(res, "dictname");
14458
14459         for (i = 0; i < ntups; i++)
14460         {
14461                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
14462                 char       *dictname = PQgetvalue(res, i, i_dictname);
14463
14464                 if (i == 0 ||
14465                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14466                 {
14467                         /* starting a new token type, so start a new command */
14468                         if (i > 0)
14469                                 appendPQExpBufferStr(q, ";\n");
14470                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14471                                                           fmtId(cfginfo->dobj.name));
14472                         /* tokenname needs quoting, dictname does NOT */
14473                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
14474                                                           fmtId(tokenname), dictname);
14475                 }
14476                 else
14477                         appendPQExpBuffer(q, ", %s", dictname);
14478         }
14479
14480         if (ntups > 0)
14481                 appendPQExpBufferStr(q, ";\n");
14482
14483         PQclear(res);
14484
14485         /*
14486          * DROP must be fully qualified in case same name appears in pg_catalog
14487          */
14488         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
14489                                           fmtId(cfginfo->dobj.namespace->dobj.name));
14490         appendPQExpBuffer(delq, ".%s;\n",
14491                                           fmtId(cfginfo->dobj.name));
14492
14493         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
14494                                           fmtId(cfginfo->dobj.name));
14495
14496         if (dopt->binary_upgrade)
14497                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
14498
14499         if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14500                 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14501                                          cfginfo->dobj.name,
14502                                          cfginfo->dobj.namespace->dobj.name,
14503                                          NULL,
14504                                          cfginfo->rolname,
14505                                          false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14506                                          q->data, delq->data, NULL,
14507                                          NULL, 0,
14508                                          NULL, NULL);
14509
14510         /* Dump Configuration Comments */
14511         if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14512                 dumpComment(fout, labelq->data,
14513                                         cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14514                                         cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14515
14516         destroyPQExpBuffer(q);
14517         destroyPQExpBuffer(delq);
14518         destroyPQExpBuffer(labelq);
14519         destroyPQExpBuffer(query);
14520 }
14521
14522 /*
14523  * dumpForeignDataWrapper
14524  *        write out a single foreign-data wrapper definition
14525  */
14526 static void
14527 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14528 {
14529         DumpOptions *dopt = fout->dopt;
14530         PQExpBuffer q;
14531         PQExpBuffer delq;
14532         PQExpBuffer labelq;
14533         char       *qfdwname;
14534
14535         /* Skip if not to be dumped */
14536         if (!fdwinfo->dobj.dump || dopt->dataOnly)
14537                 return;
14538
14539         q = createPQExpBuffer();
14540         delq = createPQExpBuffer();
14541         labelq = createPQExpBuffer();
14542
14543         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14544
14545         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14546                                           qfdwname);
14547
14548         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14549                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14550
14551         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14552                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14553
14554         if (strlen(fdwinfo->fdwoptions) > 0)
14555                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
14556
14557         appendPQExpBufferStr(q, ";\n");
14558
14559         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14560                                           qfdwname);
14561
14562         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
14563                                           qfdwname);
14564
14565         if (dopt->binary_upgrade)
14566                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
14567
14568         if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14569                 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14570                                          fdwinfo->dobj.name,
14571                                          NULL,
14572                                          NULL,
14573                                          fdwinfo->rolname,
14574                                          false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14575                                          q->data, delq->data, NULL,
14576                                          NULL, 0,
14577                                          NULL, NULL);
14578
14579         /* Dump Foreign Data Wrapper Comments */
14580         if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14581                 dumpComment(fout, labelq->data,
14582                                         NULL, fdwinfo->rolname,
14583                                         fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14584
14585         /* Handle the ACL */
14586         if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14587                 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14588                                 "FOREIGN DATA WRAPPER",
14589                                 qfdwname, NULL, labelq->data,
14590                                 NULL, fdwinfo->rolname,
14591                                 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14592                                 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14593
14594         free(qfdwname);
14595
14596         destroyPQExpBuffer(q);
14597         destroyPQExpBuffer(delq);
14598         destroyPQExpBuffer(labelq);
14599 }
14600
14601 /*
14602  * dumpForeignServer
14603  *        write out a foreign server definition
14604  */
14605 static void
14606 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14607 {
14608         DumpOptions *dopt = fout->dopt;
14609         PQExpBuffer q;
14610         PQExpBuffer delq;
14611         PQExpBuffer labelq;
14612         PQExpBuffer query;
14613         PGresult   *res;
14614         char       *qsrvname;
14615         char       *fdwname;
14616
14617         /* Skip if not to be dumped */
14618         if (!srvinfo->dobj.dump || dopt->dataOnly)
14619                 return;
14620
14621         q = createPQExpBuffer();
14622         delq = createPQExpBuffer();
14623         labelq = createPQExpBuffer();
14624         query = createPQExpBuffer();
14625
14626         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14627
14628         /* look up the foreign-data wrapper */
14629         selectSourceSchema(fout, "pg_catalog");
14630         appendPQExpBuffer(query, "SELECT fdwname "
14631                                           "FROM pg_foreign_data_wrapper w "
14632                                           "WHERE w.oid = '%u'",
14633                                           srvinfo->srvfdw);
14634         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14635         fdwname = PQgetvalue(res, 0, 0);
14636
14637         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14638         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14639         {
14640                 appendPQExpBufferStr(q, " TYPE ");
14641                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14642         }
14643         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14644         {
14645                 appendPQExpBufferStr(q, " VERSION ");
14646                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14647         }
14648
14649         appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14650         appendPQExpBufferStr(q, fmtId(fdwname));
14651
14652         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14653                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
14654
14655         appendPQExpBufferStr(q, ";\n");
14656
14657         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14658                                           qsrvname);
14659
14660         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
14661
14662         if (dopt->binary_upgrade)
14663                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
14664
14665         if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14666                 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14667                                          srvinfo->dobj.name,
14668                                          NULL,
14669                                          NULL,
14670                                          srvinfo->rolname,
14671                                          false, "SERVER", SECTION_PRE_DATA,
14672                                          q->data, delq->data, NULL,
14673                                          NULL, 0,
14674                                          NULL, NULL);
14675
14676         /* Dump Foreign Server Comments */
14677         if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14678                 dumpComment(fout, labelq->data,
14679                                         NULL, srvinfo->rolname,
14680                                         srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14681
14682         /* Handle the ACL */
14683         if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14684                 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14685                                 "FOREIGN SERVER",
14686                                 qsrvname, NULL, labelq->data,
14687                                 NULL, srvinfo->rolname,
14688                                 srvinfo->srvacl, srvinfo->rsrvacl,
14689                                 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14690
14691         /* Dump user mappings */
14692         if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14693                 dumpUserMappings(fout,
14694                                                  srvinfo->dobj.name, NULL,
14695                                                  srvinfo->rolname,
14696                                                  srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14697
14698         free(qsrvname);
14699
14700         destroyPQExpBuffer(q);
14701         destroyPQExpBuffer(delq);
14702         destroyPQExpBuffer(labelq);
14703         destroyPQExpBuffer(query);
14704 }
14705
14706 /*
14707  * dumpUserMappings
14708  *
14709  * This routine is used to dump any user mappings associated with the
14710  * server handed to this routine. Should be called after ArchiveEntry()
14711  * for the server.
14712  */
14713 static void
14714 dumpUserMappings(Archive *fout,
14715                                  const char *servername, const char *namespace,
14716                                  const char *owner,
14717                                  CatalogId catalogId, DumpId dumpId)
14718 {
14719         PQExpBuffer q;
14720         PQExpBuffer delq;
14721         PQExpBuffer query;
14722         PQExpBuffer tag;
14723         PGresult   *res;
14724         int                     ntups;
14725         int                     i_usename;
14726         int                     i_umoptions;
14727         int                     i;
14728
14729         q = createPQExpBuffer();
14730         tag = createPQExpBuffer();
14731         delq = createPQExpBuffer();
14732         query = createPQExpBuffer();
14733
14734         /*
14735          * We read from the publicly accessible view pg_user_mappings, so as not
14736          * to fail if run by a non-superuser.  Note that the view will show
14737          * umoptions as null if the user hasn't got privileges for the associated
14738          * server; this means that pg_dump will dump such a mapping, but with no
14739          * OPTIONS clause.  A possible alternative is to skip such mappings
14740          * altogether, but it's not clear that that's an improvement.
14741          */
14742         selectSourceSchema(fout, "pg_catalog");
14743
14744         appendPQExpBuffer(query,
14745                                           "SELECT usename, "
14746                                           "array_to_string(ARRAY("
14747                                           "SELECT quote_ident(option_name) || ' ' || "
14748                                           "quote_literal(option_value) "
14749                                           "FROM pg_options_to_table(umoptions) "
14750                                           "ORDER BY option_name"
14751                                           "), E',\n    ') AS umoptions "
14752                                           "FROM pg_user_mappings "
14753                                           "WHERE srvid = '%u' "
14754                                           "ORDER BY usename",
14755                                           catalogId.oid);
14756
14757         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14758
14759         ntups = PQntuples(res);
14760         i_usename = PQfnumber(res, "usename");
14761         i_umoptions = PQfnumber(res, "umoptions");
14762
14763         for (i = 0; i < ntups; i++)
14764         {
14765                 char       *usename;
14766                 char       *umoptions;
14767
14768                 usename = PQgetvalue(res, i, i_usename);
14769                 umoptions = PQgetvalue(res, i, i_umoptions);
14770
14771                 resetPQExpBuffer(q);
14772                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14773                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14774
14775                 if (umoptions && strlen(umoptions) > 0)
14776                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
14777
14778                 appendPQExpBufferStr(q, ";\n");
14779
14780                 resetPQExpBuffer(delq);
14781                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14782                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14783
14784                 resetPQExpBuffer(tag);
14785                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14786                                                   usename, servername);
14787
14788                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14789                                          tag->data,
14790                                          namespace,
14791                                          NULL,
14792                                          owner, false,
14793                                          "USER MAPPING", SECTION_PRE_DATA,
14794                                          q->data, delq->data, NULL,
14795                                          &dumpId, 1,
14796                                          NULL, NULL);
14797         }
14798
14799         PQclear(res);
14800
14801         destroyPQExpBuffer(query);
14802         destroyPQExpBuffer(delq);
14803         destroyPQExpBuffer(tag);
14804         destroyPQExpBuffer(q);
14805 }
14806
14807 /*
14808  * Write out default privileges information
14809  */
14810 static void
14811 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14812 {
14813         DumpOptions *dopt = fout->dopt;
14814         PQExpBuffer q;
14815         PQExpBuffer tag;
14816         const char *type;
14817
14818         /* Skip if not to be dumped */
14819         if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14820                 return;
14821
14822         q = createPQExpBuffer();
14823         tag = createPQExpBuffer();
14824
14825         switch (daclinfo->defaclobjtype)
14826         {
14827                 case DEFACLOBJ_RELATION:
14828                         type = "TABLES";
14829                         break;
14830                 case DEFACLOBJ_SEQUENCE:
14831                         type = "SEQUENCES";
14832                         break;
14833                 case DEFACLOBJ_FUNCTION:
14834                         type = "FUNCTIONS";
14835                         break;
14836                 case DEFACLOBJ_TYPE:
14837                         type = "TYPES";
14838                         break;
14839                 case DEFACLOBJ_NAMESPACE:
14840                         type = "SCHEMAS";
14841                         break;
14842                 default:
14843                         /* shouldn't get here */
14844                         exit_horribly(NULL,
14845                                                   "unrecognized object type in default privileges: %d\n",
14846                                                   (int) daclinfo->defaclobjtype);
14847                         type = "";                      /* keep compiler quiet */
14848         }
14849
14850         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14851
14852         /* build the actual command(s) for this tuple */
14853         if (!buildDefaultACLCommands(type,
14854                                                                  daclinfo->dobj.namespace != NULL ?
14855                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
14856                                                                  daclinfo->defaclacl,
14857                                                                  daclinfo->rdefaclacl,
14858                                                                  daclinfo->initdefaclacl,
14859                                                                  daclinfo->initrdefaclacl,
14860                                                                  daclinfo->defaclrole,
14861                                                                  fout->remoteVersion,
14862                                                                  q))
14863                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14864                                           daclinfo->defaclacl);
14865
14866         if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14867                 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14868                                          tag->data,
14869                                          daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14870                                          NULL,
14871                                          daclinfo->defaclrole,
14872                                          false, "DEFAULT ACL", SECTION_POST_DATA,
14873                                          q->data, "", NULL,
14874                                          NULL, 0,
14875                                          NULL, NULL);
14876
14877         destroyPQExpBuffer(tag);
14878         destroyPQExpBuffer(q);
14879 }
14880
14881 /*----------
14882  * Write out grant/revoke information
14883  *
14884  * 'objCatId' is the catalog ID of the underlying object.
14885  * 'objDumpId' is the dump ID of the underlying object.
14886  * 'type' must be one of
14887  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14888  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14889  * 'name' is the formatted name of the object.  Must be quoted etc. already.
14890  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
14891  * 'tag' is the tag for the archive entry (should be the same tag as would be
14892  *              used for comments etc; for example "TABLE foo").
14893  * 'nspname' is the namespace the object is in (NULL if none).
14894  * 'owner' is the owner, NULL if there is no owner (for languages).
14895  * 'acls' contains the ACL string of the object from the appropriate system
14896  *              catalog field; it will be passed to buildACLCommands for building the
14897  *              appropriate GRANT commands.
14898  * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14899  *              object; it will be passed to buildACLCommands for building the
14900  *              appropriate REVOKE commands.
14901  * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14902  *              privileges, to be recorded into pg_init_privs
14903  * 'initracls' In binary-upgrade mode, ACL string of the object's
14904  *              revoked-from-default privileges, to be recorded into pg_init_privs
14905  *
14906  * NB: initacls/initracls are needed because extensions can set privileges on
14907  * an object during the extension's script file and we record those into
14908  * pg_init_privs as that object's initial privileges.
14909  *----------
14910  */
14911 static void
14912 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14913                 const char *type, const char *name, const char *subname,
14914                 const char *tag, const char *nspname, const char *owner,
14915                 const char *acls, const char *racls,
14916                 const char *initacls, const char *initracls)
14917 {
14918         DumpOptions *dopt = fout->dopt;
14919         PQExpBuffer sql;
14920
14921         /* Do nothing if ACL dump is not enabled */
14922         if (dopt->aclsSkip)
14923                 return;
14924
14925         /* --data-only skips ACLs *except* BLOB ACLs */
14926         if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14927                 return;
14928
14929         sql = createPQExpBuffer();
14930
14931         /*
14932          * Check to see if this object has had any initial ACLs included for it.
14933          * If so, we are in binary upgrade mode and these are the ACLs to turn
14934          * into GRANT and REVOKE statements to set and record the initial
14935          * privileges for an extension object.  Let the backend know that these
14936          * are to be recorded by calling binary_upgrade_set_record_init_privs()
14937          * before and after.
14938          */
14939         if (strlen(initacls) != 0 || strlen(initracls) != 0)
14940         {
14941                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14942                 if (!buildACLCommands(name, subname, type, initacls, initracls, owner,
14943                                                           "", fout->remoteVersion, sql))
14944                         exit_horribly(NULL,
14945                                                   "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14946                                                   initacls, initracls, name, type);
14947                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14948         }
14949
14950         if (!buildACLCommands(name, subname, type, acls, racls, owner,
14951                                                   "", fout->remoteVersion, sql))
14952                 exit_horribly(NULL,
14953                                           "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14954                                           acls, racls, name, type);
14955
14956         if (sql->len > 0)
14957                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14958                                          tag, nspname,
14959                                          NULL,
14960                                          owner ? owner : "",
14961                                          false, "ACL", SECTION_NONE,
14962                                          sql->data, "", NULL,
14963                                          &(objDumpId), 1,
14964                                          NULL, NULL);
14965
14966         destroyPQExpBuffer(sql);
14967 }
14968
14969 /*
14970  * dumpSecLabel
14971  *
14972  * This routine is used to dump any security labels associated with the
14973  * object handed to this routine. The routine takes a constant character
14974  * string for the target part of the security-label command, plus
14975  * the namespace and owner of the object (for labeling the ArchiveEntry),
14976  * plus catalog ID and subid which are the lookup key for pg_seclabel,
14977  * plus the dump ID for the object (for setting a dependency).
14978  * If a matching pg_seclabel entry is found, it is dumped.
14979  *
14980  * Note: although this routine takes a dumpId for dependency purposes,
14981  * that purpose is just to mark the dependency in the emitted dump file
14982  * for possible future use by pg_restore.  We do NOT use it for determining
14983  * ordering of the label in the dump file, because this routine is called
14984  * after dependency sorting occurs.  This routine should be called just after
14985  * calling ArchiveEntry() for the specified object.
14986  */
14987 static void
14988 dumpSecLabel(Archive *fout, const char *target,
14989                          const char *namespace, const char *owner,
14990                          CatalogId catalogId, int subid, DumpId dumpId)
14991 {
14992         DumpOptions *dopt = fout->dopt;
14993         SecLabelItem *labels;
14994         int                     nlabels;
14995         int                     i;
14996         PQExpBuffer query;
14997
14998         /* do nothing, if --no-security-labels is supplied */
14999         if (dopt->no_security_labels)
15000                 return;
15001
15002         /* Security labels are schema not data ... except blob labels are data */
15003         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
15004         {
15005                 if (dopt->dataOnly)
15006                         return;
15007         }
15008         else
15009         {
15010                 /* We do dump blob security labels in binary-upgrade mode */
15011                 if (dopt->schemaOnly && !dopt->binary_upgrade)
15012                         return;
15013         }
15014
15015         /* Search for security labels associated with catalogId, using table */
15016         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
15017
15018         query = createPQExpBuffer();
15019
15020         for (i = 0; i < nlabels; i++)
15021         {
15022                 /*
15023                  * Ignore label entries for which the subid doesn't match.
15024                  */
15025                 if (labels[i].objsubid != subid)
15026                         continue;
15027
15028                 appendPQExpBuffer(query,
15029                                                   "SECURITY LABEL FOR %s ON %s IS ",
15030                                                   fmtId(labels[i].provider), target);
15031                 appendStringLiteralAH(query, labels[i].label, fout);
15032                 appendPQExpBufferStr(query, ";\n");
15033         }
15034
15035         if (query->len > 0)
15036         {
15037                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15038                                          target, namespace, NULL, owner,
15039                                          false, "SECURITY LABEL", SECTION_NONE,
15040                                          query->data, "", NULL,
15041                                          &(dumpId), 1,
15042                                          NULL, NULL);
15043         }
15044         destroyPQExpBuffer(query);
15045 }
15046
15047 /*
15048  * dumpTableSecLabel
15049  *
15050  * As above, but dump security label for both the specified table (or view)
15051  * and its columns.
15052  */
15053 static void
15054 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
15055 {
15056         DumpOptions *dopt = fout->dopt;
15057         SecLabelItem *labels;
15058         int                     nlabels;
15059         int                     i;
15060         PQExpBuffer query;
15061         PQExpBuffer target;
15062
15063         /* do nothing, if --no-security-labels is supplied */
15064         if (dopt->no_security_labels)
15065                 return;
15066
15067         /* SecLabel are SCHEMA not data */
15068         if (dopt->dataOnly)
15069                 return;
15070
15071         /* Search for comments associated with relation, using table */
15072         nlabels = findSecLabels(fout,
15073                                                         tbinfo->dobj.catId.tableoid,
15074                                                         tbinfo->dobj.catId.oid,
15075                                                         &labels);
15076
15077         /* If security labels exist, build SECURITY LABEL statements */
15078         if (nlabels <= 0)
15079                 return;
15080
15081         query = createPQExpBuffer();
15082         target = createPQExpBuffer();
15083
15084         for (i = 0; i < nlabels; i++)
15085         {
15086                 const char *colname;
15087                 const char *provider = labels[i].provider;
15088                 const char *label = labels[i].label;
15089                 int                     objsubid = labels[i].objsubid;
15090
15091                 resetPQExpBuffer(target);
15092                 if (objsubid == 0)
15093                 {
15094                         appendPQExpBuffer(target, "%s %s", reltypename,
15095                                                           fmtId(tbinfo->dobj.name));
15096                 }
15097                 else
15098                 {
15099                         colname = getAttrName(objsubid, tbinfo);
15100                         /* first fmtId result must be consumed before calling it again */
15101                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
15102                         appendPQExpBuffer(target, ".%s", fmtId(colname));
15103                 }
15104                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
15105                                                   fmtId(provider), target->data);
15106                 appendStringLiteralAH(query, label, fout);
15107                 appendPQExpBufferStr(query, ";\n");
15108         }
15109         if (query->len > 0)
15110         {
15111                 resetPQExpBuffer(target);
15112                 appendPQExpBuffer(target, "%s %s", reltypename,
15113                                                   fmtId(tbinfo->dobj.name));
15114                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15115                                          target->data,
15116                                          tbinfo->dobj.namespace->dobj.name,
15117                                          NULL, tbinfo->rolname,
15118                                          false, "SECURITY LABEL", SECTION_NONE,
15119                                          query->data, "", NULL,
15120                                          &(tbinfo->dobj.dumpId), 1,
15121                                          NULL, NULL);
15122         }
15123         destroyPQExpBuffer(query);
15124         destroyPQExpBuffer(target);
15125 }
15126
15127 /*
15128  * findSecLabels
15129  *
15130  * Find the security label(s), if any, associated with the given object.
15131  * All the objsubid values associated with the given classoid/objoid are
15132  * found with one search.
15133  */
15134 static int
15135 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15136 {
15137         /* static storage for table of security labels */
15138         static SecLabelItem *labels = NULL;
15139         static int      nlabels = -1;
15140
15141         SecLabelItem *middle = NULL;
15142         SecLabelItem *low;
15143         SecLabelItem *high;
15144         int                     nmatch;
15145
15146         /* Get security labels if we didn't already */
15147         if (nlabels < 0)
15148                 nlabels = collectSecLabels(fout, &labels);
15149
15150         if (nlabels <= 0)                       /* no labels, so no match is possible */
15151         {
15152                 *items = NULL;
15153                 return 0;
15154         }
15155
15156         /*
15157          * Do binary search to find some item matching the object.
15158          */
15159         low = &labels[0];
15160         high = &labels[nlabels - 1];
15161         while (low <= high)
15162         {
15163                 middle = low + (high - low) / 2;
15164
15165                 if (classoid < middle->classoid)
15166                         high = middle - 1;
15167                 else if (classoid > middle->classoid)
15168                         low = middle + 1;
15169                 else if (objoid < middle->objoid)
15170                         high = middle - 1;
15171                 else if (objoid > middle->objoid)
15172                         low = middle + 1;
15173                 else
15174                         break;                          /* found a match */
15175         }
15176
15177         if (low > high)                         /* no matches */
15178         {
15179                 *items = NULL;
15180                 return 0;
15181         }
15182
15183         /*
15184          * Now determine how many items match the object.  The search loop
15185          * invariant still holds: only items between low and high inclusive could
15186          * match.
15187          */
15188         nmatch = 1;
15189         while (middle > low)
15190         {
15191                 if (classoid != middle[-1].classoid ||
15192                         objoid != middle[-1].objoid)
15193                         break;
15194                 middle--;
15195                 nmatch++;
15196         }
15197
15198         *items = middle;
15199
15200         middle += nmatch;
15201         while (middle <= high)
15202         {
15203                 if (classoid != middle->classoid ||
15204                         objoid != middle->objoid)
15205                         break;
15206                 middle++;
15207                 nmatch++;
15208         }
15209
15210         return nmatch;
15211 }
15212
15213 /*
15214  * collectSecLabels
15215  *
15216  * Construct a table of all security labels available for database objects.
15217  * It's much faster to pull them all at once.
15218  *
15219  * The table is sorted by classoid/objid/objsubid for speed in lookup.
15220  */
15221 static int
15222 collectSecLabels(Archive *fout, SecLabelItem **items)
15223 {
15224         PGresult   *res;
15225         PQExpBuffer query;
15226         int                     i_label;
15227         int                     i_provider;
15228         int                     i_classoid;
15229         int                     i_objoid;
15230         int                     i_objsubid;
15231         int                     ntups;
15232         int                     i;
15233         SecLabelItem *labels;
15234
15235         query = createPQExpBuffer();
15236
15237         appendPQExpBufferStr(query,
15238                                                  "SELECT label, provider, classoid, objoid, objsubid "
15239                                                  "FROM pg_catalog.pg_seclabel "
15240                                                  "ORDER BY classoid, objoid, objsubid");
15241
15242         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15243
15244         /* Construct lookup table containing OIDs in numeric form */
15245         i_label = PQfnumber(res, "label");
15246         i_provider = PQfnumber(res, "provider");
15247         i_classoid = PQfnumber(res, "classoid");
15248         i_objoid = PQfnumber(res, "objoid");
15249         i_objsubid = PQfnumber(res, "objsubid");
15250
15251         ntups = PQntuples(res);
15252
15253         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15254
15255         for (i = 0; i < ntups; i++)
15256         {
15257                 labels[i].label = PQgetvalue(res, i, i_label);
15258                 labels[i].provider = PQgetvalue(res, i, i_provider);
15259                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15260                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15261                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15262         }
15263
15264         /* Do NOT free the PGresult since we are keeping pointers into it */
15265         destroyPQExpBuffer(query);
15266
15267         *items = labels;
15268         return ntups;
15269 }
15270
15271 /*
15272  * dumpTable
15273  *        write out to fout the declarations (not data) of a user-defined table
15274  */
15275 static void
15276 dumpTable(Archive *fout, TableInfo *tbinfo)
15277 {
15278         DumpOptions *dopt = fout->dopt;
15279         char       *namecopy;
15280
15281         /*
15282          * noop if we are not dumping anything about this table, or if we are
15283          * doing a data-only dump
15284          */
15285         if (!tbinfo->dobj.dump || dopt->dataOnly)
15286                 return;
15287
15288         if (tbinfo->relkind == RELKIND_SEQUENCE)
15289                 dumpSequence(fout, tbinfo);
15290         else
15291                 dumpTableSchema(fout, tbinfo);
15292
15293         /* Handle the ACL here */
15294         namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15295         if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15296         {
15297                 const char *objtype =
15298                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15299                 char       *acltag = psprintf("%s %s", objtype, namecopy);
15300
15301                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15302                                 objtype, namecopy, NULL, acltag,
15303                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15304                                 tbinfo->relacl, tbinfo->rrelacl,
15305                                 tbinfo->initrelacl, tbinfo->initrrelacl);
15306                 free(acltag);
15307         }
15308
15309         /*
15310          * Handle column ACLs, if any.  Note: we pull these with a separate query
15311          * rather than trying to fetch them during getTableAttrs, so that we won't
15312          * miss ACLs on system columns.
15313          */
15314         if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15315         {
15316                 PQExpBuffer query = createPQExpBuffer();
15317                 PGresult   *res;
15318                 int                     i;
15319
15320                 if (fout->remoteVersion >= 90600)
15321                 {
15322                         PQExpBuffer acl_subquery = createPQExpBuffer();
15323                         PQExpBuffer racl_subquery = createPQExpBuffer();
15324                         PQExpBuffer initacl_subquery = createPQExpBuffer();
15325                         PQExpBuffer initracl_subquery = createPQExpBuffer();
15326
15327                         buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15328                                                         initracl_subquery, "at.attacl", "c.relowner", "'c'",
15329                                                         dopt->binary_upgrade);
15330
15331                         appendPQExpBuffer(query,
15332                                                           "SELECT at.attname, "
15333                                                           "%s AS attacl, "
15334                                                           "%s AS rattacl, "
15335                                                           "%s AS initattacl, "
15336                                                           "%s AS initrattacl "
15337                                                           "FROM pg_catalog.pg_attribute at "
15338                                                           "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15339                                                           "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15340                                                           "(at.attrelid = pip.objoid "
15341                                                           "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15342                                                           "AND at.attnum = pip.objsubid) "
15343                                                           "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15344                                                           "NOT at.attisdropped "
15345                                                           "AND ("
15346                                                           "%s IS NOT NULL OR "
15347                                                           "%s IS NOT NULL OR "
15348                                                           "%s IS NOT NULL OR "
15349                                                           "%s IS NOT NULL)"
15350                                                           "ORDER BY at.attnum",
15351                                                           acl_subquery->data,
15352                                                           racl_subquery->data,
15353                                                           initacl_subquery->data,
15354                                                           initracl_subquery->data,
15355                                                           tbinfo->dobj.catId.oid,
15356                                                           acl_subquery->data,
15357                                                           racl_subquery->data,
15358                                                           initacl_subquery->data,
15359                                                           initracl_subquery->data);
15360
15361                         destroyPQExpBuffer(acl_subquery);
15362                         destroyPQExpBuffer(racl_subquery);
15363                         destroyPQExpBuffer(initacl_subquery);
15364                         destroyPQExpBuffer(initracl_subquery);
15365                 }
15366                 else
15367                 {
15368                         appendPQExpBuffer(query,
15369                                                           "SELECT attname, attacl, NULL as rattacl, "
15370                                                           "NULL AS initattacl, NULL AS initrattacl "
15371                                                           "FROM pg_catalog.pg_attribute "
15372                                                           "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15373                                                           "AND attacl IS NOT NULL "
15374                                                           "ORDER BY attnum",
15375                                                           tbinfo->dobj.catId.oid);
15376                 }
15377
15378                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15379
15380                 for (i = 0; i < PQntuples(res); i++)
15381                 {
15382                         char       *attname = PQgetvalue(res, i, 0);
15383                         char       *attacl = PQgetvalue(res, i, 1);
15384                         char       *rattacl = PQgetvalue(res, i, 2);
15385                         char       *initattacl = PQgetvalue(res, i, 3);
15386                         char       *initrattacl = PQgetvalue(res, i, 4);
15387                         char       *attnamecopy;
15388                         char       *acltag;
15389
15390                         attnamecopy = pg_strdup(fmtId(attname));
15391                         acltag = psprintf("COLUMN %s.%s", namecopy, attnamecopy);
15392                         /* Column's GRANT type is always TABLE */
15393                         dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
15394                                         namecopy, attnamecopy, acltag,
15395                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15396                                         attacl, rattacl, initattacl, initrattacl);
15397                         free(attnamecopy);
15398                         free(acltag);
15399                 }
15400                 PQclear(res);
15401                 destroyPQExpBuffer(query);
15402         }
15403
15404         free(namecopy);
15405
15406         return;
15407 }
15408
15409 /*
15410  * Create the AS clause for a view or materialized view. The semicolon is
15411  * stripped because a materialized view must add a WITH NO DATA clause.
15412  *
15413  * This returns a new buffer which must be freed by the caller.
15414  */
15415 static PQExpBuffer
15416 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15417 {
15418         PQExpBuffer query = createPQExpBuffer();
15419         PQExpBuffer result = createPQExpBuffer();
15420         PGresult   *res;
15421         int                     len;
15422
15423         /* Fetch the view definition */
15424         appendPQExpBuffer(query,
15425                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15426                                           tbinfo->dobj.catId.oid);
15427
15428         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15429
15430         if (PQntuples(res) != 1)
15431         {
15432                 if (PQntuples(res) < 1)
15433                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15434                                                   tbinfo->dobj.name);
15435                 else
15436                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15437                                                   tbinfo->dobj.name);
15438         }
15439
15440         len = PQgetlength(res, 0, 0);
15441
15442         if (len == 0)
15443                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15444                                           tbinfo->dobj.name);
15445
15446         /* Strip off the trailing semicolon so that other things may follow. */
15447         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15448         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15449
15450         PQclear(res);
15451         destroyPQExpBuffer(query);
15452
15453         return result;
15454 }
15455
15456 /*
15457  * Create a dummy AS clause for a view.  This is used when the real view
15458  * definition has to be postponed because of circular dependencies.
15459  * We must duplicate the view's external properties -- column names and types
15460  * (including collation) -- so that it works for subsequent references.
15461  *
15462  * This returns a new buffer which must be freed by the caller.
15463  */
15464 static PQExpBuffer
15465 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15466 {
15467         PQExpBuffer result = createPQExpBuffer();
15468         int                     j;
15469
15470         appendPQExpBufferStr(result, "SELECT");
15471
15472         for (j = 0; j < tbinfo->numatts; j++)
15473         {
15474                 if (j > 0)
15475                         appendPQExpBufferChar(result, ',');
15476                 appendPQExpBufferStr(result, "\n    ");
15477
15478                 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15479
15480                 /*
15481                  * Must add collation if not default for the type, because CREATE OR
15482                  * REPLACE VIEW won't change it
15483                  */
15484                 if (OidIsValid(tbinfo->attcollation[j]))
15485                 {
15486                         CollInfo   *coll;
15487
15488                         coll = findCollationByOid(tbinfo->attcollation[j]);
15489                         if (coll)
15490                         {
15491                                 /* always schema-qualify, don't try to be smart */
15492                                 appendPQExpBuffer(result, " COLLATE %s.",
15493                                                                   fmtId(coll->dobj.namespace->dobj.name));
15494                                 appendPQExpBufferStr(result, fmtId(coll->dobj.name));
15495                         }
15496                 }
15497
15498                 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15499         }
15500
15501         return result;
15502 }
15503
15504 /*
15505  * dumpTableSchema
15506  *        write the declaration (not data) of one user-defined table or view
15507  */
15508 static void
15509 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15510 {
15511         DumpOptions *dopt = fout->dopt;
15512         PQExpBuffer q = createPQExpBuffer();
15513         PQExpBuffer delq = createPQExpBuffer();
15514         PQExpBuffer labelq = createPQExpBuffer();
15515         int                     numParents;
15516         TableInfo **parents;
15517         int                     actual_atts;    /* number of attrs in this CREATE statement */
15518         const char *reltypename;
15519         char       *storage;
15520         char       *srvname;
15521         char       *ftoptions;
15522         int                     j,
15523                                 k;
15524
15525         /* Make sure we are in proper schema */
15526         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
15527
15528         if (dopt->binary_upgrade)
15529                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15530                                                                                                 tbinfo->dobj.catId.oid);
15531
15532         /* Is it a table or a view? */
15533         if (tbinfo->relkind == RELKIND_VIEW)
15534         {
15535                 PQExpBuffer result;
15536
15537                 /*
15538                  * Note: keep this code in sync with the is_view case in dumpRule()
15539                  */
15540
15541                 reltypename = "VIEW";
15542
15543                 /*
15544                  * DROP must be fully qualified in case same name appears in
15545                  * pg_catalog
15546                  */
15547                 appendPQExpBuffer(delq, "DROP VIEW %s.",
15548                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
15549                 appendPQExpBuffer(delq, "%s;\n",
15550                                                   fmtId(tbinfo->dobj.name));
15551
15552                 if (dopt->binary_upgrade)
15553                         binary_upgrade_set_pg_class_oids(fout, q,
15554                                                                                          tbinfo->dobj.catId.oid, false);
15555
15556                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
15557                 if (tbinfo->dummy_view)
15558                         result = createDummyViewAsClause(fout, tbinfo);
15559                 else
15560                 {
15561                         if (nonemptyReloptions(tbinfo->reloptions))
15562                         {
15563                                 appendPQExpBufferStr(q, " WITH (");
15564                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15565                                 appendPQExpBufferChar(q, ')');
15566                         }
15567                         result = createViewAsClause(fout, tbinfo);
15568                 }
15569                 appendPQExpBuffer(q, " AS\n%s", result->data);
15570                 destroyPQExpBuffer(result);
15571
15572                 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15573                         appendPQExpBuffer(q, "\n  WITH %s CHECK OPTION", tbinfo->checkoption);
15574                 appendPQExpBufferStr(q, ";\n");
15575
15576                 appendPQExpBuffer(labelq, "VIEW %s",
15577                                                   fmtId(tbinfo->dobj.name));
15578         }
15579         else
15580         {
15581                 switch (tbinfo->relkind)
15582                 {
15583                         case RELKIND_FOREIGN_TABLE:
15584                                 {
15585                                         PQExpBuffer query = createPQExpBuffer();
15586                                         PGresult   *res;
15587                                         int                     i_srvname;
15588                                         int                     i_ftoptions;
15589
15590                                         reltypename = "FOREIGN TABLE";
15591
15592                                         /* retrieve name of foreign server and generic options */
15593                                         appendPQExpBuffer(query,
15594                                                                           "SELECT fs.srvname, "
15595                                                                           "pg_catalog.array_to_string(ARRAY("
15596                                                                           "SELECT pg_catalog.quote_ident(option_name) || "
15597                                                                           "' ' || pg_catalog.quote_literal(option_value) "
15598                                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
15599                                                                           "ORDER BY option_name"
15600                                                                           "), E',\n    ') AS ftoptions "
15601                                                                           "FROM pg_catalog.pg_foreign_table ft "
15602                                                                           "JOIN pg_catalog.pg_foreign_server fs "
15603                                                                           "ON (fs.oid = ft.ftserver) "
15604                                                                           "WHERE ft.ftrelid = '%u'",
15605                                                                           tbinfo->dobj.catId.oid);
15606                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15607                                         i_srvname = PQfnumber(res, "srvname");
15608                                         i_ftoptions = PQfnumber(res, "ftoptions");
15609                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15610                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15611                                         PQclear(res);
15612                                         destroyPQExpBuffer(query);
15613                                         break;
15614                                 }
15615                         case RELKIND_MATVIEW:
15616                                 reltypename = "MATERIALIZED VIEW";
15617                                 srvname = NULL;
15618                                 ftoptions = NULL;
15619                                 break;
15620                         default:
15621                                 reltypename = "TABLE";
15622                                 srvname = NULL;
15623                                 ftoptions = NULL;
15624                 }
15625
15626                 numParents = tbinfo->numParents;
15627                 parents = tbinfo->parents;
15628
15629                 /*
15630                  * DROP must be fully qualified in case same name appears in
15631                  * pg_catalog
15632                  */
15633                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
15634                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
15635                 appendPQExpBuffer(delq, "%s;\n",
15636                                                   fmtId(tbinfo->dobj.name));
15637
15638                 appendPQExpBuffer(labelq, "%s %s", reltypename,
15639                                                   fmtId(tbinfo->dobj.name));
15640
15641                 if (dopt->binary_upgrade)
15642                         binary_upgrade_set_pg_class_oids(fout, q,
15643                                                                                          tbinfo->dobj.catId.oid, false);
15644
15645                 appendPQExpBuffer(q, "CREATE %s%s %s",
15646                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15647                                                   "UNLOGGED " : "",
15648                                                   reltypename,
15649                                                   fmtId(tbinfo->dobj.name));
15650
15651                 /*
15652                  * Attach to type, if reloftype; except in case of a binary upgrade,
15653                  * we dump the table normally and attach it to the type afterward.
15654                  */
15655                 if (tbinfo->reloftype && !dopt->binary_upgrade)
15656                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15657
15658                 /*
15659                  * If the table is a partition, dump it as such; except in the case of
15660                  * a binary upgrade, we dump the table normally and attach it to the
15661                  * parent afterward.
15662                  */
15663                 if (tbinfo->ispartition && !dopt->binary_upgrade)
15664                 {
15665                         TableInfo  *parentRel = tbinfo->parents[0];
15666
15667                         /*
15668                          * With partitions, unlike inheritance, there can only be one
15669                          * parent.
15670                          */
15671                         if (tbinfo->numParents != 1)
15672                                 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15673                                                           tbinfo->numParents, tbinfo->dobj.name);
15674
15675                         appendPQExpBuffer(q, " PARTITION OF ");
15676                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15677                                 appendPQExpBuffer(q, "%s.",
15678                                                                   fmtId(parentRel->dobj.namespace->dobj.name));
15679                         appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15680                 }
15681
15682                 if (tbinfo->relkind != RELKIND_MATVIEW)
15683                 {
15684                         /* Dump the attributes */
15685                         actual_atts = 0;
15686                         for (j = 0; j < tbinfo->numatts; j++)
15687                         {
15688                                 /*
15689                                  * Normally, dump if it's locally defined in this table, and
15690                                  * not dropped.  But for binary upgrade, we'll dump all the
15691                                  * columns, and then fix up the dropped and nonlocal cases
15692                                  * below.
15693                                  */
15694                                 if (shouldPrintColumn(dopt, tbinfo, j))
15695                                 {
15696                                         /*
15697                                          * Default value --- suppress if to be printed separately.
15698                                          */
15699                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
15700                                                                                            !tbinfo->attrdefs[j]->separate);
15701
15702                                         /*
15703                                          * Not Null constraint --- suppress if inherited, except
15704                                          * in binary-upgrade case where that won't work.
15705                                          */
15706                                         bool            has_notnull = (tbinfo->notnull[j] &&
15707                                                                                            (!tbinfo->inhNotNull[j] ||
15708                                                                                                 dopt->binary_upgrade));
15709
15710                                         /*
15711                                          * Skip column if fully defined by reloftype or the
15712                                          * partition parent.
15713                                          */
15714                                         if ((tbinfo->reloftype || tbinfo->ispartition) &&
15715                                                 !has_default && !has_notnull && !dopt->binary_upgrade)
15716                                                 continue;
15717
15718                                         /* Format properly if not first attr */
15719                                         if (actual_atts == 0)
15720                                                 appendPQExpBufferStr(q, " (");
15721                                         else
15722                                                 appendPQExpBufferChar(q, ',');
15723                                         appendPQExpBufferStr(q, "\n    ");
15724                                         actual_atts++;
15725
15726                                         /* Attribute name */
15727                                         appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15728
15729                                         if (tbinfo->attisdropped[j])
15730                                         {
15731                                                 /*
15732                                                  * ALTER TABLE DROP COLUMN clears
15733                                                  * pg_attribute.atttypid, so we will not have gotten a
15734                                                  * valid type name; insert INTEGER as a stopgap. We'll
15735                                                  * clean things up later.
15736                                                  */
15737                                                 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15738                                                 /* Skip all the rest, too */
15739                                                 continue;
15740                                         }
15741
15742                                         /*
15743                                          * Attribute type
15744                                          *
15745                                          * In binary-upgrade mode, we always include the type. If
15746                                          * we aren't in binary-upgrade mode, then we skip the type
15747                                          * when creating a typed table ('OF type_name') or a
15748                                          * partition ('PARTITION OF'), since the type comes from
15749                                          * the parent/partitioned table.
15750                                          */
15751                                         if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15752                                         {
15753                                                 appendPQExpBuffer(q, " %s",
15754                                                                                   tbinfo->atttypnames[j]);
15755                                         }
15756
15757                                         /* Add collation if not default for the type */
15758                                         if (OidIsValid(tbinfo->attcollation[j]))
15759                                         {
15760                                                 CollInfo   *coll;
15761
15762                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
15763                                                 if (coll)
15764                                                 {
15765                                                         /* always schema-qualify, don't try to be smart */
15766                                                         appendPQExpBuffer(q, " COLLATE %s.",
15767                                                                                           fmtId(coll->dobj.namespace->dobj.name));
15768                                                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
15769                                                 }
15770                                         }
15771
15772                                         if (has_default)
15773                                                 appendPQExpBuffer(q, " DEFAULT %s",
15774                                                                                   tbinfo->attrdefs[j]->adef_expr);
15775
15776                                         if (has_notnull)
15777                                                 appendPQExpBufferStr(q, " NOT NULL");
15778                                 }
15779                         }
15780
15781                         /*
15782                          * Add non-inherited CHECK constraints, if any.
15783                          */
15784                         for (j = 0; j < tbinfo->ncheck; j++)
15785                         {
15786                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15787
15788                                 if (constr->separate || !constr->conislocal)
15789                                         continue;
15790
15791                                 if (actual_atts == 0)
15792                                         appendPQExpBufferStr(q, " (\n    ");
15793                                 else
15794                                         appendPQExpBufferStr(q, ",\n    ");
15795
15796                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
15797                                                                   fmtId(constr->dobj.name));
15798                                 appendPQExpBufferStr(q, constr->condef);
15799
15800                                 actual_atts++;
15801                         }
15802
15803                         if (actual_atts)
15804                                 appendPQExpBufferStr(q, "\n)");
15805                         else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15806                                            !dopt->binary_upgrade))
15807                         {
15808                                 /*
15809                                  * We must have a parenthesized attribute list, even though
15810                                  * empty, when not using the OF TYPE or PARTITION OF syntax.
15811                                  */
15812                                 appendPQExpBufferStr(q, " (\n)");
15813                         }
15814
15815                         if (tbinfo->ispartition && !dopt->binary_upgrade)
15816                         {
15817                                 appendPQExpBufferChar(q, '\n');
15818                                 appendPQExpBufferStr(q, tbinfo->partbound);
15819                         }
15820
15821                         /* Emit the INHERITS clause, except if this is a partition. */
15822                         if (numParents > 0 &&
15823                                 !tbinfo->ispartition &&
15824                                 !dopt->binary_upgrade)
15825                         {
15826                                 appendPQExpBufferStr(q, "\nINHERITS (");
15827                                 for (k = 0; k < numParents; k++)
15828                                 {
15829                                         TableInfo  *parentRel = parents[k];
15830
15831                                         if (k > 0)
15832                                                 appendPQExpBufferStr(q, ", ");
15833                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15834                                                 appendPQExpBuffer(q, "%s.",
15835                                                                                   fmtId(parentRel->dobj.namespace->dobj.name));
15836                                         appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15837                                 }
15838                                 appendPQExpBufferChar(q, ')');
15839                         }
15840
15841                         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15842                                 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15843
15844                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15845                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15846                 }
15847
15848                 if (nonemptyReloptions(tbinfo->reloptions) ||
15849                         nonemptyReloptions(tbinfo->toast_reloptions))
15850                 {
15851                         bool            addcomma = false;
15852
15853                         appendPQExpBufferStr(q, "\nWITH (");
15854                         if (nonemptyReloptions(tbinfo->reloptions))
15855                         {
15856                                 addcomma = true;
15857                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15858                         }
15859                         if (nonemptyReloptions(tbinfo->toast_reloptions))
15860                         {
15861                                 if (addcomma)
15862                                         appendPQExpBufferStr(q, ", ");
15863                                 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15864                                                                                 fout);
15865                         }
15866                         appendPQExpBufferChar(q, ')');
15867                 }
15868
15869                 /* Dump generic options if any */
15870                 if (ftoptions && ftoptions[0])
15871                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
15872
15873                 /*
15874                  * For materialized views, create the AS clause just like a view. At
15875                  * this point, we always mark the view as not populated.
15876                  */
15877                 if (tbinfo->relkind == RELKIND_MATVIEW)
15878                 {
15879                         PQExpBuffer result;
15880
15881                         result = createViewAsClause(fout, tbinfo);
15882                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
15883                                                           result->data);
15884                         destroyPQExpBuffer(result);
15885                 }
15886                 else
15887                         appendPQExpBufferStr(q, ";\n");
15888
15889                 /*
15890                  * To create binary-compatible heap files, we have to ensure the same
15891                  * physical column order, including dropped columns, as in the
15892                  * original.  Therefore, we create dropped columns above and drop them
15893                  * here, also updating their attlen/attalign values so that the
15894                  * dropped column can be skipped properly.  (We do not bother with
15895                  * restoring the original attbyval setting.)  Also, inheritance
15896                  * relationships are set up by doing ALTER TABLE INHERIT rather than
15897                  * using an INHERITS clause --- the latter would possibly mess up the
15898                  * column order.  That also means we have to take care about setting
15899                  * attislocal correctly, plus fix up any inherited CHECK constraints.
15900                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
15901                  */
15902                 if (dopt->binary_upgrade &&
15903                         (tbinfo->relkind == RELKIND_RELATION ||
15904                          tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15905                          tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15906                 {
15907                         for (j = 0; j < tbinfo->numatts; j++)
15908                         {
15909                                 if (tbinfo->attisdropped[j])
15910                                 {
15911                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15912                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15913                                                                           "SET attlen = %d, "
15914                                                                           "attalign = '%c', attbyval = false\n"
15915                                                                           "WHERE attname = ",
15916                                                                           tbinfo->attlen[j],
15917                                                                           tbinfo->attalign[j]);
15918                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15919                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15920                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15921                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15922
15923                                         if (tbinfo->relkind == RELKIND_RELATION ||
15924                                                 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15925                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15926                                                                                   fmtId(tbinfo->dobj.name));
15927                                         else
15928                                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15929                                                                                   fmtId(tbinfo->dobj.name));
15930                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15931                                                                           fmtId(tbinfo->attnames[j]));
15932                                 }
15933                                 else if (!tbinfo->attislocal[j])
15934                                 {
15935                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15936                                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15937                                                                                  "SET attislocal = false\n"
15938                                                                                  "WHERE attname = ");
15939                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15940                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15941                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15942                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15943                                 }
15944                         }
15945
15946                         for (k = 0; k < tbinfo->ncheck; k++)
15947                         {
15948                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15949
15950                                 if (constr->separate || constr->conislocal)
15951                                         continue;
15952
15953                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15954                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15955                                                                   fmtId(tbinfo->dobj.name));
15956                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15957                                                                   fmtId(constr->dobj.name));
15958                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
15959                                 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15960                                                                          "SET conislocal = false\n"
15961                                                                          "WHERE contype = 'c' AND conname = ");
15962                                 appendStringLiteralAH(q, constr->dobj.name, fout);
15963                                 appendPQExpBufferStr(q, "\n  AND conrelid = ");
15964                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15965                                 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15966                         }
15967
15968                         if (numParents > 0)
15969                         {
15970                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15971                                 for (k = 0; k < numParents; k++)
15972                                 {
15973                                         TableInfo  *parentRel = parents[k];
15974                                         PQExpBuffer parentname = createPQExpBuffer();
15975
15976                                         /* Schema-qualify the parent table, if necessary */
15977                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15978                                                 appendPQExpBuffer(parentname, "%s.",
15979                                                                                   fmtId(parentRel->dobj.namespace->dobj.name));
15980
15981                                         appendPQExpBuffer(parentname, "%s",
15982                                                                           fmtId(parentRel->dobj.name));
15983
15984                                         /* In the partitioning case, we alter the parent */
15985                                         if (tbinfo->ispartition)
15986                                                 appendPQExpBuffer(q,
15987                                                                                   "ALTER TABLE ONLY %s ATTACH PARTITION ",
15988                                                                                   parentname->data);
15989                                         else
15990                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15991                                                                                   fmtId(tbinfo->dobj.name));
15992
15993                                         /* Partition needs specifying the bounds */
15994                                         if (tbinfo->ispartition)
15995                                                 appendPQExpBuffer(q, "%s %s;\n",
15996                                                                                   fmtId(tbinfo->dobj.name),
15997                                                                                   tbinfo->partbound);
15998                                         else
15999                                                 appendPQExpBuffer(q, "%s;\n", parentname->data);
16000
16001                                         destroyPQExpBuffer(parentname);
16002                                 }
16003                         }
16004
16005                         if (tbinfo->reloftype)
16006                         {
16007                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
16008                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
16009                                                                   fmtId(tbinfo->dobj.name),
16010                                                                   tbinfo->reloftype);
16011                         }
16012
16013                         appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
16014                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16015                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16016                                                           "WHERE oid = ",
16017                                                           tbinfo->frozenxid, tbinfo->minmxid);
16018                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
16019                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16020
16021                         if (tbinfo->toast_oid)
16022                         {
16023                                 /* We preserve the toast oids, so we can use it during restore */
16024                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
16025                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16026                                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16027                                                                   "WHERE oid = '%u';\n",
16028                                                                   tbinfo->toast_frozenxid,
16029                                                                   tbinfo->toast_minmxid, tbinfo->toast_oid);
16030                         }
16031                 }
16032
16033                 /*
16034                  * In binary_upgrade mode, restore matviews' populated status by
16035                  * poking pg_class directly.  This is pretty ugly, but we can't use
16036                  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
16037                  * matview is not populated even though this matview is.
16038                  */
16039                 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
16040                         tbinfo->relispopulated)
16041                 {
16042                         appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
16043                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
16044                                                                  "SET relispopulated = 't'\n"
16045                                                                  "WHERE oid = ");
16046                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
16047                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16048                 }
16049
16050                 /*
16051                  * Dump additional per-column properties that we can't handle in the
16052                  * main CREATE TABLE command.
16053                  */
16054                 for (j = 0; j < tbinfo->numatts; j++)
16055                 {
16056                         /* None of this applies to dropped columns */
16057                         if (tbinfo->attisdropped[j])
16058                                 continue;
16059
16060                         /*
16061                          * If we didn't dump the column definition explicitly above, and
16062                          * it is NOT NULL and did not inherit that property from a parent,
16063                          * we have to mark it separately.
16064                          */
16065                         if (!shouldPrintColumn(dopt, tbinfo, j) &&
16066                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
16067                         {
16068                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16069                                                                   fmtId(tbinfo->dobj.name));
16070                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
16071                                                                   fmtId(tbinfo->attnames[j]));
16072                         }
16073
16074                         /*
16075                          * Dump per-column statistics information. We only issue an ALTER
16076                          * TABLE statement if the attstattarget entry for this column is
16077                          * non-negative (i.e. it's not the default value)
16078                          */
16079                         if (tbinfo->attstattarget[j] >= 0)
16080                         {
16081                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16082                                                                   fmtId(tbinfo->dobj.name));
16083                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16084                                                                   fmtId(tbinfo->attnames[j]));
16085                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
16086                                                                   tbinfo->attstattarget[j]);
16087                         }
16088
16089                         /*
16090                          * Dump per-column storage information.  The statement is only
16091                          * dumped if the storage has been changed from the type's default.
16092                          */
16093                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
16094                         {
16095                                 switch (tbinfo->attstorage[j])
16096                                 {
16097                                         case 'p':
16098                                                 storage = "PLAIN";
16099                                                 break;
16100                                         case 'e':
16101                                                 storage = "EXTERNAL";
16102                                                 break;
16103                                         case 'm':
16104                                                 storage = "MAIN";
16105                                                 break;
16106                                         case 'x':
16107                                                 storage = "EXTENDED";
16108                                                 break;
16109                                         default:
16110                                                 storage = NULL;
16111                                 }
16112
16113                                 /*
16114                                  * Only dump the statement if it's a storage type we recognize
16115                                  */
16116                                 if (storage != NULL)
16117                                 {
16118                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16119                                                                           fmtId(tbinfo->dobj.name));
16120                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
16121                                                                           fmtId(tbinfo->attnames[j]));
16122                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
16123                                                                           storage);
16124                                 }
16125                         }
16126
16127                         /*
16128                          * Dump per-column attributes.
16129                          */
16130                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
16131                         {
16132                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16133                                                                   fmtId(tbinfo->dobj.name));
16134                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16135                                                                   fmtId(tbinfo->attnames[j]));
16136                                 appendPQExpBuffer(q, "SET (%s);\n",
16137                                                                   tbinfo->attoptions[j]);
16138                         }
16139
16140                         /*
16141                          * Dump per-column fdw options.
16142                          */
16143                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16144                                 tbinfo->attfdwoptions[j] &&
16145                                 tbinfo->attfdwoptions[j][0] != '\0')
16146                         {
16147                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16148                                                                   fmtId(tbinfo->dobj.name));
16149                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16150                                                                   fmtId(tbinfo->attnames[j]));
16151                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
16152                                                                   tbinfo->attfdwoptions[j]);
16153                         }
16154                 }
16155         }
16156
16157         /*
16158          * dump properties we only have ALTER TABLE syntax for
16159          */
16160         if ((tbinfo->relkind == RELKIND_RELATION ||
16161                  tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16162                  tbinfo->relkind == RELKIND_MATVIEW) &&
16163                 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16164         {
16165                 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16166                 {
16167                         /* nothing to do, will be set when the index is dumped */
16168                 }
16169                 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16170                 {
16171                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16172                                                           fmtId(tbinfo->dobj.name));
16173                 }
16174                 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16175                 {
16176                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16177                                                           fmtId(tbinfo->dobj.name));
16178                 }
16179         }
16180
16181         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
16182                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
16183                                                   fmtId(tbinfo->dobj.name));
16184
16185         if (tbinfo->forcerowsec)
16186                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16187                                                   fmtId(tbinfo->dobj.name));
16188
16189         if (dopt->binary_upgrade)
16190                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
16191
16192         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16193                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16194                                          tbinfo->dobj.name,
16195                                          tbinfo->dobj.namespace->dobj.name,
16196                                          (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16197                                          tbinfo->rolname,
16198                                          (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
16199                                          reltypename,
16200                                          tbinfo->postponed_def ?
16201                                          SECTION_POST_DATA : SECTION_PRE_DATA,
16202                                          q->data, delq->data, NULL,
16203                                          NULL, 0,
16204                                          NULL, NULL);
16205
16206
16207         /* Dump Table Comments */
16208         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16209                 dumpTableComment(fout, tbinfo, reltypename);
16210
16211         /* Dump Table Security Labels */
16212         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16213                 dumpTableSecLabel(fout, tbinfo, reltypename);
16214
16215         /* Dump comments on inlined table constraints */
16216         for (j = 0; j < tbinfo->ncheck; j++)
16217         {
16218                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16219
16220                 if (constr->separate || !constr->conislocal)
16221                         continue;
16222
16223                 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16224                         dumpTableConstraintComment(fout, constr);
16225         }
16226
16227         destroyPQExpBuffer(q);
16228         destroyPQExpBuffer(delq);
16229         destroyPQExpBuffer(labelq);
16230 }
16231
16232 /*
16233  * dumpAttrDef --- dump an attribute's default-value declaration
16234  */
16235 static void
16236 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16237 {
16238         DumpOptions *dopt = fout->dopt;
16239         TableInfo  *tbinfo = adinfo->adtable;
16240         int                     adnum = adinfo->adnum;
16241         PQExpBuffer q;
16242         PQExpBuffer delq;
16243         char       *tag;
16244
16245         /* Skip if table definition not to be dumped */
16246         if (!tbinfo->dobj.dump || dopt->dataOnly)
16247                 return;
16248
16249         /* Skip if not "separate"; it was dumped in the table's definition */
16250         if (!adinfo->separate)
16251                 return;
16252
16253         q = createPQExpBuffer();
16254         delq = createPQExpBuffer();
16255
16256         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16257                                           fmtId(tbinfo->dobj.name));
16258         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16259                                           fmtId(tbinfo->attnames[adnum - 1]),
16260                                           adinfo->adef_expr);
16261
16262         /*
16263          * DROP must be fully qualified in case same name appears in pg_catalog
16264          */
16265         appendPQExpBuffer(delq, "ALTER TABLE %s.",
16266                                           fmtId(tbinfo->dobj.namespace->dobj.name));
16267         appendPQExpBuffer(delq, "%s ",
16268                                           fmtId(tbinfo->dobj.name));
16269         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16270                                           fmtId(tbinfo->attnames[adnum - 1]));
16271
16272         tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16273
16274         if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16275                 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16276                                          tag,
16277                                          tbinfo->dobj.namespace->dobj.name,
16278                                          NULL,
16279                                          tbinfo->rolname,
16280                                          false, "DEFAULT", SECTION_PRE_DATA,
16281                                          q->data, delq->data, NULL,
16282                                          NULL, 0,
16283                                          NULL, NULL);
16284
16285         free(tag);
16286         destroyPQExpBuffer(q);
16287         destroyPQExpBuffer(delq);
16288 }
16289
16290 /*
16291  * getAttrName: extract the correct name for an attribute
16292  *
16293  * The array tblInfo->attnames[] only provides names of user attributes;
16294  * if a system attribute number is supplied, we have to fake it.
16295  * We also do a little bit of bounds checking for safety's sake.
16296  */
16297 static const char *
16298 getAttrName(int attrnum, TableInfo *tblInfo)
16299 {
16300         if (attrnum > 0 && attrnum <= tblInfo->numatts)
16301                 return tblInfo->attnames[attrnum - 1];
16302         switch (attrnum)
16303         {
16304                 case SelfItemPointerAttributeNumber:
16305                         return "ctid";
16306                 case ObjectIdAttributeNumber:
16307                         return "oid";
16308                 case MinTransactionIdAttributeNumber:
16309                         return "xmin";
16310                 case MinCommandIdAttributeNumber:
16311                         return "cmin";
16312                 case MaxTransactionIdAttributeNumber:
16313                         return "xmax";
16314                 case MaxCommandIdAttributeNumber:
16315                         return "cmax";
16316                 case TableOidAttributeNumber:
16317                         return "tableoid";
16318         }
16319         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16320                                   attrnum, tblInfo->dobj.name);
16321         return NULL;                            /* keep compiler quiet */
16322 }
16323
16324 /*
16325  * dumpIndex
16326  *        write out to fout a user-defined index
16327  */
16328 static void
16329 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16330 {
16331         DumpOptions *dopt = fout->dopt;
16332         TableInfo  *tbinfo = indxinfo->indextable;
16333         bool            is_constraint = (indxinfo->indexconstraint != 0);
16334         PQExpBuffer q;
16335         PQExpBuffer delq;
16336         PQExpBuffer labelq;
16337
16338         if (dopt->dataOnly)
16339                 return;
16340
16341         q = createPQExpBuffer();
16342         delq = createPQExpBuffer();
16343         labelq = createPQExpBuffer();
16344
16345         appendPQExpBuffer(labelq, "INDEX %s",
16346                                           fmtId(indxinfo->dobj.name));
16347
16348         /*
16349          * If there's an associated constraint, don't dump the index per se, but
16350          * do dump any comment for it.  (This is safe because dependency ordering
16351          * will have ensured the constraint is emitted first.)  Note that the
16352          * emitted comment has to be shown as depending on the constraint, not the
16353          * index, in such cases.
16354          */
16355         if (!is_constraint)
16356         {
16357                 if (dopt->binary_upgrade)
16358                         binary_upgrade_set_pg_class_oids(fout, q,
16359                                                                                          indxinfo->dobj.catId.oid, true);
16360
16361                 /* Plain secondary index */
16362                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16363
16364                 /* If the index is clustered, we need to record that. */
16365                 if (indxinfo->indisclustered)
16366                 {
16367                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16368                                                           fmtId(tbinfo->dobj.name));
16369                         appendPQExpBuffer(q, " ON %s;\n",
16370                                                           fmtId(indxinfo->dobj.name));
16371                 }
16372
16373                 /* If the index defines identity, we need to record that. */
16374                 if (indxinfo->indisreplident)
16375                 {
16376                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16377                                                           fmtId(tbinfo->dobj.name));
16378                         appendPQExpBuffer(q, " INDEX %s;\n",
16379                                                           fmtId(indxinfo->dobj.name));
16380                 }
16381
16382                 /*
16383                  * DROP must be fully qualified in case same name appears in
16384                  * pg_catalog
16385                  */
16386                 appendPQExpBuffer(delq, "DROP INDEX %s.",
16387                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16388                 appendPQExpBuffer(delq, "%s;\n",
16389                                                   fmtId(indxinfo->dobj.name));
16390
16391                 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16392                         ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16393                                                  indxinfo->dobj.name,
16394                                                  tbinfo->dobj.namespace->dobj.name,
16395                                                  indxinfo->tablespace,
16396                                                  tbinfo->rolname, false,
16397                                                  "INDEX", SECTION_POST_DATA,
16398                                                  q->data, delq->data, NULL,
16399                                                  NULL, 0,
16400                                                  NULL, NULL);
16401         }
16402
16403         /* Dump Index Comments */
16404         if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16405                 dumpComment(fout, labelq->data,
16406                                         tbinfo->dobj.namespace->dobj.name,
16407                                         tbinfo->rolname,
16408                                         indxinfo->dobj.catId, 0,
16409                                         is_constraint ? indxinfo->indexconstraint :
16410                                         indxinfo->dobj.dumpId);
16411
16412         destroyPQExpBuffer(q);
16413         destroyPQExpBuffer(delq);
16414         destroyPQExpBuffer(labelq);
16415 }
16416
16417 /*
16418  * dumpIndexAttach
16419  *        write out to fout a partitioned-index attachment clause
16420  */
16421 static void
16422 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16423 {
16424         if (fout->dopt->dataOnly)
16425                 return;
16426
16427         if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16428         {
16429                 PQExpBuffer q = createPQExpBuffer();
16430
16431                 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16432                                                   fmtQualifiedId(fout->remoteVersion,
16433                                                                                  attachinfo->parentIdx->dobj.namespace->dobj.name,
16434                                                                                  attachinfo->parentIdx->dobj.name));
16435                 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16436                                                   fmtQualifiedId(fout->remoteVersion,
16437                                                                                  attachinfo->partitionIdx->dobj.namespace->dobj.name,
16438                                                                                  attachinfo->partitionIdx->dobj.name));
16439
16440                 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16441                                          attachinfo->dobj.name,
16442                                          NULL, NULL,
16443                                          "",
16444                                          false, "INDEX ATTACH", SECTION_POST_DATA,
16445                                          q->data, "", NULL,
16446                                          NULL, 0,
16447                                          NULL, NULL);
16448
16449                 destroyPQExpBuffer(q);
16450         }
16451 }
16452
16453 /*
16454  * dumpStatisticsExt
16455  *        write out to fout an extended statistics object
16456  */
16457 static void
16458 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16459 {
16460         DumpOptions *dopt = fout->dopt;
16461         PQExpBuffer q;
16462         PQExpBuffer delq;
16463         PQExpBuffer labelq;
16464         PQExpBuffer query;
16465         PGresult   *res;
16466         char       *stxdef;
16467
16468         /* Skip if not to be dumped */
16469         if (!statsextinfo->dobj.dump || dopt->dataOnly)
16470                 return;
16471
16472         q = createPQExpBuffer();
16473         delq = createPQExpBuffer();
16474         labelq = createPQExpBuffer();
16475         query = createPQExpBuffer();
16476
16477         /* Make sure we are in proper schema so references are qualified */
16478         selectSourceSchema(fout, statsextinfo->dobj.namespace->dobj.name);
16479
16480         appendPQExpBuffer(query, "SELECT "
16481                                           "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16482                                           statsextinfo->dobj.catId.oid);
16483
16484         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16485
16486         stxdef = PQgetvalue(res, 0, 0);
16487
16488         appendPQExpBuffer(labelq, "STATISTICS %s",
16489                                           fmtId(statsextinfo->dobj.name));
16490
16491         /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16492         appendPQExpBuffer(q, "%s;\n", stxdef);
16493
16494         appendPQExpBuffer(delq, "DROP STATISTICS %s.",
16495                                           fmtId(statsextinfo->dobj.namespace->dobj.name));
16496         appendPQExpBuffer(delq, "%s;\n",
16497                                           fmtId(statsextinfo->dobj.name));
16498
16499         if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16500                 ArchiveEntry(fout, statsextinfo->dobj.catId,
16501                                          statsextinfo->dobj.dumpId,
16502                                          statsextinfo->dobj.name,
16503                                          statsextinfo->dobj.namespace->dobj.name,
16504                                          NULL,
16505                                          statsextinfo->rolname, false,
16506                                          "STATISTICS", SECTION_POST_DATA,
16507                                          q->data, delq->data, NULL,
16508                                          NULL, 0,
16509                                          NULL, NULL);
16510
16511         /* Dump Statistics Comments */
16512         if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16513                 dumpComment(fout, labelq->data,
16514                                         statsextinfo->dobj.namespace->dobj.name,
16515                                         statsextinfo->rolname,
16516                                         statsextinfo->dobj.catId, 0,
16517                                         statsextinfo->dobj.dumpId);
16518
16519         PQclear(res);
16520         destroyPQExpBuffer(q);
16521         destroyPQExpBuffer(delq);
16522         destroyPQExpBuffer(labelq);
16523         destroyPQExpBuffer(query);
16524 }
16525
16526 /*
16527  * dumpConstraint
16528  *        write out to fout a user-defined constraint
16529  */
16530 static void
16531 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16532 {
16533         DumpOptions *dopt = fout->dopt;
16534         TableInfo  *tbinfo = coninfo->contable;
16535         PQExpBuffer q;
16536         PQExpBuffer delq;
16537         char       *tag = NULL;
16538
16539         /* Skip if not to be dumped */
16540         if (!coninfo->dobj.dump || dopt->dataOnly)
16541                 return;
16542
16543         q = createPQExpBuffer();
16544         delq = createPQExpBuffer();
16545
16546         if (coninfo->contype == 'p' ||
16547                 coninfo->contype == 'u' ||
16548                 coninfo->contype == 'x')
16549         {
16550                 /* Index-related constraint */
16551                 IndxInfo   *indxinfo;
16552                 int                     k;
16553
16554                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16555
16556                 if (indxinfo == NULL)
16557                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16558                                                   coninfo->dobj.name);
16559
16560                 if (dopt->binary_upgrade)
16561                         binary_upgrade_set_pg_class_oids(fout, q,
16562                                                                                          indxinfo->dobj.catId.oid, true);
16563
16564                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16565                                                   fmtId(tbinfo->dobj.name));
16566                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
16567                                                   fmtId(coninfo->dobj.name));
16568
16569                 if (coninfo->condef)
16570                 {
16571                         /* pg_get_constraintdef should have provided everything */
16572                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16573                 }
16574                 else
16575                 {
16576                         appendPQExpBuffer(q, "%s (",
16577                                                           coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16578                         for (k = 0; k < indxinfo->indnkeys; k++)
16579                         {
16580                                 int                     indkey = (int) indxinfo->indkeys[k];
16581                                 const char *attname;
16582
16583                                 if (indkey == InvalidAttrNumber)
16584                                         break;
16585                                 attname = getAttrName(indkey, tbinfo);
16586
16587                                 appendPQExpBuffer(q, "%s%s",
16588                                                                   (k == 0) ? "" : ", ",
16589                                                                   fmtId(attname));
16590                         }
16591
16592                         appendPQExpBufferChar(q, ')');
16593
16594                         if (nonemptyReloptions(indxinfo->indreloptions))
16595                         {
16596                                 appendPQExpBufferStr(q, " WITH (");
16597                                 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16598                                 appendPQExpBufferChar(q, ')');
16599                         }
16600
16601                         if (coninfo->condeferrable)
16602                         {
16603                                 appendPQExpBufferStr(q, " DEFERRABLE");
16604                                 if (coninfo->condeferred)
16605                                         appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16606                         }
16607
16608                         appendPQExpBufferStr(q, ";\n");
16609                 }
16610
16611                 /* If the index is clustered, we need to record that. */
16612                 if (indxinfo->indisclustered)
16613                 {
16614                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16615                                                           fmtId(tbinfo->dobj.name));
16616                         appendPQExpBuffer(q, " ON %s;\n",
16617                                                           fmtId(indxinfo->dobj.name));
16618                 }
16619
16620                 /*
16621                  * DROP must be fully qualified in case same name appears in
16622                  * pg_catalog
16623                  */
16624                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16625                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16626                 appendPQExpBuffer(delq, "%s ",
16627                                                   fmtId(tbinfo->dobj.name));
16628                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16629                                                   fmtId(coninfo->dobj.name));
16630
16631                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16632
16633                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16634                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16635                                                  tag,
16636                                                  tbinfo->dobj.namespace->dobj.name,
16637                                                  indxinfo->tablespace,
16638                                                  tbinfo->rolname, false,
16639                                                  "CONSTRAINT", SECTION_POST_DATA,
16640                                                  q->data, delq->data, NULL,
16641                                                  NULL, 0,
16642                                                  NULL, NULL);
16643         }
16644         else if (coninfo->contype == 'f')
16645         {
16646                 /*
16647                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16648                  * current table data is not processed
16649                  */
16650                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16651                                                   fmtId(tbinfo->dobj.name));
16652                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16653                                                   fmtId(coninfo->dobj.name),
16654                                                   coninfo->condef);
16655
16656                 /*
16657                  * DROP must be fully qualified in case same name appears in
16658                  * pg_catalog
16659                  */
16660                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16661                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16662                 appendPQExpBuffer(delq, "%s ",
16663                                                   fmtId(tbinfo->dobj.name));
16664                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16665                                                   fmtId(coninfo->dobj.name));
16666
16667                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16668
16669                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16670                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16671                                                  tag,
16672                                                  tbinfo->dobj.namespace->dobj.name,
16673                                                  NULL,
16674                                                  tbinfo->rolname, false,
16675                                                  "FK CONSTRAINT", SECTION_POST_DATA,
16676                                                  q->data, delq->data, NULL,
16677                                                  NULL, 0,
16678                                                  NULL, NULL);
16679         }
16680         else if (coninfo->contype == 'c' && tbinfo)
16681         {
16682                 /* CHECK constraint on a table */
16683
16684                 /* Ignore if not to be dumped separately, or if it was inherited */
16685                 if (coninfo->separate && coninfo->conislocal)
16686                 {
16687                         /* not ONLY since we want it to propagate to children */
16688                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
16689                                                           fmtId(tbinfo->dobj.name));
16690                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16691                                                           fmtId(coninfo->dobj.name),
16692                                                           coninfo->condef);
16693
16694                         /*
16695                          * DROP must be fully qualified in case same name appears in
16696                          * pg_catalog
16697                          */
16698                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
16699                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
16700                         appendPQExpBuffer(delq, "%s ",
16701                                                           fmtId(tbinfo->dobj.name));
16702                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16703                                                           fmtId(coninfo->dobj.name));
16704
16705                         tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16706
16707                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16708                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16709                                                          tag,
16710                                                          tbinfo->dobj.namespace->dobj.name,
16711                                                          NULL,
16712                                                          tbinfo->rolname, false,
16713                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16714                                                          q->data, delq->data, NULL,
16715                                                          NULL, 0,
16716                                                          NULL, NULL);
16717                 }
16718         }
16719         else if (coninfo->contype == 'c' && tbinfo == NULL)
16720         {
16721                 /* CHECK constraint on a domain */
16722                 TypeInfo   *tyinfo = coninfo->condomain;
16723
16724                 /* Ignore if not to be dumped separately */
16725                 if (coninfo->separate)
16726                 {
16727                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16728                                                           fmtId(tyinfo->dobj.name));
16729                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16730                                                           fmtId(coninfo->dobj.name),
16731                                                           coninfo->condef);
16732
16733                         /*
16734                          * DROP must be fully qualified in case same name appears in
16735                          * pg_catalog
16736                          */
16737                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
16738                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
16739                         appendPQExpBuffer(delq, "%s ",
16740                                                           fmtId(tyinfo->dobj.name));
16741                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16742                                                           fmtId(coninfo->dobj.name));
16743
16744                         tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16745
16746                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16747                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16748                                                          tag,
16749                                                          tyinfo->dobj.namespace->dobj.name,
16750                                                          NULL,
16751                                                          tyinfo->rolname, false,
16752                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16753                                                          q->data, delq->data, NULL,
16754                                                          NULL, 0,
16755                                                          NULL, NULL);
16756                 }
16757         }
16758         else
16759         {
16760                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16761                                           coninfo->contype);
16762         }
16763
16764         /* Dump Constraint Comments --- only works for table constraints */
16765         if (tbinfo && coninfo->separate &&
16766                 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16767                 dumpTableConstraintComment(fout, coninfo);
16768
16769         free(tag);
16770         destroyPQExpBuffer(q);
16771         destroyPQExpBuffer(delq);
16772 }
16773
16774 /*
16775  * dumpTableConstraintComment --- dump a constraint's comment if any
16776  *
16777  * This is split out because we need the function in two different places
16778  * depending on whether the constraint is dumped as part of CREATE TABLE
16779  * or as a separate ALTER command.
16780  */
16781 static void
16782 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16783 {
16784         TableInfo  *tbinfo = coninfo->contable;
16785         PQExpBuffer labelq = createPQExpBuffer();
16786
16787         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
16788                                           fmtId(coninfo->dobj.name));
16789         appendPQExpBuffer(labelq, "ON %s",
16790                                           fmtId(tbinfo->dobj.name));
16791
16792         if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16793                 dumpComment(fout, labelq->data,
16794                                         tbinfo->dobj.namespace->dobj.name,
16795                                         tbinfo->rolname,
16796                                         coninfo->dobj.catId, 0,
16797                                         coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16798
16799         destroyPQExpBuffer(labelq);
16800 }
16801
16802 /*
16803  * findLastBuiltinOid_V71 -
16804  *
16805  * find the last built in oid
16806  *
16807  * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16808  * pg_database entry for the current database.
16809  */
16810 static Oid
16811 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
16812 {
16813         PGresult   *res;
16814         Oid                     last_oid;
16815         PQExpBuffer query = createPQExpBuffer();
16816
16817         resetPQExpBuffer(query);
16818         appendPQExpBufferStr(query, "SELECT datlastsysoid from pg_database where datname = ");
16819         appendStringLiteralAH(query, dbname, fout);
16820
16821         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16822         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16823         PQclear(res);
16824         destroyPQExpBuffer(query);
16825
16826         return last_oid;
16827 }
16828
16829 /*
16830  * dumpSequence
16831  *        write the declaration (not data) of one user-defined sequence
16832  */
16833 static void
16834 dumpSequence(Archive *fout, TableInfo *tbinfo)
16835 {
16836         DumpOptions *dopt = fout->dopt;
16837         PGresult   *res;
16838         char       *startv,
16839                            *incby,
16840                            *maxv,
16841                            *minv,
16842                            *cache,
16843                            *seqtype;
16844         bool            cycled;
16845         bool            is_ascending;
16846         int64           default_minv,
16847                                 default_maxv;
16848         char            bufm[32],
16849                                 bufx[32];
16850         PQExpBuffer query = createPQExpBuffer();
16851         PQExpBuffer delqry = createPQExpBuffer();
16852         PQExpBuffer labelq = createPQExpBuffer();
16853
16854         if (fout->remoteVersion >= 100000)
16855         {
16856                 /* Make sure we are in proper schema */
16857                 selectSourceSchema(fout, "pg_catalog");
16858
16859                 appendPQExpBuffer(query,
16860                                                   "SELECT format_type(seqtypid, NULL), "
16861                                                   "seqstart, seqincrement, "
16862                                                   "seqmax, seqmin, "
16863                                                   "seqcache, seqcycle "
16864                                                   "FROM pg_class c "
16865                                                   "JOIN pg_sequence s ON (s.seqrelid = c.oid) "
16866                                                   "WHERE c.oid = '%u'::oid",
16867                                                   tbinfo->dobj.catId.oid);
16868         }
16869         else if (fout->remoteVersion >= 80400)
16870         {
16871                 /*
16872                  * Before PostgreSQL 10, sequence metadata is in the sequence itself,
16873                  * so switch to the sequence's schema instead of pg_catalog.
16874                  *
16875                  * Note: it might seem that 'bigint' potentially needs to be
16876                  * schema-qualified, but actually that's a keyword.
16877                  */
16878
16879                 /* Make sure we are in proper schema */
16880                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16881
16882                 appendPQExpBuffer(query,
16883                                                   "SELECT 'bigint' AS sequence_type, "
16884                                                   "start_value, increment_by, max_value, min_value, "
16885                                                   "cache_value, is_cycled FROM %s",
16886                                                   fmtId(tbinfo->dobj.name));
16887         }
16888         else
16889         {
16890                 /* Make sure we are in proper schema */
16891                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16892
16893                 appendPQExpBuffer(query,
16894                                                   "SELECT 'bigint' AS sequence_type, "
16895                                                   "0 AS start_value, increment_by, max_value, min_value, "
16896                                                   "cache_value, is_cycled FROM %s",
16897                                                   fmtId(tbinfo->dobj.name));
16898         }
16899
16900         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16901
16902         if (PQntuples(res) != 1)
16903         {
16904                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16905                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16906                                                                  PQntuples(res)),
16907                                   tbinfo->dobj.name, PQntuples(res));
16908                 exit_nicely(1);
16909         }
16910
16911         seqtype = PQgetvalue(res, 0, 0);
16912         startv = PQgetvalue(res, 0, 1);
16913         incby = PQgetvalue(res, 0, 2);
16914         maxv = PQgetvalue(res, 0, 3);
16915         minv = PQgetvalue(res, 0, 4);
16916         cache = PQgetvalue(res, 0, 5);
16917         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16918
16919         /* Calculate default limits for a sequence of this type */
16920         is_ascending = (incby[0] != '-');
16921         if (strcmp(seqtype, "smallint") == 0)
16922         {
16923                 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16924                 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16925         }
16926         else if (strcmp(seqtype, "integer") == 0)
16927         {
16928                 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16929                 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16930         }
16931         else if (strcmp(seqtype, "bigint") == 0)
16932         {
16933                 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16934                 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16935         }
16936         else
16937         {
16938                 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16939                 default_minv = default_maxv = 0;        /* keep compiler quiet */
16940         }
16941
16942         /*
16943          * 64-bit strtol() isn't very portable, so convert the limits to strings
16944          * and compare that way.
16945          */
16946         snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16947         snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16948
16949         /* Don't print minv/maxv if they match the respective default limit */
16950         if (strcmp(minv, bufm) == 0)
16951                 minv = NULL;
16952         if (strcmp(maxv, bufx) == 0)
16953                 maxv = NULL;
16954
16955         /*
16956          * DROP must be fully qualified in case same name appears in pg_catalog
16957          */
16958         if (!tbinfo->is_identity_sequence)
16959         {
16960                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
16961                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16962                 appendPQExpBuffer(delqry, "%s;\n",
16963                                                   fmtId(tbinfo->dobj.name));
16964         }
16965
16966         resetPQExpBuffer(query);
16967
16968         if (dopt->binary_upgrade)
16969         {
16970                 binary_upgrade_set_pg_class_oids(fout, query,
16971                                                                                  tbinfo->dobj.catId.oid, false);
16972                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16973                                                                                                 tbinfo->dobj.catId.oid);
16974         }
16975
16976         if (tbinfo->is_identity_sequence)
16977         {
16978                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16979
16980                 appendPQExpBuffer(query,
16981                                                   "ALTER TABLE %s ",
16982                                                   fmtId(owning_tab->dobj.name));
16983                 appendPQExpBuffer(query,
16984                                                   "ALTER COLUMN %s ADD GENERATED ",
16985                                                   fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16986                 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16987                         appendPQExpBuffer(query, "ALWAYS");
16988                 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16989                         appendPQExpBuffer(query, "BY DEFAULT");
16990                 appendPQExpBuffer(query, " AS IDENTITY (\n    SEQUENCE NAME %s\n",
16991                                                   fmtId(tbinfo->dobj.name));
16992         }
16993         else
16994         {
16995                 appendPQExpBuffer(query,
16996                                                   "CREATE SEQUENCE %s\n",
16997                                                   fmtId(tbinfo->dobj.name));
16998
16999                 if (strcmp(seqtype, "bigint") != 0)
17000                         appendPQExpBuffer(query, "    AS %s\n", seqtype);
17001         }
17002
17003         if (fout->remoteVersion >= 80400)
17004                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
17005
17006         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
17007
17008         if (minv)
17009                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
17010         else
17011                 appendPQExpBufferStr(query, "    NO MINVALUE\n");
17012
17013         if (maxv)
17014                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
17015         else
17016                 appendPQExpBufferStr(query, "    NO MAXVALUE\n");
17017
17018         appendPQExpBuffer(query,
17019                                           "    CACHE %s%s",
17020                                           cache, (cycled ? "\n    CYCLE" : ""));
17021
17022         if (tbinfo->is_identity_sequence)
17023                 appendPQExpBufferStr(query, "\n);\n");
17024         else
17025                 appendPQExpBufferStr(query, ";\n");
17026
17027         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
17028
17029         /* binary_upgrade:      no need to clear TOAST table oid */
17030
17031         if (dopt->binary_upgrade)
17032                 binary_upgrade_extension_member(query, &tbinfo->dobj,
17033                                                                                 labelq->data);
17034
17035         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17036                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
17037                                          tbinfo->dobj.name,
17038                                          tbinfo->dobj.namespace->dobj.name,
17039                                          NULL,
17040                                          tbinfo->rolname,
17041                                          false, "SEQUENCE", SECTION_PRE_DATA,
17042                                          query->data, delqry->data, NULL,
17043                                          NULL, 0,
17044                                          NULL, NULL);
17045
17046         /*
17047          * If the sequence is owned by a table column, emit the ALTER for it as a
17048          * separate TOC entry immediately following the sequence's own entry. It's
17049          * OK to do this rather than using full sorting logic, because the
17050          * dependency that tells us it's owned will have forced the table to be
17051          * created first.  We can't just include the ALTER in the TOC entry
17052          * because it will fail if we haven't reassigned the sequence owner to
17053          * match the table's owner.
17054          *
17055          * We need not schema-qualify the table reference because both sequence
17056          * and table must be in the same schema.
17057          */
17058         if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
17059         {
17060                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
17061
17062                 if (owning_tab == NULL)
17063                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
17064                                                   tbinfo->owning_tab, tbinfo->dobj.catId.oid);
17065
17066                 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
17067                 {
17068                         resetPQExpBuffer(query);
17069                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
17070                                                           fmtId(tbinfo->dobj.name));
17071                         appendPQExpBuffer(query, " OWNED BY %s",
17072                                                           fmtId(owning_tab->dobj.name));
17073                         appendPQExpBuffer(query, ".%s;\n",
17074                                                           fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17075
17076                         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17077                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17078                                                          tbinfo->dobj.name,
17079                                                          tbinfo->dobj.namespace->dobj.name,
17080                                                          NULL,
17081                                                          tbinfo->rolname,
17082                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
17083                                                          query->data, "", NULL,
17084                                                          &(tbinfo->dobj.dumpId), 1,
17085                                                          NULL, NULL);
17086                 }
17087         }
17088
17089         /* Dump Sequence Comments and Security Labels */
17090         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17091                 dumpComment(fout, labelq->data,
17092                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17093                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17094
17095         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
17096                 dumpSecLabel(fout, labelq->data,
17097                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17098                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17099
17100         PQclear(res);
17101
17102         destroyPQExpBuffer(query);
17103         destroyPQExpBuffer(delqry);
17104         destroyPQExpBuffer(labelq);
17105 }
17106
17107 /*
17108  * dumpSequenceData
17109  *        write the data of one user-defined sequence
17110  */
17111 static void
17112 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
17113 {
17114         TableInfo  *tbinfo = tdinfo->tdtable;
17115         PGresult   *res;
17116         char       *last;
17117         bool            called;
17118         PQExpBuffer query = createPQExpBuffer();
17119
17120         /* Make sure we are in proper schema */
17121         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
17122
17123         appendPQExpBuffer(query,
17124                                           "SELECT last_value, is_called FROM %s",
17125                                           fmtId(tbinfo->dobj.name));
17126
17127         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17128
17129         if (PQntuples(res) != 1)
17130         {
17131                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
17132                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
17133                                                                  PQntuples(res)),
17134                                   tbinfo->dobj.name, PQntuples(res));
17135                 exit_nicely(1);
17136         }
17137
17138         last = PQgetvalue(res, 0, 0);
17139         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17140
17141         resetPQExpBuffer(query);
17142         appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17143         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
17144         appendPQExpBuffer(query, ", %s, %s);\n",
17145                                           last, (called ? "true" : "false"));
17146
17147         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17148                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17149                                          tbinfo->dobj.name,
17150                                          tbinfo->dobj.namespace->dobj.name,
17151                                          NULL,
17152                                          tbinfo->rolname,
17153                                          false, "SEQUENCE SET", SECTION_DATA,
17154                                          query->data, "", NULL,
17155                                          &(tbinfo->dobj.dumpId), 1,
17156                                          NULL, NULL);
17157
17158         PQclear(res);
17159
17160         destroyPQExpBuffer(query);
17161 }
17162
17163 /*
17164  * dumpTrigger
17165  *        write the declaration of one user-defined table trigger
17166  */
17167 static void
17168 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17169 {
17170         DumpOptions *dopt = fout->dopt;
17171         TableInfo  *tbinfo = tginfo->tgtable;
17172         PQExpBuffer query;
17173         PQExpBuffer delqry;
17174         PQExpBuffer labelq;
17175         char       *tgargs;
17176         size_t          lentgargs;
17177         const char *p;
17178         int                     findx;
17179         char       *tag;
17180
17181         /*
17182          * we needn't check dobj.dump because TriggerInfo wouldn't have been
17183          * created in the first place for non-dumpable triggers
17184          */
17185         if (dopt->dataOnly)
17186                 return;
17187
17188         query = createPQExpBuffer();
17189         delqry = createPQExpBuffer();
17190         labelq = createPQExpBuffer();
17191
17192         /*
17193          * DROP must be fully qualified in case same name appears in pg_catalog
17194          */
17195         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17196                                           fmtId(tginfo->dobj.name));
17197         appendPQExpBuffer(delqry, "ON %s.",
17198                                           fmtId(tbinfo->dobj.namespace->dobj.name));
17199         appendPQExpBuffer(delqry, "%s;\n",
17200                                           fmtId(tbinfo->dobj.name));
17201
17202         if (tginfo->tgdef)
17203         {
17204                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17205         }
17206         else
17207         {
17208                 if (tginfo->tgisconstraint)
17209                 {
17210                         appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17211                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17212                 }
17213                 else
17214                 {
17215                         appendPQExpBufferStr(query, "CREATE TRIGGER ");
17216                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17217                 }
17218                 appendPQExpBufferStr(query, "\n    ");
17219
17220                 /* Trigger type */
17221                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17222                         appendPQExpBufferStr(query, "BEFORE");
17223                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17224                         appendPQExpBufferStr(query, "AFTER");
17225                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17226                         appendPQExpBufferStr(query, "INSTEAD OF");
17227                 else
17228                 {
17229                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17230                         exit_nicely(1);
17231                 }
17232
17233                 findx = 0;
17234                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17235                 {
17236                         appendPQExpBufferStr(query, " INSERT");
17237                         findx++;
17238                 }
17239                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17240                 {
17241                         if (findx > 0)
17242                                 appendPQExpBufferStr(query, " OR DELETE");
17243                         else
17244                                 appendPQExpBufferStr(query, " DELETE");
17245                         findx++;
17246                 }
17247                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17248                 {
17249                         if (findx > 0)
17250                                 appendPQExpBufferStr(query, " OR UPDATE");
17251                         else
17252                                 appendPQExpBufferStr(query, " UPDATE");
17253                         findx++;
17254                 }
17255                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17256                 {
17257                         if (findx > 0)
17258                                 appendPQExpBufferStr(query, " OR TRUNCATE");
17259                         else
17260                                 appendPQExpBufferStr(query, " TRUNCATE");
17261                         findx++;
17262                 }
17263                 appendPQExpBuffer(query, " ON %s\n",
17264                                                   fmtId(tbinfo->dobj.name));
17265
17266                 if (tginfo->tgisconstraint)
17267                 {
17268                         if (OidIsValid(tginfo->tgconstrrelid))
17269                         {
17270                                 /* regclass output is already quoted */
17271                                 appendPQExpBuffer(query, "    FROM %s\n    ",
17272                                                                   tginfo->tgconstrrelname);
17273                         }
17274                         if (!tginfo->tgdeferrable)
17275                                 appendPQExpBufferStr(query, "NOT ");
17276                         appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17277                         if (tginfo->tginitdeferred)
17278                                 appendPQExpBufferStr(query, "DEFERRED\n");
17279                         else
17280                                 appendPQExpBufferStr(query, "IMMEDIATE\n");
17281                 }
17282
17283                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17284                         appendPQExpBufferStr(query, "    FOR EACH ROW\n    ");
17285                 else
17286                         appendPQExpBufferStr(query, "    FOR EACH STATEMENT\n    ");
17287
17288                 /* regproc output is already sufficiently quoted */
17289                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17290                                                   tginfo->tgfname);
17291
17292                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17293                                                                                   &lentgargs);
17294                 p = tgargs;
17295                 for (findx = 0; findx < tginfo->tgnargs; findx++)
17296                 {
17297                         /* find the embedded null that terminates this trigger argument */
17298                         size_t          tlen = strlen(p);
17299
17300                         if (p + tlen >= tgargs + lentgargs)
17301                         {
17302                                 /* hm, not found before end of bytea value... */
17303                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17304                                                   tginfo->tgargs,
17305                                                   tginfo->dobj.name,
17306                                                   tbinfo->dobj.name);
17307                                 exit_nicely(1);
17308                         }
17309
17310                         if (findx > 0)
17311                                 appendPQExpBufferStr(query, ", ");
17312                         appendStringLiteralAH(query, p, fout);
17313                         p += tlen + 1;
17314                 }
17315                 free(tgargs);
17316                 appendPQExpBufferStr(query, ");\n");
17317         }
17318
17319         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17320         {
17321                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17322                                                   fmtId(tbinfo->dobj.name));
17323                 switch (tginfo->tgenabled)
17324                 {
17325                         case 'D':
17326                         case 'f':
17327                                 appendPQExpBufferStr(query, "DISABLE");
17328                                 break;
17329                         case 'A':
17330                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17331                                 break;
17332                         case 'R':
17333                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17334                                 break;
17335                         default:
17336                                 appendPQExpBufferStr(query, "ENABLE");
17337                                 break;
17338                 }
17339                 appendPQExpBuffer(query, " TRIGGER %s;\n",
17340                                                   fmtId(tginfo->dobj.name));
17341         }
17342
17343         appendPQExpBuffer(labelq, "TRIGGER %s ",
17344                                           fmtId(tginfo->dobj.name));
17345         appendPQExpBuffer(labelq, "ON %s",
17346                                           fmtId(tbinfo->dobj.name));
17347
17348         tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17349
17350         if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17351                 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17352                                          tag,
17353                                          tbinfo->dobj.namespace->dobj.name,
17354                                          NULL,
17355                                          tbinfo->rolname, false,
17356                                          "TRIGGER", SECTION_POST_DATA,
17357                                          query->data, delqry->data, NULL,
17358                                          NULL, 0,
17359                                          NULL, NULL);
17360
17361         if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17362                 dumpComment(fout, labelq->data,
17363                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17364                                         tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17365
17366         free(tag);
17367         destroyPQExpBuffer(query);
17368         destroyPQExpBuffer(delqry);
17369         destroyPQExpBuffer(labelq);
17370 }
17371
17372 /*
17373  * dumpEventTrigger
17374  *        write the declaration of one user-defined event trigger
17375  */
17376 static void
17377 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17378 {
17379         DumpOptions *dopt = fout->dopt;
17380         PQExpBuffer query;
17381         PQExpBuffer delqry;
17382         PQExpBuffer labelq;
17383
17384         /* Skip if not to be dumped */
17385         if (!evtinfo->dobj.dump || dopt->dataOnly)
17386                 return;
17387
17388         query = createPQExpBuffer();
17389         delqry = createPQExpBuffer();
17390         labelq = createPQExpBuffer();
17391
17392         appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17393         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
17394         appendPQExpBufferStr(query, " ON ");
17395         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17396
17397         if (strcmp("", evtinfo->evttags) != 0)
17398         {
17399                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
17400                 appendPQExpBufferStr(query, evtinfo->evttags);
17401                 appendPQExpBufferChar(query, ')');
17402         }
17403
17404         appendPQExpBufferStr(query, "\n   EXECUTE PROCEDURE ");
17405         appendPQExpBufferStr(query, evtinfo->evtfname);
17406         appendPQExpBufferStr(query, "();\n");
17407
17408         if (evtinfo->evtenabled != 'O')
17409         {
17410                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17411                                                   fmtId(evtinfo->dobj.name));
17412                 switch (evtinfo->evtenabled)
17413                 {
17414                         case 'D':
17415                                 appendPQExpBufferStr(query, "DISABLE");
17416                                 break;
17417                         case 'A':
17418                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17419                                 break;
17420                         case 'R':
17421                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17422                                 break;
17423                         default:
17424                                 appendPQExpBufferStr(query, "ENABLE");
17425                                 break;
17426                 }
17427                 appendPQExpBufferStr(query, ";\n");
17428         }
17429
17430         appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17431                                           fmtId(evtinfo->dobj.name));
17432
17433         appendPQExpBuffer(labelq, "EVENT TRIGGER %s",
17434                                           fmtId(evtinfo->dobj.name));
17435
17436         if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17437                 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17438                                          evtinfo->dobj.name, NULL, NULL,
17439                                          evtinfo->evtowner, false,
17440                                          "EVENT TRIGGER", SECTION_POST_DATA,
17441                                          query->data, delqry->data, NULL,
17442                                          NULL, 0,
17443                                          NULL, NULL);
17444
17445         if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17446                 dumpComment(fout, labelq->data,
17447                                         NULL, evtinfo->evtowner,
17448                                         evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17449
17450         destroyPQExpBuffer(query);
17451         destroyPQExpBuffer(delqry);
17452         destroyPQExpBuffer(labelq);
17453 }
17454
17455 /*
17456  * dumpRule
17457  *              Dump a rule
17458  */
17459 static void
17460 dumpRule(Archive *fout, RuleInfo *rinfo)
17461 {
17462         DumpOptions *dopt = fout->dopt;
17463         TableInfo  *tbinfo = rinfo->ruletable;
17464         bool            is_view;
17465         PQExpBuffer query;
17466         PQExpBuffer cmd;
17467         PQExpBuffer delcmd;
17468         PQExpBuffer labelq;
17469         PGresult   *res;
17470         char       *tag;
17471
17472         /* Skip if not to be dumped */
17473         if (!rinfo->dobj.dump || dopt->dataOnly)
17474                 return;
17475
17476         /*
17477          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17478          * we do not want to dump it as a separate object.
17479          */
17480         if (!rinfo->separate)
17481                 return;
17482
17483         /*
17484          * If it's an ON SELECT rule, we want to print it as a view definition,
17485          * instead of a rule.
17486          */
17487         is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17488
17489         /*
17490          * Make sure we are in proper schema.
17491          */
17492         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
17493
17494         query = createPQExpBuffer();
17495         cmd = createPQExpBuffer();
17496         delcmd = createPQExpBuffer();
17497         labelq = createPQExpBuffer();
17498
17499         if (is_view)
17500         {
17501                 PQExpBuffer result;
17502
17503                 /*
17504                  * We need OR REPLACE here because we'll be replacing a dummy view.
17505                  * Otherwise this should look largely like the regular view dump code.
17506                  */
17507                 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17508                                                   fmtId(tbinfo->dobj.name));
17509                 if (nonemptyReloptions(tbinfo->reloptions))
17510                 {
17511                         appendPQExpBufferStr(cmd, " WITH (");
17512                         appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17513                         appendPQExpBufferChar(cmd, ')');
17514                 }
17515                 result = createViewAsClause(fout, tbinfo);
17516                 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17517                 destroyPQExpBuffer(result);
17518                 if (tbinfo->checkoption != NULL)
17519                         appendPQExpBuffer(cmd, "\n  WITH %s CHECK OPTION",
17520                                                           tbinfo->checkoption);
17521                 appendPQExpBufferStr(cmd, ";\n");
17522         }
17523         else
17524         {
17525                 /* In the rule case, just print pg_get_ruledef's result verbatim */
17526                 appendPQExpBuffer(query,
17527                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17528                                                   rinfo->dobj.catId.oid);
17529
17530                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17531
17532                 if (PQntuples(res) != 1)
17533                 {
17534                         write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17535                                           rinfo->dobj.name, tbinfo->dobj.name);
17536                         exit_nicely(1);
17537                 }
17538
17539                 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17540
17541                 PQclear(res);
17542         }
17543
17544         /*
17545          * Add the command to alter the rules replication firing semantics if it
17546          * differs from the default.
17547          */
17548         if (rinfo->ev_enabled != 'O')
17549         {
17550                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
17551                 switch (rinfo->ev_enabled)
17552                 {
17553                         case 'A':
17554                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17555                                                                   fmtId(rinfo->dobj.name));
17556                                 break;
17557                         case 'R':
17558                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17559                                                                   fmtId(rinfo->dobj.name));
17560                                 break;
17561                         case 'D':
17562                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17563                                                                   fmtId(rinfo->dobj.name));
17564                                 break;
17565                 }
17566         }
17567
17568         /*
17569          * DROP must be fully qualified in case same name appears in pg_catalog
17570          */
17571         if (is_view)
17572         {
17573                 /*
17574                  * We can't DROP a view's ON SELECT rule.  Instead, use CREATE OR
17575                  * REPLACE VIEW to replace the rule with something with minimal
17576                  * dependencies.
17577                  */
17578                 PQExpBuffer result;
17579
17580                 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s.",
17581                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
17582                 appendPQExpBufferStr(delcmd, fmtId(tbinfo->dobj.name));
17583                 result = createDummyViewAsClause(fout, tbinfo);
17584                 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17585                 destroyPQExpBuffer(result);
17586         }
17587         else
17588         {
17589                 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17590                                                   fmtId(rinfo->dobj.name));
17591                 appendPQExpBuffer(delcmd, "ON %s.",
17592                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
17593                 appendPQExpBuffer(delcmd, "%s;\n",
17594                                                   fmtId(tbinfo->dobj.name));
17595         }
17596
17597         appendPQExpBuffer(labelq, "RULE %s",
17598                                           fmtId(rinfo->dobj.name));
17599         appendPQExpBuffer(labelq, " ON %s",
17600                                           fmtId(tbinfo->dobj.name));
17601
17602         tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17603
17604         if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17605                 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17606                                          tag,
17607                                          tbinfo->dobj.namespace->dobj.name,
17608                                          NULL,
17609                                          tbinfo->rolname, false,
17610                                          "RULE", SECTION_POST_DATA,
17611                                          cmd->data, delcmd->data, NULL,
17612                                          NULL, 0,
17613                                          NULL, NULL);
17614
17615         /* Dump rule comments */
17616         if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17617                 dumpComment(fout, labelq->data,
17618                                         tbinfo->dobj.namespace->dobj.name,
17619                                         tbinfo->rolname,
17620                                         rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17621
17622         free(tag);
17623         destroyPQExpBuffer(query);
17624         destroyPQExpBuffer(cmd);
17625         destroyPQExpBuffer(delcmd);
17626         destroyPQExpBuffer(labelq);
17627 }
17628
17629 /*
17630  * getExtensionMembership --- obtain extension membership data
17631  *
17632  * We need to identify objects that are extension members as soon as they're
17633  * loaded, so that we can correctly determine whether they need to be dumped.
17634  * Generally speaking, extension member objects will get marked as *not* to
17635  * be dumped, as they will be recreated by the single CREATE EXTENSION
17636  * command.  However, in binary upgrade mode we still need to dump the members
17637  * individually.
17638  */
17639 void
17640 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17641                                            int numExtensions)
17642 {
17643         PQExpBuffer query;
17644         PGresult   *res;
17645         int                     ntups,
17646                                 nextmembers,
17647                                 i;
17648         int                     i_classid,
17649                                 i_objid,
17650                                 i_refobjid;
17651         ExtensionMemberId *extmembers;
17652         ExtensionInfo *ext;
17653
17654         /* Nothing to do if no extensions */
17655         if (numExtensions == 0)
17656                 return;
17657
17658         /* Make sure we are in proper schema */
17659         selectSourceSchema(fout, "pg_catalog");
17660
17661         query = createPQExpBuffer();
17662
17663         /* refclassid constraint is redundant but may speed the search */
17664         appendPQExpBufferStr(query, "SELECT "
17665                                                  "classid, objid, refobjid "
17666                                                  "FROM pg_depend "
17667                                                  "WHERE refclassid = 'pg_extension'::regclass "
17668                                                  "AND deptype = 'e' "
17669                                                  "ORDER BY 3");
17670
17671         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17672
17673         ntups = PQntuples(res);
17674
17675         i_classid = PQfnumber(res, "classid");
17676         i_objid = PQfnumber(res, "objid");
17677         i_refobjid = PQfnumber(res, "refobjid");
17678
17679         extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17680         nextmembers = 0;
17681
17682         /*
17683          * Accumulate data into extmembers[].
17684          *
17685          * Since we ordered the SELECT by referenced ID, we can expect that
17686          * multiple entries for the same extension will appear together; this
17687          * saves on searches.
17688          */
17689         ext = NULL;
17690
17691         for (i = 0; i < ntups; i++)
17692         {
17693                 CatalogId       objId;
17694                 Oid                     extId;
17695
17696                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17697                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17698                 extId = atooid(PQgetvalue(res, i, i_refobjid));
17699
17700                 if (ext == NULL ||
17701                         ext->dobj.catId.oid != extId)
17702                         ext = findExtensionByOid(extId);
17703
17704                 if (ext == NULL)
17705                 {
17706                         /* shouldn't happen */
17707                         fprintf(stderr, "could not find referenced extension %u\n", extId);
17708                         continue;
17709                 }
17710
17711                 extmembers[nextmembers].catId = objId;
17712                 extmembers[nextmembers].ext = ext;
17713                 nextmembers++;
17714         }
17715
17716         PQclear(res);
17717
17718         /* Remember the data for use later */
17719         setExtensionMembership(extmembers, nextmembers);
17720
17721         destroyPQExpBuffer(query);
17722 }
17723
17724 /*
17725  * processExtensionTables --- deal with extension configuration tables
17726  *
17727  * There are two parts to this process:
17728  *
17729  * 1. Identify and create dump records for extension configuration tables.
17730  *
17731  *        Extensions can mark tables as "configuration", which means that the user
17732  *        is able and expected to modify those tables after the extension has been
17733  *        loaded.  For these tables, we dump out only the data- the structure is
17734  *        expected to be handled at CREATE EXTENSION time, including any indexes or
17735  *        foreign keys, which brings us to-
17736  *
17737  * 2. Record FK dependencies between configuration tables.
17738  *
17739  *        Due to the FKs being created at CREATE EXTENSION time and therefore before
17740  *        the data is loaded, we have to work out what the best order for reloading
17741  *        the data is, to avoid FK violations when the tables are restored.  This is
17742  *        not perfect- we can't handle circular dependencies and if any exist they
17743  *        will cause an invalid dump to be produced (though at least all of the data
17744  *        is included for a user to manually restore).  This is currently documented
17745  *        but perhaps we can provide a better solution in the future.
17746  */
17747 void
17748 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17749                                            int numExtensions)
17750 {
17751         DumpOptions *dopt = fout->dopt;
17752         PQExpBuffer query;
17753         PGresult   *res;
17754         int                     ntups,
17755                                 i;
17756         int                     i_conrelid,
17757                                 i_confrelid;
17758
17759         /* Nothing to do if no extensions */
17760         if (numExtensions == 0)
17761                 return;
17762
17763         /*
17764          * Identify extension configuration tables and create TableDataInfo
17765          * objects for them, ensuring their data will be dumped even though the
17766          * tables themselves won't be.
17767          *
17768          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17769          * user data in a configuration table is treated like schema data. This
17770          * seems appropriate since system data in a config table would get
17771          * reloaded by CREATE EXTENSION.
17772          */
17773         for (i = 0; i < numExtensions; i++)
17774         {
17775                 ExtensionInfo *curext = &(extinfo[i]);
17776                 char       *extconfig = curext->extconfig;
17777                 char       *extcondition = curext->extcondition;
17778                 char      **extconfigarray = NULL;
17779                 char      **extconditionarray = NULL;
17780                 int                     nconfigitems;
17781                 int                     nconditionitems;
17782
17783                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17784                         parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17785                         nconfigitems == nconditionitems)
17786                 {
17787                         int                     j;
17788
17789                         for (j = 0; j < nconfigitems; j++)
17790                         {
17791                                 TableInfo  *configtbl;
17792                                 Oid                     configtbloid = atooid(extconfigarray[j]);
17793                                 bool            dumpobj =
17794                                 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17795
17796                                 configtbl = findTableByOid(configtbloid);
17797                                 if (configtbl == NULL)
17798                                         continue;
17799
17800                                 /*
17801                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
17802                                  * unless the table or its schema is explicitly included
17803                                  */
17804                                 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17805                                 {
17806                                         /* check table explicitly requested */
17807                                         if (table_include_oids.head != NULL &&
17808                                                 simple_oid_list_member(&table_include_oids,
17809                                                                                            configtbloid))
17810                                                 dumpobj = true;
17811
17812                                         /* check table's schema explicitly requested */
17813                                         if (configtbl->dobj.namespace->dobj.dump &
17814                                                 DUMP_COMPONENT_DATA)
17815                                                 dumpobj = true;
17816                                 }
17817
17818                                 /* check table excluded by an exclusion switch */
17819                                 if (table_exclude_oids.head != NULL &&
17820                                         simple_oid_list_member(&table_exclude_oids,
17821                                                                                    configtbloid))
17822                                         dumpobj = false;
17823
17824                                 /* check schema excluded by an exclusion switch */
17825                                 if (simple_oid_list_member(&schema_exclude_oids,
17826                                                                                    configtbl->dobj.namespace->dobj.catId.oid))
17827                                         dumpobj = false;
17828
17829                                 if (dumpobj)
17830                                 {
17831                                         /*
17832                                          * Note: config tables are dumped without OIDs regardless
17833                                          * of the --oids setting.  This is because row filtering
17834                                          * conditions aren't compatible with dumping OIDs.
17835                                          */
17836                                         makeTableDataInfo(dopt, configtbl, false);
17837                                         if (configtbl->dataObj != NULL)
17838                                         {
17839                                                 if (strlen(extconditionarray[j]) > 0)
17840                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17841                                         }
17842                                 }
17843                         }
17844                 }
17845                 if (extconfigarray)
17846                         free(extconfigarray);
17847                 if (extconditionarray)
17848                         free(extconditionarray);
17849         }
17850
17851         /*
17852          * Now that all the TableInfoData objects have been created for all the
17853          * extensions, check their FK dependencies and register them to try and
17854          * dump the data out in an order that they can be restored in.
17855          *
17856          * Note that this is not a problem for user tables as their FKs are
17857          * recreated after the data has been loaded.
17858          */
17859
17860         /* Make sure we are in proper schema */
17861         selectSourceSchema(fout, "pg_catalog");
17862
17863         query = createPQExpBuffer();
17864
17865         printfPQExpBuffer(query,
17866                                           "SELECT conrelid, confrelid "
17867                                           "FROM pg_constraint "
17868                                           "JOIN pg_depend ON (objid = confrelid) "
17869                                           "WHERE contype = 'f' "
17870                                           "AND refclassid = 'pg_extension'::regclass "
17871                                           "AND classid = 'pg_class'::regclass;");
17872
17873         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17874         ntups = PQntuples(res);
17875
17876         i_conrelid = PQfnumber(res, "conrelid");
17877         i_confrelid = PQfnumber(res, "confrelid");
17878
17879         /* Now get the dependencies and register them */
17880         for (i = 0; i < ntups; i++)
17881         {
17882                 Oid                     conrelid,
17883                                         confrelid;
17884                 TableInfo  *reftable,
17885                                    *contable;
17886
17887                 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17888                 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17889                 contable = findTableByOid(conrelid);
17890                 reftable = findTableByOid(confrelid);
17891
17892                 if (reftable == NULL ||
17893                         reftable->dataObj == NULL ||
17894                         contable == NULL ||
17895                         contable->dataObj == NULL)
17896                         continue;
17897
17898                 /*
17899                  * Make referencing TABLE_DATA object depend on the referenced table's
17900                  * TABLE_DATA object.
17901                  */
17902                 addObjectDependency(&contable->dataObj->dobj,
17903                                                         reftable->dataObj->dobj.dumpId);
17904         }
17905         PQclear(res);
17906         destroyPQExpBuffer(query);
17907 }
17908
17909 /*
17910  * getDependencies --- obtain available dependency data
17911  */
17912 static void
17913 getDependencies(Archive *fout)
17914 {
17915         PQExpBuffer query;
17916         PGresult   *res;
17917         int                     ntups,
17918                                 i;
17919         int                     i_classid,
17920                                 i_objid,
17921                                 i_refclassid,
17922                                 i_refobjid,
17923                                 i_deptype;
17924         DumpableObject *dobj,
17925                            *refdobj;
17926
17927         if (g_verbose)
17928                 write_msg(NULL, "reading dependency data\n");
17929
17930         /* Make sure we are in proper schema */
17931         selectSourceSchema(fout, "pg_catalog");
17932
17933         query = createPQExpBuffer();
17934
17935         /*
17936          * PIN dependencies aren't interesting, and EXTENSION dependencies were
17937          * already processed by getExtensionMembership.
17938          */
17939         appendPQExpBufferStr(query, "SELECT "
17940                                                  "classid, objid, refclassid, refobjid, deptype "
17941                                                  "FROM pg_depend "
17942                                                  "WHERE deptype != 'p' AND deptype != 'e' "
17943                                                  "ORDER BY 1,2");
17944
17945         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17946
17947         ntups = PQntuples(res);
17948
17949         i_classid = PQfnumber(res, "classid");
17950         i_objid = PQfnumber(res, "objid");
17951         i_refclassid = PQfnumber(res, "refclassid");
17952         i_refobjid = PQfnumber(res, "refobjid");
17953         i_deptype = PQfnumber(res, "deptype");
17954
17955         /*
17956          * Since we ordered the SELECT by referencing ID, we can expect that
17957          * multiple entries for the same object will appear together; this saves
17958          * on searches.
17959          */
17960         dobj = NULL;
17961
17962         for (i = 0; i < ntups; i++)
17963         {
17964                 CatalogId       objId;
17965                 CatalogId       refobjId;
17966                 char            deptype;
17967
17968                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17969                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17970                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17971                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17972                 deptype = *(PQgetvalue(res, i, i_deptype));
17973
17974                 if (dobj == NULL ||
17975                         dobj->catId.tableoid != objId.tableoid ||
17976                         dobj->catId.oid != objId.oid)
17977                         dobj = findObjectByCatalogId(objId);
17978
17979                 /*
17980                  * Failure to find objects mentioned in pg_depend is not unexpected,
17981                  * since for example we don't collect info about TOAST tables.
17982                  */
17983                 if (dobj == NULL)
17984                 {
17985 #ifdef NOT_USED
17986                         fprintf(stderr, "no referencing object %u %u\n",
17987                                         objId.tableoid, objId.oid);
17988 #endif
17989                         continue;
17990                 }
17991
17992                 refdobj = findObjectByCatalogId(refobjId);
17993
17994                 if (refdobj == NULL)
17995                 {
17996 #ifdef NOT_USED
17997                         fprintf(stderr, "no referenced object %u %u\n",
17998                                         refobjId.tableoid, refobjId.oid);
17999 #endif
18000                         continue;
18001                 }
18002
18003                 /*
18004                  * Ordinarily, table rowtypes have implicit dependencies on their
18005                  * tables.  However, for a composite type the implicit dependency goes
18006                  * the other way in pg_depend; which is the right thing for DROP but
18007                  * it doesn't produce the dependency ordering we need. So in that one
18008                  * case, we reverse the direction of the dependency.
18009                  */
18010                 if (deptype == 'i' &&
18011                         dobj->objType == DO_TABLE &&
18012                         refdobj->objType == DO_TYPE)
18013                         addObjectDependency(refdobj, dobj->dumpId);
18014                 else
18015                         /* normal case */
18016                         addObjectDependency(dobj, refdobj->dumpId);
18017         }
18018
18019         PQclear(res);
18020
18021         destroyPQExpBuffer(query);
18022 }
18023
18024
18025 /*
18026  * createBoundaryObjects - create dummy DumpableObjects to represent
18027  * dump section boundaries.
18028  */
18029 static DumpableObject *
18030 createBoundaryObjects(void)
18031 {
18032         DumpableObject *dobjs;
18033
18034         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
18035
18036         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
18037         dobjs[0].catId = nilCatalogId;
18038         AssignDumpId(dobjs + 0);
18039         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
18040
18041         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
18042         dobjs[1].catId = nilCatalogId;
18043         AssignDumpId(dobjs + 1);
18044         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
18045
18046         return dobjs;
18047 }
18048
18049 /*
18050  * addBoundaryDependencies - add dependencies as needed to enforce the dump
18051  * section boundaries.
18052  */
18053 static void
18054 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
18055                                                 DumpableObject *boundaryObjs)
18056 {
18057         DumpableObject *preDataBound = boundaryObjs + 0;
18058         DumpableObject *postDataBound = boundaryObjs + 1;
18059         int                     i;
18060
18061         for (i = 0; i < numObjs; i++)
18062         {
18063                 DumpableObject *dobj = dobjs[i];
18064
18065                 /*
18066                  * The classification of object types here must match the SECTION_xxx
18067                  * values assigned during subsequent ArchiveEntry calls!
18068                  */
18069                 switch (dobj->objType)
18070                 {
18071                         case DO_NAMESPACE:
18072                         case DO_EXTENSION:
18073                         case DO_TYPE:
18074                         case DO_SHELL_TYPE:
18075                         case DO_FUNC:
18076                         case DO_AGG:
18077                         case DO_OPERATOR:
18078                         case DO_ACCESS_METHOD:
18079                         case DO_OPCLASS:
18080                         case DO_OPFAMILY:
18081                         case DO_COLLATION:
18082                         case DO_CONVERSION:
18083                         case DO_TABLE:
18084                         case DO_ATTRDEF:
18085                         case DO_PROCLANG:
18086                         case DO_CAST:
18087                         case DO_DUMMY_TYPE:
18088                         case DO_TSPARSER:
18089                         case DO_TSDICT:
18090                         case DO_TSTEMPLATE:
18091                         case DO_TSCONFIG:
18092                         case DO_FDW:
18093                         case DO_FOREIGN_SERVER:
18094                         case DO_TRANSFORM:
18095                         case DO_BLOB:
18096                                 /* Pre-data objects: must come before the pre-data boundary */
18097                                 addObjectDependency(preDataBound, dobj->dumpId);
18098                                 break;
18099                         case DO_TABLE_DATA:
18100                         case DO_SEQUENCE_SET:
18101                         case DO_BLOB_DATA:
18102                                 /* Data objects: must come between the boundaries */
18103                                 addObjectDependency(dobj, preDataBound->dumpId);
18104                                 addObjectDependency(postDataBound, dobj->dumpId);
18105                                 break;
18106                         case DO_INDEX:
18107                         case DO_INDEX_ATTACH:
18108                         case DO_STATSEXT:
18109                         case DO_REFRESH_MATVIEW:
18110                         case DO_TRIGGER:
18111                         case DO_EVENT_TRIGGER:
18112                         case DO_DEFAULT_ACL:
18113                         case DO_POLICY:
18114                         case DO_PUBLICATION:
18115                         case DO_PUBLICATION_REL:
18116                         case DO_SUBSCRIPTION:
18117                                 /* Post-data objects: must come after the post-data boundary */
18118                                 addObjectDependency(dobj, postDataBound->dumpId);
18119                                 break;
18120                         case DO_RULE:
18121                                 /* Rules are post-data, but only if dumped separately */
18122                                 if (((RuleInfo *) dobj)->separate)
18123                                         addObjectDependency(dobj, postDataBound->dumpId);
18124                                 break;
18125                         case DO_CONSTRAINT:
18126                         case DO_FK_CONSTRAINT:
18127                                 /* Constraints are post-data, but only if dumped separately */
18128                                 if (((ConstraintInfo *) dobj)->separate)
18129                                         addObjectDependency(dobj, postDataBound->dumpId);
18130                                 break;
18131                         case DO_PRE_DATA_BOUNDARY:
18132                                 /* nothing to do */
18133                                 break;
18134                         case DO_POST_DATA_BOUNDARY:
18135                                 /* must come after the pre-data boundary */
18136                                 addObjectDependency(dobj, preDataBound->dumpId);
18137                                 break;
18138                 }
18139         }
18140 }
18141
18142
18143 /*
18144  * BuildArchiveDependencies - create dependency data for archive TOC entries
18145  *
18146  * The raw dependency data obtained by getDependencies() is not terribly
18147  * useful in an archive dump, because in many cases there are dependency
18148  * chains linking through objects that don't appear explicitly in the dump.
18149  * For example, a view will depend on its _RETURN rule while the _RETURN rule
18150  * will depend on other objects --- but the rule will not appear as a separate
18151  * object in the dump.  We need to adjust the view's dependencies to include
18152  * whatever the rule depends on that is included in the dump.
18153  *
18154  * Just to make things more complicated, there are also "special" dependencies
18155  * such as the dependency of a TABLE DATA item on its TABLE, which we must
18156  * not rearrange because pg_restore knows that TABLE DATA only depends on
18157  * its table.  In these cases we must leave the dependencies strictly as-is
18158  * even if they refer to not-to-be-dumped objects.
18159  *
18160  * To handle this, the convention is that "special" dependencies are created
18161  * during ArchiveEntry calls, and an archive TOC item that has any such
18162  * entries will not be touched here.  Otherwise, we recursively search the
18163  * DumpableObject data structures to build the correct dependencies for each
18164  * archive TOC item.
18165  */
18166 static void
18167 BuildArchiveDependencies(Archive *fout)
18168 {
18169         ArchiveHandle *AH = (ArchiveHandle *) fout;
18170         TocEntry   *te;
18171
18172         /* Scan all TOC entries in the archive */
18173         for (te = AH->toc->next; te != AH->toc; te = te->next)
18174         {
18175                 DumpableObject *dobj;
18176                 DumpId     *dependencies;
18177                 int                     nDeps;
18178                 int                     allocDeps;
18179
18180                 /* No need to process entries that will not be dumped */
18181                 if (te->reqs == 0)
18182                         continue;
18183                 /* Ignore entries that already have "special" dependencies */
18184                 if (te->nDeps > 0)
18185                         continue;
18186                 /* Otherwise, look up the item's original DumpableObject, if any */
18187                 dobj = findObjectByDumpId(te->dumpId);
18188                 if (dobj == NULL)
18189                         continue;
18190                 /* No work if it has no dependencies */
18191                 if (dobj->nDeps <= 0)
18192                         continue;
18193                 /* Set up work array */
18194                 allocDeps = 64;
18195                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18196                 nDeps = 0;
18197                 /* Recursively find all dumpable dependencies */
18198                 findDumpableDependencies(AH, dobj,
18199                                                                  &dependencies, &nDeps, &allocDeps);
18200                 /* And save 'em ... */
18201                 if (nDeps > 0)
18202                 {
18203                         dependencies = (DumpId *) pg_realloc(dependencies,
18204                                                                                                  nDeps * sizeof(DumpId));
18205                         te->dependencies = dependencies;
18206                         te->nDeps = nDeps;
18207                 }
18208                 else
18209                         free(dependencies);
18210         }
18211 }
18212
18213 /* Recursive search subroutine for BuildArchiveDependencies */
18214 static void
18215 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18216                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
18217 {
18218         int                     i;
18219
18220         /*
18221          * Ignore section boundary objects: if we search through them, we'll
18222          * report lots of bogus dependencies.
18223          */
18224         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18225                 dobj->objType == DO_POST_DATA_BOUNDARY)
18226                 return;
18227
18228         for (i = 0; i < dobj->nDeps; i++)
18229         {
18230                 DumpId          depid = dobj->dependencies[i];
18231
18232                 if (TocIDRequired(AH, depid) != 0)
18233                 {
18234                         /* Object will be dumped, so just reference it as a dependency */
18235                         if (*nDeps >= *allocDeps)
18236                         {
18237                                 *allocDeps *= 2;
18238                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
18239                                                                                                           *allocDeps * sizeof(DumpId));
18240                         }
18241                         (*dependencies)[*nDeps] = depid;
18242                         (*nDeps)++;
18243                 }
18244                 else
18245                 {
18246                         /*
18247                          * Object will not be dumped, so recursively consider its deps. We
18248                          * rely on the assumption that sortDumpableObjects already broke
18249                          * any dependency loops, else we might recurse infinitely.
18250                          */
18251                         DumpableObject *otherdobj = findObjectByDumpId(depid);
18252
18253                         if (otherdobj)
18254                                 findDumpableDependencies(AH, otherdobj,
18255                                                                                  dependencies, nDeps, allocDeps);
18256                 }
18257         }
18258 }
18259
18260
18261 /*
18262  * selectSourceSchema - make the specified schema the active search path
18263  * in the source database.
18264  *
18265  * NB: pg_catalog is explicitly searched after the specified schema;
18266  * so user names are only qualified if they are cross-schema references,
18267  * and system names are only qualified if they conflict with a user name
18268  * in the current schema.
18269  *
18270  * Whenever the selected schema is not pg_catalog, be careful to qualify
18271  * references to system catalogs and types in our emitted commands!
18272  *
18273  * This function is called only from selectSourceSchemaOnAH and
18274  * selectSourceSchema.
18275  */
18276 static void
18277 selectSourceSchema(Archive *fout, const char *schemaName)
18278 {
18279         PQExpBuffer query;
18280
18281         /* This is checked by the callers already */
18282         Assert(schemaName != NULL && *schemaName != '\0');
18283
18284         query = createPQExpBuffer();
18285         appendPQExpBuffer(query, "SET search_path = %s",
18286                                           fmtId(schemaName));
18287         if (strcmp(schemaName, "pg_catalog") != 0)
18288                 appendPQExpBufferStr(query, ", pg_catalog");
18289
18290         ExecuteSqlStatement(fout, query->data);
18291
18292         destroyPQExpBuffer(query);
18293 }
18294
18295 /*
18296  * getFormattedTypeName - retrieve a nicely-formatted type name for the
18297  * given type name.
18298  *
18299  * NB: the result may depend on the currently-selected search_path; this is
18300  * why we don't try to cache the names.
18301  */
18302 static char *
18303 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18304 {
18305         char       *result;
18306         PQExpBuffer query;
18307         PGresult   *res;
18308
18309         if (oid == 0)
18310         {
18311                 if ((opts & zeroAsOpaque) != 0)
18312                         return pg_strdup(g_opaque_type);
18313                 else if ((opts & zeroAsAny) != 0)
18314                         return pg_strdup("'any'");
18315                 else if ((opts & zeroAsStar) != 0)
18316                         return pg_strdup("*");
18317                 else if ((opts & zeroAsNone) != 0)
18318                         return pg_strdup("NONE");
18319         }
18320
18321         query = createPQExpBuffer();
18322         appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18323                                           oid);
18324
18325         res = ExecuteSqlQueryForSingleRow(fout, query->data);
18326
18327         /* result of format_type is already quoted */
18328         result = pg_strdup(PQgetvalue(res, 0, 0));
18329
18330         PQclear(res);
18331         destroyPQExpBuffer(query);
18332
18333         return result;
18334 }
18335
18336 /*
18337  * Return a column list clause for the given relation.
18338  *
18339  * Special case: if there are no undropped columns in the relation, return
18340  * "", not an invalid "()" column list.
18341  */
18342 static const char *
18343 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18344 {
18345         int                     numatts = ti->numatts;
18346         char      **attnames = ti->attnames;
18347         bool       *attisdropped = ti->attisdropped;
18348         bool            needComma;
18349         int                     i;
18350
18351         appendPQExpBufferChar(buffer, '(');
18352         needComma = false;
18353         for (i = 0; i < numatts; i++)
18354         {
18355                 if (attisdropped[i])
18356                         continue;
18357                 if (needComma)
18358                         appendPQExpBufferStr(buffer, ", ");
18359                 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18360                 needComma = true;
18361         }
18362
18363         if (!needComma)
18364                 return "";                              /* no undropped columns */
18365
18366         appendPQExpBufferChar(buffer, ')');
18367         return buffer->data;
18368 }
18369
18370 /*
18371  * Check if a reloptions array is nonempty.
18372  */
18373 static bool
18374 nonemptyReloptions(const char *reloptions)
18375 {
18376         /* Don't want to print it if it's just "{}" */
18377         return (reloptions != NULL && strlen(reloptions) > 2);
18378 }
18379
18380 /*
18381  * Format a reloptions array and append it to the given buffer.
18382  *
18383  * "prefix" is prepended to the option names; typically it's "" or "toast.".
18384  */
18385 static void
18386 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18387                                                 const char *prefix, Archive *fout)
18388 {
18389         bool            res;
18390
18391         res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18392                                                                 fout->std_strings);
18393         if (!res)
18394                 write_msg(NULL, "WARNING: could not parse reloptions array\n");
18395 }